zblob 0.3.0

Resumable verified-streaming blob & directory transfer over Zenoh (BLAKE3/bao, range resume, content-addressed dedup)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
//! Tier-2 — content-addressed **directory** transfer (the casync-over-Zenoh
//! model). A snapshot is a [`TreeIndex`] (a depth-first list of entries; files
//! reference their chunks by content hash) plus a content-addressed chunk store.
//!
//! The client GETs the index, computes the set of chunk hashes it is **missing**
//! (`needed − have`), fetches only those — concurrently, re-hashing each on
//! receipt — and reconstructs the tree. Because progress *is* "which hashes
//! are on disk", a dropped connection or a process restart loses nothing, and
//! identical chunks across files/versions transfer once.
//!
//! **Naming.** A snapshot's `id` is a key segment the caller chooses. Prefer
//! [`TreeIndex::keyed_by_root`] — keying a snapshot by its own root hash makes
//! the key immutable (so any holder's copy is as good as any other's, and
//! re-publishing is a no-op) and makes
//! [`DownloadRequest::by_root`](crate::DownloadRequest::by_root) pin
//! automatically. Human names ("nightly") are mutable facts; publish them
//! wherever the application keeps mutable state, pointing at the current root,
//! and resolve in two hops. A caller-chosen name is still supported for
//! deployments that want it, with the usual consequence: the key means
//! whatever its last writer said.
//!
//! Security model: the index is attacker input until proven otherwise.
//! Every path is sanitized (relative, `Normal` components only), symlinks are
//! materialized **last** and their targets confined to the tree, file parents
//! are canonicalized back under the destination root before writing, and the
//! `root_hash` is a canonical postcard digest a caller can pin out of band
//! (`mtime` is excluded, so byte-identical trees hash identically).

use std::collections::HashMap;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use serde::{Deserialize, Serialize};
use tokio::sync::{Notify, Semaphore};
use zenoh::qos::Priority;
use zenoh::query::ConsolidationMode;

use crate::cancel::CancelToken;
use crate::chunk::CdcParams;
use crate::client::DownloadRequest;
use crate::compress::{ChunkCompression, pack};
use crate::error::{BlobError, Result};
use crate::hash::{Hash, HashAlgo};
use crate::id::BlobId;
use crate::keys::{store_key, tree_key};
use crate::obs::{TransferStats, zdebug};
use crate::paths::{
    assert_parent_within, create_dir_confined, sanitize_rel_path, sanitize_symlink_target,
};
use crate::prefix::{QueryPrefix, ServePrefix};
use crate::progress::{Progress, ProgressSink};
use crate::server::{ErrorCallback, FifoQueryable, ServerHandle, report_error};
use crate::store::ContentStore;
use crate::wire::{ENC_CHUNK, ENC_INDEX, WIRE_VERSION, decode, encode};

/// A reference to one content-addressed chunk.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChunkRef {
    /// Content hash of the chunk.
    pub hash: Hash,
    /// Length of the chunk in bytes.
    pub len: u32,
}

/// One entry in a tree snapshot (paths are relative, `/`-separated, UTF-8 —
/// non-UTF-8 names are a build error, not silently mangled).
///
/// Serialized with serde's default (variant-indexed) representation; postcard
/// is not self-describing.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Entry {
    /// A directory.
    Dir {
        /// Relative path.
        path: String,
        /// Unix mode bits (0 on non-unix).
        mode: u32,
        /// Modification time, Unix seconds (restored on materialization;
        /// excluded from the identity `root_hash`).
        mtime: i64,
    },
    /// A regular file, reconstructed by concatenating `chunks` in order.
    File {
        /// Relative path.
        path: String,
        /// Unix mode bits (0 on non-unix).
        mode: u32,
        /// Modification time, Unix seconds (see [`Entry::Dir::mtime`]).
        mtime: i64,
        /// Total file size in bytes (must equal the sum of chunk lengths).
        size: u64,
        /// Ordered chunk references.
        chunks: Vec<ChunkRef>,
    },
    /// A symbolic link. Materialized after all files/dirs, targets confined to
    /// the tree root.
    Symlink {
        /// Relative path.
        path: String,
        /// Link target (relative).
        target: String,
    },
    /// A hard link to an earlier [`Entry::File`] in the same snapshot.
    Hardlink {
        /// Relative path.
        path: String,
        /// Relative path of the linked-to file entry.
        target: String,
    },
}

impl Entry {
    /// The entry's relative path.
    pub fn path(&self) -> &str {
        match self {
            Entry::Dir { path, .. }
            | Entry::File { path, .. }
            | Entry::Symlink { path, .. }
            | Entry::Hardlink { path, .. } => path,
        }
    }
}

/// A directory snapshot: an ordered entry list + a digest over it (`root_hash`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TreeIndex {
    /// Wire schema version (first field; postcard is positional).
    pub version: u16,
    /// Snapshot id (a single key segment).
    pub id: BlobId,
    /// Hash algorithm the chunk references are addressed under.
    pub algo: HashAlgo,
    /// The content-defined-chunking parameters this snapshot was cut with.
    /// Producers sharing a store must share these for dedup to work.
    pub cdc: CdcParams,
    /// Depth-first entries.
    pub entries: Vec<Entry>,
    /// BLAKE3 digest over the canonical (versioned, mtime-free) postcard
    /// serialization of `entries` — the identity a caller pins out of band.
    pub root_hash: Hash,
}

/// The identity view of an [`Entry`]: what `root_hash` covers. `mtime` is
/// deliberately absent — byte-identical trees copied at different times must
/// hash identically for content addressing to mean anything.
#[derive(Serialize)]
enum IdentityEntry<'a> {
    Dir {
        path: &'a str,
        mode: u32,
    },
    File {
        path: &'a str,
        mode: u32,
        size: u64,
        chunks: &'a Vec<ChunkRef>,
    },
    Symlink {
        path: &'a str,
        target: &'a str,
    },
    Hardlink {
        path: &'a str,
        target: &'a str,
    },
}

/// Digest over the canonical serialization of an entry list (the tree root).
fn root_digest(entries: &[Entry]) -> Result<Hash> {
    let view: Vec<IdentityEntry> = entries
        .iter()
        .map(|e| match e {
            Entry::Dir { path, mode, .. } => IdentityEntry::Dir { path, mode: *mode },
            Entry::File {
                path,
                mode,
                size,
                chunks,
                ..
            } => IdentityEntry::File {
                path,
                mode: *mode,
                size: *size,
                chunks,
            },
            Entry::Symlink { path, target } => IdentityEntry::Symlink { path, target },
            Entry::Hardlink { path, target } => IdentityEntry::Hardlink { path, target },
        })
        .collect();
    // A versioned, canonical encoding — the hash preimage is defined by this
    // crate's wire format, not by an accident of a JSON library's escaping.
    let bytes = encode(&(WIRE_VERSION, Hash::ALGO, view))?;
    Ok(Hash::of(&bytes))
}

impl TreeIndex {
    /// All distinct chunk hashes referenced by file entries.
    pub fn needed_chunks(&self) -> Vec<Hash> {
        let mut seen = std::collections::HashSet::new();
        let mut out = Vec::new();
        for e in &self.entries {
            if let Entry::File { chunks, .. } = e {
                for c in chunks {
                    if seen.insert(c.hash) {
                        out.push(c.hash);
                    }
                }
            }
        }
        out
    }

    /// All distinct chunk references, carrying each chunk's declared length.
    ///
    /// The length matters on the fetch path: it is the bound a reply must
    /// respect, and `validate()` has already capped it at `cdc.max`. Where two
    /// entries disagree about one hash's length — which only a malformed index
    /// does, since content determines length — the larger is kept, so an
    /// honest reply is never rejected for being too long.
    pub fn needed_chunk_refs(&self) -> Vec<ChunkRef> {
        let mut index: std::collections::HashMap<Hash, u32> = std::collections::HashMap::new();
        let mut order = Vec::new();
        for e in &self.entries {
            if let Entry::File { chunks, .. } = e {
                for c in chunks {
                    match index.entry(c.hash) {
                        std::collections::hash_map::Entry::Occupied(mut slot) => {
                            let len = slot.get_mut();
                            *len = (*len).max(c.len);
                        }
                        std::collections::hash_map::Entry::Vacant(slot) => {
                            slot.insert(c.len);
                            order.push(c.hash);
                        }
                    }
                }
            }
        }
        order
            .into_iter()
            .map(|hash| ChunkRef {
                hash,
                len: index[&hash],
            })
            .collect()
    }

    /// The entry at `path`, if the snapshot has one.
    ///
    /// Paths are as the index spells them: relative, `/`-separated, no
    /// leading slash. A snapshot's entries are ordered but not indexed, so
    /// this is a linear scan — fine for a lookup, wrong for a loop over many
    /// paths, which should build a map from [`entries`](Self::entries) once.
    #[must_use]
    pub fn entry(&self, path: &str) -> Option<&Entry> {
        self.entries.iter().find(|e| e.path() == path)
    }

    /// Every entry, in depth-first order.
    #[must_use]
    pub fn entries(&self) -> &[Entry] {
        &self.entries
    }

    /// The file entries only, as `(path, size, chunks)`.
    ///
    /// A caller wanting to know what a snapshot *contains* — to show it, to
    /// diff it, to fetch one thing out of it — had to match `Entry` itself and
    /// skip the four non-file variants.
    pub fn files(&self) -> impl Iterator<Item = (&str, u64, &[ChunkRef])> {
        self.entries.iter().filter_map(|e| match e {
            Entry::File {
                path, size, chunks, ..
            } => Some((path.as_str(), *size, chunks.as_slice())),
            _ => None,
        })
    }

    /// The chunks making up the file at `path`, in order.
    ///
    /// `None` if there is no such entry or it is not a file. This is what
    /// [`TreeClient::fetch_file`] fetches.
    #[must_use]
    pub fn file_chunks(&self, path: &str) -> Option<&[ChunkRef]> {
        match self.entry(path)? {
            Entry::File { chunks, .. } => Some(chunks),
            _ => None,
        }
    }

    /// Total size in bytes of all file entries (the reconstructed tree's payload).
    pub fn total_size(&self) -> u64 {
        self.entries
            .iter()
            .map(|e| match e {
                Entry::File { size, .. } => *size,
                _ => 0,
            })
            .sum()
    }

    /// Number of file entries in the snapshot.
    pub fn file_count(&self) -> usize {
        self.entries
            .iter()
            .filter(|e| matches!(e, Entry::File { .. }))
            .count()
    }

    /// Recompute the canonical root digest over `entries`.
    pub fn compute_root(&self) -> Result<Hash> {
        root_digest(&self.entries)
    }

    /// Re-key this snapshot by its own root hash, so the key it is served
    /// under *is* its identity (`<tree_prefix>/<root>`).
    ///
    /// This is the content-addressed shape a keyspace convention wants for
    /// bulk data, and it is what makes a tree key behave like a chunk key:
    /// immutable, so any holder's copy is as good as any other's, so
    /// re-publishing is a no-op and a router storage's last-writer-wins
    /// reconciliation cannot lose anything. It also removes
    /// trust-on-first-use for free — a consumer that asks for a root already
    /// stated the identity it demands, so
    /// [`DownloadRequest::by_root`](crate::DownloadRequest::by_root) pins
    /// automatically.
    ///
    /// The trade is that a *name* ("nightly") is no longer a key here. Names
    /// are mutable facts and belong wherever the application publishes
    /// mutable state — a small record pointing at the current root. The
    /// consumer then resolves in two hops: name → root, then fetch the root.
    ///
    /// The id is not part of the root digest, so re-keying never invalidates
    /// the index.
    #[must_use]
    pub fn keyed_by_root(mut self) -> Self {
        // A hex digest is always a legal id, so this cannot fail.
        self.id = BlobId::new(self.root_hash.to_string())
            .expect("a hex root hash is a valid single key segment");
        self
    }

