lix 0.17.1

Embeddable version control for apps and AI agents.
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
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::ops::Bound;

use crate::binary_cas::{BlobChunkReceipt, BlobId, ChunkHash};
use crate::storage_adapter::{
    MAX_SCAN_PAGE_ROWS, Storage, StorageBeginScanOptions, StorageCoreProjection,
    StorageGetManyRequest, StorageGetOptions, StorageKey, StorageKeyRange, StoragePrecondition,
    StorageProjectedValue, StorageReadOptions, StorageSpace, StorageSpaceId, StorageValue,
    StorageWriteOptions, ValueSemantics, exact_get_many,
};
use crate::transaction::{begin_commit_boundary, commit_at_boundary};
use crate::{Blob, LixError};

use super::SessionContext;

pub(crate) const UPLOAD_STATE_SPACE: StorageSpace = StorageSpace::declare(
    StorageSpaceId(0x0007_0006),
    "session.file_upload.v2",
    ValueSemantics::Mutable,
);
pub(crate) const UPLOAD_MANIFEST_LEAF_SPACE: StorageSpace = StorageSpace::declare(
    StorageSpaceId(0x0007_0007),
    "session.file_upload_manifest_leaf.v2",
    ValueSemantics::Mutable,
);
pub const FILE_UPLOAD_PART_BYTES: usize = 16 * 1024 * 1024;
const MAX_FILE_UPLOAD_BYTES: u64 = 20 * 1024 * 1024 * 1024;
const UPLOAD_PART_WINDOW: u32 = 4;
const UPLOAD_MANIFEST_LEAF_MAGIC: &[u8; 8] = b"LIXUML2\0";

/// Collects active resumable-upload receipt chunks and stages receipt cleanup.
/// Upload leaves contain hashes and sizes only; they are never a second payload
/// authority. Open uploads retain their receipt chunks. A completed state is
/// only an idempotency receipt: the published file reference is the sole blob
/// root, so a completed state with no live file root can be retired.
pub(crate) async fn stage_reclaimable_upload_receipts(
    store: &(impl crate::storage_adapter::StorageAdapterRead + ?Sized),
    writes: &mut crate::storage_adapter::StorageWriteSet,
    live_blob_roots: &BTreeSet<BlobId>,
) -> Result<BTreeMap<ChunkHash, u64>, LixError> {
    let mut states = Vec::<(String, UploadState)>::new();
    let mut state_cursor = store
        .begin_scan(
            UPLOAD_STATE_SPACE,
            StorageKeyRange {
                lower: Bound::Unbounded,
                upper: Bound::Unbounded,
            },
            StorageBeginScanOptions {
                projection: StorageCoreProjection::FullValue,
                ..StorageBeginScanOptions::default()
            },
        )
        .await?;
    loop {
        let (page, page_has_more) = state_cursor
            .next_page(MAX_SCAN_PAGE_ROWS)
            .await?
            .into_parts();
        for entry in page {
            let upload_id = std::str::from_utf8(&entry.key.0)
                .map_err(|_| invalid_upload_storage("upload state key is not UTF-8"))?
                .to_owned();
            validate_upload_id_for_storage(&upload_id)?;
            let StorageProjectedValue::FullValue(value) = entry.value else {
                return Err(invalid_upload_storage(
                    "upload state scan omitted its value",
                ));
            };
            let state = serde_json::from_slice(&value)
                .map_err(|_| invalid_upload_storage("upload state value is invalid JSON"))?;
            states.push((upload_id, state));
        }
        if !page_has_more {
            break;
        }
    }

    let mut open_ids = BTreeSet::new();
    for (upload_id, state) in states {
        match state {
            UploadState::Open(_) => {
                open_ids.insert(upload_id);
            }
            UploadState::Complete(complete) => {
                if !live_blob_roots.contains(&BlobId::from_bytes(complete.blob_id)) {
                    writes.delete(UPLOAD_STATE_SPACE, upload_state_key(&upload_id)?);
                }
            }
        }
    }

    let mut upload_chunks = BTreeMap::new();
    let mut leaf_cursor = store
        .begin_scan(
            UPLOAD_MANIFEST_LEAF_SPACE,
            StorageKeyRange {
                lower: Bound::Unbounded,
                upper: Bound::Unbounded,
            },
            StorageBeginScanOptions {
                projection: StorageCoreProjection::FullValue,
                ..StorageBeginScanOptions::default()
            },
        )
        .await?;
    loop {
        let (page, page_has_more) = leaf_cursor
            .next_page(MAX_SCAN_PAGE_ROWS)
            .await?
            .into_parts();
        for entry in page {
            let upload_id = decode_upload_manifest_leaf_upload_id(&entry.key)?;
            if !open_ids.contains(&upload_id) {
                // Finalized or state-less receipts are not active roots; the
                // published file snapshot, if any, owns the blob instead.
                writes.delete(UPLOAD_MANIFEST_LEAF_SPACE, entry.key);
                continue;
            }
            let StorageProjectedValue::FullValue(value) = entry.value else {
                return Err(invalid_upload_storage(
                    "active upload manifest leaf scan omitted its value",
                ));
            };
            let leaf = decode_upload_manifest_leaf(&value)?;
            for chunk in leaf.chunks {
                match upload_chunks.entry(chunk.hash) {
                    std::collections::btree_map::Entry::Vacant(entry) => {
                        entry.insert(chunk.size_bytes);
                    }
                    std::collections::btree_map::Entry::Occupied(entry)
                        if *entry.get() != chunk.size_bytes =>
                    {
                        return Err(invalid_upload_storage(format!(
                            "active upload chunk '{}' has conflicting declared sizes {} and {}",
                            chunk.hash.to_hex(),
                            entry.get(),
                            chunk.size_bytes
                        )));
                    }
                    std::collections::btree_map::Entry::Occupied(_) => {}
                }
            }
        }
        if !page_has_more {
            break;
        }
    }

    Ok(upload_chunks)
}

fn decode_upload_manifest_leaf_upload_id(key: &StorageKey) -> Result<String, LixError> {
    if key.0.len() < 2 + 4 {
        return Err(invalid_upload_storage(
            "upload manifest leaf key is too short",
        ));
    }
    let id_len = usize::from(u16::from_be_bytes([key.0[0], key.0[1]]));
    if key.0.len() != 2 + id_len + 4 {
        return Err(invalid_upload_storage(
            "upload manifest leaf key has an invalid upload id length",
        ));
    }
    let upload_id = std::str::from_utf8(&key.0[2..2 + id_len])
        .map_err(|_| invalid_upload_storage("upload manifest leaf id is not UTF-8"))?
        .to_owned();
    validate_upload_id_for_storage(&upload_id)?;
    Ok(upload_id)
}

fn validate_upload_id_for_storage(upload_id: &str) -> Result<(), LixError> {
    if upload_id.is_empty() || upload_id.len() > 200 || !upload_id.is_ascii() {
        return Err(invalid_upload_storage("upload id is not a valid ASCII key"));
    }
    Ok(())
}

