slatedb 0.16.0

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

use crate::db::builder::CloneSourceSpec;
use crate::error::SlateDBError;
use crate::error::SlateDBError::CheckpointMissing;
use crate::manifest::store::{ManifestStore, StoredManifest};
use crate::manifest::{Manifest, ProjectionConfig, VersionedManifest};
use crate::utils::IdGenerator;
use crate::wal::WalAdmin;
use bytes::Bytes;
use fail_parallel::{fail_point, FailPointRegistry};
use object_store::path::Path;
use object_store::ObjectStore;
use slatedb_common::clock::SystemClock;
use slatedb_common::DbRand;
use std::ops::RangeBounds;
use std::sync::Arc;
use std::time::Duration;
use uuid::Uuid;

/// User-supplied predicate deciding whether a segment is included in the
/// clone. Receives the segment's prefix (the unsegmented tree participates as
/// the empty prefix). Returning `false` drops the segment entirely.
pub(crate) type SegmentFilterFn = Arc<dyn Fn(&[u8]) -> bool + Send + Sync>;

/// User-supplied projector returning the effective range for a segment. The
/// returned range's bounded ends must fall within `[prefix, prefix++)`;
/// `Unbounded` ends resolve to the segment edges. Empty ranges surface to the
/// caller as `SlateDBError::InvalidProjection`.
pub(crate) type SegmentProjectionFn =
    Arc<dyn Fn(&[u8]) -> Result<BytesRange, SlateDBError> + Send + Sync>;

struct CopyWalParams {
    from_path: Path,
    from_manifest: VersionedManifest,
    to_path: Path,
}

struct CreateCloneManifestResult {
    clone_manifest: StoredManifest,
    copy_wal_params: Option<CopyWalParams>,
}

pub(crate) async fn create_clone<P: Into<Path>, R: RangeBounds<Bytes> + Clone>(
    clone_sources: Vec<CloneSourceSpec<R>>,
    clone_path: P,
    object_store: Arc<dyn ObjectStore>,
    wal_admin: Arc<dyn WalAdmin>,
    fp_registry: Arc<FailPointRegistry>,
    system_clock: Arc<dyn SystemClock>,
    rand: Arc<DbRand>,
    projection_range: Option<R>,
    segment_filter: Option<SegmentFilterFn>,
    segment_projection: Option<SegmentProjectionFn>,
) -> Result<(), SlateDBError> {
    let clone_path = clone_path.into();

    validate_clone_source_specs(&clone_sources, &clone_path)?;

    let CreateCloneManifestResult {
        mut clone_manifest,
        copy_wal_params,
    } = create_clone_manifest(
        clone_path.clone(),
        clone_sources,
        object_store,
        system_clock.clone(),
        rand,
        fp_registry.clone(),
        projection_range,
        segment_filter,
        segment_projection,
        wal_admin.as_ref(),
    )
    .await?;

    if !clone_manifest.db_state().initialized {
        let (replay_after_wal_id, wal_id_last_seen) = match copy_wal_params {
            Some(params) => copy_wal(wal_admin.as_ref(), params).await?,
            None => (0, 0),
        };
        let next_wal_sst_id = wal_id_last_seen
            .checked_add(1)
            .ok_or(SlateDBError::InvalidDBState)?;

        let mut dirty = clone_manifest.prepare_dirty()?;
        dirty.value.core.replay_after_wal_id = replay_after_wal_id;
        dirty.value.core.next_wal_sst_id = next_wal_sst_id;
        dirty.value.core.initialized = true;
        clone_manifest.update(dirty).await?;
    }

    Ok(())
}

async fn create_clone_manifest<R: RangeBounds<Bytes> + Clone>(
    clone_path: Path,
    source_specs: Vec<CloneSourceSpec<R>>,
    object_store: Arc<dyn ObjectStore>,
    system_clock: Arc<dyn SystemClock>,
    rand: Arc<DbRand>,
    #[allow(unused)] fp_registry: Arc<FailPointRegistry>,
    projection_range: Option<R>,
    segment_filter: Option<SegmentFilterFn>,
    segment_projection: Option<SegmentProjectionFn>,
    wal_admin: &dyn WalAdmin,
) -> Result<CreateCloneManifestResult, SlateDBError> {
    let clone_manifest_store = Arc::new(ManifestStore::new(&clone_path, object_store.clone()));

    let (clone_manifest, copy_wal_params) =
        match StoredManifest::try_load(clone_manifest_store.clone(), system_clock.clone()).await? {
            Some(initialized_clone_manifest)
                if initialized_clone_manifest.db_state().initialized =>
            {
                for source_spec in &source_specs {
                    validate_attached_to_external_db(
                        source_spec.path.to_string(),
                        source_spec.checkpoint,
                        &initialized_clone_manifest,
                    )?;
                    validate_external_dbs_contain_final_checkpoint(
                        Arc::new(ManifestStore::new(&source_spec.path, object_store.clone())),
                        source_spec.path.to_string(),
                        &initialized_clone_manifest,
                        object_store.clone(),
                    )
                    .await?;
                }
                return Ok(CreateCloneManifestResult {
                    clone_manifest: initialized_clone_manifest,
                    copy_wal_params: None,
                });
            }
            Some(uninitialized_clone_manifest) => {
                for source_spec in &source_specs {
                    validate_attached_to_external_db(
                        source_spec.path.to_string(),
                        source_spec.checkpoint,
                        &uninitialized_clone_manifest,
                    )?;
                }
                let copy_wal_params = match &source_specs[..] {
                    [source_spec] => {
                        let source = rebuild_source(
                            source_spec,
                            &uninitialized_clone_manifest,
                            &object_store,
                            &system_clock,
                            &rand,
                            &projection_range,
                            segment_filter.as_ref(),
                            segment_projection.as_ref(),
                        )
                        .await?;
                        Some(copy_wal_params_for_source(&source, &clone_path))
                    }
                    _ => None,
                };
                (uninitialized_clone_manifest, copy_wal_params)
            }
            None => {
                let sources = build_sources(
                    &source_specs,
                    &object_store,
                    &system_clock,
                    &rand,
                    &projection_range,
                    segment_filter.as_ref(),
                    segment_projection.as_ref(),
                )
                .await?;
                let copy_wal_params = match &sources[..] {
                    [source] => Some(copy_wal_params_for_source(source, &clone_path)),
                    _ => None,
                };

                let projection_requested = projection_range.is_some()
                    || segment_filter.is_some()
                    || segment_projection.is_some()
                    || source_specs.iter().any(|s| s.projection_range.is_some());

                let mut manifest: Manifest = match &sources[..] {
                    [single_source] => {
                        // WAL SSTs are copied to the clone verbatim and replayed in full
                        // when the clone is opened, so entries outside the projected
                        // range would leak into the clone. So we reject projections if
                        // there are non-fence WALs to copy.
                        if projection_requested {
                            validate_no_data_wal(&sources, wal_admin).await?;
                        }
                        Manifest::cloned(
                            &single_source.manifest,
                            single_source.path.to_string(),
                            single_source.checkpoint.id,
                            rand.clone(),
                        )
                    }
                    [..] => {
                        validate_no_data_wal(&sources, wal_admin).await?;
                        Manifest::cloned_from_union(sources, rand.clone())?
                    }
                };
                manifest.core.initialized = false;

                (
                    StoredManifest::store_uninitialized_clone(
                        clone_manifest_store,
                        manifest,
                        system_clock.clone(),
                    )
                    .await?,
                    copy_wal_params,
                )
            }
        };

    fail_point!(fp_registry, "create-clone-manifest-io-error", |_| Err(
        SlateDBError::from(std::io::Error::other("oops"))
    ));

    // Ensure all external databases contain the final checkpoint.
    for external_db in &clone_manifest.manifest().external_dbs {
        let Some(final_checkpoint_id) = external_db.final_checkpoint_id else {
            // If the final checkpoint id is not set, we can skip this check
            continue;
        };
        let external_db_manifest_store = source_specs
            .iter()
            .find(|p| p.path.to_string() == external_db.path)
            .map(|p| Arc::new(ManifestStore::new(&p.path, object_store.clone())))
            .unwrap_or_else(|| {
                Arc::new(ManifestStore::new(
                    &external_db.path.clone().into(),
                    object_store.clone(),
                ))
            });

        let mut external_db_manifest =
            load_initialized_manifest(external_db_manifest_store, system_clock.clone()).await?;

        if external_db_manifest
            .db_state()
            .find_checkpoint(final_checkpoint_id)
            .is_none()
        {
            external_db_manifest
                .write_checkpoint(
                    final_checkpoint_id,
                    &CheckpointOptions {
                        lifetime: None,
                        source: Some(external_db.source_checkpoint_id),
                        name: None,
                    },
                )
                .await?;
        }
    }

    Ok(CreateCloneManifestResult {
        clone_manifest,
        copy_wal_params,
    })
}

fn to_byte_range<T: RangeBounds<Bytes> + Clone>(bounds: &T) -> BytesRange {
    BytesRange::from(bounds.clone())
}

#[derive(Clone)]
pub(crate) struct CloneSource {
    pub path: Path,
    pub manifest: Manifest,
    pub checkpoint: Checkpoint,
}

impl CloneSource {
    fn versioned_manifest(&self) -> VersionedManifest {
        VersionedManifest::from_manifest(self.checkpoint.manifest_id, self.manifest.clone())
    }
}

/// Builds a list of clone sources from the provided specifications. For each source spec, a
/// manifest at the specified checkpoint is loaded (if the checkpoint is not specified then it is
/// created). Additionally, if any of `projection_range`, `segment_filter`, or
/// `segment_projection` are specified then they are applied to the returned
/// manifests using `Manifest::projected`.
async fn build_sources<R: RangeBounds<Bytes> + Clone>(
    source_specs: &Vec<CloneSourceSpec<R>>,
    object_store: &Arc<dyn ObjectStore>,
    system_clock: &Arc<dyn SystemClock>,
    rand: &Arc<DbRand>,
    projection_range: &Option<R>,
    segment_filter: Option<&SegmentFilterFn>,
    segment_projection: Option<&SegmentProjectionFn>,
) -> Result<Vec<CloneSource>, SlateDBError> {
    let mut result: Vec<CloneSource> = vec![];
    for source in source_specs {
        result.push(
            build_source(
                source,
                source.checkpoint,
                object_store,
                system_clock,
                rand,
                projection_range,
                segment_filter,
                segment_projection,
            )
            .await?,
        );
    }
    Ok(result)
}

async fn build_source<R: RangeBounds<Bytes> + Clone>(
    source: &CloneSourceSpec<R>,
    checkpoint_id: Option<Uuid>,
    object_store: &Arc<dyn ObjectStore>,
    system_clock: &Arc<dyn SystemClock>,
    rand: &Arc<DbRand>,
    projection_range: &Option<R>,
    segment_filter: Option<&SegmentFilterFn>,
    segment_projection: Option<&SegmentProjectionFn>,
) -> Result<CloneSource, SlateDBError> {
    let manifest_store = Arc::new(ManifestStore::new(&source.path, object_store.clone()));
    let mut latest_manifest =
        load_initialized_manifest(manifest_store.clone(), system_clock.clone()).await?;
    let checkpoint =
        get_or_create_parent_checkpoint(&mut latest_manifest, checkpoint_id, rand.clone()).await?;
    let mut manifest_at_checkpoint = manifest_store.read_manifest(checkpoint.manifest_id).await?;

    let range: Option<BytesRange> = match (source.projection_range.clone(), projection_range) {
        (Some(l), Some(r)) => to_byte_range(&l).intersect(&to_byte_range(r)),
        (Some(l), None) => Some(to_byte_range(&l)),
        (None, Some(r)) => Some(to_byte_range(r)),
        (None, None) => None,
    };

    let config = ProjectionConfig {
        global_range: range,
        segment_filter: segment_filter.cloned(),
        segment_projection: segment_projection.cloned(),
    };
    manifest_at_checkpoint = if config.is_noop() {
        manifest_at_checkpoint
    } else {
        Manifest::projected(&manifest_at_checkpoint, &config)?
    };

    Ok(CloneSource {
        path: source.path.clone(),
        manifest: manifest_at_checkpoint,
        checkpoint,
    })
}