    /// Whether this index is keyed by its own root (see
    /// [`keyed_by_root`](Self::keyed_by_root)).
    pub fn is_content_addressed(&self) -> bool {
        self.id.as_str() == self.root_hash.to_string()
    }

    /// Validate an index received from the network: schema version, CDC
    /// parameters, every entry path/target (traversal-safe), file size↔chunk
    /// consistency, and that `root_hash` matches the entries.
    ///
    /// The id and the hash algorithm are *not* checked here — they cannot be
    /// wrong. [`BlobId`] and [`HashAlgo`] refuse to decode from anything this
    /// crate could not use, so an index that exists has already passed both.
    pub fn validate(&self) -> Result<()> {
        if self.version != WIRE_VERSION {
            return Err(BlobError::UnsupportedVersion(self.version));
        }
        self.cdc.validate()?;
        // Two entries claiming one path let a snapshot destroy its own output
        // (and, with `Entry::Dir` first, turn a directory into a file). The
        // comparison is on the sanitized path, which is what actually lands on
        // disk — though `sanitize_rel_path` has already refused the aliasing
        // spellings (`.`, `..`) by this point, so in practice this catches an
        // exact repeat.
        let mut seen: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
        // Declared symlinks, collected for the whole-index containment check
        // below — a single link's target cannot be judged on its own.
        let mut links: std::collections::BTreeMap<Vec<String>, String> = Default::default();
        for e in &self.entries {
            let rel = sanitize_rel_path(e.path())?;
            if !seen.insert(rel.clone()) {
                return Err(BlobError::InvalidManifest(format!(
                    "duplicate entry path {:?}",
                    e.path()
                )));
            }
            match e {
                Entry::File { size, chunks, .. } => {
                    let sum: u64 = chunks.iter().map(|c| c.len as u64).sum();
                    if sum != *size {
                        return Err(BlobError::InvalidManifest(format!(
                            "file {:?}: size {size} != chunk sum {sum}",
                            e.path()
                        )));
                    }
                    // Each declared length is an allocation the receiver (and
                    // the zero-seed synthesizer) will perform: bound it by the
                    // declared CDC maximum, which validate() capped above.
                    if let Some(bad) = chunks.iter().find(|c| c.len == 0 || c.len > self.cdc.max) {
                        return Err(BlobError::InvalidManifest(format!(
                            "file {:?}: chunk len {} outside 1..={}",
                            e.path(),
                            bad.len,
                            self.cdc.max
                        )));
                    }
                }
                Entry::Symlink { target, .. } => {
                    sanitize_symlink_target(&rel, target)?;
                    links.insert(
                        rel.components()
                            .map(|c| c.as_os_str().to_string_lossy().into_owned())
                            .collect(),
                        target.clone(),
                    );
                }
                Entry::Hardlink { target, .. } => {
                    sanitize_rel_path(target)?;
                }
                Entry::Dir { .. } => {}
            }
        }
        // Now that every link is known, decide containment against the set —
        // the per-entry lexical check above cannot see a chain.
        crate::paths::assert_symlinks_confined(&links)?;
        let actual = self.compute_root()?;
        if actual != self.root_hash {
            return Err(BlobError::RootMismatch {
                expected: self.root_hash,
                actual,
            });
        }
        Ok(())
    }
}

/// Build a [`TreeIndex`] for the directory at `root`, streaming every file
/// through the content-defined chunker and `put`ting each new chunk into
/// `store`. Memory stays O(max chunk size) regardless of tree size.
///
/// Synchronous (run it in `spawn_blocking`). Walks depth-first in a
/// deterministic (sorted) order so the snapshot is reproducible. Policy:
/// non-UTF-8 names and non-regular files (FIFOs, sockets, devices) are
/// **errors**, not silent drops; hard links are detected (unix) and recorded
/// as [`Entry::Hardlink`].
pub fn build_tree(
    root: &Path,
    id: impl Into<String>,
    cdc: &CdcParams,
    store: &dyn ContentStore,
) -> Result<TreeIndex> {
    build_tree_from(root, id, cdc, store, None)
}

/// [`build_tree`], reusing a previous snapshot's work where the tree has not
/// changed.
///
/// For each file, if `(path, size, mtime)` matches the parent snapshot's entry
/// and the parent's chunks are all still in `store`, that entry's chunk
/// references are reused and the file is not read at all. Everything else is
/// chunked as usual.
///
/// This is restic's parent-snapshot trick, and it is the producer-side
/// counterpart of [`seed`](crate::seed) — which grows a *consumer's* store
/// from what it already has locally, while a producer re-hashed its entire
/// tree on every snapshot. For a sensor snapshotting a mostly-static directory
/// repeatedly, that was the dominant cost.
///
/// Three things it is careful about:
///
/// - **The CDC parameters must match.** Chunk boundaries are a function of the
///   parameters *and* the data, so reusing references cut with different ones
///   would produce an index whose chunks do not tile as its own parameters
///   say. A mismatched parent is an error, not a silent full rebuild.
/// - **`(size, mtime)` is a heuristic, and it has a real blind spot.** mtime
///   is deliberately excluded from `root_hash` — byte-identical trees must
///   hash identically whenever they were copied — and is used here for the
///   different question of *has this file changed*, which is what rsync, tar
///   and restic all use it for.
///
///   It is wrong when a file is rewritten **to the same length within the same
///   second**: `"mode = 'a'\n"` becoming `"mode = 'b'\n"` is exactly that, and
///   it is not a contrived case — it is a config edit. The snapshot then
///   claims the old content. Nothing is corrupted (every reused reference is
///   still content-addressed and every chunk still verifies), but the snapshot
///   does not describe the tree.
///
///   Filesystem mtime granularity is what bounds this: a snapshot taken a
///   second or more after the last write is safe. When that cannot be assumed
///   — a producer snapshotting immediately after writing — use
///   [`build_tree`], which reads everything and cannot be fooled. There is no
///   middle setting on purpose: "sometimes verify" is the option that reads
///   like safety and is not.
/// - **Reused chunks must still exist.** A reference to a chunk the store no
///   longer holds would build an index nobody can fetch, so presence is
///   checked and a miss falls back to re-chunking.
pub fn build_tree_from(
    root: &Path,
    id: impl Into<String>,
    cdc: &CdcParams,
    store: &dyn ContentStore,
    parent: Option<&TreeIndex>,
) -> Result<TreeIndex> {
    cdc.validate()?;
    let id = BlobId::new(id.into())?;
    // Index the parent's file entries by path for O(1) lookup during the walk.
    let mut reusable: HashMap<&str, &Entry> = HashMap::new();
    if let Some(parent) = parent {
        if parent.cdc != *cdc {
            return Err(BlobError::Usage(format!(
                "parent snapshot was cut with different CDC parameters ({:?} vs {:?}); \
                 its chunk references would not tile under these",
                parent.cdc, cdc
            )));
        }
        for e in &parent.entries {
            if matches!(e, Entry::File { .. }) {
                reusable.insert(e.path(), e);
            }
        }
    }
    let mut entries = Vec::new();
    walk(root, cdc, store, &reusable, &mut entries)?;
    let root_hash = root_digest(&entries)?;
    let index = TreeIndex {
        version: WIRE_VERSION,
        id,
        algo: HashAlgo::Blake3,
        cdc: *cdc,
        entries,
        root_hash,
    };
    // Refuse to hand back a snapshot no client would accept.
    //
    // Every consumer runs `validate()` on receipt, and it rejects things a
    // *source tree* can perfectly well contain — an absolute symlink such as
    // `/etc/localtime`, or one pointing above the tree. Without this check
    // such a snapshot builds, registers and publishes without complaint, and
    // is then rejected by every consumer forever, with the error surfacing on
    // machines that did not build it. That is the same shape as the leading-`@`
    // id rule (see `manifest::validate_id`): reject it at the door, where the
    // producer can act on it.
    index.validate()?;
    Ok(index)
}

fn rel_path_of(root: &Path, path: &Path) -> Result<String> {
    let rel = path.strip_prefix(root).unwrap_or(path);
    let mut out = String::new();
    for comp in rel.components() {
        let s = comp
            .as_os_str()
            .to_str()
            .ok_or_else(|| BlobError::Usage(format!("non-UTF-8 file name in tree: {rel:?}")))?;
        if !out.is_empty() {
            out.push('/');
        }
        out.push_str(s);
    }
    Ok(out)
}

#[cfg(unix)]
fn mode_of(meta: &std::fs::Metadata) -> u32 {
    use std::os::unix::fs::PermissionsExt;
    meta.permissions().mode()
}
#[cfg(not(unix))]
fn mode_of(_meta: &std::fs::Metadata) -> u32 {
    0
}