fn invalid_upload_storage(message: impl Into<String>) -> LixError {
    LixError::new(LixError::CODE_STORAGE_ERROR, message)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FileUploadProgress {
    pub next_offset: u64,
    pub total_size: u64,
    pub finalized: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
enum UploadState {
    Open(UploadOpen),
    Complete(UploadComplete),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct UploadOpen {
    path: String,
    total_size: u64,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct UploadManifestLeaf {
    part_size: u64,
    chunks: Vec<BlobChunkReceipt>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct UploadComplete {
    path: String,
    total_size: u64,
    blob_id: [u8; 32],
    part_identities: Vec<[u8; 32]>,
}

impl<StorageImpl> SessionContext<StorageImpl>
where
    StorageImpl: Storage + Clone + Send + Sync + 'static,
{
    /// Stages one aligned part through the ordinary file-upsert abstraction.
    /// Up to four 16 MiB parts may complete out of order. Each request persists
    /// one manifest leaf plus its missing immutable payloads; publication folds
    /// the leaves into the root manifest atomically with ordinary file history.
    pub(crate) async fn upsert_file_content_part(
        &self,
        upload_id: String,
        path: String,
        start: u64,
        total_size: u64,
        content: Blob,
    ) -> Result<FileUploadProgress, LixError> {
        self.ensure_open()?;
        crate::common::LixPath::try_from_file_path(&path)?;
        validate_upload_request(&upload_id, start, total_size, content.len())?;
        let operation_guard = self.begin_waitable_session_operation().await?;
        let state_key = upload_state_key(&upload_id)?;
        let part_number = u32::try_from(start / FILE_UPLOAD_PART_BYTES as u64)
            .map_err(|_| invalid_upload("upload part number exceeds u32"))?;
        let leaf_key = upload_manifest_leaf_key(&upload_id, part_number)?;
        let state = UploadOpen {
            path: path.clone(),
            total_size,
        };

        let mut last_error = None;
        for _attempt in 0..UPLOAD_PART_WINDOW {
            let read = self
                .storage
                .begin_read(StorageReadOptions::default())
                .await?;
            let loaded_state = load_upload_state(&read, &state_key).await?;
            match &loaded_state {
                Some(UploadState::Complete(complete)) => {
                    validate_upload_binding(&complete.path, complete.total_size, &path, total_size)?
                }
                Some(UploadState::Open(existing)) => {
                    validate_upload_binding(
                        &existing.path,
                        existing.total_size,
                        &path,
                        total_size,
                    )?;
                }
                None => {}
            }

            let mut writes = self.storage.new_write_set();
            let mut writer = self
                .binary_cas
                .writer_skipping_existing_chunks(&read, &mut writes);
            let chunks = if content.is_empty() {
                Vec::new()
            } else {
                writer.stage_upload_part(&content).await?
            };
            drop(writer);
            let leaf = UploadManifestLeaf {
                part_size: content.len() as u64,
                chunks,
            };
            if let Some(UploadState::Complete(complete)) = &loaded_state {
                if complete.part_identities.get(part_number as usize)
                    != Some(&upload_manifest_leaf_identity(&leaf))
                {
                    return Err(invalid_upload(
                        "completed upload part was replayed with different bytes",
                    ));
                }
                return Ok(FileUploadProgress {
                    next_offset: complete.total_size,
                    total_size: complete.total_size,
                    finalized: true,
                });
            }

            if let Some(existing_leaf) = load_upload_manifest_leaf(&read, &leaf_key).await? {
                if existing_leaf != leaf {
                    return Err(invalid_upload(
                        "upload part was replayed with different bytes",
                    ));
                }
                let progress = load_upload_progress(&read, &upload_id, total_size).await?;
                drop(read);
                drop(operation_guard);
                return self
                    .publish_completed_upload(upload_id, state_key, state, progress)
                    .await;
            }
            let progress = load_upload_progress(&read, &upload_id, total_size).await?;
            let next_part = u32::try_from(progress.next_offset / FILE_UPLOAD_PART_BYTES as u64)
                .map_err(|_| invalid_upload("upload progress exceeds u32"))?;
            if part_number >= next_part.saturating_add(UPLOAD_PART_WINDOW) {
                return Err(invalid_upload(
                    "upload part is outside the four-part completion window",
                ));
            }

            stage_upload_manifest_leaf(&mut writes, leaf_key.clone(), &leaf)?;
            let mut preconditions = vec![StoragePrecondition::KeyAbsent {
                space: UPLOAD_MANIFEST_LEAF_SPACE,
                key: leaf_key.clone(),
            }];
            match loaded_state {
                Some(UploadState::Open(existing)) => {
                    preconditions.push(StoragePrecondition::KeyValueEquals {
                        space: UPLOAD_STATE_SPACE,
                        key: state_key.clone(),
                        expected: Bytes::from(encode_upload_state(&UploadState::Open(existing))?),
                    });
                }
                None => {
                    stage_upload_state(
                        &mut writes,
                        state_key.clone(),
                        &UploadState::Open(state.clone()),
                    )?;
                    preconditions.push(StoragePrecondition::KeyAbsent {
                        space: UPLOAD_STATE_SPACE,
                        key: state_key.clone(),
                    });
                }
                Some(UploadState::Complete(_)) => unreachable!("complete state returned above"),
            }
            crate::binary_cas::stage_cas_publication_fence(&read, &mut writes, &mut preconditions)
                .await?;
            drop(read);

            let commit_boundary = self.transaction_commit_boundary();
            let _commit_guard = begin_commit_boundary(Some(&commit_boundary));
            let result = async {
                let prepared = self
                    .storage
                    .prepare_write_set(
                        writes,
                        StorageWriteOptions {
                            preconditions,
                            await_durable: true,
                            ..StorageWriteOptions::default()
                        },
                    )
                    .await?;
                commit_at_boundary(Some(&commit_boundary), || async move {
                    let (_, stats) = prepared.commit().await?;
                    Ok(stats)
                })
                .await
            }
            .await;
            match result {
                Ok(stats) => {
                    #[cfg(feature = "storage-benches")]
                    crate::storage_bench::record_media_upload_manifest_leaf(leaf.chunks.len());
                    self.observe_invalidation.bump_if_storage_changed(&stats);
                    let read = self
                        .storage
                        .begin_read(StorageReadOptions::default())
                        .await?;
                    let progress = load_upload_progress(&read, &upload_id, total_size).await?;
                    drop(read);
                    drop(operation_guard);
                    return self
                        .publish_completed_upload(upload_id, state_key, state, progress)
                        .await;
                }
                Err(error) => last_error = Some(error),
            }
        }
        Err(last_error.expect("bounded upload retry loop records an error"))
    }

    async fn publish_completed_upload(
        &self,
        upload_id: String,
        state_key: StorageKey,
        state: UploadOpen,
        progress: FileUploadProgress,
    ) -> Result<FileUploadProgress, LixError> {
        if progress.next_offset != state.total_size {
            return Ok(progress);
        }
        let read = self
            .storage
            .begin_read(StorageReadOptions::default())
            .await?;
        let (receipts, part_identities) =
            load_upload_manifest_leaves(&read, &upload_id, state.total_size).await?;
        let mut finalization_writes = self.storage.new_write_set();
        finalization_writes
            .delete_range_exclusive(
                UPLOAD_MANIFEST_LEAF_SPACE,
                upload_manifest_leaf_range(&upload_id)?,
            )
            .map_err(LixError::from)?;
        let receipt = self
            .binary_cas
            .writer_skipping_existing_chunks(&read, &mut finalization_writes)
            .stage_upload_manifest(&receipts)?;
        let complete = UploadState::Complete(UploadComplete {
            path: state.path.clone(),
            total_size: state.total_size,
            blob_id: receipt.hash.into_bytes(),
            part_identities,
        });
        let publication_blob_id = receipt.hash;
        let expected_blob_id = receipt.hash.into_bytes();
        stage_upload_state(&mut finalization_writes, state_key.clone(), &complete)?;
        let expected_open = encode_upload_state(&UploadState::Open(state.clone()))?;
        let finalization_preconditions = vec![StoragePrecondition::KeyValueEquals {
            space: UPLOAD_STATE_SPACE,
            key: state_key,
            expected: Bytes::from(expected_open),
        }];
        drop(read);
        let path = state.path.clone();
        let write_access = self.begin_session_write_access().await?;
        let publish_result = self
            .with_write_transaction_reserved_lending(
                write_access,
                async move |transaction| {
                    transaction.stage_atomic_cas_publication(
                        finalization_writes,
                        finalization_preconditions,
                        publication_blob_id,
                    )?;
                    crate::sql2::execute_fast_lix_file_prepared_path_write(
                        transaction,
                        path,
                        receipt,
                    )
                    .await?
                    .ok_or_else(|| {
                        LixError::new(
                            LixError::CODE_CONSTRAINT_VIOLATION,
                            "resumable file publication requires an unambiguous filesystem layout",
                        )
                    })
                },
                |_| Ok(()),
            )
            .await;
        if let Err(error) = publish_result {
            let read = self
                .storage
                .begin_read(StorageReadOptions::default())
                .await?;
            if matches!(
                load_upload_state(&read, &upload_state_key(&upload_id)?).await?,
                Some(UploadState::Complete(complete))
                    if complete.path == state.path
                        && complete.total_size == state.total_size
                        && complete.blob_id == expected_blob_id
            ) {
                return Ok(FileUploadProgress {
                    next_offset: state.total_size,
                    total_size: state.total_size,
                    finalized: true,
                });
            }
            return Err(error);
        }
        Ok(FileUploadProgress {
            next_offset: state.total_size,
            total_size: state.total_size,
            finalized: true,
        })
    }
}

fn validate_upload_request(
    upload_id: &str,
    start: u64,
    total_size: u64,
    part_len: usize,
) -> Result<(), LixError> {
    if upload_id.is_empty() || upload_id.len() > 200 || !upload_id.is_ascii() {
        return Err(invalid_upload("upload id must be 1-200 ASCII bytes"));
    }
    if total_size > MAX_FILE_UPLOAD_BYTES {
        return Err(invalid_upload("file exceeds the 20 GiB media target"));
    }
    let end = start
        .checked_add(part_len as u64)
        .ok_or_else(|| invalid_upload("upload range exceeds u64"))?;
    if end > total_size || part_len > FILE_UPLOAD_PART_BYTES {
        return Err(invalid_upload(
            "upload part is outside the declared file size",
        ));
    }
    if end < total_size && part_len != FILE_UPLOAD_PART_BYTES {
        return Err(invalid_upload(
            "non-final upload parts must be exactly 16 MiB",
        ));
    }
    if start % FILE_UPLOAD_PART_BYTES as u64 != 0 {
        return Err(invalid_upload("upload part offset must be 16 MiB aligned"));
    }
    Ok(())
}

fn upload_state_key(upload_id: &str) -> Result<StorageKey, LixError> {
    if upload_id.is_empty() || upload_id.len() > 200 || !upload_id.is_ascii() {
        return Err(invalid_upload("upload id must be 1-200 ASCII bytes"));
    }
    Ok(StorageKey(Bytes::copy_from_slice(upload_id.as_bytes())))
}

async fn load_upload_state(
    store: &impl crate::storage_adapter::StorageAdapterRead,
    key: &StorageKey,
) -> Result<Option<UploadState>, LixError> {
    let values = exact_get_many(
        store,
        &[StorageGetManyRequest {
            space: UPLOAD_STATE_SPACE,
            keys: std::slice::from_ref(key),
            opts: StorageGetOptions {
                projection: StorageCoreProjection::FullValue,
            },
        }],
    )
    .await?;
    let Some(value) = values.values.into_iter().next().flatten() else {
        return Ok(None);
    };
    let StorageProjectedValue::FullValue(value) = value else {
        return Err(LixError::new(
            LixError::CODE_INTERNAL_ERROR,
            "upload state read returned no value bytes",
        ));
    };
    serde_json::from_slice(&value).map(Some).map_err(|error| {
        LixError::new(
            LixError::CODE_STORAGE_ERROR,
            format!("decode file upload state: {error}"),
        )
    })
}

fn stage_upload_state(
    writes: &mut crate::storage_adapter::StorageWriteSet,
    key: StorageKey,
    state: &UploadState,
) -> Result<(), LixError> {
    let value = encode_upload_state(state)?;
    writes.put(
        UPLOAD_STATE_SPACE,
        key,
        StorageValue {
            bytes: Bytes::from(value),
        },
    );
    Ok(())
}

fn encode_upload_state(state: &UploadState) -> Result<Vec<u8>, LixError> {
    serde_json::to_vec(state).map_err(|error| {
        LixError::new(
            LixError::CODE_INTERNAL_ERROR,
            format!("encode file upload state: {error}"),
        )
    })
}

fn validate_upload_binding(
    existing_path: &str,
    existing_total_size: u64,
    path: &str,
    total_size: u64,
) -> Result<(), LixError> {
    if existing_path != path || existing_total_size != total_size {
        return Err(invalid_upload(
            "upload id is already bound to a different path or size",
        ));
    }
    Ok(())
}

fn upload_manifest_leaf_prefix(upload_id: &str) -> Result<Vec<u8>, LixError> {
    let id_len = u16::try_from(upload_id.len())
        .map_err(|_| invalid_upload("upload id exceeds receipt key limit"))?;
    let mut key = Vec::with_capacity(2 + upload_id.len());
    key.extend_from_slice(&id_len.to_be_bytes());
    key.extend_from_slice(upload_id.as_bytes());
    Ok(key)
}

fn upload_manifest_leaf_key(upload_id: &str, part_number: u32) -> Result<StorageKey, LixError> {
    let mut key = upload_manifest_leaf_prefix(upload_id)?;
    key.extend_from_slice(&part_number.to_be_bytes());
    Ok(StorageKey(Bytes::from(key)))
}

fn stage_upload_manifest_leaf(
    writes: &mut crate::storage_adapter::StorageWriteSet,
    key: StorageKey,
    leaf: &UploadManifestLeaf,
) -> Result<(), LixError> {
    writes.put(
        UPLOAD_MANIFEST_LEAF_SPACE,
        key,
        StorageValue {
            bytes: Bytes::from(encode_upload_manifest_leaf(leaf)?),
        },
    );
    Ok(())
}

fn encode_upload_manifest_leaf(leaf: &UploadManifestLeaf) -> Result<Vec<u8>, LixError> {
    let chunk_count = u32::try_from(leaf.chunks.len())
        .map_err(|_| invalid_upload("upload manifest leaf has too many chunks"))?;
    let mut value = Vec::with_capacity(
        UPLOAD_MANIFEST_LEAF_MAGIC.len() + 8 + 4 + leaf.chunks.len().saturating_mul(40),
    );
    value.extend_from_slice(UPLOAD_MANIFEST_LEAF_MAGIC);
    value.extend_from_slice(&leaf.part_size.to_be_bytes());
    value.extend_from_slice(&chunk_count.to_be_bytes());
    for chunk in &leaf.chunks {
        value.extend_from_slice(chunk.hash.as_bytes());
        value.extend_from_slice(&chunk.size_bytes.to_be_bytes());
    }
    Ok(value)
}

fn upload_manifest_leaf_identity(leaf: &UploadManifestLeaf) -> [u8; 32] {
    let mut identity = blake3::Hasher::new_derive_key("lix upload manifest leaf identity v1");
    identity.update(&leaf.part_size.to_le_bytes());
    for chunk in &leaf.chunks {
        identity.update(chunk.hash.as_bytes());
        identity.update(&chunk.size_bytes.to_le_bytes());
    }
    *identity.finalize().as_bytes()
}

fn decode_upload_manifest_leaf(value: &[u8]) -> Result<UploadManifestLeaf, LixError> {
    const HEADER_BYTES: usize = 8 + 8 + 4;
    if value.len() < HEADER_BYTES || !value.starts_with(UPLOAD_MANIFEST_LEAF_MAGIC) {
        return Err(LixError::new(
            LixError::CODE_STORAGE_ERROR,
            "upload manifest leaf header is invalid",
        ));
    }
    let part_size = u64::from_be_bytes(
        value[8..16]
            .try_into()
            .expect("upload manifest leaf part size"),
    );
    let chunk_count = u32::from_be_bytes(
        value[16..20]
            .try_into()
            .expect("upload manifest leaf chunk count"),
    ) as usize;
    let expected_len = HEADER_BYTES
        .checked_add(chunk_count.saturating_mul(40))
        .ok_or_else(|| invalid_upload("upload manifest leaf size overflows usize"))?;
    if value.len() != expected_len {
        return Err(LixError::new(
            LixError::CODE_STORAGE_ERROR,
            "upload manifest leaf body is invalid",
        ));
    }
    let mut chunks = Vec::with_capacity(chunk_count);
    for encoded in value[HEADER_BYTES..].chunks_exact(40) {
        let mut hash = [0; 32];
        hash.copy_from_slice(&encoded[..32]);
        let size_bytes = u64::from_be_bytes(
            encoded[32..]
                .try_into()
                .expect("upload manifest leaf chunk size"),
        );
        chunks.push(BlobChunkReceipt {
            hash: ChunkHash::from_bytes(hash),
            size_bytes,
        });
    }
    let encoded_part_size = chunks
        .iter()
        .try_fold(0_u64, |total, chunk| total.checked_add(chunk.size_bytes));
    if encoded_part_size != Some(part_size) {
        return Err(LixError::new(
            LixError::CODE_STORAGE_ERROR,
            "upload manifest leaf chunk sizes do not match its part size",
        ));
    }
    Ok(UploadManifestLeaf { part_size, chunks })
}

async fn load_upload_manifest_leaf(
    store: &impl crate::storage_adapter::StorageAdapterRead,
    key: &StorageKey,
) -> Result<Option<UploadManifestLeaf>, LixError> {
    let values = exact_get_many(
        store,
        &[StorageGetManyRequest {
            space: UPLOAD_MANIFEST_LEAF_SPACE,
            keys: std::slice::from_ref(key),
            opts: StorageGetOptions {
                projection: StorageCoreProjection::FullValue,
            },
        }],
    )
    .await?;
    let Some(StorageProjectedValue::FullValue(value)) = values.values.into_iter().next().flatten()
    else {
        return Ok(None);
    };
    decode_upload_manifest_leaf(&value).map(Some)
}

async fn load_upload_progress(
    store: &impl crate::storage_adapter::StorageAdapterRead,
    upload_id: &str,
    total_size: u64,
) -> Result<FileUploadProgress, LixError> {
    let range = upload_manifest_leaf_range(upload_id)?;
    let mut expected_part = 0_u32;
    let mut cursor = store
        .begin_scan(
            UPLOAD_MANIFEST_LEAF_SPACE,
            range,
            StorageBeginScanOptions {
                projection: StorageCoreProjection::KeyOnly,
                ..StorageBeginScanOptions::default()
            },
        )
        .await?;
    'pages: loop {
        let (page, page_has_more) = cursor.next_page(MAX_SCAN_PAGE_ROWS).await?.into_parts();
        for entry in &page {
            let part_number = decode_upload_manifest_leaf_part_number(upload_id, &entry.key)?;
            if part_number != expected_part {
                break 'pages;
            }
            expected_part = expected_part
                .checked_add(1)
                .ok_or_else(|| invalid_upload("upload part count exceeds u32"))?;
        }
        if !page_has_more {
            break;
        }
    }
    let next_offset = u64::from(expected_part)
        .saturating_mul(FILE_UPLOAD_PART_BYTES as u64)
        .min(total_size);
    Ok(FileUploadProgress {
        next_offset,
        total_size,
        finalized: false,
    })
}

async fn load_upload_manifest_leaves(
    store: &impl crate::storage_adapter::StorageAdapterRead,
    upload_id: &str,
    total_size: u64,
) -> Result<(Vec<BlobChunkReceipt>, Vec<[u8; 32]>), LixError> {
    let range = upload_manifest_leaf_range(upload_id)?;
    let expected_leaf_count = upload_part_count(total_size)?;
    let mut receipts = Vec::new();
    let mut part_identities = Vec::new();
    let mut next_part = 0_u32;
    let mut cursor = store
        .begin_scan(
            UPLOAD_MANIFEST_LEAF_SPACE,
            range,
            StorageBeginScanOptions {
                projection: StorageCoreProjection::FullValue,
                ..StorageBeginScanOptions::default()
            },
        )
        .await?;
    loop {
        let (page, page_has_more) = cursor.next_page(MAX_SCAN_PAGE_ROWS).await?.into_parts();
        for entry in &page {
            let part_number = decode_upload_manifest_leaf_part_number(upload_id, &entry.key)?;
            if part_number != next_part {
                return Err(LixError::new(
                    LixError::CODE_STORAGE_ERROR,
                    "upload manifest leaf sequence is incomplete",
                ));
            }
            let StorageProjectedValue::FullValue(value) = &entry.value else {
                return Err(LixError::new(
                    LixError::CODE_INTERNAL_ERROR,
                    "upload manifest leaf read returned no value bytes",
                ));
            };
            let leaf = decode_upload_manifest_leaf(value)?;
            let expected_part_size = upload_part_size(total_size, part_number)?;
            if leaf.part_size != expected_part_size {
                return Err(LixError::new(
                    LixError::CODE_STORAGE_ERROR,
                    "upload manifest leaf has the wrong part size",
                ));
            }
            part_identities.push(upload_manifest_leaf_identity(&leaf));
            receipts.extend(leaf.chunks);
            next_part = next_part
                .checked_add(1)
                .ok_or_else(|| invalid_upload("upload part count exceeds u32"))?;
        }
        if !page_has_more {
            break;
        }
    }
    if next_part != expected_leaf_count {
        return Err(LixError::new(
            LixError::CODE_STORAGE_ERROR,
            "upload manifest leaf sequence is incomplete",
        ));
    }
    Ok((receipts, part_identities))
}

fn decode_upload_manifest_leaf_part_number(
    upload_id: &str,
    key: &StorageKey,
) -> Result<u32, LixError> {
    let prefix = upload_manifest_leaf_prefix(upload_id)?;
    let suffix = key.0.strip_prefix(prefix.as_slice()).ok_or_else(|| {
        LixError::new(
            LixError::CODE_STORAGE_ERROR,
            "upload manifest leaf key has the wrong prefix",
        )
    })?;
    let encoded: [u8; 4] = suffix.try_into().map_err(|_| {
        LixError::new(
            LixError::CODE_STORAGE_ERROR,
            "upload manifest leaf key has an invalid part number",
        )
    })?;
    Ok(u32::from_be_bytes(encoded))
}

fn upload_part_count(total_size: u64) -> Result<u32, LixError> {
    if total_size == 0 {
        return Ok(1);
    }
    let parts = total_size.div_ceil(FILE_UPLOAD_PART_BYTES as u64);
    u32::try_from(parts).map_err(|_| invalid_upload("upload part count exceeds u32"))
}

fn upload_part_size(total_size: u64, part_number: u32) -> Result<u64, LixError> {
    if total_size == 0 && part_number == 0 {
        return Ok(0);
    }
    let start = u64::from(part_number)
        .checked_mul(FILE_UPLOAD_PART_BYTES as u64)
        .ok_or_else(|| invalid_upload("upload part offset exceeds u64"))?;
    if start >= total_size {
        return Err(invalid_upload("upload part number exceeds declared size"));
    }
    Ok((total_size - start).min(FILE_UPLOAD_PART_BYTES as u64))
}

fn upload_manifest_leaf_range(upload_id: &str) -> Result<StorageKeyRange, LixError> {
    let prefix = upload_manifest_leaf_prefix(upload_id)?;
    let mut upper = prefix.clone();
    upper.push(0xff);
    Ok(StorageKeyRange {
        lower: Bound::Included(StorageKey(Bytes::from(prefix))),
        upper: Bound::Excluded(StorageKey(Bytes::from(upper))),
    })
}

fn invalid_upload(message: &'static str) -> LixError {
    LixError::new(LixError::CODE_INVALID_PARAM, message)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::binary_cas::BINARY_CAS_CHUNK_SPACE;
    use crate::storage_adapter::{
        StorageAdapter, StorageAdapterRead, StorageBeginScanOptions, StorageCoreProjection,
        StorageKeyRange, StorageWriteOptions, StorageWriteSet,
    };
    use crate::{Memory, engine::Engine};
    use std::ops::Bound;

    #[tokio::test]
    async fn direct_file_helpers_create_update_read_and_validate_paths() {
        let lix = crate::open_lix().await.expect("open lix");

        assert_eq!(
            lix.upsert_file_content("/native/file.bin", b"first".as_slice())
                .await
                .expect("create file"),
            1
        );
        assert_eq!(
            lix.upsert_file_content("/native/file.bin", b"second".as_slice())
                .await
                .expect("update file"),
            1
        );
        let read = lix
            .read_file_content("/native/file.bin", None)
            .await
            .expect("read file")
            .expect("file exists");
        assert_eq!(read.content().as_ref(), b"second");

        lix.upsert_file_content("/native/file.bin", Vec::<u8>::new())
            .await
            .expect("write empty file");
        let empty = lix
            .read_file_content("/native/file.bin", None)
            .await
            .expect("read empty file")
            .expect("empty file exists");
        assert!(empty.content().is_empty());
        assert!(
            lix.read_file_content("/native/missing.bin", None)
                .await
                .expect("read missing file")
                .is_none()
        );

        let relative = lix
            .upsert_file_content("relative.bin", b"invalid".as_slice())
            .await
            .expect_err("relative path is invalid");
        assert_eq!(relative.code, "LIX_ERROR_PATH_MISSING_LEADING_SLASH");
        let nul = lix
            .upsert_file_content("/nul\0name.bin", b"invalid".as_slice())
            .await
            .expect_err("NUL path is invalid");
        assert_eq!(nul.code, "LIX_ERROR_PATH_NUL");
    }

    #[tokio::test]
    async fn direct_file_batch_is_atomic_and_rejects_invalid_input() {
        let lix = crate::open_lix().await.expect("open lix");
        let writes = vec![
            ("/native/one.bin".to_owned(), Blob::from(b"one".as_slice())),
            ("/native/two.bin".to_owned(), Blob::from(b"two".as_slice())),
            ("/native/empty.bin".to_owned(), Blob::from(Vec::<u8>::new())),
        ];
        assert_eq!(
            lix.upsert_file_content_batch(writes)
                .await
                .expect("write batch"),
            3
        );
        for (path, expected) in [
            ("/native/one.bin", b"one".as_slice()),
            ("/native/two.bin", b"two".as_slice()),
            ("/native/empty.bin", b"".as_slice()),
        ] {
            let read = lix
                .read_file_content(path, None)
                .await
                .expect("read batch file")
                .expect("batch file exists");
            assert_eq!(read.content().as_ref(), expected);
        }

        let empty = lix
            .upsert_file_content_batch(Vec::new())
            .await
            .expect_err("empty batch is invalid");
        assert_eq!(empty.code, LixError::CODE_INVALID_PARAM);
        let duplicate = lix
            .upsert_file_content_batch(vec![
                (
                    "/native/duplicate.bin".to_owned(),
                    Blob::from(b"one".as_slice()),
                ),
                (
                    "/native/duplicate.bin".to_owned(),
                    Blob::from(b"two".as_slice()),
                ),
            ])
            .await
            .expect_err("duplicate path is invalid");
        assert_eq!(duplicate.code, LixError::CODE_INVALID_PARAM);
        assert!(
            lix.read_file_content("/native/duplicate.bin", None)
                .await
                .expect("read duplicate target")
                .is_none(),
            "a rejected batch must not partially commit"
        );
    }

    async fn seed_orphan_upload_chunk(
        storage: &StorageAdapter<Memory>,
        payload: &[u8],
    ) -> ChunkHash {
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("orphan chunk staging read should open");
        let mut writes = storage.new_write_set();
        let receipts = crate::binary_cas::BinaryCasContext::new()
            .writer_skipping_existing_chunks(&read, &mut writes)
            .stage_upload_part(payload)
            .await
            .expect("orphan upload chunk should stage");
        assert_eq!(receipts.len(), 1);
        drop(read);
        storage
            .commit_write_set(writes, StorageWriteOptions::default())
            .await
            .expect("orphan upload chunk should commit");
        receipts[0].hash
    }

    /// A resumable upload keeps four parts in flight by design, and the engine —
    /// not the caller — owns that window. Parts staged from one snapshot write
    /// disjoint manifest leaves over content-addressed payloads, so they are
    /// independent publications: every one of them must commit.
    ///
    /// Making publishers share a compare-and-set row broke exactly this. It was
    /// invisible at the public surface because `upsert_file_content_part` retries
    /// a bounded number of times — a full window plus any other concurrent writer
    /// exhausts that budget, which is how the movie-repository qualification fails
    /// its upload acknowledgement.
    #[tokio::test]
    async fn concurrent_upload_part_publications_from_one_snapshot_all_commit() {
        let storage = StorageAdapter::new(Memory::new());
        let payload = b"windowed-upload-part-payload";
        seed_orphan_upload_chunk(&storage, payload).await;
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("upload window read should open");
        let mut window = Vec::new();
        for part in 0..4 {
            window.push(
                stage_deduplicated_receipt_publication(
                    &storage,
                    &read,
                    &format!("windowed-part-{part}"),
                    payload,
                    true,
                )
                .await,
            );
        }
        drop(read);

        for (part, (writes, preconditions)) in window.into_iter().enumerate() {
            storage
                .commit_write_set(
                    writes,
                    StorageWriteOptions {
                        preconditions,
                        ..StorageWriteOptions::default()
                    },
                )
                .await
                .unwrap_or_else(|error| {
                    panic!(
                        "every part of one upload window must commit; part {part} was rejected: {error:?}"
                    )
                });
        }
    }

    async fn stage_deduplicated_receipt_publication(
        storage: &StorageAdapter<Memory>,
        read: &impl StorageAdapterRead,
        upload_id: &str,
        payload: &[u8],
        expect_deduplicated: bool,
    ) -> (StorageWriteSet, Vec<StoragePrecondition>) {
        let mut writes = storage.new_write_set();
        let chunks = crate::binary_cas::BinaryCasContext::new()
            .writer_skipping_existing_chunks(read, &mut writes)
            .stage_upload_part(payload)
            .await
            .expect("deduplicated receipt chunk should stage");
        assert_eq!(
            writes.is_empty(),
            expect_deduplicated,
            "receipt payload staging did not match the expected deduplication state"
        );
        let leaf_key = upload_manifest_leaf_key(upload_id, 0).unwrap();
        stage_upload_manifest_leaf(
            &mut writes,
            leaf_key.clone(),
            &UploadManifestLeaf {
                part_size: payload.len() as u64,
                chunks,
            },
        )
        .expect("deduplicated receipt leaf should stage");
        let state_key = upload_state_key(upload_id).unwrap();
        stage_upload_state(
            &mut writes,
            state_key.clone(),
            &UploadState::Open(UploadOpen {
                path: format!("/{upload_id}.bin"),
                total_size: payload.len() as u64 + 1,
            }),
        )
        .expect("deduplicated receipt state should stage");
        let mut preconditions = vec![
            StoragePrecondition::KeyAbsent {
                space: UPLOAD_MANIFEST_LEAF_SPACE,
                key: leaf_key,
            },
            StoragePrecondition::KeyAbsent {
                space: UPLOAD_STATE_SPACE,
                key: state_key,
            },
        ];
        crate::binary_cas::stage_cas_publication_fence(read, &mut writes, &mut preconditions)
            .await
            .expect("deduplicated receipt publication fence should stage");
        (writes, preconditions)
    }

    async fn stage_cas_sweep(
        storage: &StorageAdapter<Memory>,
        read: &impl StorageAdapterRead,
    ) -> (StorageWriteSet, Vec<StoragePrecondition>) {
        let mut writes = storage.new_write_set();
        let mut preconditions = Vec::new();
        let upload_chunks = stage_reclaimable_upload_receipts(read, &mut writes, &BTreeSet::new())
            .await
            .expect("stale sweep upload mark should collect");
        let swept = crate::binary_cas::stage_gc_reclamation(
            read,
            &mut writes,
            &BTreeSet::new(),
            &upload_chunks,
        )
        .await
        .expect("stale CAS sweep should stage");
        assert_eq!(swept.reclaimed_chunk_rows, 1);
        crate::binary_cas::stage_cas_reclamation_fence(read, &mut writes, &mut preconditions)
            .await
            .expect("stale sweep reclamation fence should stage");
        (writes, preconditions)
    }

    async fn chunk_exists(storage: &StorageAdapter<Memory>, hash: ChunkHash) -> bool {
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("chunk verification read should open");
        let mut cursor = read
            .begin_scan(
                BINARY_CAS_CHUNK_SPACE,
                StorageKeyRange {
                    lower: Bound::Included(StorageKey(Bytes::copy_from_slice(hash.as_bytes()))),
                    upper: Bound::Included(StorageKey(Bytes::copy_from_slice(hash.as_bytes()))),
                },
                StorageBeginScanOptions {
                    projection: StorageCoreProjection::KeyOnly,
                    ..StorageBeginScanOptions::default()
                },
            )
            .await
            .expect("chunk verification scan should succeed");
        let (page, _page_has_more) = cursor
            .next_page(1)
            .await
            .expect("chunk verification page should succeed")
            .into_parts();
        !page.is_empty()
    }

    #[tokio::test]
    async fn receipt_first_rejects_stale_gc_deleting_a_deduplicated_chunk() {
        let storage = StorageAdapter::new(Memory::new());
        let payload = b"deduplicated-upload-race";
        let hash = seed_orphan_upload_chunk(&storage, payload).await;
        let sweep_read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("stale sweep read should open");
        let receipt_read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("receipt publication read should open");
        let (sweep, sweep_preconditions) = stage_cas_sweep(&storage, &sweep_read).await;
        let (receipt, receipt_preconditions) = stage_deduplicated_receipt_publication(
            &storage,
            &receipt_read,
            "receipt-first",
            payload,
            true,
        )
        .await;
        drop(sweep_read);
        drop(receipt_read);

        storage
            .commit_write_set(
                receipt,
                StorageWriteOptions {
                    preconditions: receipt_preconditions,
                    ..StorageWriteOptions::default()
                },
            )
            .await
            .expect("receipt should win the publication fence");
        assert!(
            storage
                .commit_write_set(
                    sweep,
                    StorageWriteOptions {
                        preconditions: sweep_preconditions,
                        ..StorageWriteOptions::default()
                    },
                )
                .await
                .is_err(),
            "stale GC must lose after receipt publication",
        );
        assert!(chunk_exists(&storage, hash).await);
    }

    #[tokio::test]
    async fn gc_first_rejects_stale_receipt_publication_after_payload_deletion() {
        let storage = StorageAdapter::new(Memory::new());
        let payload = b"deduplicated-upload-race";
        let hash = seed_orphan_upload_chunk(&storage, payload).await;
        let sweep_read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("sweep read should open");
        let receipt_read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("stale receipt read should open");
        let (sweep, sweep_preconditions) = stage_cas_sweep(&storage, &sweep_read).await;
        let (receipt, receipt_preconditions) = stage_deduplicated_receipt_publication(
            &storage,
            &receipt_read,
            "gc-first",
            payload,
            true,
        )
        .await;
        drop(sweep_read);
        drop(receipt_read);

        storage
            .commit_write_set(
                sweep,
                StorageWriteOptions {
                    preconditions: sweep_preconditions,
                    ..StorageWriteOptions::default()
                },
            )
            .await
            .expect("GC should win the publication fence");
        assert!(!chunk_exists(&storage, hash).await);
        assert!(
            storage
                .commit_write_set(
                    receipt,
                    StorageWriteOptions {
                        preconditions: receipt_preconditions,
                        ..StorageWriteOptions::default()
                    },
                )
                .await
                .is_err(),
            "stale receipt must not publish after GC deletes its payload",
        );
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("receipt absence verification read should open");
        assert!(
            load_upload_state(&read, &upload_state_key("gc-first").unwrap())
                .await
                .expect("stale receipt state lookup should succeed")
                .is_none()
        );
        assert!(
            load_upload_manifest_leaf(&read, &upload_manifest_leaf_key("gc-first", 0).unwrap())
                .await
                .expect("stale receipt leaf lookup should succeed")
                .is_none()
        );
        drop(read);

        let retry_read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("receipt retry read should open after GC");
        let (retry, retry_preconditions) = stage_deduplicated_receipt_publication(
            &storage,
            &retry_read,
            "gc-first",
            payload,
            false,
        )
        .await;
        drop(retry_read);
        storage
            .commit_write_set(
                retry,
                StorageWriteOptions {
                    preconditions: retry_preconditions,
                    ..StorageWriteOptions::default()
                },
            )
            .await
            .expect("fresh receipt retry should restage the deleted payload");
        assert!(chunk_exists(&storage, hash).await);
        let cold_read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("cold receipt verification read should open");
        assert!(
            load_upload_manifest_leaf(
                &cold_read,
                &upload_manifest_leaf_key("gc-first", 0).unwrap()
            )
            .await
            .expect("retried receipt leaf lookup should succeed")
            .is_some()
        );
    }

    #[tokio::test]
    async fn completed_receipt_without_a_live_file_root_is_reclaimed() {
        let storage = StorageAdapter::new(Memory::new());
        let upload_id = "completed-receipt";
        let mut initial = storage.new_write_set();
        stage_upload_state(
            &mut initial,
            upload_state_key(upload_id).expect("upload state key should encode"),
            &UploadState::Complete(UploadComplete {
                path: "/orphaned.bin".to_owned(),
                total_size: 7,
                blob_id: BlobId::from_content(b"orphaned").into_bytes(),
                part_identities: Vec::new(),
            }),
        )
        .expect("completed state should encode");
        storage
            .commit_write_set(initial, StorageWriteOptions::default())
            .await
            .expect("completed receipt should commit");

        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("receipt read should open");
        let mut writes = storage.new_write_set();
        let chunks = stage_reclaimable_upload_receipts(&read, &mut writes, &BTreeSet::new())
            .await
            .expect("receipt sweep should succeed");
        assert!(chunks.is_empty());
        drop(read);
        storage
            .commit_write_set(writes, StorageWriteOptions::default())
            .await
            .expect("completed receipt cleanup should commit");

        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("reopened receipt read should open");
        assert!(
            load_upload_state(&read, &upload_state_key(upload_id).unwrap())
                .await
                .expect("completed receipt lookup should succeed")
                .is_none()
        );
    }

    #[tokio::test]
    async fn active_receipt_declared_size_must_match_authenticated_chunk_bytes() {
        let storage = StorageAdapter::new(Memory::new());
        let payload = b"active-upload-chunk";
        let chunk_hash = ChunkHash::from_content(payload);
        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("active receipt staging read should open");
        let mut initial = storage.new_write_set();
        crate::binary_cas::BinaryCasContext::new()
            .writer_skipping_existing_chunks(&read, &mut initial)
            .stage_payload(&crate::binary_cas::BlobPayload::from_bytes(
                payload.to_vec(),
            ))
            .await
            .expect("active receipt chunk should stage");
        stage_upload_state(
            &mut initial,
            upload_state_key("wrong-size-receipt").unwrap(),
            &UploadState::Open(UploadOpen {
                path: "/wrong-size.bin".to_owned(),
                total_size: payload.len() as u64 + 1,
            }),
        )
        .expect("active upload state should stage");
        stage_upload_manifest_leaf(
            &mut initial,
            upload_manifest_leaf_key("wrong-size-receipt", 0).unwrap(),
            &UploadManifestLeaf {
                part_size: payload.len() as u64 + 1,
                chunks: vec![BlobChunkReceipt {
                    hash: chunk_hash,
                    size_bytes: payload.len() as u64 + 1,
                }],
            },
        )
        .expect("wrong-size receipt should stage");
        drop(read);
        storage
            .commit_write_set(initial, StorageWriteOptions::default())
            .await
            .expect("wrong-size receipt fixture should commit");

        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("wrong-size receipt GC read should open");
        let mut sweep = storage.new_write_set();
        let upload_chunks = stage_reclaimable_upload_receipts(&read, &mut sweep, &BTreeSet::new())
            .await
            .expect("active receipt should collect");
        let error = crate::binary_cas::stage_gc_reclamation(
            &read,
            &mut sweep,
            &BTreeSet::new(),
            &upload_chunks,
        )
        .await
        .expect_err("wrong declared upload size must fail GC closed");
        assert!(
            error.message.contains("expected 20 uncompressed bytes"),
            "{error:?}"
        );
        assert!(sweep.is_empty(), "wrong size must stage no reclamation");
    }

    #[tokio::test]
    async fn active_receipts_reject_conflicting_sizes_for_one_chunk() {
        let storage = StorageAdapter::new(Memory::new());
        let hash = ChunkHash::from_content(b"shared-active-upload-chunk");
        let mut initial = storage.new_write_set();
        for (upload_id, size_bytes) in [("receipt-a", 7), ("receipt-b", 9)] {
            stage_upload_state(
                &mut initial,
                upload_state_key(upload_id).unwrap(),
                &UploadState::Open(UploadOpen {
                    path: format!("/{upload_id}.bin"),
                    total_size: size_bytes,
                }),
            )
            .expect("active upload state should stage");
            stage_upload_manifest_leaf(
                &mut initial,
                upload_manifest_leaf_key(upload_id, 0).unwrap(),
                &UploadManifestLeaf {
                    part_size: size_bytes,
                    chunks: vec![BlobChunkReceipt { hash, size_bytes }],
                },
            )
            .expect("active upload receipt should stage");
        }
        storage
            .commit_write_set(initial, StorageWriteOptions::default())
            .await
            .expect("conflicting active receipt fixture should commit");

        let read = storage
            .begin_read(StorageReadOptions::default())
            .await
            .expect("conflicting receipt read should open");
        let mut sweep = storage.new_write_set();
        let error = stage_reclaimable_upload_receipts(&read, &mut sweep, &BTreeSet::new())
            .await
            .expect_err("conflicting active receipt sizes must fail closed");
        assert!(error.message.contains("conflicting declared sizes"));
        assert!(sweep.is_empty(), "conflict must stage no receipt cleanup");
    }

    #[tokio::test]
    async fn sequential_parts_survive_a_new_session_and_publish_one_file() {
        let storage = Memory::default();
        Engine::initialize(storage.clone())
            .await
            .expect("initialize storage");
        let engine = Engine::new(storage.clone()).await.expect("open engine");
        let first_session = engine.open_session().await.expect("open first session");
        let first = vec![0x31; FILE_UPLOAD_PART_BYTES];
        let tail = vec![0x72; 123];
        let total = (first.len() + tail.len()) as u64;

        let progress = first_session
            .upsert_file_content_part(
                "movie-proxy-1".into(),
                "/media/proxy.mov".into(),
                0,
                total,
                first.clone().into(),
            )
            .await
            .expect("stage first part");
        assert_eq!(progress.next_offset, FILE_UPLOAD_PART_BYTES as u64);
        assert!(!progress.finalized);
        assert!(
            first_session
                .read_file_content("/media/proxy.mov".into(), None)
                .await
                .expect("read before publish")
                .is_none()
        );

        let resumed_session = engine.open_session().await.expect("open resumed session");
        let progress = resumed_session
            .upsert_file_content_part(
                "movie-proxy-1".into(),
                "/media/proxy.mov".into(),
                FILE_UPLOAD_PART_BYTES as u64,
                total,
                tail.clone().into(),
            )
            .await
            .expect("finalize resumed upload");
        assert!(progress.finalized);

        let boundary = resumed_session
            .read_file_content(
                "/media/proxy.mov".into(),
                Some((FILE_UPLOAD_PART_BYTES as u64 - 4)..(FILE_UPLOAD_PART_BYTES as u64 + 4)),
            )
            .await
            .expect("range read")
            .expect("published file");
        assert_eq!(
            boundary.content().as_ref(),
            [vec![0x31; 4], vec![0x72; 4]].concat().as_slice()
        );
        let adapter = StorageAdapter::new(storage.clone());
        let read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("open upload cleanup read");
        let mut cursor = read
            .begin_scan(
                UPLOAD_MANIFEST_LEAF_SPACE,
                upload_manifest_leaf_range("movie-proxy-1").expect("upload leaf range"),
                StorageBeginScanOptions {
                    projection: StorageCoreProjection::KeyOnly,
                    ..StorageBeginScanOptions::default()
                },
            )
            .await
            .expect("begin temporary upload receipt scan");
        let (temporary_receipts, _temporary_receipts_has_more) = cursor
            .next_page(MAX_SCAN_PAGE_ROWS)
            .await
            .expect("scan temporary upload receipts")
            .into_parts();
        assert!(
            temporary_receipts.is_empty(),
            "publication must atomically remove temporary chunk receipts",
        );
        drop(cursor);
        drop(read);
        let published_commit_id = resumed_session
            .execute("SELECT lix_active_branch_commit_id() AS commit_id", &[])
            .await
            .expect("published branch head")
            .rows()[0]
            .get::<String>("commit_id")
            .expect("published commit id");

        let replay = resumed_session
            .upsert_file_content_part(
                "movie-proxy-1".into(),
                "/media/proxy.mov".into(),
                FILE_UPLOAD_PART_BYTES as u64,
                total,
                tail.into(),
            )
            .await
            .expect("replay final part");
        assert!(replay.finalized);
        assert_eq!(replay.next_offset, total);
        let replayed_commit_id = resumed_session
            .execute("SELECT lix_active_branch_commit_id() AS commit_id", &[])
            .await
            .expect("replayed branch head")
            .rows()[0]
            .get::<String>("commit_id")
            .expect("replayed commit id");
        assert_eq!(
            replayed_commit_id, published_commit_id,
            "a completed upload replay must not publish duplicate history",
        );
        let mismatched_replay = resumed_session
            .upsert_file_content_part(
                "movie-proxy-1".into(),
                "/media/proxy.mov".into(),
                FILE_UPLOAD_PART_BYTES as u64,
                total,
                vec![0x73; 123].into(),
            )
            .await
            .expect_err("completed part replay must preserve content identity");
        assert_eq!(mismatched_replay.code, LixError::CODE_INVALID_PARAM);

        resumed_session
            .upsert_file_content_part(
                "movie-proxy-copy".into(),
                "/media/proxy-copy.mov".into(),
                0,
                total,
                first.into(),
            )
            .await
            .expect("stage identical first part");
        resumed_session
            .upsert_file_content_part(
                "movie-proxy-copy".into(),
                "/media/proxy-copy.mov".into(),
                FILE_UPLOAD_PART_BYTES as u64,
                total,
                vec![0x72; 123].into(),
            )
            .await
            .expect("publish identical copy");

        let adapter = StorageAdapter::new(storage);
        let read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("open CAS accounting read");
        let mut cursor = read
            .begin_scan(
                BINARY_CAS_CHUNK_SPACE,
                StorageKeyRange {
                    lower: Bound::Unbounded,
                    upper: Bound::Unbounded,
                },
                StorageBeginScanOptions {
                    projection: StorageCoreProjection::KeyOnly,
                    ..StorageBeginScanOptions::default()
                },
            )
            .await
            .expect("begin CAS chunk scan");
        let (chunks, chunks_has_more) = cursor
            .next_page(MAX_SCAN_PAGE_ROWS)
            .await
            .expect("scan CAS chunks")
            .into_parts();
        assert!(!chunks_has_more);
        assert_eq!(
            chunks.len(),
            3,
            "two media chunks plus the bootstrap README; identical media must reuse payloads"
        );
    }

    #[tokio::test]
    async fn four_part_window_persists_one_leaf_per_completed_part() {
        let storage = Memory::default();
        Engine::initialize(storage.clone())
            .await
            .expect("initialize storage");
        let engine = Engine::new(storage.clone()).await.expect("open engine");
        let session = engine.open_session().await.expect("open session");
        let total_size = 4 * FILE_UPLOAD_PART_BYTES as u64;

        let second = session.upsert_file_content_part(
            "windowed-proxy".into(),
            "/media/windowed.mov".into(),
            FILE_UPLOAD_PART_BYTES as u64,
            total_size,
            vec![0x22; FILE_UPLOAD_PART_BYTES].into(),
        );
        let third = session.upsert_file_content_part(
            "windowed-proxy".into(),
            "/media/windowed.mov".into(),
            2 * FILE_UPLOAD_PART_BYTES as u64,
            total_size,
            vec![0x33; FILE_UPLOAD_PART_BYTES].into(),
        );
        let fourth = session.upsert_file_content_part(
            "windowed-proxy".into(),
            "/media/windowed.mov".into(),
            3 * FILE_UPLOAD_PART_BYTES as u64,
            total_size,
            vec![0x44; FILE_UPLOAD_PART_BYTES].into(),
        );
        let (second, third, fourth) = tokio::join!(second, third, fourth);
        for progress in [second, third, fourth] {
            let progress = progress.expect("windowed part completes");
            assert_eq!(progress.next_offset, 0);
            assert!(!progress.finalized);
        }

        let adapter = StorageAdapter::new(storage.clone());
        let read = adapter
            .begin_read(StorageReadOptions::default())
            .await
            .expect("read upload leaves");
        let mut cursor = read
            .begin_scan(
                UPLOAD_MANIFEST_LEAF_SPACE,
                upload_manifest_leaf_range("windowed-proxy").expect("leaf range"),
                StorageBeginScanOptions {
                    projection: StorageCoreProjection::FullValue,
                    ..StorageBeginScanOptions::default()
                },
            )
            .await
            .expect("begin upload leaf scan");
        let (leaves, _leaves_has_more) = cursor
            .next_page(MAX_SCAN_PAGE_ROWS)
            .await
            .expect("scan upload leaves")
            .into_parts();
        assert_eq!(leaves.len(), 3);
        for entry in leaves {
            let StorageProjectedValue::FullValue(value) = entry.value else {
                panic!("manifest leaf scan must return values");
            };
            let leaf = decode_upload_manifest_leaf(&value).expect("decode manifest leaf");
            assert!(!leaf.chunks.is_empty());
            assert_eq!(
                leaf.chunks
                    .iter()
                    .map(|chunk| chunk.size_bytes)
                    .sum::<u64>(),
                FILE_UPLOAD_PART_BYTES as u64,
                "a part's content-defined chunks must tile the part exactly"
            );
        }
        drop(cursor);
        drop(read);

        let outside_window = session
            .upsert_file_content_part(
                "window-gap".into(),
                "/media/window-gap.mov".into(),
                4 * FILE_UPLOAD_PART_BYTES as u64,
                5 * FILE_UPLOAD_PART_BYTES as u64,
                vec![0x55; FILE_UPLOAD_PART_BYTES].into(),
            )
            .await
            .expect_err("fifth part cannot pass a missing first part");
        assert_eq!(outside_window.code, LixError::CODE_INVALID_PARAM);

        session
            .upsert_file_content_part(
                "sparse-chain".into(),
                "/media/sparse-chain.mov".into(),
                0,
                9 * FILE_UPLOAD_PART_BYTES as u64,
                vec![0x10; FILE_UPLOAD_PART_BYTES].into(),
            )
            .await
            .expect("stage sparse-chain first part");
        session
            .upsert_file_content_part(
                "sparse-chain".into(),
                "/media/sparse-chain.mov".into(),
                4 * FILE_UPLOAD_PART_BYTES as u64,
                9 * FILE_UPLOAD_PART_BYTES as u64,
                vec![0x14; FILE_UPLOAD_PART_BYTES].into(),
            )
            .await
            .expect("stage last part inside the first moving window");
        let sparse_escape = session
            .upsert_file_content_part(
                "sparse-chain".into(),
                "/media/sparse-chain.mov".into(),
                8 * FILE_UPLOAD_PART_BYTES as u64,
                9 * FILE_UPLOAD_PART_BYTES as u64,
                vec![0x18; FILE_UPLOAD_PART_BYTES].into(),
            )
            .await
            .expect_err("sparse receipts cannot advance the bounded window");
        assert_eq!(sparse_escape.code, LixError::CODE_INVALID_PARAM);

        let mismatched_active_replay = session
            .upsert_file_content_part(
                "windowed-proxy".into(),
                "/media/windowed.mov".into(),
                FILE_UPLOAD_PART_BYTES as u64,
                total_size,
                vec![0x23; FILE_UPLOAD_PART_BYTES].into(),
            )
            .await
            .expect_err("staged part replay must preserve content identity");
        assert_eq!(mismatched_active_replay.code, LixError::CODE_INVALID_PARAM);

        let completed = session
            .upsert_file_content_part(
                "windowed-proxy".into(),
                "/media/windowed.mov".into(),
                0,
                total_size,
                vec![0x11; FILE_UPLOAD_PART_BYTES].into(),
            )
            .await
            .expect("first part closes the completion gap");
        assert!(completed.finalized);
        assert_eq!(completed.next_offset, total_size);

        for (part, expected) in [0x11, 0x22, 0x33, 0x44].into_iter().enumerate() {
            let offset = part as u64 * FILE_UPLOAD_PART_BYTES as u64;
            let byte = session
                .read_file_content(
                    "/media/windowed.mov".into(),
                    Some(offset..offset.saturating_add(1)),
                )
                .await
                .expect("read completed part")
                .expect("published file");
            assert_eq!(byte.content().as_ref(), &[expected]);
        }
    }
}

/// Completed upload receipts are bookkeeping; only unfinished or unknown state
/// needs user recovery. This does not inspect or download payload bytes at open.
pub(crate) async fn has_recoverable_uploads(
    read: &(impl crate::storage_adapter::StorageAdapterRead + ?Sized),
) -> Result<bool, LixError> {
    let mut cursor = read
        .begin_scan(
            UPLOAD_STATE_SPACE,
            StorageKeyRange {
                lower: Bound::Unbounded,
                upper: Bound::Unbounded,
            },
            StorageBeginScanOptions::default(),
        )
        .await?;
    while let Some(page) = cursor.next_chunk().await? {
        for entry in page {
            let StorageProjectedValue::FullValue(raw) = entry.value else {
                return Ok(true);
            };
            if !matches!(
                serde_json::from_slice::<UploadState>(&raw),
                Ok(UploadState::Complete(_))
            ) {
                return Ok(true);
            }
        }
    }
    Ok(false)
}

/// Explicit recovery export includes the bytes of available unfinished parts.
/// These parts have never become files and must not be silently published.
pub(crate) async fn export_recoverable_uploads(
    read: &(impl crate::storage_adapter::StorageAdapterRead + ?Sized),
) -> Result<Vec<serde_json::Value>, LixError> {
    use base64::Engine as _;
    let mut exported_bytes = 0_u64;
    let mut result = BTreeMap::<String, serde_json::Value>::new();
    let mut cursor = read
        .begin_scan(
            UPLOAD_STATE_SPACE,
            StorageKeyRange {
                lower: Bound::Unbounded,
                upper: Bound::Unbounded,
            },
            StorageBeginScanOptions::default(),
        )
        .await?;
    while let Some(page) = cursor.next_chunk().await? {
        for entry in page {
            let StorageProjectedValue::FullValue(raw) = entry.value else {
                continue;
            };
            let state = serde_json::from_slice::<serde_json::Value>(&raw)
                .map_err(|error| invalid_upload_storage(error.to_string()))?;
            if state.get("state").and_then(serde_json::Value::as_str) == Some("complete") {
                continue;
            }
            let id = std::str::from_utf8(&entry.key.0)
                .map_err(|error| invalid_upload_storage(error.to_string()))?
                .to_owned();
            result.insert(
                id.clone(),
                serde_json::json!({"id":id,"state":state,"parts":[]}),
            );
        }
    }
    let mut leaves = read
        .begin_scan(
            UPLOAD_MANIFEST_LEAF_SPACE,
            StorageKeyRange {
                lower: Bound::Unbounded,
                upper: Bound::Unbounded,
            },
            StorageBeginScanOptions::default(),
        )
        .await?;
    while let Some(page) = leaves.next_chunk().await? {
        for entry in page {
            let id = decode_upload_manifest_leaf_upload_id(&entry.key)?;
            let Some(upload) = result.get_mut(&id) else {
                continue;
            };
            let StorageProjectedValue::FullValue(raw) = entry.value else {
                return Err(invalid_upload_storage("recovery part has no manifest"));
            };
            let leaf = decode_upload_manifest_leaf(&raw)?;
            let part = u32::from_be_bytes(
                entry.key.0[entry.key.0.len() - 4..]
                    .try_into()
                    .expect("validated upload part key"),
            );
            let mut chunks = Vec::new();
            for chunk in leaf.chunks {
                exported_bytes = exported_bytes.saturating_add(chunk.size_bytes);
                if exported_bytes > 128 * 1024 * 1024 {
                    return Err(LixError::new(
                        "LIX_RECOVERY_EXPORT_TOO_LARGE",
                        "Unfinished upload export exceeds the memory budget; the complete source remains retained",
                    ));
                }
                let bytes = crate::binary_cas::load_verified_chunk(read, chunk.hash).await?;
                chunks.push(serde_json::json!({"id":chunk.hash.to_hex(),"sizeBytes":chunk.size_bytes,"contentBase64":bytes.map(|bytes| base64::engine::general_purpose::STANDARD.encode(bytes))}));
            }
            upload["parts"].as_array_mut().expect("recovery parts array").push(serde_json::json!({"partNumber":part,"offset":u64::from(part)*FILE_UPLOAD_PART_BYTES as u64,"sizeBytes":leaf.part_size,"chunks":chunks}));
        }
    }
    Ok(result.into_values().collect())
}

#[cfg(test)]
mod recovery_tests {
    use super::*;

    #[tokio::test]
    async fn recovery_distinguishes_completed_receipts_and_exports_unfinished_part_bytes() {
        let lix = crate::open_lix().await.unwrap();
        let adapter = lix.storage_adapter();
        let mut writes = adapter.new_write_set();
        writes.put(
            UPLOAD_STATE_SPACE,
            upload_state_key("completed").unwrap(),
            serde_json::to_vec(&UploadState::Complete(UploadComplete {
                path: "/completed.bin".to_owned(),
                total_size: 0,
                blob_id: [0; 32],
                part_identities: Vec::new(),
            }))
            .unwrap(),
        );
        adapter
            .commit_write_set(writes, Default::default())
            .await
            .unwrap();
        let read = adapter.begin_read(Default::default()).await.unwrap();
        assert!(!has_recoverable_uploads(&read).await.unwrap());
        drop(read);
        let mut writes = adapter.new_write_set();
        writes.put(
            UPLOAD_STATE_SPACE,
            upload_state_key("unfinished").unwrap(),
            serde_json::to_vec(&UploadState::Open(UploadOpen {
                path: "/unfinished.bin".to_owned(),
                total_size: 20,
            }))
            .unwrap(),
        );
        let chunk = crate::binary_cas::stage_verified_raw_chunk(
            &mut writes,
            ChunkHash::from_content(b"part"),
            b"part",
        )
        .unwrap();
        stage_upload_manifest_leaf(
            &mut writes,
            upload_manifest_leaf_key("unfinished", 0).unwrap(),
            &UploadManifestLeaf {
                part_size: 4,
                chunks: vec![chunk],
            },
        )
        .unwrap();
        adapter
            .commit_write_set(writes, Default::default())
            .await
            .unwrap();
        let read = adapter.begin_read(Default::default()).await.unwrap();
        assert!(has_recoverable_uploads(&read).await.unwrap());
        let export = export_recoverable_uploads(&read).await.unwrap();
        assert_eq!(export.len(), 1);
        assert_eq!(export[0]["state"]["path"], "/unfinished.bin");
        assert_eq!(
            export[0]["parts"][0]["chunks"][0]["contentBase64"],
            "cGFydA=="
        );
        drop(read);
        lix.close().await.unwrap();
    }
}