fn copy_wal_params_for_source(source: &CloneSource, to_path: &Path) -> CopyWalParams {
    CopyWalParams {
        from_path: source.path.clone(),
        from_manifest: source.versioned_manifest(),
        to_path: to_path.clone(),
    }
}

async fn rebuild_source<R: RangeBounds<Bytes> + Clone>(
    source_spec: &CloneSourceSpec<R>,
    clone_manifest: &StoredManifest,
    object_store: &Arc<dyn ObjectStore>,
    system_clock: &Arc<dyn SystemClock>,
    rand: &Arc<DbRand>,
    projection_range: &Option<R>,
    segment_filter: Option<&SegmentFilterFn>,
    segment_projection: Option<&SegmentProjectionFn>,
) -> Result<CloneSource, SlateDBError> {
    // `Manifest::cloned` appends the direct parent after inherited external DBs. Search in reverse
    // so a parent that also appears in its own ancestry still resolves to the direct source.
    let source_path = source_spec.path.to_string();
    let external_db = clone_manifest
        .manifest()
        .external_dbs
        .iter()
        .rev()
        .find(|external_db| external_db.path == source_path)
        .ok_or(SlateDBError::CloneExternalDbMissing)?;
    let manifest_store = Arc::new(ManifestStore::new(&source_spec.path, object_store.clone()));
    let latest_manifest = load_initialized_manifest(manifest_store, system_clock.clone()).await?;
    let checkpoint_id = external_db
        .final_checkpoint_id
        .filter(|checkpoint_id| {
            latest_manifest
                .db_state()
                .find_checkpoint(*checkpoint_id)
                .is_some()
        })
        .unwrap_or(external_db.source_checkpoint_id);
    build_source(
        source_spec,
        Some(checkpoint_id),
        object_store,
        system_clock,
        rand,
        projection_range,
        segment_filter,
        segment_projection,
    )
    .await
}

// Get a checkpoint and the corresponding manifest that will be used as the source
// for the clone's initial state.
//
// If `parent_checkpoint_id` is `None`, then create an ephemeral checkpoint from
// the latest state.  Making it ephemeral ensures that it will
// get cleaned up if the clone operation fails.
async fn get_or_create_parent_checkpoint(
    manifest: &mut StoredManifest,
    maybe_checkpoint_id: Option<Uuid>,
    rand: Arc<DbRand>,
) -> Result<Checkpoint, SlateDBError> {
    let checkpoint = match maybe_checkpoint_id {
        Some(checkpoint_id) => match manifest.db_state().find_checkpoint(checkpoint_id) {
            Some(found_checkpoint) => found_checkpoint.clone(),
            None => return Err(CheckpointMissing(checkpoint_id)),
        },
        None => {
            let checkpoint_id = rand.rng().gen_uuid();
            manifest
                .write_checkpoint(
                    checkpoint_id,
                    &CheckpointOptions {
                        lifetime: Some(Duration::from_secs(300)),
                        source: None,
                        name: None,
                    },
                )
                .await?
        }
    };
    Ok(checkpoint)
}

fn validate_clone_source_specs<R: RangeBounds<Bytes> + Clone>(
    specs: &[CloneSourceSpec<R>],
    clone_path: &Path,
) -> Result<(), SlateDBError> {
    if specs.is_empty() {
        return Err(SlateDBError::InvalidUnionSetEmpty());
    }

    let mut seen_paths = std::collections::HashSet::new();
    for source in specs {
        if clone_path == &source.path {
            return Err(SlateDBError::IdenticalClonePaths(clone_path.clone()));
        }
        if !seen_paths.insert(source.path.to_string()) {
            return Err(SlateDBError::DuplicatedCloneSourcePath(source.path.clone()));
        }
    }
    Ok(())
}

async fn validate_no_data_wal(
    sources: &[CloneSource],
    wal_admin: &dyn WalAdmin,
) -> Result<(), SlateDBError> {
    let mut parents_with_wal = vec![];
    for source in sources {
        let replay_after_wal_id = source.manifest.core.replay_after_wal_id;
        let wal_id_last_seen = source
            .manifest
            .core
            .next_wal_sst_id
            .checked_sub(1)
            .ok_or(SlateDBError::InvalidDBState)?;
        if !wal_admin
            .is_empty(&source.path, replay_after_wal_id, wal_id_last_seen)
            .await?
        {
            parents_with_wal.push(source.path.clone());
        }
    }
    if !parents_with_wal.is_empty() {
        return Err(SlateDBError::InvalidCloneSourceWithWal {
            paths: parents_with_wal,
        });
    }
    Ok(())
}

// Validate that the manifest is attached to an external database at specific checkpoint.
fn validate_attached_to_external_db(
    path: String,
    checkpoint_id: Option<Uuid>,
    clone_manifest: &StoredManifest,
) -> Result<(), SlateDBError> {
    let external_dbs = &clone_manifest.manifest().external_dbs;
    if external_dbs.is_empty() {
        return Err(SlateDBError::CloneExternalDbMissing);
    }
    if !external_dbs.iter().any(|external_db| {
        path == external_db.path
            && checkpoint_id
                .map(|id| id == external_db.source_checkpoint_id)
                .unwrap_or(true)
    }) {
        return Err(SlateDBError::CloneIncorrectExternalDbCheckpoint {
            path,
            checkpoint_id,
        });
    };
    Ok(())
}

async fn validate_external_dbs_contain_final_checkpoint(
    parent_manifest_store: Arc<ManifestStore>,
    parent_path: String,
    clone_manifest: &StoredManifest,
    object_store: Arc<dyn ObjectStore>,
) -> Result<(), SlateDBError> {
    // Validate external dbs all contain the final checkpoint
    for external_db in &clone_manifest.manifest().external_dbs {
        let Some(final_checkpoint_id) = external_db.final_checkpoint_id else {
            // If the final checkpoint id is not set, we can skip this check
            continue;
        };
        let external_manifest_store = if external_db.path == parent_path {
            parent_manifest_store.clone()
        } else {
            Arc::new(ManifestStore::new(
                &external_db.path.clone().into(),
                object_store.clone(),
            ))
        };
        let external_manifest = external_manifest_store
            .read_latest_manifest()
            .await?
            .manifest;
        if external_manifest
            .core
            .find_checkpoint(final_checkpoint_id)
            .is_none()
        {
            return Err(SlateDBError::CloneIncorrectFinalCheckpoint {
                path: external_db.path.clone(),
                checkpoint_id: final_checkpoint_id,
            });
        }
    }

    Ok(())
}

async fn load_initialized_manifest(
    manifest_store: Arc<ManifestStore>,
    system_clock: Arc<dyn SystemClock>,
) -> Result<StoredManifest, SlateDBError> {
    let Some(manifest) =
        StoredManifest::try_load(manifest_store.clone(), system_clock.clone()).await?
    else {
        return Err(SlateDBError::LatestTransactionalObjectVersionMissing);
    };

    if !manifest.db_state().initialized {
        return Err(SlateDBError::InvalidDBState);
    }

    Ok(manifest)
}

async fn copy_wal(
    wal_admin: &dyn WalAdmin,
    params: CopyWalParams,
) -> Result<(u64, u64), SlateDBError> {
    let CopyWalParams {
        from_path,
        from_manifest,
        to_path,
    } = params;
    wal_admin
        .clone_wal(&from_path, from_manifest, &to_path)
        .await
        .map_err(Into::into)
}

#[cfg(test)]
mod tests {
    use super::{SegmentFilterFn, SegmentProjectionFn};
    use crate::config::{
        CheckpointOptions, CheckpointScope, FlushOptions, FlushType, PutOptions, Settings,
        WriteOptions,
    };
    use crate::db::builder::CloneSourceSpec;
    use crate::db::Db;
    use crate::db_reader::DbReader;
    use crate::db_state::SsTableId;
    use crate::error::SlateDBError;
    use crate::iter::IterationOrder;
    use crate::manifest::store::{ManifestStore, StoredManifest};
    use crate::manifest::Manifest;
    use crate::manifest::{ManifestCore, VersionedManifest};
    use crate::object_stores::ObjectStores;
    use crate::paths::PathResolver;
    use crate::proptest_util::{rng, sample};
    use crate::test_utils;
    use crate::utils::IdGenerator;
    use crate::wal::slatedb::admin::SlateDbWalAdmin;
    use crate::wal::{WalAdmin, WalError, WalFileRange, WalGc};
    use async_trait::async_trait;
    use bytes::Bytes;
    use fail_parallel::FailPointRegistry;
    use object_store::memory::InMemory;
    use object_store::path::Path;
    use object_store::Error as ObjectStoreError;
    use object_store::ObjectStore;
    use slatedb_common::clock::DefaultSystemClock;
    use slatedb_common::DbRand;
    use slatedb_common::SystemClock;
    use slatedb_txn_obj::TransactionalObject;
    use std::collections::BTreeMap;
    use std::ops::Bound;
    use std::ops::RangeBounds;
    use std::sync::Arc;
    use std::time::Duration;
    use uuid::Uuid;

    struct RemappingWalAdmin {
        replay_range: (u64, u64),
        expected_manifest_id: Option<u64>,
    }

    struct NoopWalGc;

    #[async_trait]
    impl WalGc for NoopWalGc {
        async fn collect(
            &self,
            _referenced_ranges: Vec<WalFileRange>,
            _min_age: Duration,
            _dry_run: bool,
        ) -> Result<(), WalError> {
            Ok(())
        }
    }

    #[async_trait]
    impl WalAdmin for RemappingWalAdmin {
        fn garbage_collector(&self, _path: &Path) -> Arc<dyn WalGc> {
            Arc::new(NoopWalGc)
        }

        async fn delete_wal(&self, _path: &Path, _dry_run: bool) -> Result<Vec<String>, WalError> {
            Ok(vec![])
        }

        async fn is_empty(
            &self,
            _path: &Path,
            _replay_after_wal_id: u64,
            _wal_id_last_seen: u64,
        ) -> Result<bool, WalError> {
            Ok(true)
        }

        async fn clone_wal(
            &self,
            _from_path: &Path,
            from_manifest: VersionedManifest,
            _to_path: &Path,
        ) -> Result<(u64, u64), WalError> {
            if let Some(expected_manifest_id) = self.expected_manifest_id {
                assert_eq!(from_manifest.id(), expected_manifest_id);
            }
            Ok(self.replay_range)
        }
    }

    async fn create_native_clone<P: Into<Path>, R: RangeBounds<Bytes> + Clone>(
        clone_sources: Vec<CloneSourceSpec<R>>,
        clone_path: P,
        object_stores: ObjectStores,
        fp_registry: Arc<FailPointRegistry>,
        system_clock: Arc<dyn SystemClock>,
        rand: Arc<DbRand>,
        projection_range: Option<R>,
        segment_filter: Option<SegmentFilterFn>,
        segment_projection: Option<SegmentProjectionFn>,
    ) -> Result<(), SlateDBError> {
        let wal_admin = Arc::new(SlateDbWalAdmin::new(
            object_stores
                .store_of(crate::object_stores::ObjectStoreType::Wal)
                .clone(),
            fp_registry.clone(),
        ));
        crate::clone::create_clone(
            clone_sources,
            clone_path,
            object_stores
                .store_of(crate::object_stores::ObjectStoreType::Main)
                .clone(),
            wal_admin,
            fp_registry,
            system_clock,
            rand,
            projection_range,
            segment_filter,
            segment_projection,
        )
        .await
    }