fn mtime_of(meta: &std::fs::Metadata) -> i64 {
    meta.modified()
        .ok()
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

/// Iterative depth-first walk (explicit stack — a deep tree must not blow the
/// call stack), sorted per directory for reproducibility.
fn walk(
    root: &Path,
    cdc: &CdcParams,
    store: &dyn ContentStore,
    reusable: &HashMap<&str, &Entry>,
    entries: &mut Vec<Entry>,
) -> Result<()> {
    fn read_dir_sorted(dir: &Path) -> std::io::Result<std::vec::IntoIter<std::fs::DirEntry>> {
        let mut items: Vec<_> = std::fs::read_dir(dir)?.collect::<std::io::Result<Vec<_>>>()?;
        items.sort_by_key(|e| e.file_name());
        Ok(items.into_iter())
    }

    // (dev, ino) → first path seen, for hard-link detection.
    let mut inodes: HashMap<(u64, u64), String> = HashMap::new();
    let mut stack = vec![read_dir_sorted(root)?];
    while let Some(top) = stack.last_mut() {
        let Some(item) = top.next() else {
            stack.pop();
            continue;
        };
        let path = item.path();
        let meta = std::fs::symlink_metadata(&path)?;
        let rel = rel_path_of(root, &path)?;
        let ftype = meta.file_type();
        if ftype.is_symlink() {
            let target_os = std::fs::read_link(&path)?;
            let target = target_os
                .to_str()
                .ok_or_else(|| BlobError::Usage(format!("non-UTF-8 symlink target at {rel:?}")))?
                .to_string();
            entries.push(Entry::Symlink { path: rel, target });
        } else if ftype.is_dir() {
            entries.push(Entry::Dir {
                path: rel,
                mode: mode_of(&meta),
                mtime: mtime_of(&meta),
            });
            stack.push(read_dir_sorted(&path)?);
        } else if ftype.is_file() {
            if let Some(first) = hardlink_target(&meta, &rel, &mut inodes) {
                entries.push(Entry::Hardlink {
                    path: rel,
                    target: first,
                });
                continue;
            }
            // Unchanged since the parent snapshot? Then its chunk references
            // still describe this file, and it need not be read at all.
            let mtime = mtime_of(&meta);
            if let Some(Entry::File {
                size: prev_size,
                mtime: prev_mtime,
                chunks: prev_chunks,
                ..
            }) = reusable.get(rel.as_str()).copied()
                && *prev_size == meta.len()
                && *prev_mtime == mtime
                && prev_chunks
                    .iter()
                    .try_fold(true, |acc, c| store.has(&c.hash).map(|p| acc && p))?
            {
                entries.push(Entry::File {
                    path: rel,
                    mode: mode_of(&meta),
                    mtime,
                    size: *prev_size,
                    chunks: prev_chunks.clone(),
                });
                continue;
            }
            let file = std::fs::File::open(&path)?;
            let mut refs = Vec::new();
            let mut size: u64 = 0;
            for chunk in cdc.chunk_reader(file) {
                let bytes = chunk?;
                let hash = Hash::of(&bytes);
                size += bytes.len() as u64;
                refs.push(ChunkRef {
                    hash,
                    len: bytes.len() as u32,
                });
                if !store.has(&hash)? {
                    store.put(&hash, &bytes)?;
                }
            }
            entries.push(Entry::File {
                path: rel,
                mode: mode_of(&meta),
                mtime,
                size,
                chunks: refs,
            });
        } else {
            // FIFO / socket / device: refusing loudly beats silently producing
            // a snapshot that claims to be the tree but isn't.
            return Err(BlobError::Usage(format!(
                "unsupported file type at {rel:?} (fifo/socket/device)"
            )));
        }
    }
    Ok(())
}

/// If this file shares an inode with an earlier file, return that path.
#[cfg(unix)]
fn hardlink_target(
    meta: &std::fs::Metadata,
    rel: &str,
    inodes: &mut HashMap<(u64, u64), String>,
) -> Option<String> {
    use std::os::unix::fs::MetadataExt;
    if meta.nlink() > 1 {
        let key = (meta.dev(), meta.ino());
        match inodes.get(&key) {
            Some(first) => return Some(first.clone()),
            None => {
                inodes.insert(key, rel.to_string());
            }
        }
    }
    None
}
#[cfg(not(unix))]
fn hardlink_target(
    _meta: &std::fs::Metadata,
    _rel: &str,
    _inodes: &mut HashMap<(u64, u64), String>,
) -> Option<String> {
    None
}

/// What a snapshot is allowed to do to the destination directory.
///
/// Materialization is in place (the rsync/casync model), so a snapshot writes
/// into a directory that may already hold data the caller cares about. Two of
/// the things an index can ask for are destructive enough that they are off
/// unless the caller says otherwise — an index is remote input, and the
/// default has to be the one that cannot surprise.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct MaterializePolicy {
    replace_directories: bool,
    restore_setid: bool,
}

impl MaterializePolicy {
    /// Allow an entry to replace an existing **directory** — which deletes it
    /// and everything under it.
    ///
    /// Off by default. A snapshot in which `foo/` became the file `foo` is a
    /// real and ordinary change, so this exists; but with it off, an index
    /// entry named `Documents` cannot recursively delete `<dest>/Documents`
    /// on its way to writing a file there. Off, such an entry is an error.
    #[must_use]
    pub fn replace_directories(mut self, allow: bool) -> Self {
        self.replace_directories = allow;
        self
    }

    /// Restore setuid/setgid/sticky bits from the index instead of masking
    /// them off.
    ///
    /// Off by default: the mode is remote input, so a privileged extraction of
    /// an index with attacker-chosen file content and `mode = 0o104755` would
    /// otherwise produce a setuid-root binary. tar and rsync gate this the
    /// same way. With it off, modes are masked to `0o0777`.
    #[must_use]
    pub fn restore_setid(mut self, allow: bool) -> Self {
        self.restore_setid = allow;
        self
    }
}

/// Serves a tree snapshot: an index queryable + a content-addressed chunk
/// queryable, both backed by a [`ContentStore`]. Each query is served on its
/// own task under an in-flight semaphore, so one slow client cannot stall the
/// rest.
#[derive(Clone)]
pub struct TreeServer {
    inner: Arc<TreeInner>,
}

impl std::fmt::Debug for TreeServer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TreeServer")
            .field("store_prefix", &self.inner.store_prefix)
            .field("tree_prefix", &self.inner.tree_prefix)
            .field("compression", &self.inner.compression)
            .field("max_want_list", &self.inner.max_want_list)
            .finish_non_exhaustive()
    }
}

struct TreeInner {
    session: zenoh::Session,
    store_prefix: ServePrefix,
    tree_prefix: ServePrefix,
    store: Arc<dyn ContentStore>,
    index: tokio::sync::RwLock<std::collections::HashMap<BlobId, Registered>>,
    index_shard_threshold: usize,
    inflight: Arc<Semaphore>,
    compression: ChunkCompression,
    max_want_list: usize,
    on_error: Option<ErrorCallback>,
}

/// Builder for a [`TreeServer`] (see [`TreeServer::builder`]).
pub struct TreeServerBuilder {
    session: zenoh::Session,
    store_prefix: ServePrefix,
    tree_prefix: ServePrefix,
    store: Arc<dyn ContentStore>,
    max_inflight: usize,
    compression: ChunkCompression,
    max_want_list: usize,
    index_shard_threshold: usize,
    on_error: Option<ErrorCallback>,
}

impl std::fmt::Debug for TreeServerBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TreeServerBuilder")
            .field("store_prefix", &self.store_prefix)
            .field("tree_prefix", &self.tree_prefix)
            .field("max_inflight", &self.max_inflight)
            .field("compression", &self.compression)
            .field("max_want_list", &self.max_want_list)
            .field("index_shard_threshold", &self.index_shard_threshold)
            .finish_non_exhaustive()
    }
}

/// A registered snapshot, plus its sharded form when it is large enough to
/// need one.
struct Registered {
    index: TreeIndex,
    sharded: Option<crate::wire::IndexDescriptor>,
}

/// Fixed-size pieces the encoded index is cut into when it is sharded.
///
/// Fixed, not content-defined: the CDC parameters live *inside* the index, so
/// chunking it by content would be circular — and an index is written once,
/// which is precisely the case CDC does nothing for. 64 KiB matches Zenoh's
/// batch size, so a piece is one fragment.
const INDEX_SHARD: usize = 64 * 1024;

/// Cut an encoded index into content-addressed pieces, store them, and
/// describe the result.
fn shard_index(
    encoded: &[u8],
    store: &dyn ContentStore,
    root: Hash,
) -> Result<crate::wire::IndexDescriptor> {
    let mut chunks = Vec::new();
    for piece in encoded.chunks(INDEX_SHARD) {
        let hash = Hash::of(piece);
        if !store.has(&hash)? {
            store.put(&hash, piece)?;
        }
        chunks.push(ChunkRef {
            hash,
            len: piece.len() as u32,
        });
    }
    Ok(crate::wire::IndexDescriptor {
        version: WIRE_VERSION,
        root,
        algo: HashAlgo::Blake3,
        index_chunks: chunks,
        index_len: encoded.len() as u64,
        ext: crate::wire::Ext::new(),
    })
}

impl TreeServerBuilder {
    /// Max concurrent in-flight queries served at once (default 8).
    #[must_use]
    pub fn max_inflight(mut self, n: usize) -> Self {
        self.max_inflight = n.max(1);
        self
    }

    /// Compression for chunk replies (default none; requires the `zstd`
    /// feature for [`ChunkCompression::Zstd`]).
    #[must_use]
    pub fn compression(mut self, c: ChunkCompression) -> Self {
        self.compression = c;
        self
    }

    /// Encoded-index size above which the index is served as content-addressed
    /// chunks rather than as one reply (default 256 KiB).
    ///
    /// An index costs roughly 0.05–0.10% of the payload it describes, so this
    /// threshold is reached by snapshots of a couple of hundred MB and up.
    /// Below it, a single reply is strictly better: one round trip, no
    /// descriptor. Above it, Zenoh's 64 KiB fragmentation starts to bite —
    /// a dropped fragment discards the whole message — and chunks resume.
    #[must_use]
    pub fn index_shard_threshold(mut self, bytes: usize) -> Self {
        self.index_shard_threshold = bytes;
        self
    }

    /// Largest want-list this server will answer in one batch fetch or probe
    /// (default [`MAX_WANT_LIST`](crate::wire::MAX_WANT_LIST)).
    ///
    /// The bound on how much work one request can commit this server to —
    /// tier 2's counterpart of `max_chunks_per_query`. Checked before any
    /// store access.
    #[must_use]
    pub fn max_want_list(mut self, n: usize) -> Self {
        self.max_want_list = n.max(1);
        self
    }

    /// Invoke `cb` with every serve error (default: a `tracing` warn event
    /// with the `tracing` feature, else stderr in debug builds only).
    #[must_use]
    pub fn on_error(mut self, cb: ErrorCallback) -> Self {
        self.on_error = Some(cb);
        self
    }

    /// Build the server.
    pub fn build(self) -> TreeServer {
        TreeServer {
            inner: Arc::new(TreeInner {
                session: self.session,
                store_prefix: self.store_prefix,
                tree_prefix: self.tree_prefix,
                store: self.store,
                index: tokio::sync::RwLock::new(std::collections::HashMap::new()),
                index_shard_threshold: self.index_shard_threshold,
                inflight: Arc::new(Semaphore::new(self.max_inflight)),
                compression: self.compression,
                max_want_list: self.max_want_list,
                on_error: self.on_error,
            }),
        }
    }
}

impl TreeServer {
    /// Start building a server. `store_prefix` serves `<prefix>/<algo>/<hash>`;
    /// `tree_prefix` serves `<prefix>/<id>`.
    pub fn builder(
        session: &zenoh::Session,
        store_prefix: ServePrefix,
        tree_prefix: ServePrefix,
        store: Arc<dyn ContentStore>,
    ) -> TreeServerBuilder {
        TreeServerBuilder {
            session: session.clone(),
            store_prefix,
            tree_prefix,
            store,
            max_inflight: 8,
            compression: ChunkCompression::default(),
            max_want_list: crate::wire::MAX_WANT_LIST,
            // Above this, an index is served as chunks instead of whole. Set
            // so that ordinary snapshots — which produce indices of a few KB —
            // keep their single round trip, and only indices big enough to
            // fragment badly pay for the extra hop.
            index_shard_threshold: 256 * 1024,
            on_error: None,
        }
    }

    /// Build a server with default configuration.
    pub fn new(
        session: &zenoh::Session,
        store_prefix: ServePrefix,
        tree_prefix: ServePrefix,
        store: Arc<dyn ContentStore>,
    ) -> Self {
        Self::builder(session, store_prefix, tree_prefix, store).build()
    }

    /// Register a snapshot index (its chunks must already be in the store).
    ///
    /// An index larger than
    /// [`index_shard_threshold`](TreeServerBuilder::index_shard_threshold) is
    /// additionally cut into content-addressed chunks and put in the store, so
    /// it can be served as an [`IndexDescriptor`](crate::wire::IndexDescriptor)
    /// — resumable and batched like any other content. Smaller ones are served
    /// whole, as they always were.
    pub async fn register(&self, index: TreeIndex) -> Result<()> {
        let encoded = encode(&index)?;
        let sharded = if encoded.len() > self.inner.index_shard_threshold {
            // Sharding is `has` + `put` per 64 KiB piece, and every `put` is an
            // fsynced atomic rename. A few megabytes of index is dozens of
            // fsyncs, which must not run on an async thread.
            let store = self.inner.store.clone();
            let root = index.root_hash;
            Some(tokio::task::spawn_blocking(move || shard_index(&encoded, &*store, root)).await??)
        } else {
            None
        };
        self.inner
            .index
            .write()
            .await
            .insert(index.id.clone(), Registered { index, sharded });
        Ok(())
    }

    /// The snapshot ids this server currently serves.
    pub async fn registered(&self) -> Vec<BlobId> {
        self.inner.index.read().await.keys().cloned().collect()
    }

    /// The index this server serves for `id`, if any.
    pub async fn index(&self, id: &str) -> Option<TreeIndex> {
        self.inner
            .index
            .read()
            .await
            .get(id)
            .map(|r| r.index.clone())
    }

    /// Whether `id` is currently served.
    pub async fn serves(&self, id: &str) -> bool {
        self.inner.index.read().await.contains_key(id)
    }

    /// Drop a previously-registered snapshot index by id (e.g. on TTL expiry). The
    /// chunks themselves are owned by the [`ContentStore`] and freed separately.
    pub async fn unregister(&self, id: &str) {
        self.inner.index.write().await.remove(id);
    }

    async fn declare(&self) -> Result<(FifoQueryable, FifoQueryable)> {
        let store_q = self
            .inner
            .session
            .declare_queryable(format!("{}/**", self.inner.store_prefix))
            .await
            .map_err(BlobError::zenoh)?;
        let tree_q = self
            .inner
            .session
            .declare_queryable(format!("{}/**", self.inner.tree_prefix))
            .await
            .map_err(BlobError::zenoh)?;
        Ok((store_q, tree_q))
    }

    /// Declare both queryables, spawn the serve loop, and return a stop
    /// handle. Queryables are live when this returns.
    pub async fn spawn(self) -> Result<ServerHandle> {
        let (store_q, tree_q) = self.declare().await?;
        let stop = Arc::new(Notify::new());
        let stop2 = stop.clone();
        Ok(ServerHandle::new(
            tokio::spawn(self.serve_loop(store_q, tree_q, stop2)),
            stop,
        ))
    }

    /// Declare both queryables and serve until the session closes.
    pub async fn run(self) -> Result<()> {
        let (store_q, tree_q) = self.declare().await?;
        self.serve_loop(store_q, tree_q, Arc::new(Notify::new()))
            .await
    }

    async fn serve_loop(
        self,
        store_q: FifoQueryable,
        tree_q: FifoQueryable,
        stop: Arc<Notify>,
    ) -> Result<()> {
        loop {
            tokio::select! {
                _ = stop.notified() => break,
                q = store_q.recv_async() => {
                    let Ok(query) = q else { break };
                    let inner = self.inner.clone();
                    // Permit before spawn — see BlobServer::serve_loop: taken
                    // inside the task it bounds work but not the queue of
                    // tasks holding queries.
                    let Ok(permit) = inner.inflight.clone().acquire_owned().await else { break };
                    tokio::spawn(async move {
                        let _permit = permit;
                        if let Err(e) = serve_chunk_query(&inner, query).await {
                            report_error(&inner.on_error, &e);
                        }
                    });
                }
                q = tree_q.recv_async() => {
                    let Ok(query) = q else { break };
                    let inner = self.inner.clone();
                    let Ok(permit) = inner.inflight.clone().acquire_owned().await else { break };
                    tokio::spawn(async move {
                        let _permit = permit;
                        if let Err(e) = serve_index_query(&inner, query).await {
                            report_error(&inner.on_error, &e);
                        }
                    });
                }
            }
        }
        Ok(())
    }
}

async fn serve_chunk_query(inner: &TreeInner, query: zenoh::query::Query) -> Result<()> {
    let key = query.key_expr().as_str().to_string();
    // Not one of our keys, or not the `<algo>/<x>` shape a store key has.
    let Some(crate::keys::Tier2Tail::Two(algo, last)) =
        crate::keys::parse_tier2_tail(inner.store_prefix.as_str(), &key)
    else {
        return Ok(());
    };
    if algo != Hash::ALGO {
        return Ok(()); // foreign algorithm; not ours to answer.
    }
    match last {
        crate::keys::STORE_BATCH => serve_chunk_batch(inner, query).await,
        crate::keys::STORE_HAVE => serve_chunk_probe(inner, query).await,
        hex => {
            let Ok(hash) = hex.parse::<Hash>() else {
                return Ok(()); // not a chunk address; ignore.
            };
            let store = inner.store.clone();
            let compression = inner.compression;
            let packed = tokio::task::spawn_blocking(move || -> Result<Option<Vec<u8>>> {
                match store.get(&hash)? {
                    Some(bytes) => Ok(Some(pack(&bytes, compression)?)),
                    None => Ok(None),
                }
            })
            .await??;
            if let Some(packed) = packed {
                query
                    // This server's own key, not `query.key_expr()`. For a
                    // concrete GET they are the same; for a wildcard-origin
                    // one the query's expression names *every* origin, so
                    // replying with it makes the answer unattributable and
                    // uncacheable. A reply must say who is answering.
                    .reply(
                        store_key(inner.store_prefix.as_str(), HashAlgo::Blake3, &hash),
                        packed,
                    )
                    .encoding(&ENC_CHUNK)
                    .await
                    .map_err(BlobError::zenoh)?;
            }
            Ok(())
        }
    }
}

/// Read and validate a [`WantList`] out of a query payload, replying with the
/// reason if it is unusable.
async fn want_list_of(
    inner: &TreeInner,
    query: &zenoh::query::Query,
) -> Result<Option<crate::wire::WantList>> {
    let Some(payload) = query.payload() else {
        let _ = query
            .reply_err("want-list endpoint requires a payload")
            .await;
        return Ok(None);
    };
    let want: crate::wire::WantList = match decode(&payload.to_bytes()) {
        Ok(w) => w,
        Err(e) => {
            let _ = query.reply_err(format!("undecodable want list: {e}")).await;
            return Ok(None);
        }
    };
    // Validate before any I/O, exactly as `parse_ranges` does for tier 1: a
    // malformed request must not be able to drive unbounded work.
    if let Err(e) = want.validate(inner.max_want_list) {
        let _ = query.reply_err(e.to_string()).await;
        return Ok(None);
    }
    Ok(Some(want))
}

/// Serve a batched want-list: one reply per held chunk, each on its ordinary
/// store key.
///
/// Those keys are **disjoint** from the `…/batch` key this query arrived on,
/// so Zenoh refuses them unless the client asked for
/// `ReplyKeyExpr::Any` — and it refuses them *here*, on the serving side, once
/// per chunk. Checking first turns that into one clear error for the client
/// that got it wrong.
async fn serve_chunk_batch(inner: &TreeInner, query: zenoh::query::Query) -> Result<()> {
    if query.accepts_replies() != zenoh::query::ReplyKeyExpr::Any {
        let _ = query
            .reply_err(
                "a batch fetch replies on each chunk's own key, which does not \
                 intersect the batch key: issue the query with \
                 accept_replies(ReplyKeyExpr::Any)",
            )
            .await;
        return Ok(());
    }
    let Some(want) = want_list_of(inner, &query).await? else {
        return Ok(());
    };

    let store = inner.store.clone();
    let compression = inner.compression;
    let prefix = inner.store_prefix.as_str().to_string();
    // One blocking pass for the whole batch: a store `get` is a syscall (or a
    // transaction), and hundreds of them do not belong on an async worker
    // one at a time.
    let packed: Vec<(String, Vec<u8>)> =
        tokio::task::spawn_blocking(move || -> Result<Vec<(String, Vec<u8>)>> {
            want.hashes
                .iter()
                .filter_map(|h| match store.get(h) {
                    Ok(Some(bytes)) => match pack(&bytes, compression) {
                        Ok(framed) => Some(Ok((store_key(&prefix, HashAlgo::Blake3, h), framed))),
                        // Framing failed for a chunk we hold. Silently dropping it
                        // would leave the client re-asking forever with nothing on
                        // either side to explain it.
                        Err(e) => Some(Err(e)),
                    },
                    Ok(None) => None,
                    Err(e) => Some(Err(BlobError::from(e))),
                })
                .collect::<Result<Vec<_>>>()
        })
        .await??;

    // Silence for what we do not hold: the client re-asks elsewhere, and a
    // per-chunk "no" would defeat the point of batching.
    for (key, bytes) in packed {
        if query
            .reply(key, bytes)
            .encoding(&ENC_CHUNK)
            .await
            .map_err(BlobError::zenoh)
            .is_err()
        {
            break; // the client went away; stop streaming into the void.
        }
    }
    Ok(())
}

/// Serve a chunk probe: one bit per want-list entry, in order.
async fn serve_chunk_probe(inner: &TreeInner, query: zenoh::query::Query) -> Result<()> {
    let Some(want) = want_list_of(inner, &query).await? else {
        return Ok(());
    };
    let store = inner.store.clone();
    let bits = tokio::task::spawn_blocking(move || -> std::io::Result<crate::wire::HaveBits> {
        Ok(crate::wire::HaveBits::from_presence(
            store.has_many(&want.hashes)?,
        ))
    })
    .await??;
    query
        // Our own key: a probe exists to be attributed (see the chunk reply).
        .reply(
            crate::keys::store_have_key(inner.store_prefix.as_str(), HashAlgo::Blake3),
            encode(&bits)?,
        )
        .encoding(&crate::wire::ENC_HAVEBITS)
        .await
        .map_err(BlobError::zenoh)?;
    Ok(())
}

async fn serve_index_query(inner: &TreeInner, query: zenoh::query::Query) -> Result<()> {
    let key = query.key_expr().as_str().to_string();
    let Some(tail) = crate::keys::parse_tier2_tail(inner.tree_prefix.as_str(), &key) else {
        return Ok(());
    };
    let id = match tail {
        crate::keys::Tier2Tail::One(id) => id,
        // `<tree_prefix>/<id>/have`: how much of this snapshot do you have?
        crate::keys::Tier2Tail::Two(id, crate::keys::STORE_HAVE) => {
            return serve_tree_probe(inner, &query, id).await;
        }
        crate::keys::Tier2Tail::Two(..) => return Ok(()),
    };
    let (payload, encoding) = {
        let registry = inner.index.read().await;
        let Some(reg) = registry.get(id) else {
            // Unknown id: silence, not an error reply. A query finalizes when
            // its matching queryables complete, so this resolves on the client
            // in about a millisecond rather than on the timeout — see the
            // `BlobServer` docs on sharing a prefix.
            return Ok(());
        };
        // A small index goes whole, as it always has: one reply, one round
        // trip. A large one goes as a descriptor pointing at chunks the client
        // fetches like any other content — resumable, batched, unbounded. The
        // encoding tag is what tells the two apart, which is what tags are for.
        match &reg.sharded {
            Some(desc) => (encode(desc)?, &crate::wire::ENC_INDEX_DESC),
            None => (encode(&reg.index)?, &ENC_INDEX),
        }
    };
    query
        // Our own key, so a wildcard-origin index query can tell holders apart.
        .reply(tree_key(inner.tree_prefix.as_str(), id), payload)
        .encoding(encoding)
        .await
        .map_err(BlobError::zenoh)?;
    Ok(())
}