    // helper method for tests that creates CloneSourceSpec
    async fn create_clone<P: Into<Path>>(
        clone_path: P,
        parent_path: P,
        object_store: Arc<dyn ObjectStore>,
        wal_object_store: Arc<dyn ObjectStore>,
        parent_checkpoint: Option<Uuid>,
        fp_registry: Arc<FailPointRegistry>,
        system_clock: Arc<dyn SystemClock>,
        rand: Arc<DbRand>,
    ) -> Result<(), SlateDBError> {
        let source: CloneSourceSpec = match parent_checkpoint {
            Some(cp) => CloneSourceSpec::with_checkpoint(parent_path, cp),
            None => CloneSourceSpec::new(parent_path),
        };
        create_native_clone(
            vec![source],
            clone_path,
            ObjectStores::new(object_store, Some(wal_object_store)),
            fp_registry,
            system_clock,
            rand,
            None,
            None,
            None,
        )
        .await
    }

    #[tokio::test]
    async fn should_stamp_wal_range_returned_by_wal_admin() {
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let parent_path = Path::from("/tmp/test_parent_remapped_wal");
        let clone_path = Path::from("/tmp/test_clone_remapped_wal");
        let system_clock: Arc<dyn SystemClock> = Arc::new(DefaultSystemClock::new());

        let mut parent_manifest = StoredManifest::create_new_db(
            Arc::new(ManifestStore::new(&parent_path, object_store.clone())),
            ManifestCore::new(),
            system_clock.clone(),
        )
        .await
        .unwrap();
        let checkpoint = parent_manifest
            .write_checkpoint(Uuid::new_v4(), &CheckpointOptions::default())
            .await
            .unwrap();

        let wal_admin = RemappingWalAdmin {
            replay_range: (41, 46),
            expected_manifest_id: Some(checkpoint.manifest_id),
        };
        let source: CloneSourceSpec = CloneSourceSpec::with_checkpoint(parent_path, checkpoint.id);
        crate::clone::create_clone(
            vec![source],
            clone_path.clone(),
            object_store.clone(),
            Arc::new(wal_admin),
            Arc::new(FailPointRegistry::new()),
            system_clock.clone(),
            Arc::new(DbRand::default()),
            None,
            None,
            None,
        )
        .await
        .unwrap();

        let manifest = StoredManifest::load(
            Arc::new(ManifestStore::new(&clone_path, object_store)),
            system_clock,
        )
        .await
        .unwrap();
        assert!(manifest.db_state().initialized);
        assert_eq!(manifest.db_state().replay_after_wal_id, 41);
        assert_eq!(manifest.db_state().next_wal_sst_id, 47);
    }

    #[tokio::test]
    async fn should_reset_wal_range_when_clone_does_not_copy_wal() {
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let parent_paths = [
            Path::from("/tmp/test_parent_no_wal_a"),
            Path::from("/tmp/test_parent_no_wal_b"),
        ];
        let clone_path = Path::from("/tmp/test_clone_no_wal");
        let system_clock: Arc<dyn SystemClock> = Arc::new(DefaultSystemClock::new());

        for parent_path in &parent_paths {
            StoredManifest::create_new_db(
                Arc::new(ManifestStore::new(parent_path, object_store.clone())),
                ManifestCore::new(),
                system_clock.clone(),
            )
            .await
            .unwrap();
        }

        crate::clone::create_clone(
            parent_paths.into_iter().map(CloneSourceSpec::new).collect(),
            clone_path.clone(),
            object_store.clone(),
            Arc::new(RemappingWalAdmin {
                replay_range: (41, 47),
                expected_manifest_id: None,
            }),
            Arc::new(FailPointRegistry::new()),
            system_clock.clone(),
            Arc::new(DbRand::default()),
            None,
            None,
            None,
        )
        .await
        .unwrap();

        let manifest = StoredManifest::load(
            Arc::new(ManifestStore::new(&clone_path, object_store)),
            system_clock,
        )
        .await
        .unwrap();
        assert!(manifest.db_state().initialized);
        assert_eq!(manifest.db_state().replay_after_wal_id, 0);
        assert_eq!(manifest.db_state().next_wal_sst_id, 1);
    }

    #[tokio::test]
    async fn should_clone_latest_state_if_no_checkpoint_provided() {
        let mut rng = rng::new_test_rng(None);
        let table = sample::table(&mut rng, 5000, 10);

        let object_store = Arc::new(InMemory::new());
        let parent_path = Path::from("/tmp/test_parent");
        let clone_path = Path::from("/tmp/test_clone");

        let parent_db = Db::open(parent_path.clone(), object_store.clone())
            .await
            .unwrap();
        test_utils::seed_database(&parent_db, &table, false)
            .await
            .unwrap();
        parent_db.flush().await.unwrap();
        parent_db.close().await.unwrap();

        create_clone(
            clone_path.clone(),
            parent_path.clone(),
            object_store.clone(),
            object_store.clone(),
            None,
            Arc::new(FailPointRegistry::new()),
            Arc::new(DefaultSystemClock::new()),
            Arc::new(DbRand::default()),
        )
        .await
        .unwrap();

        let clone_db = Db::open(clone_path.clone(), object_store.clone())
            .await
            .unwrap();
        let mut db_iter = clone_db.scan(..).await.unwrap();
        test_utils::assert_ranged_db_scan(&table, .., IterationOrder::Ascending, &mut db_iter)
            .await;
        clone_db.close().await.unwrap();
    }

    #[tokio::test]
    async fn should_read_clone_with_db_reader() {
        let mut rng = rng::new_test_rng(None);
        let table = sample::table(&mut rng, 5000, 10);

        let object_store = Arc::new(InMemory::new());
        let parent_path = Path::from("/tmp/test_parent");
        let clone_path = Path::from("/tmp/test_clone");

        let parent_db = Db::open(parent_path.clone(), object_store.clone())
            .await
            .unwrap();
        test_utils::seed_database(&parent_db, &table, false)
            .await
            .unwrap();
        parent_db.flush().await.unwrap();
        // Flush the memtable so the parent's data lives in L0 SSTs, which the
        // clone references as external SSTs instead of replaying WALs.
        parent_db
            .flush_with_options(FlushOptions {
                flush_type: FlushType::MemTable,
            })
            .await
            .unwrap();
        parent_db.close().await.unwrap();

        create_clone(
            clone_path.clone(),
            parent_path.clone(),
            object_store.clone(),
            object_store.clone(),
            None,
            Arc::new(FailPointRegistry::new()),
            Arc::new(DefaultSystemClock::new()),
            Arc::new(DbRand::default()),
        )
        .await
        .unwrap();

        // Sanity check that reads must resolve parent-resident SSTs.
        let clone_manifest_store = Arc::new(ManifestStore::new(&clone_path, object_store.clone()));
        let clone_manifest = clone_manifest_store
            .read_latest_manifest()
            .await
            .unwrap()
            .manifest;
        assert!(!clone_manifest.external_ssts().is_empty());

        let reader = DbReader::builder(clone_path.clone(), object_store.clone())
            .build()
            .await
            .unwrap();
        let mut db_iter = reader.scan(..).await.unwrap();
        test_utils::assert_ranged_db_scan(&table, .., IterationOrder::Ascending, &mut db_iter)
            .await;
        reader.close().await.unwrap();
    }

    #[tokio::test]
    async fn should_read_clone_with_db_reader_from_checkpoint_with_pruned_external_ssts() {
        let mut rng = rng::new_test_rng(None);
        let table = sample::table(&mut rng, 5000, 10);

        let object_store = Arc::new(InMemory::new());
        let parent_path = Path::from("/tmp/test_parent");
        let clone_path = Path::from("/tmp/test_clone");
        let system_clock: Arc<dyn SystemClock> = Arc::new(DefaultSystemClock::new());
        let rand = Arc::new(DbRand::default());

        let parent_db = Db::open(parent_path.clone(), object_store.clone())
            .await
            .unwrap();
        test_utils::seed_database(&parent_db, &table, false)
            .await
            .unwrap();
        parent_db.flush().await.unwrap();
        parent_db
            .flush_with_options(FlushOptions {
                flush_type: FlushType::MemTable,
            })
            .await
            .unwrap();
        parent_db.close().await.unwrap();

        create_clone(
            clone_path.clone(),
            parent_path.clone(),
            object_store.clone(),
            object_store.clone(),
            None,
            Arc::new(FailPointRegistry::new()),
            system_clock.clone(),
            rand.clone(),
        )
        .await
        .unwrap();

        // Pin a checkpoint to the clone's current manifest, which references
        // the parent's SSTs externally.
        let clone_manifest_store = Arc::new(ManifestStore::new(&clone_path, object_store.clone()));
        let mut clone_sm = StoredManifest::load(clone_manifest_store.clone(), system_clock.clone())
            .await
            .unwrap();
        let checkpoint_id = rand.rng().gen_uuid();
        clone_sm
            .write_checkpoint(checkpoint_id, &CheckpointOptions::default())
            .await
            .unwrap();

        // Simulate a post-checkpoint compaction that re-localized all external
        // SSTs and pruned their ids from the latest manifest. The checkpoint's
        // manifest still references them.
        clone_sm
            .maybe_apply_update(|sr| {
                let mut dirty = sr.prepare_dirty()?;
                dirty
                    .value
                    .external_dbs
                    .iter_mut()
                    .for_each(|external_db| external_db.sst_ids.clear());
                Ok(Some(dirty))
            })
            .await
            .unwrap();
        let latest_manifest = clone_manifest_store
            .read_latest_manifest()
            .await
            .unwrap()
            .manifest;
        assert!(latest_manifest.external_ssts().is_empty());

        // A reader pinned to the checkpoint must resolve the external SSTs
        // referenced by the checkpoint's manifest.
        let reader = DbReader::builder(clone_path.clone(), object_store.clone())
            .with_reader_mode(crate::DbReaderMode::Checkpoint(checkpoint_id))
            .build()
            .await
            .unwrap();
        let mut db_iter = reader.scan(..).await.unwrap();
        test_utils::assert_ranged_db_scan(&table, .., IterationOrder::Ascending, &mut db_iter)
            .await;
        reader.close().await.unwrap();
    }

    #[tokio::test]
    async fn should_clone_from_checkpoint_wal_enabled() {
        should_clone_from_checkpoint(Settings::default()).await
    }

    #[cfg(feature = "wal_disable")]
    #[tokio::test]
    async fn should_clone_from_checkpoint_wal_disabled() {
        should_clone_from_checkpoint(Settings {
            wal_enabled: false,
            ..Settings::default()
        })
        .await
    }

    async fn should_clone_from_checkpoint(db_opts: Settings) {
        let mut rng = rng::new_test_rng(None);
        let checkpoint_table = sample::table(&mut rng, 5000, 10);
        let post_checkpoint_table = sample::table(&mut rng, 1000, 10);

        let object_store = Arc::new(InMemory::new());
        let parent_path = "/tmp/test_parent";
        let clone_path = "/tmp/test_clone";

        let parent_db = Db::builder(parent_path, object_store.clone())
            .with_settings(db_opts.clone())
            .build()
            .await
            .unwrap();
        test_utils::seed_database(&parent_db, &checkpoint_table, false)
            .await
            .unwrap();
        let checkpoint = parent_db
            .create_checkpoint(CheckpointScope::All, &CheckpointOptions::default())
            .await
            .unwrap();

        // Add some more data so that we can be sure that the clone was created
        // from the checkpoint and not the latest state.
        test_utils::seed_database(&parent_db, &post_checkpoint_table, false)
            .await
            .unwrap();
        parent_db.flush().await.unwrap();
        parent_db.close().await.unwrap();

        create_clone(
            clone_path,
            parent_path,
            object_store.clone(),
            object_store.clone(),
            Some(checkpoint.id),
            Arc::new(FailPointRegistry::new()),
            Arc::new(DefaultSystemClock::new()),
            Arc::new(DbRand::default()),
        )
        .await
        .unwrap();

        let clone_db = Db::builder(clone_path, object_store.clone())
            .with_settings(db_opts)
            .build()
            .await
            .unwrap();
        let mut db_iter = clone_db.scan(..).await.unwrap();
        test_utils::assert_ranged_db_scan(
            &checkpoint_table,
            ..,
            IterationOrder::Ascending,
            &mut db_iter,
        )
        .await;
        clone_db.close().await.unwrap();
    }