/// Answer "how much of snapshot `id` do you have": four numbers, whatever the
/// size of the snapshot.
///
/// A holder that does not know the snapshot says nothing, exactly as it does
/// for an unknown chunk — silence means "not mine" and costs the asker
/// nothing.
async fn serve_tree_probe(inner: &TreeInner, query: &zenoh::query::Query, id: &str) -> Result<()> {
    let Some(index) = inner
        .index
        .read()
        .await
        .get(id)
        .map(|reg| reg.index.clone())
    else {
        return Ok(());
    };
    let store = inner.store.clone();
    let needed = index.needed_chunks();
    let total = needed.len() as u32;
    let present = tokio::task::spawn_blocking(move || -> std::io::Result<u32> {
        Ok(store.has_many(&needed)?.iter().filter(|p| **p).count() as u32)
    })
    .await??;
    let probe = crate::wire::TreeProbe {
        version: WIRE_VERSION,
        have_index: true,
        chunks_present: present,
        chunks_total: total,
    };
    query
        // Our own key, so a wildcard-origin probe can attribute the answer.
        .reply(
            crate::keys::tree_have_key(inner.tree_prefix.as_str(), id),
            encode(&probe)?,
        )
        .encoding(&crate::wire::ENC_TREEPROBE)
        .await
        .map_err(BlobError::zenoh)?;
    Ok(())
}

/// Downloads a tree snapshot. Stateless server; persistent client (the store).
#[derive(Debug)]
pub struct TreeClient {
    session: zenoh::Session,
    store_prefix: QueryPrefix,
    tree_prefix: QueryPrefix,
    cfg: TreeClientConfig,
}

#[derive(Debug, Clone)]
struct TreeClientConfig {
    query_timeout: Duration,
    fetch_concurrency: usize,
    max_index_bytes: usize,
    max_tree_bytes: u64,
    max_tree_chunks: u32,
    batch_size: usize,
    priority: Priority,
    policy: MaterializePolicy,
    temps: Option<Arc<crate::gc::TempTags>>,
}

impl Default for TreeClientConfig {
    fn default() -> Self {
        TreeClientConfig {
            query_timeout: Duration::from_secs(30),
            fetch_concurrency: 16,
            max_index_bytes: 64 * 1024 * 1024,
            // Tier 1 has bounded the blob a remote peer can make us fetch since
            // v2 (`BlobClientBuilder::max_blob_size`); tier 2 bounded only the
            // index, so an index within its cap could still reference tens of
            // TiB. These are the missing halves of that defence.
            max_tree_bytes: 1 << 40,
            max_tree_chunks: 4_000_000,
            // Chunks asked for per batched round. 256 keeps a round's reply
            // volume sane on a shared bus while cutting queries by two orders
            // of magnitude against the old one-query-per-chunk shape.
            batch_size: 256,
            // Bulk transfer yields — see `BlobClientBuilder::priority`.
            priority: Priority::DataLow,
            policy: MaterializePolicy::default(),
            temps: None,
        }
    }
}

/// Builder for a [`TreeClient`] (see [`TreeClient::builder`]).
#[derive(Debug)]
pub struct TreeClientBuilder {
    session: zenoh::Session,
    store_prefix: QueryPrefix,
    tree_prefix: QueryPrefix,
    cfg: TreeClientConfig,
}

impl TreeClientBuilder {
    /// Per-query timeout (default 30 s).
    #[must_use]
    pub fn query_timeout(mut self, t: Duration) -> Self {
        self.cfg.query_timeout = t;
        self
    }

    /// Concurrent chunk fetches (default 16). A serial fetch pays one full
    /// round trip per chunk — tens of thousands of RTTs on a large tree.
    #[must_use]
    pub fn fetch_concurrency(mut self, n: usize) -> Self {
        self.cfg.fetch_concurrency = n.max(1);
        self
    }

    /// Largest index payload accepted, in bytes (default 64 MiB) — the
    /// allocation bound against a hostile index reply.
    #[must_use]
    pub fn max_index_bytes(mut self, n: usize) -> Self {
        self.cfg.max_index_bytes = n;
        self
    }

    /// Largest snapshot this client will fetch, in total bytes
    /// (default 1 TiB).
    ///
    /// Bounding the *index* is not enough: an index comfortably inside
    /// [`max_index_bytes`](Self::max_index_bytes) can reference millions of
    /// chunks of up to `CdcParams::max` each, and `download_tree` would fetch
    /// and store every one. This is tier 2's counterpart to
    /// [`BlobClientBuilder::max_blob_size`](crate::BlobClientBuilder::max_blob_size):
    /// a remote peer must not choose how much disk or memory we commit. The
    /// check runs against the validated index before the first chunk is
    /// requested.
    #[must_use]
    pub fn max_tree_bytes(mut self, n: u64) -> Self {
        self.cfg.max_tree_bytes = n;
        self
    }

    /// Largest number of distinct chunks a snapshot may reference
    /// (default 4,000,000) — the companion bound to
    /// [`max_tree_bytes`](Self::max_tree_bytes), since a great many *small*
    /// chunks cost queries and bookkeeping rather than bytes.
    #[must_use]
    pub fn max_tree_chunks(mut self, n: u32) -> Self {
        self.cfg.max_tree_chunks = n;
        self
    }

    /// Chunks requested per batched round (default 256; `0` disables
    /// batching and falls back to one query per chunk).
    ///
    /// Clamped to the server's [`MAX_WANT_LIST`](crate::wire::MAX_WANT_LIST),
    /// since a server validates the list before doing any work for it.
    /// Batching is what makes a large snapshot affordable — but it is only
    /// answered by holders that implement the endpoint, so a fleet served
    /// entirely by router storages will silently fall back. Watch
    /// [`TransferStats::queries`](crate::TransferStats::queries) to tell the
    /// difference.
    #[must_use]
    pub fn batch_size(mut self, n: usize) -> Self {
        self.cfg.batch_size = n.min(crate::wire::MAX_WANT_LIST);
        self
    }

    /// What a snapshot may do to the destination directory
    /// (see [`MaterializePolicy`]; the default refuses both destructive
    /// operations).
    #[must_use]
    pub fn materialize_policy(mut self, policy: MaterializePolicy) -> Self {
        self.cfg.policy = policy;
        self
    }

    /// Protect in-flight downloads from a concurrent
    /// [`gc::sweep`](crate::gc::sweep) by registering their chunks in `temps`.
    ///
    /// Pass the same registry the sweep is given. Progress in tier 2 *is*
    /// "which hashes are in the store", so a sweep running mid-download sees
    /// chunks that no tagged snapshot references yet and collects them — and
    /// the download then fails on a chunk it had already fetched. The
    /// mechanism for this has always existed in `gc`; this is what connects
    /// it. Without a registry, downloads are unprotected (the previous, and
    /// only, behaviour).
    #[must_use]
    pub fn temp_tags(mut self, temps: Arc<crate::gc::TempTags>) -> Self {
        self.cfg.temps = Some(temps);
        self
    }

    /// Zenoh priority for every query this client issues
    /// (default [`Priority::DataLow`]); see
    /// [`BlobClientBuilder::priority`](crate::BlobClientBuilder::priority) for
    /// why bulk transfers must yield.
    #[must_use]
    pub fn priority(mut self, priority: Priority) -> Self {
        self.cfg.priority = priority;
        self
    }

    /// Build the client.
    pub fn build(self) -> TreeClient {
        TreeClient {
            session: self.session,
            store_prefix: self.store_prefix,
            tree_prefix: self.tree_prefix,
            cfg: self.cfg,
        }
    }
}

impl TreeClient {
    /// Start building a client matching a [`TreeServer`]'s prefixes.
    pub fn builder(
        session: &zenoh::Session,
        store_prefix: QueryPrefix,
        tree_prefix: QueryPrefix,
    ) -> TreeClientBuilder {
        TreeClientBuilder {
            session: session.clone(),
            store_prefix,
            tree_prefix,
            cfg: TreeClientConfig::default(),
        }
    }

    /// Build a client with default configuration.
    pub fn new(
        session: &zenoh::Session,
        store_prefix: QueryPrefix,
        tree_prefix: QueryPrefix,
    ) -> Self {
        Self::builder(session, store_prefix, tree_prefix).build()
    }

    /// Fetch and fully validate the snapshot index `id` (schema, paths,
    /// size↔chunk consistency, root recomputation).
    ///
    /// Validation proves the index is *internally* consistent — it says
    /// nothing about *which* snapshot you got, so this is trust-on-first-use
    /// unless the id happens to be a root. Prefer
    /// [`fetch_index_by_root`](Self::fetch_index_by_root).
    pub async fn fetch_index(&self, id: &str) -> Result<TreeIndex> {
        self.fetch_index_matching(id, None).await
    }

    /// Fetch the chunks a descriptor points at and reassemble the encoded
    /// index from them.
    ///
    /// The descriptor is untrusted: it is validated before anything is
    /// fetched, each chunk is verified against its own address on arrival, and
    /// the reassembled bytes still have to decode and recompute to the root
    /// like any other index. The extra hop buys resumability, not trust.
    async fn assemble_sharded_index(&self, sample: &zenoh::sample::Sample) -> Result<Vec<u8>> {
        let desc: crate::wire::IndexDescriptor = decode(&sample.payload().to_bytes())?;
        desc.validate(self.cfg.max_index_bytes)?;

        // The pieces are ordinary content-addressed chunks, so they come back
        // through the ordinary batched path — no new machinery.
        let mut got: std::collections::HashMap<Hash, Vec<u8>> = Default::default();
        for group in desc.index_chunks.chunks(self.cfg.batch_size.max(1)) {
            let (replies, expected) = crate::store_client::batch_query(
                &self.session,
                self.store_prefix.as_str(),
                group,
                self.cfg.query_timeout,
                self.cfg.priority,
            )
            .await?;
            while let Ok(reply) = replies.recv_async().await {
                let Ok(s) = reply.result() else { continue };
                if let Some((h, bytes)) = crate::store_client::accept_batch_reply(
                    self.store_prefix.as_str(),
                    s,
                    &expected,
                ) {
                    got.entry(h).or_insert(bytes);
                }
            }
        }
        // Anything the batch left unanswered — a router storage never answers
        // one — is fetched singly.
        let mut out = Vec::with_capacity(desc.index_len as usize);
        for c in &desc.index_chunks {
            let bytes = match got.remove(&c.hash) {
                Some(b) => b,
                None => {
                    let key = store_key(self.store_prefix.as_str(), HashAlgo::Blake3, &c.hash);
                    crate::store_client::fetch_one_chunk(
                        &self.session,
                        &key,
                        &c.hash,
                        Some(c.len),
                        crate::compress::MAX_UNPACKED,
                        self.cfg.query_timeout,
                        self.cfg.priority,
                    )
                    .await?
                    .0
                }
            };
            out.extend_from_slice(&bytes);
        }
        Ok(out)
    }

    /// Ask every origin that answers how much of snapshot `id` it has.
    ///
    /// Completes RFC 07 §2.5's probe-then-fetch across all three key families.
    /// Tier 1 always had purpose-built tiny endpoints; tier 2 had none, and the
    /// reasoning for that — a `tree` or `store` key *carries the object*, so a
    /// wildcard GET on one is the bulk fan-out §3 forbids — is correct as far
    /// as it goes. What follows from it is "give tier 2 something small to
    /// ask for", which is this: the reply is four numbers regardless of the
    /// snapshot's size.
    ///
    /// Each result names the origin that answered, so the fetch that follows
    /// can go to a holder that actually has the chunks.
    pub async fn probe_snapshot(
        &self,
        id: &str,
    ) -> Result<Vec<(QueryPrefix, crate::wire::TreeProbe)>> {
        let id = BlobId::new(id)?;
        let id = id.as_str();
        let replies = self
            .session
            .get(crate::keys::tree_have_key(self.tree_prefix.as_str(), id))
            .consolidation(ConsolidationMode::None)
            .priority(self.cfg.priority)
            .timeout(self.cfg.query_timeout)
            .await
            .map_err(BlobError::zenoh)?;
        let mut out = Vec::new();
        while let Ok(reply) = replies.recv_async().await {
            let Ok(sample) = reply.result() else { continue };
            if !crate::wire::ENC_TREEPROBE.matches(sample.encoding()) {
                continue;
            }
            let Ok(probe) = decode::<crate::wire::TreeProbe>(&sample.payload().to_bytes()) else {
                continue;
            };
            if probe.validate().is_err() {
                continue;
            }
            // The reply key is `<origin>/<id>/have`.
            let Some(origin) = sample
                .key_expr()
                .as_str()
                .strip_suffix(crate::keys::STORE_HAVE)
                .and_then(|k| k.strip_suffix('/'))
                .and_then(|k| k.strip_suffix(id))
                .and_then(|k| k.strip_suffix('/'))
            else {
                continue;
            };
            let Ok(origin) = QueryPrefix::new(origin) else {
                continue;
            };
            if !out.iter().any(|(o, _): &(QueryPrefix, _)| *o == origin) {
                out.push((origin, probe));
            }
        }
        Ok(out)
    }

    /// Fetch and fully validate the snapshot whose identity **is** `root`.
    ///
    /// Content-addressed by construction, so it cannot be
    /// trust-on-first-use: the caller has already named the identity it
    /// demands, and an index that recomputes to anything else is rejected like
    /// any other unusable reply — one wrong-root responder cannot mask an
    /// honest replica.
    ///
    /// This is the shape RFC 07 §2.3 prescribes for tier 2 and the natural
    /// partner of [`TreeIndex::keyed_by_root`]. Note that it needs no
    /// [`ContentStore`]: an explorer that wants to *inspect* a snapshot —
    /// entry count, total size, chunk references — is not obliged to
    /// materialize one.
    pub async fn fetch_index_by_root(&self, root: &Hash) -> Result<TreeIndex> {
        self.fetch_index_matching(&root.to_string(), Some(*root))
            .await
    }

    /// Pin-aware fetch: when `expected_root` is set, replies with a different
    /// root are skipped like any other unacceptable reply, so one wrong-root
    /// responder cannot mask an honest replica.
    async fn fetch_index_matching(
        &self,
        id: &str,
        expected_root: Option<Hash>,
    ) -> Result<TreeIndex> {
        let id = BlobId::new(id)?;
        let id = id.as_str();
        let key = tree_key(self.tree_prefix.as_str(), id);
        let replies = self
            .session
            .get(&key)
            .consolidation(ConsolidationMode::None)
            .priority(self.cfg.priority)
            .timeout(self.cfg.query_timeout)
            .await
            .map_err(BlobError::zenoh)?;
        let mut rejected: Option<BlobError> = None;
        while let Ok(reply) = replies.recv_async().await {
            let Ok(sample) = reply.result() else { continue };
            let enc = sample.encoding();
            // A large index arrives as a descriptor pointing at chunks; a
            // small one arrives whole. Assemble the former into the latter and
            // then run the identical validation — the extra hop must not buy
            // an index any weaker guarantees.
            let payload: Vec<u8> = if crate::wire::ENC_INDEX_DESC.matches(enc) {
                match self.assemble_sharded_index(sample).await {
                    Ok(bytes) => bytes,
                    Err(e) => {
                        rejected.get_or_insert(e);
                        continue;
                    }
                }
            } else if ENC_INDEX.matches(enc) {
                sample.payload().to_bytes().into_owned()
            } else {
                continue;
            };
            // A bad reply from one responder is skipped, not fatal — a
            // hostile or stale replier must not deny what an honest replica
            // still answers. The first rejection is kept for diagnostics.
            let verdict = if payload.len() > self.cfg.max_index_bytes {
                Err(BlobError::InvalidManifest(format!(
                    "index payload {} exceeds the {} byte limit",
                    payload.len(),
                    self.cfg.max_index_bytes
                )))
            } else {
                decode::<TreeIndex>(&payload)
                    .and_then(|index| index.validate().map(|()| index))
                    .and_then(|index| {
                        if index.id != id {
                            return Err(BlobError::MalformedMessage(format!(
                                "index id {:?} does not match requested {id:?}",
                                index.id
                            )));
                        }
                        if let Some(expected) = expected_root
                            && index.root_hash != expected
                        {
                            return Err(BlobError::RootMismatch {
                                expected,
                                actual: index.root_hash,
                            });
                        }
                        Ok(index)
                    })
            };
            match verdict {
                Ok(index) => return Ok(index),
                Err(e) => {
                    rejected.get_or_insert(e);
                }
            }
        }
        Err(rejected.unwrap_or_else(|| BlobError::NotFound(id.to_string())))
    }