    #[tokio::test]
    async fn should_fail_retry_if_uninitialized_checkpoint_is_invalid() {
        let object_store = Arc::new(InMemory::new());
        let parent_path = Path::from("/tmp/test_parent");
        let clone_path = Path::from("/tmp/test_clone");
        let rand = Arc::new(DbRand::default());
        let system_clock = Arc::new(DefaultSystemClock::new());

        // Create the parent with empty state
        let parent_db = Db::open(parent_path.clone(), object_store.clone())
            .await
            .unwrap();
        parent_db.close().await.unwrap();

        // Create an uninitialized manifest with an invalid checkpoint id
        let clone_manifest_store = Arc::new(ManifestStore::new(&clone_path, object_store.clone()));
        let non_existent_source_checkpoint_id = Uuid::new_v4();
        StoredManifest::store_uninitialized_clone(
            clone_manifest_store,
            Manifest::cloned(
                &Manifest::initial(ManifestCore::new()),
                parent_path.to_string(),
                non_existent_source_checkpoint_id,
                rand.clone(),
            ),
            system_clock.clone(),
        )
        .await
        .unwrap();

        // Cloning should reset the checkpoint to a newly generated id
        let err = create_clone(
            clone_path.clone(),
            parent_path.clone(),
            object_store.clone(),
            object_store.clone(),
            None,
            Arc::new(FailPointRegistry::new()),
            system_clock.clone(),
            rand.clone(),
        )
        .await
        .unwrap_err();

        assert!(
            matches!(err, SlateDBError::CheckpointMissing(id) if id == non_existent_source_checkpoint_id)
        );
    }

    #[tokio::test]
    async fn should_fail_retry_if_uninitialized_checkpoint_differs_from_provided() {
        let object_store = Arc::new(InMemory::new());
        let parent_path = Path::from("/tmp/test_parent");
        let clone_path = Path::from("/tmp/test_clone");
        let rand = Arc::new(DbRand::default());
        let system_clock = Arc::new(DefaultSystemClock::new());

        // Create the parent with empty state
        let parent_manifest_store =
            Arc::new(ManifestStore::new(&parent_path, object_store.clone()));
        let mut parent_sm = StoredManifest::create_new_db(
            parent_manifest_store,
            ManifestCore::new(),
            system_clock.clone(),
        )
        .await
        .unwrap();
        let uuid_1 = rand.rng().gen_uuid();
        let checkpoint_1 = parent_sm
            .write_checkpoint(uuid_1, &CheckpointOptions::default())
            .await
            .unwrap();
        let uuid_2 = rand.rng().gen_uuid();
        let checkpoint_2 = parent_sm
            .write_checkpoint(uuid_2, &CheckpointOptions::default())
            .await
            .unwrap();

        // Create an uninitialized manifest referring to the first checkpoint
        let clone_manifest_store = Arc::new(ManifestStore::new(&clone_path, object_store.clone()));
        StoredManifest::store_uninitialized_clone(
            clone_manifest_store,
            Manifest::cloned(
                &Manifest::initial(ManifestCore::new()),
                parent_path.to_string(),
                checkpoint_1.id,
                rand.clone(),
            ),
            system_clock.clone(),
        )
        .await
        .unwrap();

        // Cloning with the second checkpoint should fail
        let err = create_clone(
            clone_path.clone(),
            parent_path.clone(),
            object_store.clone(),
            object_store.clone(),
            Some(checkpoint_2.id),
            Arc::new(FailPointRegistry::new()),
            system_clock.clone(),
            rand.clone(),
        )
        .await
        .unwrap_err();

        assert!(matches!(
            err,
            SlateDBError::CloneIncorrectExternalDbCheckpoint { .. }
        ));
    }

    #[tokio::test]
    async fn should_fail_retry_if_parent_path_is_different() {
        let object_store = Arc::new(InMemory::new());
        let original_parent_path = Path::from("/tmp/test_parent");
        let updated_parent_path = Path::from("/tmp/test_parent/new");
        let clone_path = Path::from("/tmp/test_clone");
        let rand = Arc::new(DbRand::default());
        let system_clock = Arc::new(DefaultSystemClock::new());

        // Setup an uninitialized manifest pointing to a different parent
        let parent_manifest = Manifest::initial(ManifestCore::new());
        let clone_manifest_store = Arc::new(ManifestStore::new(&clone_path, object_store.clone()));
        StoredManifest::store_uninitialized_clone(
            clone_manifest_store,
            Manifest::cloned(
                &parent_manifest,
                original_parent_path.to_string(),
                Uuid::new_v4(),
                rand.clone(),
            ),
            system_clock.clone(),
        )
        .await
        .unwrap();

        // Initialize the parent at the updated path
        let parent_db = Db::open(updated_parent_path.clone(), object_store.clone())
            .await
            .unwrap();
        parent_db.close().await.unwrap();

        // The clone should fail because of inconsistent parent information
        let err = create_clone(
            clone_path.clone(),
            updated_parent_path.clone(),
            object_store.clone(),
            object_store.clone(),
            None,
            Arc::new(FailPointRegistry::new()),
            system_clock.clone(),
            rand.clone(),
        )
        .await
        .unwrap_err();

        assert!(matches!(
            err,
            SlateDBError::CloneIncorrectExternalDbCheckpoint { .. }
        ));
    }

    #[tokio::test]
    async fn clone_retry_should_be_idempotent_after_success() -> Result<(), SlateDBError> {
        let object_store = Arc::new(InMemory::new());
        let parent_path = "/tmp/test_parent";
        let clone_path = "/tmp/test_clone";
        let rand = Arc::new(DbRand::default());
        let system_clock = Arc::new(DefaultSystemClock::new());

        let parent_db = Db::open(parent_path, object_store.clone()).await.unwrap();
        parent_db.close().await.unwrap();

        create_clone(
            clone_path,
            parent_path,
            object_store.clone(),
            object_store.clone(),
            None,
            Arc::new(FailPointRegistry::new()),
            system_clock.clone(),
            rand.clone(),
        )
        .await
        .unwrap();

        let clone_manifest_store =
            ManifestStore::new(&Path::from(clone_path), object_store.clone());
        let manifest_id = clone_manifest_store
            .read_latest_manifest()
            .await
            .unwrap()
            .id;

        create_clone(
            clone_path,
            parent_path,
            object_store.clone(),
            object_store.clone(),
            None,
            Arc::new(FailPointRegistry::new()),
            system_clock.clone(),
            rand.clone(),
        )
        .await?;

        assert_eq!(
            manifest_id,
            clone_manifest_store
                .read_latest_manifest()
                .await
                .unwrap()
                .id
        );

        Ok(())
    }