    /// Download snapshot `req.id` into `dest_root`: fetch only the chunks
    /// missing from `store` (concurrently, re-hashing each on receipt),
    /// reconstruct the tree safely, and restore modes + mtimes.
    ///
    /// Pin `req.expected_root` whenever known — without it the index's
    /// `root_hash` only proves internal consistency, not *which* tree you get.
    /// Because progress *is* "which hashes are on disk", a cancelled or failed
    /// transfer leaves `store` populated with whatever it fetched, so calling
    /// again resumes — across reconnect and process restart — for free.
    ///
    /// Materialization is **in place and not atomic** (the rsync/casync
    /// model): entries are written into `dest_root` directly so unchanged
    /// files need no work, but an error mid-materialization leaves a mix of
    /// old and new entries. Re-run the same call to converge — every chunk is
    /// already in `store`, so a re-run only redoes local writes. Callers who
    /// need an atomic cut-over should materialize into a fresh directory and
    /// swap it in themselves.
    pub fn download_tree<'a>(
        &'a self,
        req: &'a DownloadRequest,
        dest_root: &'a Path,
        store: &'a Arc<dyn ContentStore>,
    ) -> TreeDownload<'a> {
        TreeDownload {
            client: self,
            req,
            dest_root,
            store,
            sink: None,
            cancel: None,
        }
    }

    /// Fetch **one file** out of a snapshot, without materializing the tree.
    ///
    /// Resolves the index, looks `path` up in it, fetches only that file's
    /// chunks (reusing anything `store` already holds, and putting what it
    /// fetches back), and returns the assembled bytes.
    ///
    /// This is the capability a snapshot most obviously implies and did not
    /// have: a caller wanting one config file out of a 4 GiB tree had to
    /// download the whole tree to a scratch directory and read one path out of
    /// it. Everything it needs already existed — the index knows the chunk
    /// list, the store client knows how to fetch chunks — nothing joined them.
    ///
    /// Chunks are verified against their content address exactly as
    /// [`download_tree`](Self::download_tree) verifies them, and `size` from
    /// the index is enforced, so a peer cannot answer with more bytes than the
    /// snapshot said the file has.
    ///
    /// # Errors
    ///
    /// [`BlobError::NotFound`] if the snapshot has no such path or the entry
    /// is not a regular file.
    pub async fn fetch_file(
        &self,
        req: &DownloadRequest,
        path: &str,
        store: &Arc<dyn ContentStore>,
    ) -> Result<Vec<u8>> {
        let index = self
            .fetch_index_matching(&req.id, req.expected_root)
            .await?;
        let Some(chunks) = index.file_chunks(path) else {
            return Err(BlobError::NotFound(format!(
                "snapshot {:?} has no file at {path:?}",
                index.id
            )));
        };
        let size: u64 = chunks.iter().map(|c| u64::from(c.len)).sum();
        if size > self.cfg.max_tree_bytes {
            return Err(BlobError::InvalidManifest(format!(
                "file {path:?} totals {size} bytes, over the configured limit of {}",
                self.cfg.max_tree_bytes
            )));
        }

        // Fetch what is missing into the store, then assemble from it. Going
        // through the store rather than keeping fetched chunks in hand is what
        // makes a second `fetch_file` over an overlapping file free, and what
        // makes this share a cache with `download_tree`.
        let wanted: Vec<ChunkRef> = chunks.to_vec();
        self.fetch_missing(
            &wanted,
            store,
            crate::client::NO_PROGRESS,
            &CancelToken::new(),
            wanted.len() as u32,
        )
        .await?;

        let store = store.clone();
        tokio::task::spawn_blocking(move || -> Result<Vec<u8>> {
            let mut out = Vec::with_capacity(size as usize);
            for c in &wanted {
                let bytes = store
                    .get(&c.hash)?
                    .ok_or(BlobError::CorruptStore { hash: c.hash })?;
                // The store is content-addressed, so this can only fail if the
                // store itself is wrong — but the whole file is assembled from
                // it, so checking here is what keeps that from becoming the
                // caller's problem silently.
                if bytes.len() as u32 != c.len {
                    return Err(BlobError::ChunkLengthMismatch {
                        expected: c.len,
                        actual: bytes.len() as u32,
                    });
                }
                out.extend_from_slice(&bytes);
            }
            Ok(out)
        })
        .await?
    }

    async fn run_download_tree(
        &self,
        req: &DownloadRequest,
        dest_root: &Path,
        store: &Arc<dyn ContentStore>,
        sink: &dyn ProgressSink,
        cancel: &CancelToken,
    ) -> Result<TransferStats> {
        let started_at = tokio::time::Instant::now();
        let index = self
            .fetch_index_matching(&req.id, req.expected_root)
            .await?;

        // Bound the work a remote index can commit us to, *before* the first
        // chunk GET. `validate()` has already established the index is
        // self-consistent; that says nothing about whether it is affordable.
        let total_size = index.total_size();
        if total_size > self.cfg.max_tree_bytes {
            return Err(BlobError::InvalidManifest(format!(
                "snapshot totals {total_size} bytes, over the configured limit of {}",
                self.cfg.max_tree_bytes
            )));
        }
        let needed = index.needed_chunks();
        // Hold a temp tag over this snapshot's chunks for the whole transfer,
        // so a sweep racing us cannot collect what we have already fetched.
        let _protect = self
            .cfg
            .temps
            .as_ref()
            .map(|t| t.protect(needed.iter().copied()));
        if needed.len() as u64 > self.cfg.max_tree_chunks as u64 {
            return Err(BlobError::InvalidManifest(format!(
                "snapshot references {} chunks, over the configured limit of {}",
                needed.len(),
                self.cfg.max_tree_chunks
            )));
        }
        let total = needed.len() as u32;
        sink.emit(Progress::Started {
            total_len: total_size,
            chunk_count: total,
        });

        zdebug!(id = %index.id, chunks = total, "tree download start");
        let mut stats = self
            .fetch_missing(&index.needed_chunk_refs(), store, sink, cancel, total)
            .await?;

        // Materialize (all blocking fs work on the blocking pool).
        sink.emit(Progress::Verifying);
        let entries = index.entries.clone();
        let dest = dest_root.to_path_buf();
        let store2 = store.clone();
        let policy = self.cfg.policy;
        tokio::task::spawn_blocking(move || reconstruct_tree(&dest, &entries, &*store2, policy))
            .await??;

        sink.emit(Progress::Completed {
            path: dest_root.to_path_buf(),
        });
        stats.elapsed = started_at.elapsed();
        zdebug!(id = %index.id, fetched = stats.chunks_fetched, "tree download complete");
        Ok(stats)
    }

    /// Resolve every needed hash: count present ones immediately, fetch the
    /// rest with bounded concurrency. `received` counts hashes *resolved*
    /// (present or fetched), so a resume reports its true position at once.
    async fn fetch_missing(
        &self,
        needed: &[ChunkRef],
        store: &Arc<dyn ContentStore>,
        sink: &dyn ProgressSink,
        cancel: &CancelToken,
        total: u32,
    ) -> Result<TransferStats> {
        let mut stats = TransferStats::default();
        let mut received: u32 = 0;
        let mut bytes_received: u64 = 0;
        // One blocking pass decides present vs missing (DirStore's `has` is a
        // syscall per hash — tens of thousands of them do not belong on an
        // async worker thread one by one).
        let presence: Vec<bool> = {
            let store = store.clone();
            let needed = needed.to_vec();
            tokio::task::spawn_blocking(move || -> std::io::Result<Vec<bool>> {
                // `has_many` so a transactional store sees one visit for the
                // whole snapshot instead of one per chunk.
                store.has_many(&needed.iter().map(|c| c.hash).collect::<Vec<_>>())
            })
            .await??
        };
        // Split into what we already have and what we must fetch, reporting
        // the former immediately so a resume shows its true position at once.
        let mut missing: Vec<(usize, ChunkRef)> = Vec::new();
        for (i, (chunk, present)) in needed.iter().cloned().zip(presence).enumerate() {
            if present {
                received += 1;
                stats.chunks_resumed += 1;
                sink.emit(Progress::Chunk {
                    index: i as u32,
                    received,
                    total,
                    bytes_received,
                });
            } else {
                missing.push((i, chunk));
            }
        }

        // Batched rounds first.
        //
        // This is the scalability fix: a snapshot used to cost one Zenoh query
        // per chunk, so a 100k-chunk tree was 100k queries. A holder answers
        // only the addresses it has and says nothing about the rest, so a
        // partial holder shortens the round rather than failing it.
        //
        // What is left over then goes through the per-chunk path below, and
        // that fallback is not a nicety: a router-hosted Zenoh storage serves
        // by key and has nothing stored at `…/batch`, so it never answers a
        // batch at all. Without the fallback, publish-then-exit would stop
        // working entirely.
        if self.cfg.batch_size > 0 && !missing.is_empty() {
            let mut unanswered: Vec<(usize, ChunkRef)> = Vec::new();
            for group in missing.chunks(self.cfg.batch_size) {
                if cancel.is_cancelled() {
                    sink.emit(Progress::Cancelled { received, total });
                    return Err(BlobError::Cancelled { received, total });
                }
                let refs: Vec<ChunkRef> = group.iter().map(|(_, c)| c.clone()).collect();
                stats.queries += 1;
                let (replies, expected) = crate::store_client::batch_query(
                    &self.session,
                    self.store_prefix.as_str(),
                    &refs,
                    self.cfg.query_timeout,
                    self.cfg.priority,
                )
                .await?;

                // Drain the round *streaming*: a round of `batch_size` chunks
                // at the CDC maximum would be gigabytes if collected first,
                // and collecting would also make cancellation as coarse as a
                // whole round. Chunks land in the store in small flushes, so
                // memory stays bounded and a cancel keeps what it fetched.
                const FLUSH: usize = 32;
                let mut pending: Vec<(Hash, Vec<u8>)> = Vec::with_capacity(FLUSH);
                let mut arrived: std::collections::HashSet<Hash> = Default::default();
                let mut cancelled = false;
                loop {
                    if cancel.is_cancelled() {
                        cancelled = true;
                    }
                    let next = if cancelled {
                        None
                    } else {
                        replies.recv_async().await.ok()
                    };
                    if let Some(reply) = &next
                        && let Ok(sample) = reply.result()
                        && let Some((hash, bytes)) = crate::store_client::accept_batch_reply(
                            self.store_prefix.as_str(),
                            sample,
                            &expected,
                        )
                        && arrived.insert(hash)
                    {
                        pending.push((hash, bytes));
                    }
                    if pending.len() >= FLUSH || (next.is_none() && !pending.is_empty()) {
                        let batch = std::mem::take(&mut pending);
                        let put_store = store.clone();
                        let sizes: Vec<(Hash, u64)> =
                            batch.iter().map(|(h, b)| (*h, b.len() as u64)).collect();
                        tokio::task::spawn_blocking(move || -> std::io::Result<()> {
                            for (h, b) in &batch {
                                put_store.put(h, b)?;
                            }
                            Ok(())
                        })
                        .await??;
                        for (hash, len) in sizes {
                            received += 1;
                            bytes_received += len;
                            stats.chunks_fetched += 1;
                            stats.bytes_fetched += len;
                            let index = group
                                .iter()
                                .find(|(_, c)| c.hash == hash)
                                .map_or(0, |(i, _)| *i as u32);
                            sink.emit(Progress::Chunk {
                                index,
                                received,
                                total,
                                bytes_received,
                            });
                        }
                    }
                    if next.is_none() {
                        break;
                    }
                }
                for (i, chunk) in group {
                    if !arrived.contains(&chunk.hash) {
                        unanswered.push((*i, chunk.clone()));
                    }
                }
                if cancelled {
                    sink.emit(Progress::Cancelled { received, total });
                    return Err(BlobError::Cancelled { received, total });
                }
            }
            zdebug!(
                batched = missing.len() - unanswered.len(),
                falling_back = unanswered.len(),
                "tier-2 batch rounds complete"
            );
            missing = unanswered;
            // A cancel observed during the rounds must surface even if the
            // rounds happened to resolve everything — the chunks are in the
            // store, so calling again resumes from them.
            if cancel.is_cancelled() {
                sink.emit(Progress::Cancelled { received, total });
                return Err(BlobError::Cancelled { received, total });
            }
        }

        let mut iter = missing.into_iter();
        let mut join: tokio::task::JoinSet<Result<(usize, u64, u32)>> = tokio::task::JoinSet::new();

        loop {
            // Keep the pipeline full.
            while join.len() < self.cfg.fetch_concurrency {
                let Some((i, chunk)) = iter.next() else {
                    break;
                };
                stats.queries += 1;
                let session = self.session.clone();
                let hash = chunk.hash;
                let key = store_key(self.store_prefix.as_str(), HashAlgo::Blake3, &hash);
                let timeout = self.cfg.query_timeout;
                let priority = self.cfg.priority;
                let store = store.clone();
                join.spawn(async move {
                    let (bytes, rejected) = crate::store_client::fetch_one_chunk(
                        &session,
                        &key,
                        &hash,
                        Some(chunk.len),
                        crate::compress::MAX_UNPACKED,
                        timeout,
                        priority,
                    )
                    .await?;
                    let len = bytes.len() as u64;
                    let put_store = store.clone();
                    tokio::task::spawn_blocking(move || put_store.put(&hash, &bytes)).await??;
                    Ok((i, len, rejected))
                });
            }
            if join.is_empty() {
                break;
            }
            if cancel.is_cancelled() {
                join.abort_all();
                sink.emit(Progress::Cancelled { received, total });
                return Err(BlobError::Cancelled { received, total });
            }
            // Bounded wait so cancellation stays responsive.
            match tokio::time::timeout(Duration::from_millis(200), join.join_next()).await {
                Err(_) => continue, // timeout tick → re-check cancel
                Ok(None) => break,
                Ok(Some(res)) => {
                    let (i, len, rejected) = res??;
                    received += 1;
                    bytes_received += len;
                    stats.chunks_fetched += 1;
                    stats.bytes_fetched += len;
                    stats.rejected += rejected;
                    sink.emit(Progress::Chunk {
                        index: i as u32,
                        received,
                        total,
                        bytes_received,
                    });
                }
            }
        }
        Ok(stats)
    }
}

/// A configured snapshot download, awaited to run it. See
/// [`TreeClient::download_tree`].
#[must_use = "a download does nothing until it is awaited"]
pub struct TreeDownload<'a> {
    client: &'a TreeClient,
    req: &'a DownloadRequest,
    dest_root: &'a Path,
    store: &'a Arc<dyn ContentStore>,
    sink: Option<&'a dyn ProgressSink>,
    cancel: Option<&'a CancelToken>,
}

impl std::fmt::Debug for TreeDownload<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TreeDownload")
            .field("req", &self.req)
            .field("dest_root", &self.dest_root)
            .finish_non_exhaustive()
    }
}

impl<'a> TreeDownload<'a> {
    /// Send progress events to `sink` (default: discard them).
    pub fn progress(mut self, sink: &'a dyn ProgressSink) -> Self {
        self.sink = Some(sink);
        self
    }

    /// Stop when `cancel` is cancelled. Fetched chunks stay in the store, so
    /// a re-run resumes from them.
    pub fn cancel(mut self, cancel: &'a CancelToken) -> Self {
        self.cancel = Some(cancel);
        self
    }
}

impl<'a> std::future::IntoFuture for TreeDownload<'a> {
    type Output = Result<TransferStats>;
    type IntoFuture =
        std::pin::Pin<Box<dyn std::future::Future<Output = Self::Output> + Send + 'a>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let sink = self.sink.unwrap_or(crate::client::NO_PROGRESS);
            let fresh;
            let cancel = match self.cancel {
                Some(c) => c,
                None => {
                    fresh = CancelToken::new();
                    &fresh
                }
            };
            self.client
                .run_download_tree(self.req, self.dest_root, self.store, sink, cancel)
                .await
        })
    }
}

/// Materialize `entries` under `dest_root`, defensively:
/// dirs → files/hardlinks → symlinks (last), then dir mtimes. Every path is
/// sanitized and every write's parent is canonicalized back under the root.
fn reconstruct_tree(
    dest_root: &Path,
    entries: &[Entry],
    store: &dyn ContentStore,
    policy: MaterializePolicy,
) -> Result<()> {
    std::fs::create_dir_all(dest_root)?;
    let root = dest_root.canonicalize()?;

    // Pass 1: directories (DFS order → parents first). Creation is
    // component-wise and refuses to traverse pre-existing symlinks — the
    // prevention counterpart of the canonicalization checks below. Modes are
    // NOT applied yet — a read-only directory would break writing its own
    // children; like tar/casync, directory permissions land last.
    for e in entries {
        if let Entry::Dir { path, .. } = e {
            create_dir_confined(&root, &sanitize_rel_path(path)?)?;
        }
    }

    // Pass 2: files, then hard links to them (entry order preserves targets).
    for e in entries {
        match e {
            Entry::File {
                path,
                mode,
                mtime,
                size,
                chunks,
            } => {
                let rel = sanitize_rel_path(path)?;
                if let Some(parent) = rel.parent() {
                    create_dir_confined(&root, parent)?;
                }
                let p = root.join(&rel);
                assert_parent_within(&root, &p)?;
                remove_existing(&p, policy)?;
                let mut f = std::fs::File::create(&p)?;
                let mut written: u64 = 0;
                for c in chunks {
                    let bytes = store
                        .get(&c.hash)?
                        .ok_or_else(|| BlobError::NotFound(c.hash.to_string()))?;
                    if bytes.len() as u32 != c.len {
                        return Err(BlobError::ChunkLengthMismatch {
                            expected: c.len,
                            actual: bytes.len() as u32,
                        });
                    }
                    // Verify on the way *out* of the store, not only on the way
                    // in. Tier 1 guarantees every byte it writes was checked
                    // against the root; tier 2 checked chunks when it fetched
                    // them and then trusted the store, so local rot — or a
                    // `ContentStore` implementation that breaks its contract,
                    // and there are third-party ones — could still materialize
                    // wrong bytes under a snapshot the caller believes is
                    // verified. `root_hash` does not cover this: it covers the
                    // entry list, not chunk contents. One BLAKE3 pass over the
                    // tree is the price of the same guarantee tier 1 gives.
                    if Hash::of(&bytes) != c.hash {
                        return Err(BlobError::CorruptStore { hash: c.hash });
                    }
                    f.write_all(&bytes)?;
                    written += bytes.len() as u64;
                }
                if written != *size {
                    return Err(BlobError::MalformedMessage(format!(
                        "file {path:?}: wrote {written} of declared {size} bytes"
                    )));
                }
                set_mode(&p, *mode, policy);
                set_mtime(&f, *mtime);
            }
            Entry::Hardlink { path, target } => {
                let rel = sanitize_rel_path(path)?;
                if let Some(parent) = rel.parent() {
                    create_dir_confined(&root, parent)?;
                }
                let p = root.join(&rel);
                let t = root.join(sanitize_rel_path(target)?);
                assert_parent_within(&root, &p)?;
                // The *target* must also really live under the root:
                // `link(2)` resolves symlinks in its source path, so a
                // pre-existing outward-pointing symlink inside the dest could
                // otherwise be laundered into a hard link to outside data.
                let canon_t = t.canonicalize().map_err(|e| {
                    BlobError::UnsafePath(format!(
                        "hardlink target {target:?} is not materialized: {e}"
                    ))
                })?;
                if !canon_t.starts_with(&root) || !canon_t.is_file() {
                    return Err(BlobError::UnsafePath(format!(
                        "hardlink target {target:?} resolves outside the destination root"
                    )));
                }
                remove_existing(&p, policy)?;
                std::fs::hard_link(&canon_t, &p)?;
            }
            _ => {}
        }
    }

    // Pass 3: symlinks last — nothing can be written *through* them.
    for e in entries {
        if let Entry::Symlink { path, target } = e {
            let rel = sanitize_rel_path(path)?;
            sanitize_symlink_target(&rel, target)?;
            if let Some(parent) = rel.parent() {
                create_dir_confined(&root, parent)?;
            }
            let p = root.join(&rel);
            assert_parent_within(&root, &p)?;
            remove_existing(&p, policy)?;
            symlink(target, &p)?;
        }
    }

    // Pass 4: directory mtimes and modes, children-first (deepest last in
    // DFS order → reverse), so restoring a read-only or dated directory never
    // interferes with materializing its contents.
    for e in entries.iter().rev() {
        if let Entry::Dir { path, mode, mtime } = e
            && let Ok(rel) = sanitize_rel_path(path)
        {
            let p = root.join(rel);
            if *mtime > 0
                && let Ok(f) = std::fs::File::open(&p)
            {
                set_mtime(&f, *mtime);
            }
            set_mode(&p, *mode, policy);
        }
    }
    Ok(())
}

/// Remove whatever currently sits at `p` (file, symlink, or directory) so a
/// fresh entry can take its place.
///
/// Removing a *file or symlink* is the ordinary in-place update and is
/// best-effort. Removing a **directory** is not: it takes everything
/// underneath with it, on a path chosen by a remote index, so it happens only
/// when [`MaterializePolicy::replace_directories`] allows it and is otherwise
/// a loud error. See that method for why the default is off.
fn remove_existing(p: &Path, policy: MaterializePolicy) -> Result<()> {
    let Ok(meta) = std::fs::symlink_metadata(p) else {
        return Ok(());
    };
    if meta.is_dir() {
        if !policy.replace_directories {
            return Err(BlobError::UnsafePath(format!(
                "refusing to replace the existing directory {p:?} (and everything under it) \
                 with a non-directory entry; enable MaterializePolicy::replace_directories \
                 if that is intended"
            )));
        }
        let _ = std::fs::remove_dir_all(p);
    } else {
        let _ = std::fs::remove_file(p);
    }
    Ok(())
}

/// Mode bits an index may set without an explicit opt-in: permissions only.
#[cfg(unix)]
const MODE_MASK: u32 = 0o0777;

/// Apply an index-supplied mode, masking setuid/setgid/sticky unless the
/// caller opted in (see [`MaterializePolicy::restore_setid`]).
#[cfg(unix)]
fn set_mode(path: &Path, mode: u32, policy: MaterializePolicy) {
    use std::os::unix::fs::PermissionsExt;
    let mode = if policy.restore_setid {
        mode & 0o7777
    } else {
        mode & MODE_MASK
    };
    if mode != 0 {
        let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
    }
}
#[cfg(not(unix))]
fn set_mode(_path: &Path, _mode: u32, _policy: MaterializePolicy) {}

/// Restore a recorded mtime (best-effort; 0 means "unknown").
fn set_mtime(f: &std::fs::File, mtime: i64) {
    if mtime > 0 {
        let t = std::time::UNIX_EPOCH + Duration::from_secs(mtime as u64);
        let _ = f.set_modified(t);
    }
}

#[cfg(unix)]
fn symlink(target: &str, path: &Path) -> std::io::Result<()> {
    std::os::unix::fs::symlink(target, path)
}
#[cfg(not(unix))]
fn symlink(_target: &str, _path: &Path) -> std::io::Result<()> {
    // Symlink materialization is unsupported off unix: error loudly instead of
    // silently omitting entries from a "successful" download (v1's M6).
    Err(std::io::Error::other(
        "symlink entries are not supported on this platform",
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::MemoryStore;

    #[test]
    fn build_dedups_identical_chunks() {
        let dir = tempfile::tempdir().unwrap();
        // Two files with identical content → one shared chunk.
        std::fs::write(dir.path().join("a.txt"), b"same").unwrap();
        std::fs::write(dir.path().join("b.txt"), b"same").unwrap();
        let store = MemoryStore::new();
        let index = build_tree(dir.path(), "snap", &CdcParams::default(), &store).unwrap();
        assert_eq!(store.len(), 1);
        assert_eq!(index.needed_chunks().len(), 1);
        index.validate().unwrap();
        assert_eq!(index.file_count(), 2);
    }

    #[test]
    fn root_hash_ignores_mtime() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("f.txt"), b"content").unwrap();
        let store = MemoryStore::new();
        let a = build_tree(dir.path(), "snap", &CdcParams::default(), &store).unwrap();
        // Touch the file (bump mtime, same bytes) → identical root.
        let file = std::fs::File::options()
            .append(true)
            .open(dir.path().join("f.txt"))
            .unwrap();
        file.set_modified(std::time::SystemTime::now() + Duration::from_secs(1000))
            .unwrap();
        let b = build_tree(dir.path(), "snap", &CdcParams::default(), &store).unwrap();
        assert_eq!(a.root_hash, b.root_hash, "mtime must not change identity");
        // But the bytes do change it.
        std::fs::write(dir.path().join("f.txt"), b"different").unwrap();
        let c = build_tree(dir.path(), "snap", &CdcParams::default(), &store).unwrap();
        assert_ne!(a.root_hash, c.root_hash);
    }

    #[test]
    fn traversal_paths_rejected_by_validate() {
        let evil_paths = ["../evil", "/etc/passwd", "a/../../b"];
        for evil in evil_paths {
            let entries = vec![Entry::File {
                path: evil.into(),
                mode: 0,
                mtime: 0,
                size: 0,
                chunks: vec![],
            }];
            let root_hash = root_digest(&entries).unwrap();
            let index = TreeIndex {
                version: WIRE_VERSION,
                id: BlobId::new("x").unwrap(),
                algo: HashAlgo::Blake3,
                cdc: CdcParams::default(),
                entries,
                root_hash,
            };
            assert!(index.validate().is_err(), "must reject path {evil:?}");
        }
    }

    #[test]
    fn oversized_chunk_len_rejected() {
        // A declared length is an allocation the receiver performs: lens over
        // the CDC maximum (or zero) must fail validation even when the size
        // arithmetic is consistent.
        for bad_len in [0u32, CdcParams::default().max + 1, u32::MAX] {
            let entries = vec![Entry::File {
                path: "f".into(),
                mode: 0,
                mtime: 0,
                size: bad_len as u64,
                chunks: vec![ChunkRef {
                    hash: Hash::of(b"x"),
                    len: bad_len,
                }],
            }];
            let root_hash = root_digest(&entries).unwrap();
            let index = TreeIndex {
                version: WIRE_VERSION,
                id: BlobId::new("x").unwrap(),
                algo: HashAlgo::Blake3,
                cdc: CdcParams::default(),
                entries,
                root_hash,
            };
            assert!(index.validate().is_err(), "len {bad_len} must be rejected");
        }
    }

    #[test]
    fn size_chunk_mismatch_rejected() {
        let entries = vec![Entry::File {
            path: "f".into(),
            mode: 0,
            mtime: 0,
            size: 100, // but no chunks
            chunks: vec![],
        }];
        let root_hash = root_digest(&entries).unwrap();
        let index = TreeIndex {
            version: WIRE_VERSION,
            id: BlobId::new("x").unwrap(),
            algo: HashAlgo::Blake3,
            cdc: CdcParams::default(),
            entries,
            root_hash,
        };
        assert!(index.validate().is_err());
    }

    #[cfg(unix)]
    #[test]
    fn hardlinks_detected() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("orig.bin"), b"shared bytes").unwrap();
        std::fs::hard_link(dir.path().join("orig.bin"), dir.path().join("link.bin")).unwrap();
        let store = MemoryStore::new();
        let index = build_tree(dir.path(), "snap", &CdcParams::default(), &store).unwrap();
        let hardlinks: Vec<_> = index
            .entries
            .iter()
            .filter(|e| matches!(e, Entry::Hardlink { .. }))
            .collect();
        assert_eq!(hardlinks.len(), 1);
        // One File + one Hardlink, single stored chunk.
        assert_eq!(index.file_count(), 1);
        assert_eq!(store.len(), 1);
    }

    #[cfg(unix)]
    #[test]
    fn fifo_is_an_error_not_a_silent_drop() {
        use std::os::unix::ffi::OsStrExt;
        let dir = tempfile::tempdir().unwrap();
        // mkfifo via libc-less route: use the `mkfifo` binary if present, else skip.
        let fifo = dir.path().join("pipe");
        let status = std::process::Command::new("mkfifo")
            .arg(fifo.as_os_str())
            .status();
        if !status.map(|s| s.success()).unwrap_or(false) {
            return; // environment without mkfifo — skip silently.
        }
        let store = MemoryStore::new();
        let err = build_tree(dir.path(), "snap", &CdcParams::default(), &store)
            .expect_err("fifo must error");
        assert!(err.to_string().contains("unsupported file type"), "{err}");
        let _ = fifo.as_os_str().as_bytes();
    }
}