    #[tokio::test]
    async fn should_retry_clone_after_io_error_copying_wals() {
        let fp_registry = Arc::new(FailPointRegistry::new());
        let object_store = Arc::new(InMemory::new());
        let parent_path = Path::from("/tmp/test_parent");
        let clone_path = Path::from("/tmp/test_clone");
        let rand = Arc::new(DbRand::default());
        let system_clock = Arc::new(DefaultSystemClock::new());

        let parent_db = Db::builder(parent_path.clone(), object_store.clone())
            .with_fp_registry(fp_registry.clone())
            .build()
            .await
            .unwrap();
        let mut rng = rng::new_test_rng(None);
        test_utils::seed_database(&parent_db, &sample::table(&mut rng, 100, 10), false)
            .await
            .unwrap();
        parent_db.flush().await.unwrap();

        test_utils::seed_database(&parent_db, &sample::table(&mut rng, 100, 10), false)
            .await
            .unwrap();
        parent_db.flush().await.unwrap();
        // Block L0 uploads so the data remains in the WAL after close.
        fail_parallel::cfg(
            Arc::clone(&fp_registry),
            "write-compacted-sst-io-error",
            "return",
        )
        .unwrap();
        // expect to fail since l0 flush is blocked
        assert!(parent_db.close().await.is_err());
        fail_parallel::cfg(
            Arc::clone(&fp_registry),
            "write-compacted-sst-io-error",
            "off",
        )
        .unwrap();

        fail_parallel::cfg(
            Arc::clone(&fp_registry),
            "copy-wal-ssts-io-error",
            "1*off->return",
        )
        .unwrap();

        let err = create_clone(
            clone_path.clone(),
            parent_path.clone(),
            object_store.clone(),
            object_store.clone(),
            None,
            Arc::clone(&fp_registry),
            system_clock.clone(),
            rand.clone(),
        )
        .await
        .unwrap_err();
        assert!(matches!(err, SlateDBError::WalUnavailable(_)));

        fail_parallel::cfg(Arc::clone(&fp_registry), "copy-wal-ssts-io-error", "off").unwrap();
        create_clone(
            clone_path.clone(),
            parent_path.clone(),
            object_store.clone(),
            object_store.clone(),
            None,
            Arc::clone(&fp_registry),
            system_clock.clone(),
            rand.clone(),
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn should_fail_retry_if_source_checkpoint_is_missing() -> Result<(), crate::Error> {
        let fp_registry = Arc::new(FailPointRegistry::new());
        let object_store = Arc::new(InMemory::new());
        let parent_path = Path::from("/tmp/test_parent");
        let clone_path = Path::from("/tmp/test_clone");
        let rand = Arc::new(DbRand::default());
        let system_clock = Arc::new(DefaultSystemClock::new());

        let parent_db = Db::open(parent_path.clone(), object_store.clone()).await?;
        let mut rng = rng::new_test_rng(None);
        test_utils::seed_database(&parent_db, &sample::table(&mut rng, 100, 10), false).await?;
        let checkpoint = parent_db
            .create_checkpoint(CheckpointScope::All, &CheckpointOptions::default())
            .await?;
        parent_db.close().await?;

        fail_parallel::cfg(
            Arc::clone(&fp_registry),
            "create-clone-manifest-io-error",
            "return",
        )
        .unwrap();

        let err = create_clone(
            clone_path.clone(),
            parent_path.clone(),
            object_store.clone(),
            object_store.clone(),
            Some(checkpoint.id),
            Arc::clone(&fp_registry),
            system_clock.clone(),
            rand.clone(),
        )
        .await
        .unwrap_err();
        assert!(matches!(err, SlateDBError::IoError(_)));

        fail_parallel::cfg(
            Arc::clone(&fp_registry),
            "create-clone-manifest-io-error",
            "off",
        )
        .unwrap();

        // Delete the checkpoint from the parent database
        let parent_manifest_store =
            Arc::new(ManifestStore::new(&parent_path, object_store.clone()));
        let mut parent_manifest =
            StoredManifest::load(parent_manifest_store, system_clock.clone()).await?;
        parent_manifest.delete_checkpoint(checkpoint.id).await?;

        // Attempting to clone with a missing checkpoint should fail
        let err = create_clone(
            clone_path.clone(),
            parent_path.clone(),
            object_store.clone(),
            object_store.clone(),
            Some(checkpoint.id),
            Arc::clone(&fp_registry),
            system_clock.clone(),
            rand.clone(),
        )
        .await
        .unwrap_err();
        assert!(matches!(err, SlateDBError::CheckpointMissing(id) if id == checkpoint.id));

        Ok(())
    }

    #[tokio::test]
    async fn clone_should_succeed_when_wal_object_store_is_provided() {
        let object_store = Arc::new(InMemory::new());
        let wal_object_store = Arc::new(InMemory::new());
        let parent_path = "/tmp/test_parent";
        let clone_path = "/tmp/test_clone";

        let parent_db = Db::builder(parent_path, object_store.clone())
            .with_wal_object_store(wal_object_store.clone())
            .build()
            .await
            .unwrap();
        let write_options = WriteOptions {
            ..Default::default()
        };
        let put_options = PutOptions::default();
        let l0_and_wal_data = [
            (b"l0-key-1".as_slice(), b"l0-value-1".as_slice()),
            (b"l0-key-2".as_slice(), b"l0-value-2".as_slice()),
        ];
        let wal_only_data = [
            (b"wal-only-key-1".as_slice(), b"wal-only-value-1".as_slice()),
            (b"wal-only-key-2".as_slice(), b"wal-only-value-2".as_slice()),
        ];
        for &(key, value) in &l0_and_wal_data {
            parent_db
                .put_with_options(key, value, &put_options, &write_options)
                .await
                .unwrap();
        }
        parent_db.flush().await.unwrap();
        parent_db
            .flush_with_options(FlushOptions {
                flush_type: FlushType::MemTable,
            })
            .await
            .unwrap();
        for &(key, value) in &wal_only_data {
            parent_db
                .put_with_options(key, value, &put_options, &write_options)
                .await
                .unwrap();
        }
        parent_db.flush().await.unwrap();
        let manifest = parent_db.manifest();
        assert!(
            !manifest.manifest.core.tree.l0.is_empty(),
            "expected cloned state to include L0 data"
        );
        assert!(
            manifest.manifest.core.replay_after_wal_id + 1 < manifest.manifest.core.next_wal_sst_id,
            "expected cloned state to retain WAL-only SSTs"
        );
        parent_db.close().await.unwrap();

        create_clone(
            clone_path,
            parent_path,
            object_store.clone(),
            wal_object_store.clone(),
            None,
            Arc::new(FailPointRegistry::new()),
            Arc::new(DefaultSystemClock::new()),
            Arc::new(DbRand::default()),
        )
        .await
        .unwrap();

        let clone_db = Db::builder(clone_path, object_store.clone())
            .with_wal_object_store(wal_object_store.clone())
            .build()
            .await
            .unwrap();
        for &(key, value) in &l0_and_wal_data {
            assert_eq!(
                clone_db.get(key).await.unwrap(),
                Some(Bytes::copy_from_slice(value))
            );
        }
        for &(key, value) in &wal_only_data {
            assert_eq!(
                clone_db.get(key).await.unwrap(),
                Some(Bytes::copy_from_slice(value))
            );
        }
        clone_db.close().await.unwrap();
    }

    #[tokio::test]
    async fn clone_should_fail_when_wal_store_is_not_provided() {
        let fp_registry = Arc::new(FailPointRegistry::new());
        let object_store = Arc::new(InMemory::new());
        let wal_object_store = Arc::new(InMemory::new());
        let parent_path = "/tmp/test_parent";
        let clone_path = "/tmp/test_clone";

        let parent_db = Db::builder(parent_path, object_store.clone())
            .with_wal_object_store(wal_object_store.clone())
            .with_fp_registry(fp_registry.clone())
            .build()
            .await
            .unwrap();
        let write_options = WriteOptions {
            ..Default::default()
        };
        let put_options = PutOptions::default();
        let l0_and_wal_data = [
            (b"l0-key-1".as_slice(), b"l0-value-1".as_slice()),
            (b"l0-key-2".as_slice(), b"l0-value-2".as_slice()),
        ];
        let wal_only_data = [
            (b"wal-only-key-1".as_slice(), b"wal-only-value-1".as_slice()),
            (b"wal-only-key-2".as_slice(), b"wal-only-value-2".as_slice()),
        ];
        for &(key, value) in &l0_and_wal_data {
            parent_db
                .put_with_options(key, value, &put_options, &write_options)
                .await
                .unwrap();
        }
        parent_db.flush().await.unwrap();
        parent_db
            .flush_with_options(FlushOptions {
                flush_type: FlushType::MemTable,
            })
            .await
            .unwrap();
        for &(key, value) in &wal_only_data {
            parent_db
                .put_with_options(key, value, &put_options, &write_options)
                .await
                .unwrap();
        }
        parent_db.flush().await.unwrap();
        let manifest = parent_db.manifest();
        assert!(
            !manifest.manifest.core.tree.l0.is_empty(),
            "expected cloned state to include L0 data"
        );
        assert!(
            manifest.manifest.core.replay_after_wal_id + 1 < manifest.manifest.core.next_wal_sst_id,
            "expected cloned state to retain WAL-only SSTs"
        );
        let expected_missing_wal_path = PathResolver::from_root(Path::from(parent_path))
            .sst_path(&SsTableId::Wal(
                manifest.manifest.core.replay_after_wal_id + 1,
            ))
            .to_string();
        // Block L0 uploads so the WAL-only data stays in the WAL.
        fail_parallel::cfg(
            fp_registry.clone(),
            "write-compacted-sst-io-error",
            "return",
        )
        .unwrap();
        // expect to fail since l0 upload is blocked
        assert!(parent_db.close().await.is_err());
        fail_parallel::cfg(fp_registry.clone(), "write-compacted-sst-io-error", "off").unwrap();

        // Pass main store as WAL store — WAL SSTs won't be found there
        let err = create_clone(
            clone_path,
            parent_path,
            object_store.clone(),
            object_store.clone(),
            None,
            Arc::new(FailPointRegistry::new()),
            Arc::new(DefaultSystemClock::new()),
            Arc::new(DbRand::default()),
        )
        .await
        .unwrap_err();
        assert!(matches!(
            err,
            SlateDBError::WalUnavailable(ref source)
                if matches!(
                    source.downcast_ref::<ObjectStoreError>(),
                    Some(ObjectStoreError::NotFound { path, .. })
                        if path == &expected_missing_wal_path
                )
        ));
    }

    #[tokio::test]
    async fn should_disallow_projected_clone_when_source_has_data_wal() {
        // Data that only lives in the parent's WAL at the checkpoint is copied
        // to the clone verbatim and replayed in full on first open, so a
        // projection cannot be applied to it. Cloning with a projection must
        // fail while the source still has data in its WAL, and succeed once
        // that data has been flushed into L0.
        let fp_registry = Arc::new(FailPointRegistry::new());
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let parent_path = Path::from("/tmp/test_parent_wal_projection");
        let clone_path = Path::from("/tmp/test_clone_wal_projection");

        let parent_db = Db::builder(parent_path.clone(), object_store.clone())
            .with_fp_registry(fp_registry.clone())
            .build()
            .await
            .unwrap();
        let write_options = WriteOptions::default();
        let put_options = PutOptions::default();

        // Keys inside and outside the projection range [aaa, bbb), flushed
        // through to L0 ...
        parent_db
            .put_with_options(b"aaa-l0", b"v1", &put_options, &write_options)
            .await
            .unwrap();
        parent_db
            .put_with_options(b"zzz-l0", b"v2", &put_options, &write_options)
            .await
            .unwrap();
        parent_db.flush().await.unwrap();
        parent_db
            .flush_with_options(FlushOptions {
                flush_type: FlushType::MemTable,
            })
            .await
            .unwrap();

        // ... and the same shape of data made durable only in the WAL.
        parent_db
            .put_with_options(b"aaa-wal", b"v3", &put_options, &write_options)
            .await
            .unwrap();
        parent_db
            .put_with_options(b"zzz-wal", b"v4", &put_options, &write_options)
            .await
            .unwrap();
        parent_db.flush().await.unwrap();

        let manifest = parent_db.manifest();
        assert!(
            !manifest.manifest.core.tree.l0.is_empty(),
            "expected parent state to include L0 data"
        );
        assert!(
            manifest.manifest.core.replay_after_wal_id + 1 < manifest.manifest.core.next_wal_sst_id,
            "expected parent state to retain WAL-only SSTs"
        );

        // Block L0 uploads so the WAL-only data stays in the WAL.
        fail_parallel::cfg(
            fp_registry.clone(),
            "write-compacted-sst-io-error",
            "return",
        )
        .unwrap();
        // expect to fail since l0 upload is blocked
        assert!(parent_db.close().await.is_err());
        fail_parallel::cfg(fp_registry.clone(), "write-compacted-sst-io-error", "off").unwrap();

        // Cloning with a projection that keeps only keys in [aaa, bbb) must
        // be rejected while the WAL-only data is still in the WAL.
        let range = (
            Bound::Included(Bytes::from_static(b"aaa")),
            Bound::Excluded(Bytes::from_static(b"bbb")),
        );
        let err = create_native_clone(
            vec![CloneSourceSpec::new(parent_path.clone())],
            clone_path.clone(),
            ObjectStores::new(object_store.clone(), Some(object_store.clone())),
            Arc::new(FailPointRegistry::new()),
            Arc::new(DefaultSystemClock::new()),
            Arc::new(DbRand::default()),
            Some(range.clone()),
            None,
            None,
        )
        .await
        .unwrap_err();
        assert!(matches!(
            err,
            SlateDBError::InvalidCloneSourceWithWal { ref paths }
                if paths == &vec![parent_path.clone()]
        ));

        // Reopen the parent so the WAL tail is replayed, flush it into L0,
        // and close cleanly. With no data WALs left to copy the projected
        // clone is allowed.
        let parent_db = Db::open(parent_path.clone(), object_store.clone())
            .await
            .unwrap();
        parent_db
            .flush_with_options(FlushOptions {
                flush_type: FlushType::MemTable,
            })
            .await
            .unwrap();
        parent_db.close().await.unwrap();

        create_native_clone(
            vec![CloneSourceSpec::new(parent_path.clone())],
            clone_path.clone(),
            ObjectStores::new(object_store.clone(), Some(object_store.clone())),
            Arc::new(FailPointRegistry::new()),
            Arc::new(DefaultSystemClock::new()),
            Arc::new(DbRand::default()),
            Some(range),
            None,
            None,
        )
        .await
        .unwrap();

        let clone_db = Db::open(clone_path.clone(), object_store.clone())
            .await
            .unwrap();

        // L0 data respects the projection.
        assert_eq!(
            clone_db.get(b"aaa-l0").await.unwrap(),
            Some(Bytes::from_static(b"v1"))
        );
        assert_eq!(
            clone_db.get(b"zzz-l0").await.unwrap(),
            None,
            "L0 entry outside the projection range must not be visible in the clone"
        );

        // The formerly WAL-only data was flushed into L0 before the retry,
        // so it must respect the projection too.
        assert_eq!(
            clone_db.get(b"aaa-wal").await.unwrap(),
            Some(Bytes::from_static(b"v3"))
        );
        assert_eq!(
            clone_db.get(b"zzz-wal").await.unwrap(),
            None,
            "entry outside the projection range must not be visible in the clone"
        );
        clone_db.close().await.unwrap();
    }

    fn segmented_table() -> BTreeMap<Bytes, Bytes> {
        BTreeMap::from([
            (Bytes::from_static(b"aaa-001"), Bytes::from_static(b"v1")),
            (Bytes::from_static(b"aaa-003"), Bytes::from_static(b"v2")),
            (Bytes::from_static(b"bbb-001"), Bytes::from_static(b"v3")),
            (Bytes::from_static(b"bbb-002"), Bytes::from_static(b"v4")),
            (Bytes::from_static(b"ddd-001"), Bytes::from_static(b"v5")),
            (Bytes::from_static(b"ddd-004"), Bytes::from_static(b"v6")),
        ])
    }

    #[cfg(feature = "wal_disable")]
    fn wal_disabled_settings() -> Settings {
        Settings {
            wal_enabled: false,
            ..Settings::default()
        }
    }

    async fn build_segmented_parent(
        path: &Path,
        object_store: Arc<dyn ObjectStore>,
        extractor: Arc<dyn crate::prefix_extractor::PrefixExtractor>,
        settings: Settings,
        table: &BTreeMap<Bytes, Bytes>,
    ) {
        #[cfg(feature = "wal_disable")]
        let wal_enabled = settings.wal_enabled;
        #[cfg(not(feature = "wal_disable"))]
        let wal_enabled = true;
        let db = Db::builder(path.clone(), object_store)
            .with_settings(settings)
            .with_segment_extractor(extractor)
            .build()
            .await
            .unwrap();
        // Do not await the returned handle here: with wal_enabled=false, the
        // memtable flush is gated on the explicit call below.
        test_utils::seed_database(&db, table, false).await.unwrap();
        if wal_enabled {
            // Flush the WAL before the memtable so that `replay_after_wal_id`
            // covers every data WAL; projected clones of this parent would
            // otherwise be rejected.
            db.flush().await.unwrap();
        }
        db.flush_with_options(FlushOptions {
            flush_type: FlushType::MemTable,
        })
        .await
        .unwrap();
        db.close().await.unwrap();
    }

    async fn open_segmented_clone(
        path: &Path,
        object_store: Arc<dyn ObjectStore>,
        extractor: Arc<dyn crate::prefix_extractor::PrefixExtractor>,
        settings: Settings,
    ) -> Db {
        Db::builder(path.clone(), object_store)
            .with_settings(settings)
            .with_segment_extractor(extractor)
            .build()
            .await
            .unwrap()
    }

    async fn run_segmented_clone<R: RangeBounds<Bytes> + Clone>(
        sources: Vec<CloneSourceSpec<R>>,
        clone_path: &Path,
        object_store: Arc<dyn ObjectStore>,
        projection: Option<R>,
    ) {
        create_native_clone(
            sources,
            clone_path.clone(),
            ObjectStores::new(object_store.clone(), Some(object_store)),
            Arc::new(FailPointRegistry::new()),
            Arc::new(DefaultSystemClock::new()),
            Arc::new(DbRand::default()),
            projection,
            None,
            None,
        )
        .await
        .unwrap();
    }

    async fn assert_clone_segments(
        clone_path: &Path,
        object_store: Arc<dyn ObjectStore>,
        expected_prefixes: &[&[u8]],
    ) {
        let store = ManifestStore::new(clone_path, object_store);
        let stored = store.read_latest_manifest().await.unwrap();
        assert_eq!(
            stored.manifest.core.segment_extractor_name.as_deref(),
            Some("fixed-3")
        );
        let actual: Vec<Bytes> = stored
            .manifest
            .core
            .segments
            .iter()
            .map(|s| s.prefix.clone())
            .collect();
        let want: Vec<Bytes> = expected_prefixes
            .iter()
            .map(|b| Bytes::copy_from_slice(b))
            .collect();
        assert_eq!(actual, want);
    }

    async fn assert_segment_prefix_scan(
        db: &Db,
        expected: &BTreeMap<Bytes, Bytes>,
        prefix_lo: &'static [u8],
        prefix_hi: &'static [u8],
    ) {
        let mut iter = db.scan_prefix(prefix_lo, ..).await.unwrap();
        test_utils::assert_ranged_db_scan(
            expected,
            Bytes::from_static(prefix_lo)..Bytes::from_static(prefix_hi),
            IterationOrder::Ascending,
            &mut iter,
        )
        .await;
    }

    #[tokio::test]
    async fn should_filter_segments_via_clone_builder() {
        // Drop the `bbb` segment using filter_segments; verify only `aaa` and
        // `ddd` remain in the clone.
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let parent_path = Path::from("/tmp/test_parent_seg_filter");
        let clone_path = Path::from("/tmp/test_clone_seg_filter");
        let extractor = Arc::new(test_utils::FixedThreeBytePrefixExtractor);
        let table = segmented_table();

        build_segmented_parent(
            &parent_path,
            object_store.clone(),
            extractor.clone(),
            Settings::default(),
            &table,
        )
        .await;

        crate::db::builder::CloneBuilder::new(
            clone_path.clone(),
            CloneSourceSpec::new(parent_path.clone()),
            object_store.clone(),
        )
        .with_wal_object_store(object_store.clone())
        .with_segment_filter(|prefix| prefix != b"bbb")
        .build()
        .await
        .unwrap();

        assert_clone_segments(&clone_path, object_store.clone(), &[b"aaa", b"ddd"]).await;
    }

    #[tokio::test]
    async fn should_apply_segment_projection_via_clone_builder() {
        // Narrow the `aaa` segment to only keys >= "aaa-002" via
        // with_segment_projection; other segments retain full ranges.
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let parent_path = Path::from("/tmp/test_parent_seg_proj");
        let clone_path = Path::from("/tmp/test_clone_seg_proj");
        let extractor = Arc::new(test_utils::FixedThreeBytePrefixExtractor);
        let table = segmented_table();

        build_segmented_parent(
            &parent_path,
            object_store.clone(),
            extractor.clone(),
            Settings::default(),
            &table,
        )
        .await;

        crate::db::builder::CloneBuilder::new(
            clone_path.clone(),
            CloneSourceSpec::new(parent_path.clone()),
            object_store.clone(),
        )
        .with_wal_object_store(object_store.clone())
        .with_segment_projection(|prefix| {
            if prefix == b"aaa" {
                let mut start = prefix.to_vec();
                start.extend_from_slice(b"-002");
                (Bound::Included(Bytes::from(start)), Bound::Unbounded)
            } else {
                (Bound::Unbounded, Bound::Unbounded)
            }
        })
        .build()
        .await
        .unwrap();

        let clone_db = open_segmented_clone(
            &clone_path,
            object_store.clone(),
            extractor,
            Settings::default(),
        )
        .await;
        // aaa-001 was filtered out by the projection; aaa-003 remains. Other
        // segments are untouched.
        let mut expected = table.clone();
        expected.remove(&Bytes::from_static(b"aaa-001"));
        let mut full_iter = clone_db.scan(..).await.unwrap();
        test_utils::assert_ranged_db_scan(&expected, .., IterationOrder::Ascending, &mut full_iter)
            .await;
        clone_db.close().await.unwrap();
    }

    #[tokio::test]
    async fn should_clone_segmented_db() {
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let parent_path = Path::from("/tmp/test_parent_seg_clone");
        let clone_path = Path::from("/tmp/test_clone_seg_clone");
        let extractor = Arc::new(test_utils::FixedThreeBytePrefixExtractor);
        let table = segmented_table();

        build_segmented_parent(
            &parent_path,
            object_store.clone(),
            extractor.clone(),
            Settings::default(),
            &table,
        )
        .await;

        run_segmented_clone(
            vec![CloneSourceSpec::new(parent_path.clone())],
            &clone_path,
            object_store.clone(),
            None,
        )
        .await;

        assert_clone_segments(&clone_path, object_store.clone(), &[b"aaa", b"bbb", b"ddd"]).await;

        let clone_db = open_segmented_clone(
            &clone_path,
            object_store.clone(),
            extractor,
            Settings::default(),
        )
        .await;
        let mut full_iter = clone_db.scan(..).await.unwrap();
        test_utils::assert_ranged_db_scan(&table, .., IterationOrder::Ascending, &mut full_iter)
            .await;
        assert_segment_prefix_scan(&clone_db, &table, b"bbb", b"bbc").await;
        let mut cross_iter = clone_db
            .scan(b"aaa".to_vec()..=b"ddd-999".to_vec())
            .await
            .unwrap();
        test_utils::assert_ranged_db_scan(
            &table,
            Bytes::from_static(b"aaa")..=Bytes::from_static(b"ddd-999"),
            IterationOrder::Ascending,
            &mut cross_iter,
        )
        .await;
        clone_db.close().await.unwrap();
    }

    #[cfg(feature = "wal_disable")]
    #[tokio::test]
    async fn should_union_segmented_dbs() {
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let parent_path_a = Path::from("/tmp/test_parent_seg_union_a");
        let parent_path_b = Path::from("/tmp/test_parent_seg_union_b");
        let clone_path = Path::from("/tmp/test_clone_seg_union");
        let extractor = Arc::new(test_utils::FixedThreeBytePrefixExtractor);
        let settings = wal_disabled_settings();

        let table_a = BTreeMap::from([
            (Bytes::from_static(b"aaa-001"), Bytes::from_static(b"v1")),
            (Bytes::from_static(b"bbb-001"), Bytes::from_static(b"v2")),
            (Bytes::from_static(b"bbb-002"), Bytes::from_static(b"v3")),
        ]);
        let table_b = BTreeMap::from([
            (Bytes::from_static(b"ddd-001"), Bytes::from_static(b"v4")),
            (Bytes::from_static(b"eee-001"), Bytes::from_static(b"v5")),
            (Bytes::from_static(b"eee-002"), Bytes::from_static(b"v6")),
        ]);

        build_segmented_parent(
            &parent_path_a,
            object_store.clone(),
            extractor.clone(),
            settings.clone(),
            &table_a,
        )
        .await;
        build_segmented_parent(
            &parent_path_b,
            object_store.clone(),
            extractor.clone(),
            settings.clone(),
            &table_b,
        )
        .await;

        run_segmented_clone(
            vec![
                CloneSourceSpec::new(parent_path_a.clone()),
                CloneSourceSpec::new(parent_path_b.clone()),
            ],
            &clone_path,
            object_store.clone(),
            None,
        )
        .await;

        assert_clone_segments(
            &clone_path,
            object_store.clone(),
            &[b"aaa", b"bbb", b"ddd", b"eee"],
        )
        .await;
        let store = ManifestStore::new(&clone_path, object_store.clone());
        let stored = store.read_latest_manifest().await.unwrap();
        assert_eq!(stored.manifest.external_dbs.len(), 2);

        let mut expected: BTreeMap<Bytes, Bytes> = table_a.clone();
        expected.extend(table_b.clone());
        let clone_db =
            open_segmented_clone(&clone_path, object_store.clone(), extractor, settings).await;
        let mut full_iter = clone_db.scan(..).await.unwrap();
        test_utils::assert_ranged_db_scan(&expected, .., IterationOrder::Ascending, &mut full_iter)
            .await;
        assert_segment_prefix_scan(&clone_db, &expected, b"bbb", b"bbc").await;
        assert_segment_prefix_scan(&clone_db, &expected, b"eee", b"eef").await;
        clone_db.close().await.unwrap();
    }

    #[cfg(feature = "wal_disable")]
    #[tokio::test]
    async fn should_union_segmented_shards_that_each_span_every_segment() {
        // Rescale-down of a store keyed `data/{tenant}/…` and
        // `idx/{tenant}/…`, sharded by tenant. Each shard holds part of both
        // segments, so the shards' overall key ranges overlap —
        // `data/metro…` sorts below `idx/bronx…` — while neither segment
        // does. One union call must merge them; no per-source projection and
        // no staged re-slicing clones are needed.
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let parent_path_a = Path::from("/tmp/test_parent_seg_interleaved_a");
        let parent_path_b = Path::from("/tmp/test_parent_seg_interleaved_b");
        let clone_path = Path::from("/tmp/test_clone_seg_interleaved");
        let extractor = Arc::new(test_utils::DataIdxPrefixExtractor);
        let settings = wal_disabled_settings();

        fn shard(tenants: [&str; 2]) -> BTreeMap<Bytes, Bytes> {
            let mut table = BTreeMap::new();
            for tenant in tenants {
                table.insert(
                    Bytes::from(format!("data/{}/animal/lion-1", tenant)),
                    Bytes::from(format!("{} lion", tenant)),
                );
                table.insert(
                    Bytes::from(format!("idx/{}/owner/alice/lion-1", tenant)),
                    Bytes::new(),
                );
            }
            table
        }
        let table_a = shard(["bronx", "lincoln"]);
        let table_b = shard(["metro", "oakland"]);

        build_segmented_parent(
            &parent_path_a,
            object_store.clone(),
            extractor.clone(),
            settings.clone(),
            &table_a,
        )
        .await;
        build_segmented_parent(
            &parent_path_b,
            object_store.clone(),
            extractor.clone(),
            settings.clone(),
            &table_b,
        )
        .await;

        run_segmented_clone(
            vec![
                CloneSourceSpec::new(parent_path_a.clone()),
                CloneSourceSpec::new(parent_path_b.clone()),
            ],
            &clone_path,
            object_store.clone(),
            None,
        )
        .await;

        // Both shards contribute an L0 SST to each of the two segments.
        let store = ManifestStore::new(&clone_path, object_store.clone());
        let stored = store.read_latest_manifest().await.unwrap();
        assert_eq!(
            stored.manifest.core.segment_extractor_name.as_deref(),
            Some("data-idx")
        );
        let segments: Vec<(Bytes, usize)> = stored
            .manifest
            .core
            .segments
            .iter()
            .map(|s| (s.prefix.clone(), s.tree.l0.len()))
            .collect();
        assert_eq!(
            segments,
            vec![
                (Bytes::from_static(b"data"), 2),
                (Bytes::from_static(b"idx"), 2)
            ]
        );
        assert_eq!(stored.manifest.external_dbs.len(), 2);

        let mut expected: BTreeMap<Bytes, Bytes> = table_a.clone();
        expected.extend(table_b.clone());

        let clone_db =
            open_segmented_clone(&clone_path, object_store.clone(), extractor, settings).await;
        let mut full_iter = clone_db.scan(..).await.unwrap();
        test_utils::assert_ranged_db_scan(&expected, .., IterationOrder::Ascending, &mut full_iter)
            .await;
        // Each segment routes reads across both shards' contributions.
        assert_segment_prefix_scan(&clone_db, &expected, b"data", b"datb").await;
        assert_segment_prefix_scan(&clone_db, &expected, b"idx", b"idy").await;
        for (key, value) in &expected {
            assert_eq!(
                clone_db.get(key).await.unwrap().as_ref(),
                Some(value),
                "key={:?}",
                key
            );
        }
        clone_db.close().await.unwrap();
    }

    #[cfg(feature = "wal_disable")]
    #[tokio::test]
    async fn should_union_projected_segmented_dbs() {
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let parent_path_a = Path::from("/tmp/test_parent_seg_proj_union_a");
        let parent_path_b = Path::from("/tmp/test_parent_seg_proj_union_b");
        let clone_path = Path::from("/tmp/test_clone_seg_proj_union");
        let extractor = Arc::new(test_utils::FixedThreeBytePrefixExtractor);
        let settings = wal_disabled_settings();

        // Parents have overlapping key spaces; per-source projection carves
        // out disjoint slices so the union is exactly each parent's slice.
        let table_a = BTreeMap::from([
            (Bytes::from_static(b"aaa-001"), Bytes::from_static(b"v1")),
            (Bytes::from_static(b"bbb-001"), Bytes::from_static(b"v2")),
            (Bytes::from_static(b"bbb-002"), Bytes::from_static(b"v3")),
            (
                Bytes::from_static(b"ccc-001"),
                Bytes::from_static(b"vA-ccc"),
            ),
            (
                Bytes::from_static(b"ddd-001"),
                Bytes::from_static(b"vA-ddd"),
            ),
        ]);
        let table_b = BTreeMap::from([
            (
                Bytes::from_static(b"aaa-001"),
                Bytes::from_static(b"vB-aaa"),
            ),
            (
                Bytes::from_static(b"bbb-001"),
                Bytes::from_static(b"vB-bbb"),
            ),
            (Bytes::from_static(b"ccc-001"), Bytes::from_static(b"v4")),
            (Bytes::from_static(b"ddd-001"), Bytes::from_static(b"v5")),
            (Bytes::from_static(b"eee-001"), Bytes::from_static(b"v6")),
        ]);

        build_segmented_parent(
            &parent_path_a,
            object_store.clone(),
            extractor.clone(),
            settings.clone(),
            &table_a,
        )
        .await;
        build_segmented_parent(
            &parent_path_b,
            object_store.clone(),
            extractor.clone(),
            settings.clone(),
            &table_b,
        )
        .await;

        let range_a = (
            Bound::Included(Bytes::from_static(b"aaa")),
            Bound::Excluded(Bytes::from_static(b"ccc")),
        );
        let range_b = (
            Bound::Included(Bytes::from_static(b"ccc")),
            Bound::Unbounded,
        );

        run_segmented_clone(
            vec![
                CloneSourceSpec::new(parent_path_a.clone()).with_projection_range(range_a.clone()),
                CloneSourceSpec::new(parent_path_b.clone()).with_projection_range(range_b.clone()),
            ],
            &clone_path,
            object_store.clone(),
            None,
        )
        .await;

        assert_clone_segments(
            &clone_path,
            object_store.clone(),
            &[b"aaa", b"bbb", b"ccc", b"ddd", b"eee"],
        )
        .await;
        let store = ManifestStore::new(&clone_path, object_store.clone());
        let stored = store.read_latest_manifest().await.unwrap();
        assert_eq!(stored.manifest.external_dbs.len(), 2);

        let mut expected: BTreeMap<Bytes, Bytes> = BTreeMap::new();
        expected.extend(
            table_a
                .iter()
                .filter(|(k, _)| range_a.contains(*k))
                .map(|(k, v)| (k.clone(), v.clone())),
        );
        expected.extend(
            table_b
                .iter()
                .filter(|(k, _)| range_b.contains(*k))
                .map(|(k, v)| (k.clone(), v.clone())),
        );

        let clone_db =
            open_segmented_clone(&clone_path, object_store.clone(), extractor, settings).await;
        let mut full_iter = clone_db.scan(..).await.unwrap();
        test_utils::assert_ranged_db_scan(&expected, .., IterationOrder::Ascending, &mut full_iter)
            .await;
        assert_segment_prefix_scan(&clone_db, &expected, b"bbb", b"bbc").await;
        assert_segment_prefix_scan(&clone_db, &expected, b"ddd", b"dde").await;
        clone_db.close().await.unwrap();
    }

    #[cfg(feature = "wal_disable")]
    #[tokio::test]
    async fn should_union_projected_segmented_dbs_with_shared_segment() {
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let parent_path_a = Path::from("/tmp/test_parent_seg_shared_union_a");
        let parent_path_b = Path::from("/tmp/test_parent_seg_shared_union_b");
        let clone_path = Path::from("/tmp/test_clone_seg_shared_union");
        let extractor = Arc::new(test_utils::FixedThreeBytePrefixExtractor);
        let settings = wal_disabled_settings();

        // Both parents have a `bbb` segment with disjoint keys within it.
        // Per-source projection slices each parent so the union has to merge
        // their `bbb` segments — L0 SSTs from both parents land in the same
        // output segment.
        let table_a = BTreeMap::from([
            (Bytes::from_static(b"aaa-001"), Bytes::from_static(b"v1")),
            (Bytes::from_static(b"bbb-001"), Bytes::from_static(b"v2")),
            (Bytes::from_static(b"bbb-002"), Bytes::from_static(b"v3")),
        ]);
        let table_b = BTreeMap::from([
            (Bytes::from_static(b"bbb-007"), Bytes::from_static(b"v4")),
            (Bytes::from_static(b"bbb-008"), Bytes::from_static(b"v5")),
            (Bytes::from_static(b"ccc-001"), Bytes::from_static(b"v6")),
        ]);

        build_segmented_parent(
            &parent_path_a,
            object_store.clone(),
            extractor.clone(),
            settings.clone(),
            &table_a,
        )
        .await;
        build_segmented_parent(
            &parent_path_b,
            object_store.clone(),
            extractor.clone(),
            settings.clone(),
            &table_b,
        )
        .await;

        let range_a = (
            Bound::Included(Bytes::from_static(b"aaa")),
            Bound::Excluded(Bytes::from_static(b"bbb-005")),
        );
        let range_b = (
            Bound::Included(Bytes::from_static(b"bbb-005")),
            Bound::Unbounded,
        );

        run_segmented_clone(
            vec![
                CloneSourceSpec::new(parent_path_a.clone()).with_projection_range(range_a.clone()),
                CloneSourceSpec::new(parent_path_b.clone()).with_projection_range(range_b.clone()),
            ],
            &clone_path,
            object_store.clone(),
            None,
        )
        .await;

        assert_clone_segments(&clone_path, object_store.clone(), &[b"aaa", b"bbb", b"ccc"]).await;

        // The shared `bbb` segment in the union must hold one L0 SST
        // contributed by each parent.
        let store = ManifestStore::new(&clone_path, object_store.clone());
        let stored = store.read_latest_manifest().await.unwrap();
        let bbb_segment = stored
            .manifest
            .core
            .segments
            .iter()
            .find(|s| s.prefix == Bytes::from_static(b"bbb"))
            .expect("bbb segment");
        assert_eq!(bbb_segment.tree.l0.len(), 2);
        assert_eq!(stored.manifest.external_dbs.len(), 2);

        let mut expected: BTreeMap<Bytes, Bytes> = BTreeMap::new();
        expected.extend(
            table_a
                .iter()
                .filter(|(k, _)| range_a.contains(*k))
                .map(|(k, v)| (k.clone(), v.clone())),
        );
        expected.extend(
            table_b
                .iter()
                .filter(|(k, _)| range_b.contains(*k))
                .map(|(k, v)| (k.clone(), v.clone())),
        );

        let clone_db =
            open_segmented_clone(&clone_path, object_store.clone(), extractor, settings).await;
        let mut full_iter = clone_db.scan(..).await.unwrap();
        test_utils::assert_ranged_db_scan(&expected, .., IterationOrder::Ascending, &mut full_iter)
            .await;
        // The prefix scan on the shared `bbb` segment must surface rows from
        // both parents through a single segment-routed read path.
        assert_segment_prefix_scan(&clone_db, &expected, b"bbb", b"bbc").await;
        clone_db.close().await.unwrap();
    }

    #[cfg(feature = "wal_disable")]
    #[tokio::test]
    async fn should_project_segmented_db() {
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let parent_path = Path::from("/tmp/test_parent_seg_project");
        let clone_path = Path::from("/tmp/test_clone_seg_project");
        let extractor = Arc::new(test_utils::FixedThreeBytePrefixExtractor);
        let settings = wal_disabled_settings();
        let table = segmented_table();

        build_segmented_parent(
            &parent_path,
            object_store.clone(),
            extractor.clone(),
            settings.clone(),
            &table,
        )
        .await;

        let range = (
            Bound::Included(Bytes::from_static(b"bbb")),
            Bound::Excluded(Bytes::from_static(b"ddd")),
        );
        run_segmented_clone(
            vec![CloneSourceSpec::new(parent_path.clone())],
            &clone_path,
            object_store.clone(),
            Some(range),
        )
        .await;

        assert_clone_segments(&clone_path, object_store.clone(), &[b"bbb"]).await;

        let clone_db =
            open_segmented_clone(&clone_path, object_store.clone(), extractor, settings).await;
        let mut full_iter = clone_db.scan(..).await.unwrap();
        test_utils::assert_ranged_db_scan(
            &table,
            Bytes::from_static(b"bbb")..Bytes::from_static(b"ddd"),
            IterationOrder::Ascending,
            &mut full_iter,
        )
        .await;
        assert_segment_prefix_scan(&clone_db, &table, b"bbb", b"bbc").await;
        clone_db.close().await.unwrap();
    }

    /// Builds a WAL-disabled parent DB at `path` holding `table` in L0 (no
    /// segment extractor, so it can be unioned with other unsegmented sources).
    #[cfg(feature = "wal_disable")]
    async fn build_plain_wal_disabled_parent(
        path: &Path,
        object_store: Arc<dyn ObjectStore>,
        table: &BTreeMap<Bytes, Bytes>,
    ) {
        let db = Db::builder(path.clone(), object_store.clone())
            .with_settings(wal_disabled_settings())
            .build()
            .await
            .unwrap();
        test_utils::seed_database(&db, table, false).await.unwrap();
        db.flush_with_options(FlushOptions {
            flush_type: FlushType::MemTable,
        })
        .await
        .unwrap();
        db.close().await.unwrap();
    }

    /// Builds a WAL-disabled parent DB at `path` holding `table` in L0 (so the
    /// natural WAL range is empty), then manually extends the manifest's WAL
    /// range by one id and plants a WAL object at that id. `wal_bytes` controls
    /// whether the planted WAL is a fence (zero bytes) or carries data
    /// (non-empty). Returns the id of the planted WAL object.
    #[cfg(feature = "wal_disable")]
    async fn build_parent_with_planted_wal(
        path: &Path,
        object_store: Arc<dyn ObjectStore>,
        table: &BTreeMap<Bytes, Bytes>,
        wal_bytes: Bytes,
        system_clock: Arc<dyn SystemClock>,
    ) -> u64 {
        build_plain_wal_disabled_parent(path, object_store.clone(), table).await;

        // Extend the manifest's WAL range so that
        // `next_wal_sst_id - 1 > replay_after_wal_id`, forcing validation to
        // inspect the planted WAL object.
        let manifest_store = Arc::new(ManifestStore::new(path, object_store.clone()));
        let mut sm = StoredManifest::load(manifest_store, system_clock)
            .await
            .unwrap();
        let planted_wal_id = sm.db_state().next_wal_sst_id;
        let mut dirty = sm.prepare_dirty().unwrap();
        dirty.value.core.next_wal_sst_id = planted_wal_id + 1;
        sm.update(dirty).await.unwrap();

        // Plant the WAL object directly in the object store at the resolved path.
        use object_store::ObjectStoreExt;
        let wal_path =
            PathResolver::from_root(path.clone()).sst_path(&SsTableId::Wal(planted_wal_id));
        object_store.put(&wal_path, wal_bytes.into()).await.unwrap();

        planted_wal_id
    }

    /// Builds a WAL-disabled parent DB at `path` holding `table` in L0, then
    /// extends the manifest's WAL range by one id *without* planting any WAL
    /// object. This leaves a manifest-referenced WAL id whose object is missing,
    /// exercising the missing-object (`NotFound`) branch of
    /// `validate_no_data_wal`, which must fail.
    #[cfg(feature = "wal_disable")]
    async fn build_parent_with_missing_wal(
        path: &Path,
        object_store: Arc<dyn ObjectStore>,
        table: &BTreeMap<Bytes, Bytes>,
        system_clock: Arc<dyn SystemClock>,
    ) {
        build_plain_wal_disabled_parent(path, object_store.clone(), table).await;

        // Extend the manifest's WAL range so that
        // `next_wal_sst_id - 1 > replay_after_wal_id`, forcing validation to
        // inspect a WAL object that was never written.
        let manifest_store = Arc::new(ManifestStore::new(path, object_store.clone()));
        let mut sm = StoredManifest::load(manifest_store, system_clock)
            .await
            .unwrap();
        let mut dirty = sm.prepare_dirty().unwrap();
        dirty.value.core.next_wal_sst_id += 1;
        sm.update(dirty).await.unwrap();
    }

    /// A union clone whose source references only a zero-byte (fence) WAL above
    /// `replay_after_wal_id` must SUCCEED: the fence WAL holds no data and the
    /// union clone drops WAL objects anyway.
    #[cfg(feature = "wal_disable")]
    #[tokio::test]
    async fn should_union_clone_with_fence_only_wal_succeeds() {
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let system_clock: Arc<dyn SystemClock> = Arc::new(DefaultSystemClock::new());
        let parent_path_a = Path::from("/tmp/test_parent_fence_union_a");
        let parent_path_b = Path::from("/tmp/test_parent_fence_union_b");
        let clone_path = Path::from("/tmp/test_clone_fence_union");

        let table_a = BTreeMap::from([
            (Bytes::from_static(b"aaa-001"), Bytes::from_static(b"v1")),
            (Bytes::from_static(b"aaa-002"), Bytes::from_static(b"v2")),
        ]);
        let table_b = BTreeMap::from([
            (Bytes::from_static(b"zzz-001"), Bytes::from_static(b"v3")),
            (Bytes::from_static(b"zzz-002"), Bytes::from_static(b"v4")),
        ]);

        // Source A carries a fence (zero-byte) WAL above replay_after_wal_id.
        build_parent_with_planted_wal(
            &parent_path_a,
            object_store.clone(),
            &table_a,
            Bytes::new(),
            system_clock.clone(),
        )
        .await;
        // Source B has no extra WAL.
        build_plain_wal_disabled_parent(&parent_path_b, object_store.clone(), &table_b).await;

        create_native_clone(
            vec![
                CloneSourceSpec::new(parent_path_a.clone()),
                CloneSourceSpec::new(parent_path_b.clone()),
            ],
            clone_path.clone(),
            ObjectStores::new(object_store.clone(), Some(object_store.clone())),
            Arc::new(FailPointRegistry::new()),
            system_clock.clone(),
            Arc::new(DbRand::default()),
            None,
            None,
            None,
        )
        .await
        .expect("union clone with a fence-only WAL should succeed");

        // The unioned clone should contain data from both sources.
        let mut expected: BTreeMap<Bytes, Bytes> = table_a.clone();
        expected.extend(table_b.clone());
        let clone_db = Db::builder(clone_path.clone(), object_store.clone())
            .with_settings(wal_disabled_settings())
            .build()
            .await
            .unwrap();
        let mut iter = clone_db.scan(..).await.unwrap();
        test_utils::assert_ranged_db_scan(&expected, .., IterationOrder::Ascending, &mut iter)
            .await;
        clone_db.close().await.unwrap();
    }

    /// A union clone whose source references a real (non-empty) data WAL above
    /// `replay_after_wal_id` must FAIL with `InvalidCloneSourceWithWal`, since
    /// the union clone would silently drop that WAL data.
    #[cfg(feature = "wal_disable")]
    #[tokio::test]
    async fn should_fail_union_clone_with_data_wal() {
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let system_clock: Arc<dyn SystemClock> = Arc::new(DefaultSystemClock::new());
        let parent_path_a = Path::from("/tmp/test_parent_data_wal_union_a");
        let parent_path_b = Path::from("/tmp/test_parent_data_wal_union_b");
        let clone_path = Path::from("/tmp/test_clone_data_wal_union");

        let table_a = BTreeMap::from([
            (Bytes::from_static(b"aaa-001"), Bytes::from_static(b"v1")),
            (Bytes::from_static(b"aaa-002"), Bytes::from_static(b"v2")),
        ]);
        let table_b = BTreeMap::from([
            (Bytes::from_static(b"zzz-001"), Bytes::from_static(b"v3")),
            (Bytes::from_static(b"zzz-002"), Bytes::from_static(b"v4")),
        ]);

        // Source A carries a real data WAL (non-empty) above replay_after_wal_id.
        build_parent_with_planted_wal(
            &parent_path_a,
            object_store.clone(),
            &table_a,
            Bytes::from_static(b"this-is-not-a-fence-it-has-data"),
            system_clock.clone(),
        )
        .await;
        build_plain_wal_disabled_parent(&parent_path_b, object_store.clone(), &table_b).await;

        let err = create_native_clone(
            vec![
                CloneSourceSpec::new(parent_path_a.clone()),
                CloneSourceSpec::new(parent_path_b.clone()),
            ],
            clone_path.clone(),
            ObjectStores::new(object_store.clone(), Some(object_store.clone())),
            Arc::new(FailPointRegistry::new()),
            system_clock.clone(),
            Arc::new(DbRand::default()),
            None,
            None,
            None,
        )
        .await
        .unwrap_err();

        match err {
            SlateDBError::InvalidCloneSourceWithWal { paths } => {
                assert!(paths.contains(&parent_path_a));
            }
            other => panic!("expected InvalidCloneSourceWithWal, got {other:?}"),
        }
    }

    /// A union clone whose source references a WAL id that has no backing object
    /// (HEAD returns `NotFound`) must FAIL: a WAL object missing within the
    /// manifest's WAL bounds violates an invariant and signals a misconfigured
    /// WAL object store or data loss.
    #[cfg(feature = "wal_disable")]
    #[tokio::test]
    async fn should_fail_union_clone_with_missing_wal() {
        let object_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
        let system_clock: Arc<dyn SystemClock> = Arc::new(DefaultSystemClock::new());
        let parent_path_a = Path::from("/tmp/test_parent_missing_wal_union_a");
        let parent_path_b = Path::from("/tmp/test_parent_missing_wal_union_b");
        let clone_path = Path::from("/tmp/test_clone_missing_wal_union");

        let table_a = BTreeMap::from([
            (Bytes::from_static(b"aaa-001"), Bytes::from_static(b"v1")),
            (Bytes::from_static(b"aaa-002"), Bytes::from_static(b"v2")),
        ]);
        let table_b = BTreeMap::from([
            (Bytes::from_static(b"zzz-001"), Bytes::from_static(b"v3")),
            (Bytes::from_static(b"zzz-002"), Bytes::from_static(b"v4")),
        ]);

        // Source A references a WAL id above replay_after_wal_id whose object is
        // missing.
        build_parent_with_missing_wal(
            &parent_path_a,
            object_store.clone(),
            &table_a,
            system_clock.clone(),
        )
        .await;
        build_plain_wal_disabled_parent(&parent_path_b, object_store.clone(), &table_b).await;

        let expected_missing_wal_path = PathResolver::from_root(parent_path_a.clone())
            .sst_path(&SsTableId::Wal({
                let manifest_store =
                    Arc::new(ManifestStore::new(&parent_path_a, object_store.clone()));
                let sm = StoredManifest::load(manifest_store, system_clock.clone())
                    .await
                    .unwrap();
                sm.manifest().core.replay_after_wal_id + 1
            }))
            .to_string();

        let err = create_native_clone(
            vec![
                CloneSourceSpec::new(parent_path_a.clone()),
                CloneSourceSpec::new(parent_path_b.clone()),
            ],
            clone_path.clone(),
            ObjectStores::new(object_store.clone(), Some(object_store.clone())),
            Arc::new(FailPointRegistry::new()),
            system_clock.clone(),
            Arc::new(DbRand::default()),
            None,
            None,
            None,
        )
        .await
        .unwrap_err();

        assert!(
            matches!(
                err,
                SlateDBError::WalUnavailable(ref source)
                    if matches!(
                        source.downcast_ref::<ObjectStoreError>(),
                        Some(ObjectStoreError::NotFound { path, .. })
                            if path == &expected_missing_wal_path
                    )
            ),
            "expected NotFound for the missing WAL object, got {err:?}"
        );
    }
}