typst-pack 0.5.0

Portable single-file packs of Typst projects: sources, resources, packages, and fonts
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
//! OpenDAL exact-key writing vocabulary and crate-private execution.

use std::{collections::BTreeMap, future::Future};

use futures_util::StreamExt;
use opendal::ErrorKind;

use super::location::validate_decoded_artifact_key_path;
use super::{
    BoxError, Location, LocationError, LocationRoleError, OperatorBinding, OperatorResolver,
};
use crate::redacted_error::RedactedError;
use crate::{
    CanonicalIdentity, CommitCertainty, CompilationResult, CompilationStatus, PackArchiveBytes,
};
pub use crate::{
    CompilationArtifactWriteEntry, CompilationArtifactWriteProgress,
    CompilationArtifactWriteReceipt, PackExtractionWriteEntry, PackExtractionWriteProgress,
    PackExtractionWriteReceipt, WriteKeyOutcome,
};

/// The exact-key conflict policy for an OpenDAL write operation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum WritePolicy {
    /// Create absent objects and accept existing objects only when their bytes match.
    CreateOrVerify,
    /// Write every exact key without inspecting its existing value.
    OverwriteExactKeys,
}

/// The OpenDAL adapter phase reached by a write attempt.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum OpenDalWritePhase {
    ResultValidation,
    DestinationValidation,
    ResolveOperator,
    CapabilityAppraisal,
    PreflightRead,
    ConditionalCreate,
    RaceVerification,
    DirectWrite,
    Complete,
}

/// A validated request to write one exact Pack Archive object.
#[derive(Clone, Debug)]
pub struct PackArchiveWriteRequest {
    destination: Location,
    policy: WritePolicy,
}

impl PackArchiveWriteRequest {
    /// Validates an exact-object destination and retains the explicit policy.
    pub fn new(
        destination: Location,
        policy: WritePolicy,
    ) -> Result<Self, PackArchiveWriteRequestError> {
        destination.require_object().map_err(|source| {
            PackArchiveWriteRequestError::InvalidDestinationRole {
                location: destination.clone(),
                source,
            }
        })?;

        Ok(Self {
            destination,
            policy,
        })
    }

    pub fn destination(&self) -> &Location {
        &self.destination
    }

    pub const fn policy(&self) -> WritePolicy {
        self.policy
    }
}

/// A reason a Pack Archive write request cannot be accepted.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum PackArchiveWriteRequestError {
    #[error("Pack Archive destination {location} is not an exact object: {source}")]
    InvalidDestinationRole {
        location: Location,
        #[source]
        source: LocationRoleError,
    },
}

/// Writes exact borrowed Pack Archive bytes to one normalized object.
///
/// Dropping the returned future yields no receipt, and already-issued storage
/// work may have occurred. The caller retains `archive`; full replay with the
/// same exact bytes is the recovery contract.
///
/// ```no_run
/// use typst_pack::{Pack, PackArchiveBytes};
/// use typst_pack::opendal::{Location, OperatorBindings};
/// use typst_pack::opendal::pack_archive::{
///     PackArchiveReadRequest, read_pack_archive,
/// };
/// use typst_pack::opendal::write::{
///     PackArchiveWriteRequest, WritePolicy, write_pack_archive,
/// };
/// use typst_pack::pack_archive::{ReadLimits, DecodeError, DecodeLimits, decode};
///
/// enum WriteThenReadOutcome {
///     Matching {
///         read: PackArchiveBytes,
///         decoded: Result<Pack, DecodeError>,
///     },
///     DestinationChanged {
///         read: PackArchiveBytes,
///     },
/// }
///
/// async fn write_replay_and_read(
///     bindings: &OperatorBindings,
///     destination: Location,
///     archive: &PackArchiveBytes,
/// ) -> Result<WriteThenReadOutcome, Box<dyn std::error::Error>> {
///     let overwrite = PackArchiveWriteRequest::new(
///         destination.clone(),
///         WritePolicy::OverwriteExactKeys,
///     )?;
///     write_pack_archive(bindings, &overwrite, archive).await?;
///
///     let replay = PackArchiveWriteRequest::new(
///         destination.clone(),
///         WritePolicy::CreateOrVerify,
///     )?;
///     write_pack_archive(bindings, &replay, archive).await?;
///     write_pack_archive(bindings, &replay, archive).await?;
///
///     let read = PackArchiveReadRequest::new(
///         destination,
///         ReadLimits::reference_v1(),
///     )?;
///     let read = read_pack_archive(bindings, &read).await?;
///
///     // The caller still owns `archive`; preserve the independently read
///     // bytes and do not decode when the mutable destination changed.
///     if archive.as_slice() != read.as_slice() {
///         return Ok(WriteThenReadOutcome::DestinationChanged { read });
///     }
///
///     let decoded = decode(&read, DecodeLimits::reference_v1());
///     Ok(WriteThenReadOutcome::Matching { read, decoded })
/// }
/// ```
#[allow(clippy::result_large_err)]
pub async fn write_pack_archive<R: OperatorResolver + ?Sized>(
    resolver: &R,
    request: &PackArchiveWriteRequest,
    archive: &PackArchiveBytes,
) -> Result<PackArchiveWriteReceipt, PackArchiveWriteError> {
    let mut progress = PackArchiveWriteProgress::new();
    let destination_path = request.destination().operation_path();
    let keys = [ExactKey::new(destination_path, archive.as_slice())];
    {
        let mut operation = PackArchiveWriteOperation {
            request,
            progress: &mut progress,
        };
        write_exact_keys(
            resolver,
            request.destination().binding(),
            request.policy(),
            &keys,
            &mut operation,
        )
        .await?;
    }

    Ok(PackArchiveWriteReceipt {
        destination: request.destination().clone(),
        policy: request.policy(),
        progress,
    })
}

/// A failure while writing exact Pack Archive bytes through OpenDAL.
///
/// This error's own `Display` and `Debug` output omit native resolver and
/// OpenDAL messages. Rendering its source chain may disclose backend context.
#[derive(Debug, thiserror::Error)]
#[error(
    "Pack Archive write failed for binding {} at exact-object operation path {:?} during {phase:?}: {cause}",
    .destination.binding(),
    .destination.operation_path(),
)]
pub struct PackArchiveWriteError {
    destination: Location,
    policy: WritePolicy,
    failed_path: Option<String>,
    phase: OpenDalWritePhase,
    progress: PackArchiveWriteProgress,
    commit_certainty: CommitCertainty,
    #[source]
    cause: RedactedError<PackArchiveWriteErrorCause>,
}

impl PackArchiveWriteError {
    pub fn destination(&self) -> &Location {
        &self.destination
    }

    pub const fn policy(&self) -> WritePolicy {
        self.policy
    }

    pub fn failed_path(&self) -> Option<&str> {
        self.failed_path.as_deref()
    }

    pub const fn phase(&self) -> OpenDalWritePhase {
        self.phase
    }

    pub fn progress(&self) -> &PackArchiveWriteProgress {
        &self.progress
    }

    pub const fn commit_certainty(&self) -> CommitCertainty {
        self.commit_certainty
    }

    pub fn cause(&self) -> &PackArchiveWriteErrorCause {
        self.cause.inner()
    }
}

/// The typed cause of an OpenDAL Pack Archive write failure.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum PackArchiveWriteErrorCause {
    #[error("operator resolution failed")]
    ResolveOperator(#[source] BoxError),
    #[error("the write policy is unsupported")]
    UnsupportedPolicy { policy: WritePolicy },
    #[error("the archive exceeds the advertised object size")]
    UnsupportedObjectSize { byte_length: u64 },
    #[error("a preflight read failed")]
    PreflightRead(#[source] ::opendal::Error),
    #[error("destination bytes conflict")]
    ByteConflict {
        expected_byte_length: u64,
        observed_byte_length_at_least: u64,
    },
    #[error("a conditional create failed")]
    ConditionalCreate(#[source] ::opendal::Error),
    #[error("race verification failed")]
    RaceVerification(#[source] ::opendal::Error),
    #[error("a direct write failed")]
    DirectWrite(#[source] ::opendal::Error),
}

/// A validated request to write caller-supplied bytes to one package-cache object.
///
/// This request fixes [`WritePolicy::CreateOrVerify`]. It does not offer a
/// replacement mode and does not represent Package Archive Expansion or Package
/// Catalog insertion.
#[derive(Clone, Debug)]
pub struct PackageCacheArchiveWriteRequest {
    destination: Location,
}

impl PackageCacheArchiveWriteRequest {
    /// Validates and retains a normalized exact-object cache destination.
    pub fn new(destination: Location) -> Result<Self, PackageCacheArchiveWriteRequestError> {
        destination.require_object().map_err(|source| {
            PackageCacheArchiveWriteRequestError::InvalidDestinationRole {
                location: destination.clone(),
                source,
            }
        })?;

        Ok(Self { destination })
    }

    pub fn destination(&self) -> &Location {
        &self.destination
    }

    pub const fn policy(&self) -> WritePolicy {
        WritePolicy::CreateOrVerify
    }
}

/// A reason a package-cache archive write request cannot be accepted.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum PackageCacheArchiveWriteRequestError {
    #[error("package-cache archive destination {location} is not an exact object: {source}")]
    InvalidDestinationRole {
        location: Location,
        #[source]
        source: LocationRoleError,
    },
}

/// Writes caller-supplied exact archive bytes to one package-cache object.
///
/// This low-level operation does not expand the archive, validate a Package
/// Tree, or insert it into a Package Catalog. Direct use with unvalidated bytes
/// can poison a cache because a present malformed cache candidate is terminal.
/// Callers should write registry bytes only after successful expansion,
/// validation, and insertion.
///
/// Dropping the returned future yields no receipt, and already-issued storage
/// work may have occurred. The caller retains `archive`; full replay with the
/// same exact bytes is the recovery contract.
///
/// ```no_run
/// # #[cfg(feature = "package-reading")]
/// # mod example {
/// use std::error::Error;
/// use typst_pack::{
///     PackageReadFailures, PackageCatalog, PackageDisposition,
///     PackageExpansionLimits,
/// };
/// use typst_pack::opendal::OperatorBindings;
/// use typst_pack::opendal::pack_assembly::{
///     PackageRead, RegistryArchiveResidue, insert_read_package,
/// };
/// use typst_pack::opendal::write::{
///     PackageCacheArchiveWriteRequest, write_package_cache_archive,
/// };
///
/// async fn insert_then_write_registry_archive(
///     bindings: &OperatorBindings,
///     catalog: &mut PackageCatalog,
///     failures: &mut PackageReadFailures,
///     read: PackageRead,
/// ) -> Result<Option<RegistryArchiveResidue>, Box<dyn Error>> {
///     let Some(residue) = insert_read_package(
///         catalog,
///         failures,
///         read,
///         PackageDisposition::Embedded,
///         PackageExpansionLimits::reference_v1(),
///     )? else {
///         return Ok(None);
///     };
///
///     let request = PackageCacheArchiveWriteRequest::new(
///         residue.destination().clone(),
///     )?;
///     if let Err(cache_failure) =
///         write_package_cache_archive(bindings, &request, residue.bytes()).await
///     {
///         // Insertion remains successful. The residue retains the exact bytes
///         // and destination so the caller can report and replay independently.
///         drop(cache_failure);
///     }
///
///     Ok(Some(residue))
/// }
/// # }
/// ```
#[allow(clippy::result_large_err)]
pub async fn write_package_cache_archive<R: OperatorResolver + ?Sized>(
    resolver: &R,
    request: &PackageCacheArchiveWriteRequest,
    archive: &[u8],
) -> Result<PackageCacheArchiveWriteReceipt, PackageCacheArchiveWriteError> {
    let mut progress = PackageCacheArchiveWriteProgress::new();
    let destination_path = request.destination().operation_path();
    let keys = [ExactKey::new(destination_path, archive)];
    {
        let mut operation = PackageCacheArchiveWriteOperation {
            request,
            progress: &mut progress,
        };
        write_create_or_verify_exact_keys(
            resolver,
            request.destination().binding(),
            &keys,
            &mut operation,
        )
        .await?;
    }

    Ok(PackageCacheArchiveWriteReceipt {
        destination: request.destination().clone(),
        policy: request.policy(),
        progress,
    })
}

/// A failure while writing caller-supplied package-cache archive bytes.
///
/// This error's own `Display` and `Debug` output omit native resolver and
/// OpenDAL messages. Rendering its source chain may disclose backend context.
#[derive(Debug, thiserror::Error)]
#[error(
    "package-cache archive write failed for binding {} at exact-object operation path {:?} during {phase:?}: {cause}",
    .destination.binding(),
    .destination.operation_path(),
)]
pub struct PackageCacheArchiveWriteError {
    destination: Location,
    policy: WritePolicy,
    failed_path: Option<String>,
    phase: OpenDalWritePhase,
    progress: PackageCacheArchiveWriteProgress,
    commit_certainty: CommitCertainty,
    #[source]
    cause: RedactedError<PackageCacheArchiveWriteErrorCause>,
}

impl PackageCacheArchiveWriteError {
    pub fn destination(&self) -> &Location {
        &self.destination
    }

    pub const fn policy(&self) -> WritePolicy {
        self.policy
    }

    pub fn failed_path(&self) -> Option<&str> {
        self.failed_path.as_deref()
    }

    pub const fn phase(&self) -> OpenDalWritePhase {
        self.phase
    }

    pub fn progress(&self) -> &PackageCacheArchiveWriteProgress {
        &self.progress
    }

    pub const fn commit_certainty(&self) -> CommitCertainty {
        self.commit_certainty
    }

    pub fn cause(&self) -> &PackageCacheArchiveWriteErrorCause {
        self.cause.inner()
    }
}

/// The typed cause of an OpenDAL package-cache archive write failure.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum PackageCacheArchiveWriteErrorCause {
    #[error("operator resolution failed")]
    ResolveOperator(#[source] BoxError),
    #[error("the write policy is unsupported")]
    UnsupportedPolicy { policy: WritePolicy },
    #[error("the archive exceeds the advertised object size")]
    UnsupportedObjectSize { byte_length: u64 },
    #[error("a preflight read failed")]
    PreflightRead(#[source] ::opendal::Error),
    #[error("destination bytes conflict")]
    ByteConflict {
        expected_byte_length: u64,
        observed_byte_length_at_least: u64,
    },
    #[error("a conditional create failed")]
    ConditionalCreate(#[source] ::opendal::Error),
    #[error("race verification failed")]
    RaceVerification(#[source] ::opendal::Error),
}

/// A validated request to write one Pack Extraction Plan beneath a prefix.
#[derive(Clone, Debug)]
pub struct PackExtractionWriteRequest {
    destination: Location,
    policy: WritePolicy,
}

impl PackExtractionWriteRequest {
    /// Validates a normalized prefix destination and retains the explicit policy.
    pub fn new(
        destination: Location,
        policy: WritePolicy,
    ) -> Result<Self, PackExtractionWriteRequestError> {
        destination.require_prefix().map_err(|source| {
            PackExtractionWriteRequestError::InvalidDestinationRole {
                location: destination.clone(),
                source,
            }
        })?;

        Ok(Self {
            destination,
            policy,
        })
    }

    pub fn destination(&self) -> &Location {
        &self.destination
    }

    pub const fn policy(&self) -> WritePolicy {
        self.policy
    }
}

/// A reason a Pack Extraction write request cannot be accepted.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum PackExtractionWriteRequestError {
    #[error("Pack Extraction destination {location} is not a prefix: {source}")]
    InvalidDestinationRole {
        location: Location,
        #[source]
        source: LocationRoleError,
    },
}

/// A validated request to write every artifact in one succeeded Compilation Result.
#[derive(Clone, Debug)]
pub struct CompilationArtifactWriteRequest {
    compilation_result_identity: CanonicalIdentity,
    destination: Location,
    artifact_keys: Vec<String>,
    policy: WritePolicy,
}

impl CompilationArtifactWriteRequest {
    /// Validates a prefix destination and one decoded relative key per canonical artifact.
    pub fn new(
        result: &CompilationResult,
        destination: Location,
        artifact_keys: impl IntoIterator<Item = impl Into<String>>,
        policy: WritePolicy,
    ) -> Result<Self, CompilationArtifactWriteRequestRejection> {
        let compilation_result_identity = result.result_identity();
        let artifact_keys = artifact_keys
            .into_iter()
            .map(Into::into)
            .collect::<Vec<_>>();
        let mut issues = Vec::new();

        if result.status() != CompilationStatus::Succeeded {
            issues.push(CompilationArtifactWriteRequestIssue::ResultNotSucceeded);
        }
        if let Err(source) = destination.require_prefix() {
            issues.push(
                CompilationArtifactWriteRequestIssue::InvalidDestinationRole {
                    location: destination.clone(),
                    source,
                },
            );
        }
        if result.artifacts().len() != artifact_keys.len() {
            issues.push(
                CompilationArtifactWriteRequestIssue::ArtifactKeyCountMismatch {
                    expected: result.artifacts().len(),
                    actual: artifact_keys.len(),
                },
            );
        }
        let mut first_indices = BTreeMap::new();
        for (artifact_index, key) in artifact_keys.iter().enumerate() {
            if let Err(reason) = validate_artifact_key(key) {
                issues.push(CompilationArtifactWriteRequestIssue::InvalidArtifactKey {
                    artifact_index,
                    key: key.clone(),
                    reason,
                });
            }
            if let Some(&first_artifact_index) = first_indices.get(key) {
                issues.push(CompilationArtifactWriteRequestIssue::DuplicateArtifactKey {
                    key: key.clone(),
                    first_artifact_index,
                    duplicate_artifact_index: artifact_index,
                });
            } else {
                first_indices.insert(key.clone(), artifact_index);
            }
        }

        if !issues.is_empty() {
            return Err(CompilationArtifactWriteRequestRejection {
                compilation_result_identity,
                destination,
                issues: issues.into_boxed_slice(),
            });
        }

        Ok(Self {
            compilation_result_identity,
            destination,
            artifact_keys,
            policy,
        })
    }

    pub const fn compilation_result_identity(&self) -> CanonicalIdentity {
        self.compilation_result_identity
    }

    pub const fn destination(&self) -> &Location {
        &self.destination
    }

    pub fn artifact_keys(&self) -> &[String] {
        &self.artifact_keys
    }

    pub const fn policy(&self) -> WritePolicy {
        self.policy
    }
}

/// Complete deterministic rejection of a Compilation Output Artifact write request.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[error(
    "Compilation Output Artifact write request rejected for binding {} beneath prefix operation path {:?} with {} issue(s)",
    .destination.binding(),
    .destination.operation_path(),
    .issues.len(),
)]
pub struct CompilationArtifactWriteRequestRejection {
    compilation_result_identity: CanonicalIdentity,
    destination: Location,
    issues: Box<[CompilationArtifactWriteRequestIssue]>,
}

impl CompilationArtifactWriteRequestRejection {
    pub const fn compilation_result_identity(&self) -> CanonicalIdentity {
        self.compilation_result_identity
    }

    pub fn issues(&self) -> &[CompilationArtifactWriteRequestIssue] {
        &self.issues
    }
}

/// One independently detectable issue in a Compilation Output Artifact write request.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum CompilationArtifactWriteRequestIssue {
    #[error("a rejected Compilation Result cannot be written")]
    ResultNotSucceeded,
    #[error("Compilation Output Artifact destination {location} is not a prefix: {source}")]
    InvalidDestinationRole {
        location: Location,
        #[source]
        source: LocationRoleError,
    },
    #[error("expected {expected} artifact key(s), but received {actual}")]
    ArtifactKeyCountMismatch { expected: usize, actual: usize },
    #[error("artifact key {key:?} at index {artifact_index} is invalid: {reason}")]
    InvalidArtifactKey {
        artifact_index: usize,
        key: String,
        reason: CompilationArtifactKeyIssue,
    },
    #[error(
        "artifact key {key:?} at index {duplicate_artifact_index} duplicates index {first_artifact_index}"
    )]
    DuplicateArtifactKey {
        key: String,
        first_artifact_index: usize,
        duplicate_artifact_index: usize,
    },
}

/// A reason a decoded relative Compilation Output Artifact key is unsafe or ambiguous.
#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum CompilationArtifactKeyIssue {
    #[error("an artifact key cannot be empty")]
    Empty,
    #[error("an artifact key cannot start with a slash")]
    LeadingSlash,
    #[error("an artifact key cannot end with a slash")]
    TrailingSlash,
    #[error("an artifact key cannot contain a repeated separator")]
    RepeatedSeparator,
    #[error("an artifact key cannot contain a dot segment")]
    DotSegment,
    #[error("an artifact key cannot contain a backslash")]
    Backslash,
    #[error("an artifact key cannot contain a control character")]
    ControlCharacter,
    #[error("an artifact key aliases another operation path at byte {index}")]
    NormalizationAlias { index: usize },
}

fn validate_artifact_key(key: &str) -> Result<(), CompilationArtifactKeyIssue> {
    if key.is_empty() {
        return Err(CompilationArtifactKeyIssue::Empty);
    }
    if key.starts_with('/') {
        return Err(CompilationArtifactKeyIssue::LeadingSlash);
    }
    if key.ends_with('/') {
        return Err(CompilationArtifactKeyIssue::TrailingSlash);
    }
    validate_decoded_artifact_key_path(key).map_err(|error| match error {
        LocationError::RepeatedSeparator { .. } => CompilationArtifactKeyIssue::RepeatedSeparator,
        LocationError::DotSegment { .. } => CompilationArtifactKeyIssue::DotSegment,
        LocationError::Backslash { .. } => CompilationArtifactKeyIssue::Backslash,
        LocationError::ControlCharacter { .. } => CompilationArtifactKeyIssue::ControlCharacter,
        LocationError::NormalizationAlias { index } => {
            CompilationArtifactKeyIssue::NormalizationAlias { index }
        }
        _ => unreachable!("decoded operation-path validation returned an unrelated error"),
    })
}

/// Writes every entry in one Pack Extraction Plan beneath the request's prefix.
///
/// The caller-owned progress is cleared synchronously before the returned future
/// can be polled or dropped. Replaying the same plan with `CreateOrVerify`
/// accepts objects whose bytes already match.
///
/// ```no_run
/// use typst_pack::PackExtractionPlan;
/// use typst_pack::opendal::OperatorBindings;
/// use typst_pack::opendal::write::{
///     PackExtractionWriteProgress, PackExtractionWriteRequest,
///     WritePolicy, write_pack_extraction_plan,
/// };
///
/// async fn write_and_replay_partial_attempt(
///     bindings: &OperatorBindings,
///     plan: &PackExtractionPlan,
/// ) -> Result<(), Box<dyn std::error::Error>> {
///     let request = PackExtractionWriteRequest::new(
///         "project:/extracted/".parse()?,
///         WritePolicy::CreateOrVerify,
///     )?;
///     let mut progress = PackExtractionWriteProgress::new();
///
///     if let Err(error) =
///         write_pack_extraction_plan(bindings, &request, plan, &mut progress).await
///     {
///         // The caller retains the exact completed prefix after a partial attempt.
///         assert_eq!(error.progress(), &progress);
///         write_pack_extraction_plan(bindings, &request, plan, &mut progress).await?;
///     }
///
///     Ok(())
/// }
/// ```
#[allow(clippy::result_large_err)]
pub fn write_pack_extraction_plan<'a, R: OperatorResolver + ?Sized>(
    resolver: &'a R,
    request: &'a PackExtractionWriteRequest,
    plan: &'a crate::PackExtractionPlan,
    progress: &'a mut PackExtractionWriteProgress,
) -> impl Future<Output = Result<PackExtractionWriteReceipt, PackExtractionWriteError>> + 'a {
    progress.clear();
    async move {
        let mut destinations = Vec::with_capacity(plan.entries().len());
        for entry in plan.entries() {
            let destination = request
                .destination()
                .compose(entry.relative_path())
                .map_err(|_| {
                    pack_extraction_write_error(
                        request,
                        Some(entry.relative_path().to_owned()),
                        None,
                        OpenDalWritePhase::DestinationValidation,
                        progress,
                        CommitCertainty::NotCommitted,
                        PackExtractionWriteErrorCause::InvalidDestinationPath {
                            relative_path: entry.relative_path().to_owned(),
                        },
                    )
                })?;
            destinations.push(destination);
        }

        let keys = destinations
            .iter()
            .zip(plan.entries())
            .map(|(destination, entry)| ExactKey::new(destination.operation_path(), entry.bytes()))
            .collect::<Vec<_>>();
        {
            let mut operation = PackExtractionWriteOperation {
                request,
                plan,
                progress,
            };
            write_exact_keys(
                resolver,
                request.destination().binding(),
                request.policy(),
                &keys,
                &mut operation,
            )
            .await?;
        }

        Ok(PackExtractionWriteReceipt::new(
            *plan.pack_identity(),
            progress.clone(),
        ))
    }
}

/// A failure while writing a Pack Extraction Plan through OpenDAL.
///
/// This error's own `Display` and `Debug` output omit native resolver and
/// OpenDAL messages. Rendering its source chain may disclose backend context.
#[derive(Debug, thiserror::Error)]
#[error(
    "Pack Extraction write failed for binding {} beneath prefix operation path {:?} during {phase:?}: {cause}",
    .destination.binding(),
    .destination.operation_path(),
)]
pub struct PackExtractionWriteError {
    destination: Location,
    policy: WritePolicy,
    failed_relative_path: Option<String>,
    failed_destination_path: Option<String>,
    phase: OpenDalWritePhase,
    progress: PackExtractionWriteProgress,
    commit_certainty: CommitCertainty,
    #[source]
    cause: RedactedError<PackExtractionWriteErrorCause>,
}

impl PackExtractionWriteError {
    pub fn destination(&self) -> &Location {
        &self.destination
    }

    pub const fn policy(&self) -> WritePolicy {
        self.policy
    }

    pub fn failed_relative_path(&self) -> Option<&str> {
        self.failed_relative_path.as_deref()
    }

    pub fn failed_destination_path(&self) -> Option<&str> {
        self.failed_destination_path.as_deref()
    }

    pub const fn phase(&self) -> OpenDalWritePhase {
        self.phase
    }

    pub fn progress(&self) -> &PackExtractionWriteProgress {
        &self.progress
    }

    pub const fn commit_certainty(&self) -> CommitCertainty {
        self.commit_certainty
    }

    pub fn cause(&self) -> &PackExtractionWriteErrorCause {
        self.cause.inner()
    }
}

/// The typed cause of an OpenDAL Pack Extraction write failure.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum PackExtractionWriteErrorCause {
    #[error("a composed destination path was invalid")]
    InvalidDestinationPath { relative_path: String },
    #[error("operator resolution failed")]
    ResolveOperator(#[source] BoxError),
    #[error("the write policy is unsupported")]
    UnsupportedPolicy { policy: WritePolicy },
    #[error("an entry exceeds the advertised object size")]
    UnsupportedObjectSize { byte_length: u64 },
    #[error("a preflight read failed")]
    PreflightRead(#[source] ::opendal::Error),
    #[error("destination bytes conflict")]
    ByteConflict {
        expected_byte_length: u64,
        observed_byte_length_at_least: u64,
    },
    #[error("a conditional create failed")]
    ConditionalCreate(#[source] ::opendal::Error),
    #[error("race verification failed")]
    RaceVerification(#[source] ::opendal::Error),
    #[error("a direct write failed")]
    DirectWrite(#[source] ::opendal::Error),
}

fn pack_extraction_write_error(
    request: &PackExtractionWriteRequest,
    failed_relative_path: Option<String>,
    failed_destination_path: Option<String>,
    phase: OpenDalWritePhase,
    progress: &PackExtractionWriteProgress,
    commit_certainty: CommitCertainty,
    cause: PackExtractionWriteErrorCause,
) -> PackExtractionWriteError {
    PackExtractionWriteError {
        destination: request.destination().clone(),
        policy: request.policy(),
        failed_relative_path,
        failed_destination_path,
        phase,
        progress: progress.clone(),
        commit_certainty,
        cause: RedactedError::new(cause),
    }
}

/// Writes every canonical artifact beneath the request's normalized prefix.
///
/// The caller-owned progress is cleared synchronously before the returned future
/// can be polled or dropped. Replaying the same result with `CreateOrVerify`
/// accepts objects whose bytes already match.
///
/// ```no_run
/// use typst_pack::CompilationResult;
/// use typst_pack::opendal::OperatorBindings;
/// use typst_pack::opendal::write::{
///     CompilationArtifactWriteProgress, CompilationArtifactWriteRequest,
///     WritePolicy, write_compilation_artifacts,
/// };
///
/// async fn write_and_replay(
///     bindings: &OperatorBindings,
///     document_result: &CompilationResult,
///     page_result: &CompilationResult,
/// ) -> Result<(), Box<dyn std::error::Error>> {
///     let document_request = CompilationArtifactWriteRequest::new(
///         document_result,
///         "artifacts:/document/".parse()?,
///         ["document.pdf"],
///         WritePolicy::CreateOrVerify,
///     )?;
///     let page_keys = page_result
///         .artifacts()
///         .iter()
///         .map(|artifact| format!("page-{}.svg", artifact.source_page_number().unwrap()))
///         .collect::<Vec<_>>();
///     let page_request = CompilationArtifactWriteRequest::new(
///         page_result,
///         "artifacts:/pages/".parse()?,
///         page_keys,
///         WritePolicy::CreateOrVerify,
///     )?;
///
///     let mut document_progress = CompilationArtifactWriteProgress::new();
///     write_compilation_artifacts(
///         bindings,
///         &document_request,
///         document_result,
///         &mut document_progress,
///     )
///     .await?;
///     write_compilation_artifacts(
///         bindings,
///         &document_request,
///         document_result,
///         &mut document_progress,
///     )
///     .await?;
///
///     let mut page_progress = CompilationArtifactWriteProgress::new();
///     write_compilation_artifacts(bindings, &page_request, page_result, &mut page_progress)
///         .await?;
///     write_compilation_artifacts(bindings, &page_request, page_result, &mut page_progress)
///         .await?;
///     Ok(())
/// }
/// ```
#[allow(clippy::result_large_err)]
pub fn write_compilation_artifacts<'a, R: OperatorResolver + ?Sized>(
    resolver: &'a R,
    request: &'a CompilationArtifactWriteRequest,
    result: &'a CompilationResult,
    progress: &'a mut CompilationArtifactWriteProgress,
) -> impl Future<Output = Result<CompilationArtifactWriteReceipt, CompilationArtifactWriteError>> + 'a
{
    progress.clear();
    async move {
        if request.compilation_result_identity() != result.result_identity() {
            return Err(compilation_artifact_write_error(
                request,
                None,
                None,
                OpenDalWritePhase::ResultValidation,
                progress,
                CommitCertainty::NotCommitted,
                CompilationArtifactWriteErrorCause::CompilationResultMismatch {
                    expected: request.compilation_result_identity(),
                    actual: result.result_identity(),
                },
            ));
        }

        let mut destinations = Vec::with_capacity(request.artifact_keys().len());
        for (artifact_index, key) in request.artifact_keys().iter().enumerate() {
            let destination = request.destination().compose(key).map_err(|_| {
                compilation_artifact_write_error(
                    request,
                    Some(artifact_index),
                    None,
                    OpenDalWritePhase::DestinationValidation,
                    progress,
                    CommitCertainty::NotCommitted,
                    CompilationArtifactWriteErrorCause::InvalidDestinationPath {
                        artifact_index,
                        key: key.clone(),
                    },
                )
            })?;
            destinations.push(destination);
        }

        let keys = destinations
            .iter()
            .zip(result.artifacts())
            .map(|(destination, artifact)| {
                ExactKey::new(destination.operation_path(), artifact.bytes())
            })
            .collect::<Vec<_>>();
        {
            let mut operation = CompilationArtifactWriteOperation { request, progress };
            write_exact_keys(
                resolver,
                request.destination().binding(),
                request.policy(),
                &keys,
                &mut operation,
            )
            .await?;
        }

        Ok(CompilationArtifactWriteReceipt::new(
            request.compilation_result_identity(),
            progress.clone(),
        ))
    }
}

/// A failure while writing a Compilation Result's exact artifacts through OpenDAL.
///
/// This error's own `Display` and `Debug` output omit native resolver and
/// OpenDAL messages. Rendering its source chain may disclose backend context.
#[derive(Debug, thiserror::Error)]
#[error(
    "Compilation Output Artifact write failed for binding {} beneath prefix operation path {:?} during {phase:?}: {cause}",
    .destination.binding(),
    .destination.operation_path(),
)]
pub struct CompilationArtifactWriteError {
    compilation_result_identity: CanonicalIdentity,
    destination: Location,
    policy: WritePolicy,
    failed_artifact_index: Option<usize>,
    failed_key: Option<String>,
    failed_destination_path: Option<String>,
    phase: OpenDalWritePhase,
    progress: CompilationArtifactWriteProgress,
    commit_certainty: CommitCertainty,
    #[source]
    cause: RedactedError<CompilationArtifactWriteErrorCause>,
}

impl CompilationArtifactWriteError {
    pub const fn compilation_result_identity(&self) -> CanonicalIdentity {
        self.compilation_result_identity
    }

    pub const fn destination(&self) -> &Location {
        &self.destination
    }

    pub const fn policy(&self) -> WritePolicy {
        self.policy
    }

    pub const fn failed_artifact_index(&self) -> Option<usize> {
        self.failed_artifact_index
    }

    pub fn failed_key(&self) -> Option<&str> {
        self.failed_key.as_deref()
    }

    pub fn failed_destination_path(&self) -> Option<&str> {
        self.failed_destination_path.as_deref()
    }

    pub const fn phase(&self) -> OpenDalWritePhase {
        self.phase
    }

    pub const fn progress(&self) -> &CompilationArtifactWriteProgress {
        &self.progress
    }

    pub const fn commit_certainty(&self) -> CommitCertainty {
        self.commit_certainty
    }

    pub const fn cause(&self) -> &CompilationArtifactWriteErrorCause {
        self.cause.inner()
    }
}

/// The typed cause of an OpenDAL Compilation Output Artifact write failure.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CompilationArtifactWriteErrorCause {
    #[error("the Compilation Result identity mismatched")]
    CompilationResultMismatch {
        expected: CanonicalIdentity,
        actual: CanonicalIdentity,
    },
    #[error("a composed destination path was invalid")]
    InvalidDestinationPath { artifact_index: usize, key: String },
    #[error("operator resolution failed")]
    ResolveOperator(#[source] BoxError),
    #[error("the write policy is unsupported")]
    UnsupportedPolicy { policy: WritePolicy },
    #[error("an artifact exceeds the advertised object size")]
    UnsupportedObjectSize {
        artifact_index: usize,
        byte_length: u64,
    },
    #[error("a preflight read failed")]
    PreflightRead(#[source] ::opendal::Error),
    #[error("destination bytes conflict")]
    ByteConflict {
        expected_byte_length: u64,
        observed_byte_length_at_least: u64,
    },
    #[error("a conditional create failed")]
    ConditionalCreate(#[source] ::opendal::Error),
    #[error("race verification failed")]
    RaceVerification(#[source] ::opendal::Error),
    #[error("a direct write failed")]
    DirectWrite(#[source] ::opendal::Error),
}

fn compilation_artifact_write_error(
    request: &CompilationArtifactWriteRequest,
    failed_artifact_index: Option<usize>,
    failed_destination_path: Option<String>,
    phase: OpenDalWritePhase,
    progress: &CompilationArtifactWriteProgress,
    commit_certainty: CommitCertainty,
    cause: CompilationArtifactWriteErrorCause,
) -> CompilationArtifactWriteError {
    let failed_key = failed_artifact_index.map(|index| request.artifact_keys()[index].clone());
    CompilationArtifactWriteError {
        compilation_result_identity: request.compilation_result_identity(),
        destination: request.destination().clone(),
        policy: request.policy(),
        failed_artifact_index,
        failed_key,
        failed_destination_path,
        phase,
        progress: progress.clone(),
        commit_certainty,
        cause: RedactedError::new(cause),
    }
}

macro_rules! workflow_evidence {
    (
        $entry:ident, $progress:ident, $receipt:ident,
        entry { $($entry_field:ident: $entry_type:ty),* $(,)? },
        entry_accessors { $($entry_accessors:item)* },
        progress_accessors { $($progress_accessors:item)* },
        receipt { $($receipt_field:ident: $receipt_type:ty),* $(,)? },
        receipt_accessors { $($receipt_accessors:item)* }
    ) => {
        #[derive(Clone, Debug, Eq, PartialEq)]
        pub struct $entry {
            $($entry_field: $entry_type,)*
            outcome: WriteKeyOutcome,
        }

        impl $entry {
            $($entry_accessors)*

            pub const fn outcome(&self) -> WriteKeyOutcome {
                self.outcome
            }

        }

        #[derive(Clone, Debug, Default, Eq, PartialEq)]
        pub struct $progress {
            completed: Vec<$entry>,
        }

        impl $progress {
            pub const fn new() -> Self {
                Self { completed: Vec::new() }
            }

            $($progress_accessors)*

            pub(crate) fn clear(&mut self) {
                self.completed.clear();
            }

            pub(crate) fn push(&mut self, entry: $entry) {
                self.completed.push(entry);
            }
        }

        #[derive(Clone, Debug, Eq, PartialEq)]
        pub struct $receipt {
            $($receipt_field: $receipt_type,)*
            progress: $progress,
        }

        impl $receipt {
            $($receipt_accessors)*

            pub const fn progress(&self) -> &$progress {
                &self.progress
            }
        }
    };
}

workflow_evidence!(
    PackArchiveWriteEntry,
    PackArchiveWriteProgress,
    PackArchiveWriteReceipt,
    entry { destination_path: String },
    entry_accessors {
        pub fn destination_path(&self) -> &str { &self.destination_path }
    },
    progress_accessors {
        pub fn completed(&self) -> Option<&PackArchiveWriteEntry> { self.completed.first() }
        pub fn outcome(&self) -> Option<WriteKeyOutcome> {
            self.completed().map(PackArchiveWriteEntry::outcome)
        }
    },
    receipt { destination: Location, policy: WritePolicy },
    receipt_accessors {
        pub fn destination(&self) -> &Location { &self.destination }
        pub const fn policy(&self) -> WritePolicy { self.policy }
        pub fn completed(&self) -> &PackArchiveWriteEntry {
            self.progress.completed().expect("a Pack Archive receipt has one completed entry")
        }
        pub const fn outcome(&self) -> WriteKeyOutcome {
            match self.progress.completed.as_slice() {
                [entry, ..] => entry.outcome,
                [] => panic!("a Pack Archive receipt has one completed entry"),
            }
        }
    }
);

workflow_evidence!(
    PackageCacheArchiveWriteEntry,
    PackageCacheArchiveWriteProgress,
    PackageCacheArchiveWriteReceipt,
    entry { destination_path: String },
    entry_accessors {
        pub fn destination_path(&self) -> &str { &self.destination_path }
    },
    progress_accessors {
        pub fn completed(&self) -> Option<&PackageCacheArchiveWriteEntry> { self.completed.first() }
        pub fn outcome(&self) -> Option<WriteKeyOutcome> {
            self.completed().map(PackageCacheArchiveWriteEntry::outcome)
        }
    },
    receipt { destination: Location, policy: WritePolicy },
    receipt_accessors {
        pub fn destination(&self) -> &Location { &self.destination }
        pub const fn policy(&self) -> WritePolicy { self.policy }
        pub fn completed(&self) -> &PackageCacheArchiveWriteEntry {
            self.progress.completed().expect("a package-cache archive receipt has one completed entry")
        }
        pub const fn outcome(&self) -> WriteKeyOutcome {
            match self.progress.completed.as_slice() {
                [entry, ..] => entry.outcome,
                [] => panic!("a package-cache archive receipt has one completed entry"),
            }
        }
    }
);

pub(crate) struct ExactKey<'a> {
    path: &'a str,
    bytes: &'a [u8],
}

impl<'a> ExactKey<'a> {
    pub(crate) const fn new(path: &'a str, bytes: &'a [u8]) -> Self {
        Self { path, bytes }
    }
}

#[derive(Debug)]
pub(crate) struct ExactKeyWriteReceipt {
    completed: Vec<ExactKeyWriteEntry>,
}

impl ExactKeyWriteReceipt {
    #[cfg(test)]
    fn completed(&self) -> &[ExactKeyWriteEntry] {
        &self.completed
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct ExactKeyWriteEntry {
    pub(crate) index: usize,
    pub(crate) outcome: WriteKeyOutcome,
}

struct ExactKeyWriteFailure {
    phase: OpenDalWritePhase,
    failed_index: Option<usize>,
    failed_path: Option<String>,
    commit_certainty: CommitCertainty,
}

impl ExactKeyWriteFailure {
    fn operation(phase: OpenDalWritePhase) -> Self {
        Self {
            phase,
            failed_index: None,
            failed_path: None,
            commit_certainty: CommitCertainty::NotCommitted,
        }
    }

    fn key(
        phase: OpenDalWritePhase,
        index: usize,
        key: &ExactKey<'_>,
        commit_certainty: CommitCertainty,
    ) -> Self {
        Self {
            phase,
            failed_index: Some(index),
            failed_path: Some(key.path.to_owned()),
            commit_certainty,
        }
    }
}

trait ExactKeyWriteCause: Sized {
    fn resolve_operator(source: BoxError) -> Self;
    fn unsupported_policy(policy: WritePolicy) -> Self;
    fn unsupported_object_size(index: usize, byte_length: u64) -> Self;
    fn preflight_read(source: opendal::Error) -> Self;
    fn byte_conflict(expected_byte_length: u64, observed_byte_length_at_least: u64) -> Self;
    fn conditional_create(source: opendal::Error) -> Self;
    fn race_verification(source: opendal::Error) -> Self;
}

trait ExactKeyOverwriteCause: ExactKeyWriteCause {
    fn direct_write(source: opendal::Error) -> Self;
}

trait ExactKeyWriteOperation {
    type Error;
    type Cause: ExactKeyWriteCause;

    fn completed_entry(&mut self, entry: ExactKeyWriteEntry);
    fn error(&self, failure: ExactKeyWriteFailure, cause: Self::Cause) -> Self::Error;
}

struct PackArchiveWriteOperation<'a> {
    request: &'a PackArchiveWriteRequest,
    progress: &'a mut PackArchiveWriteProgress,
}

impl ExactKeyWriteOperation for PackArchiveWriteOperation<'_> {
    type Error = PackArchiveWriteError;
    type Cause = PackArchiveWriteErrorCause;

    fn completed_entry(&mut self, entry: ExactKeyWriteEntry) {
        self.progress.push(PackArchiveWriteEntry {
            destination_path: self.request.destination().operation_path().to_owned(),
            outcome: entry.outcome,
        });
    }

    fn error(&self, failure: ExactKeyWriteFailure, cause: Self::Cause) -> Self::Error {
        PackArchiveWriteError {
            destination: self.request.destination().clone(),
            policy: self.request.policy(),
            failed_path: failure.failed_path,
            phase: failure.phase,
            progress: self.progress.clone(),
            commit_certainty: failure.commit_certainty,
            cause: RedactedError::new(cause),
        }
    }
}

impl ExactKeyWriteCause for PackArchiveWriteErrorCause {
    fn resolve_operator(source: BoxError) -> Self {
        Self::ResolveOperator(source)
    }

    fn unsupported_policy(policy: WritePolicy) -> Self {
        Self::UnsupportedPolicy { policy }
    }

    fn unsupported_object_size(_: usize, byte_length: u64) -> Self {
        Self::UnsupportedObjectSize { byte_length }
    }

    fn preflight_read(source: opendal::Error) -> Self {
        Self::PreflightRead(source)
    }

    fn byte_conflict(expected_byte_length: u64, observed_byte_length_at_least: u64) -> Self {
        Self::ByteConflict {
            expected_byte_length,
            observed_byte_length_at_least,
        }
    }

    fn conditional_create(source: opendal::Error) -> Self {
        Self::ConditionalCreate(source)
    }

    fn race_verification(source: opendal::Error) -> Self {
        Self::RaceVerification(source)
    }
}

impl ExactKeyOverwriteCause for PackArchiveWriteErrorCause {
    fn direct_write(source: opendal::Error) -> Self {
        Self::DirectWrite(source)
    }
}

struct PackageCacheArchiveWriteOperation<'a> {
    request: &'a PackageCacheArchiveWriteRequest,
    progress: &'a mut PackageCacheArchiveWriteProgress,
}

impl ExactKeyWriteOperation for PackageCacheArchiveWriteOperation<'_> {
    type Error = PackageCacheArchiveWriteError;
    type Cause = PackageCacheArchiveWriteErrorCause;

    fn completed_entry(&mut self, entry: ExactKeyWriteEntry) {
        self.progress.push(PackageCacheArchiveWriteEntry {
            destination_path: self.request.destination().operation_path().to_owned(),
            outcome: entry.outcome,
        });
    }

    fn error(&self, failure: ExactKeyWriteFailure, cause: Self::Cause) -> Self::Error {
        PackageCacheArchiveWriteError {
            destination: self.request.destination().clone(),
            policy: self.request.policy(),
            failed_path: failure.failed_path,
            phase: failure.phase,
            progress: self.progress.clone(),
            commit_certainty: failure.commit_certainty,
            cause: RedactedError::new(cause),
        }
    }
}

impl ExactKeyWriteCause for PackageCacheArchiveWriteErrorCause {
    fn resolve_operator(source: BoxError) -> Self {
        Self::ResolveOperator(source)
    }

    fn unsupported_policy(policy: WritePolicy) -> Self {
        Self::UnsupportedPolicy { policy }
    }

    fn unsupported_object_size(_: usize, byte_length: u64) -> Self {
        Self::UnsupportedObjectSize { byte_length }
    }

    fn preflight_read(source: opendal::Error) -> Self {
        Self::PreflightRead(source)
    }

    fn byte_conflict(expected_byte_length: u64, observed_byte_length_at_least: u64) -> Self {
        Self::ByteConflict {
            expected_byte_length,
            observed_byte_length_at_least,
        }
    }

    fn conditional_create(source: opendal::Error) -> Self {
        Self::ConditionalCreate(source)
    }

    fn race_verification(source: opendal::Error) -> Self {
        Self::RaceVerification(source)
    }
}

struct PackExtractionWriteOperation<'a> {
    request: &'a PackExtractionWriteRequest,
    plan: &'a crate::PackExtractionPlan,
    progress: &'a mut PackExtractionWriteProgress,
}

impl ExactKeyWriteOperation for PackExtractionWriteOperation<'_> {
    type Error = PackExtractionWriteError;
    type Cause = PackExtractionWriteErrorCause;

    fn completed_entry(&mut self, entry: ExactKeyWriteEntry) {
        let index = entry.index;
        self.progress.push(PackExtractionWriteEntry::new(
            self.plan.entries()[index].relative_path().to_owned(),
            entry.outcome,
        ));
    }

    fn error(&self, failure: ExactKeyWriteFailure, cause: Self::Cause) -> Self::Error {
        let failed_relative_path = failure
            .failed_index
            .map(|index| self.plan.entries()[index].relative_path().to_owned());
        pack_extraction_write_error(
            self.request,
            failed_relative_path,
            failure.failed_path,
            failure.phase,
            self.progress,
            failure.commit_certainty,
            cause,
        )
    }
}

impl ExactKeyWriteCause for PackExtractionWriteErrorCause {
    fn resolve_operator(source: BoxError) -> Self {
        Self::ResolveOperator(source)
    }

    fn unsupported_policy(policy: WritePolicy) -> Self {
        Self::UnsupportedPolicy { policy }
    }

    fn unsupported_object_size(_: usize, byte_length: u64) -> Self {
        Self::UnsupportedObjectSize { byte_length }
    }

    fn preflight_read(source: opendal::Error) -> Self {
        Self::PreflightRead(source)
    }

    fn byte_conflict(expected_byte_length: u64, observed_byte_length_at_least: u64) -> Self {
        Self::ByteConflict {
            expected_byte_length,
            observed_byte_length_at_least,
        }
    }

    fn conditional_create(source: opendal::Error) -> Self {
        Self::ConditionalCreate(source)
    }

    fn race_verification(source: opendal::Error) -> Self {
        Self::RaceVerification(source)
    }
}

impl ExactKeyOverwriteCause for PackExtractionWriteErrorCause {
    fn direct_write(source: opendal::Error) -> Self {
        Self::DirectWrite(source)
    }
}

struct CompilationArtifactWriteOperation<'a> {
    request: &'a CompilationArtifactWriteRequest,
    progress: &'a mut CompilationArtifactWriteProgress,
}

impl ExactKeyWriteOperation for CompilationArtifactWriteOperation<'_> {
    type Error = CompilationArtifactWriteError;
    type Cause = CompilationArtifactWriteErrorCause;

    fn completed_entry(&mut self, entry: ExactKeyWriteEntry) {
        let artifact_index = entry.index;
        self.progress.push(CompilationArtifactWriteEntry::new(
            artifact_index,
            entry.outcome,
        ));
    }

    fn error(&self, failure: ExactKeyWriteFailure, cause: Self::Cause) -> Self::Error {
        compilation_artifact_write_error(
            self.request,
            failure.failed_index,
            failure.failed_path,
            failure.phase,
            self.progress,
            failure.commit_certainty,
            cause,
        )
    }
}

impl ExactKeyWriteCause for CompilationArtifactWriteErrorCause {
    fn resolve_operator(source: BoxError) -> Self {
        Self::ResolveOperator(source)
    }

    fn unsupported_policy(policy: WritePolicy) -> Self {
        Self::UnsupportedPolicy { policy }
    }

    fn unsupported_object_size(artifact_index: usize, byte_length: u64) -> Self {
        Self::UnsupportedObjectSize {
            artifact_index,
            byte_length,
        }
    }

    fn preflight_read(source: opendal::Error) -> Self {
        Self::PreflightRead(source)
    }

    fn byte_conflict(expected_byte_length: u64, observed_byte_length_at_least: u64) -> Self {
        Self::ByteConflict {
            expected_byte_length,
            observed_byte_length_at_least,
        }
    }

    fn conditional_create(source: opendal::Error) -> Self {
        Self::ConditionalCreate(source)
    }

    fn race_verification(source: opendal::Error) -> Self {
        Self::RaceVerification(source)
    }
}

impl ExactKeyOverwriteCause for CompilationArtifactWriteErrorCause {
    fn direct_write(source: opendal::Error) -> Self {
        Self::DirectWrite(source)
    }
}

async fn write_exact_keys<R, O>(
    resolver: &R,
    binding: &OperatorBinding,
    policy: WritePolicy,
    keys: &[ExactKey<'_>],
    operation: &mut O,
) -> Result<ExactKeyWriteReceipt, O::Error>
where
    R: OperatorResolver + ?Sized,
    O: ExactKeyWriteOperation,
    O::Cause: ExactKeyOverwriteCause,
{
    if keys.is_empty() {
        return Ok(ExactKeyWriteReceipt {
            completed: Vec::new(),
        });
    }

    let operator = resolver.resolve(binding).map_err(|source| {
        operation.error(
            ExactKeyWriteFailure::operation(OpenDalWritePhase::ResolveOperator),
            O::Cause::resolve_operator(Box::new(source)),
        )
    })?;
    appraise_capabilities(&operator, policy, keys, operation)?;

    let mut completed = Vec::with_capacity(keys.len());
    match policy {
        WritePolicy::OverwriteExactKeys => {
            for (index, key) in keys.iter().enumerate() {
                operator
                    .write(key.path, key.bytes.to_vec())
                    .await
                    .map_err(|source| {
                        operation.error(
                            ExactKeyWriteFailure::key(
                                OpenDalWritePhase::DirectWrite,
                                index,
                                key,
                                CommitCertainty::Indeterminate,
                            ),
                            O::Cause::direct_write(source),
                        )
                    })?;
                let entry = ExactKeyWriteEntry {
                    index,
                    outcome: WriteKeyOutcome::Written,
                };
                operation.completed_entry(entry.clone());
                completed.push(entry);
            }
        }
        WritePolicy::CreateOrVerify => {
            write_create_or_verify(&operator, keys, &mut completed, operation).await?;
        }
    }

    Ok(ExactKeyWriteReceipt { completed })
}

async fn write_create_or_verify_exact_keys<R, O>(
    resolver: &R,
    binding: &OperatorBinding,
    keys: &[ExactKey<'_>],
    operation: &mut O,
) -> Result<ExactKeyWriteReceipt, O::Error>
where
    R: OperatorResolver + ?Sized,
    O: ExactKeyWriteOperation,
{
    if keys.is_empty() {
        return Ok(ExactKeyWriteReceipt {
            completed: Vec::new(),
        });
    }

    let operator = resolver.resolve(binding).map_err(|source| {
        operation.error(
            ExactKeyWriteFailure::operation(OpenDalWritePhase::ResolveOperator),
            O::Cause::resolve_operator(Box::new(source)),
        )
    })?;
    appraise_capabilities(&operator, WritePolicy::CreateOrVerify, keys, operation)?;

    let mut completed = Vec::with_capacity(keys.len());
    write_create_or_verify(&operator, keys, &mut completed, operation).await?;
    Ok(ExactKeyWriteReceipt { completed })
}

fn appraise_capabilities<O: ExactKeyWriteOperation>(
    operator: &opendal::Operator,
    policy: WritePolicy,
    keys: &[ExactKey<'_>],
    operation: &O,
) -> Result<(), O::Error> {
    let capability = operator.info().capability();
    let policy_supported = capability.write
        && (!keys.iter().any(|key| key.bytes.is_empty()) || capability.write_can_empty)
        && (policy != WritePolicy::CreateOrVerify
            || (capability.read && capability.write_with_if_not_exists));
    if !policy_supported {
        return Err(operation.error(
            ExactKeyWriteFailure::operation(OpenDalWritePhase::CapabilityAppraisal),
            O::Cause::unsupported_policy(policy),
        ));
    }
    if let Some(maximum) = capability.write_total_max_size {
        for (index, key) in keys.iter().enumerate() {
            if key.bytes.len() > maximum {
                return Err(operation.error(
                    ExactKeyWriteFailure::key(
                        OpenDalWritePhase::CapabilityAppraisal,
                        index,
                        key,
                        CommitCertainty::NotCommitted,
                    ),
                    O::Cause::unsupported_object_size(index, byte_length(key.bytes)),
                ));
            }
        }
    }
    Ok(())
}

async fn write_create_or_verify<O: ExactKeyWriteOperation>(
    operator: &opendal::Operator,
    keys: &[ExactKey<'_>],
    completed: &mut Vec<ExactKeyWriteEntry>,
    operation: &mut O,
) -> Result<(), O::Error> {
    let mut observations = Vec::with_capacity(keys.len());
    for (index, key) in keys.iter().enumerate() {
        let observation = match compare_object(operator, key.path, key.bytes).await {
            Ok(observation) => observation,
            Err(CompareError::Read {
                source,
                observed_byte_length: 0,
            }) if source.kind() == ErrorKind::NotFound => ExistingObject::Absent,
            Err(CompareError::Read { source, .. }) => {
                return Err(operation.error(
                    ExactKeyWriteFailure::key(
                        OpenDalWritePhase::PreflightRead,
                        index,
                        key,
                        CommitCertainty::NotCommitted,
                    ),
                    O::Cause::preflight_read(source),
                ));
            }
            Err(CompareError::Conflict {
                observed_byte_length_at_least,
            }) => {
                return Err(byte_conflict_error(
                    operation,
                    OpenDalWritePhase::PreflightRead,
                    index,
                    key,
                    observed_byte_length_at_least,
                ));
            }
        };
        if observation == ExistingObject::Matching && completed.len() == index {
            let entry = ExactKeyWriteEntry {
                index,
                outcome: WriteKeyOutcome::AlreadyMatching,
            };
            operation.completed_entry(entry.clone());
            completed.push(entry);
        }
        observations.push(observation);
    }

    for (index, (key, observation)) in keys.iter().zip(observations).enumerate() {
        if index < completed.len() {
            debug_assert_eq!(observation, ExistingObject::Matching);
            continue;
        }
        let outcome = match observation {
            ExistingObject::Matching => WriteKeyOutcome::AlreadyMatching,
            ExistingObject::Absent => {
                match operator
                    .write_with(key.path, key.bytes.to_vec())
                    .if_not_exists(true)
                    .await
                {
                    Ok(_) => WriteKeyOutcome::Created,
                    Err(source)
                        if matches!(
                            source.kind(),
                            ErrorKind::AlreadyExists | ErrorKind::ConditionNotMatch
                        ) =>
                    {
                        match compare_object(operator, key.path, key.bytes).await {
                            Ok(ExistingObject::Matching) => WriteKeyOutcome::AlreadyMatching,
                            Ok(ExistingObject::Absent) => {
                                unreachable!("a successful comparison never reports absence")
                            }
                            Err(CompareError::Read { source, .. }) => {
                                return Err(operation.error(
                                    ExactKeyWriteFailure::key(
                                        OpenDalWritePhase::RaceVerification,
                                        index,
                                        key,
                                        CommitCertainty::NotCommitted,
                                    ),
                                    O::Cause::race_verification(source),
                                ));
                            }
                            Err(CompareError::Conflict {
                                observed_byte_length_at_least,
                            }) => {
                                return Err(byte_conflict_error(
                                    operation,
                                    OpenDalWritePhase::RaceVerification,
                                    index,
                                    key,
                                    observed_byte_length_at_least,
                                ));
                            }
                        }
                    }
                    Err(source) => {
                        return Err(operation.error(
                            ExactKeyWriteFailure::key(
                                OpenDalWritePhase::ConditionalCreate,
                                index,
                                key,
                                CommitCertainty::Indeterminate,
                            ),
                            O::Cause::conditional_create(source),
                        ));
                    }
                }
            }
        };
        let entry = ExactKeyWriteEntry { index, outcome };
        operation.completed_entry(entry.clone());
        completed.push(entry);
    }
    Ok(())
}

fn byte_conflict_error<O: ExactKeyWriteOperation>(
    operation: &O,
    phase: OpenDalWritePhase,
    index: usize,
    key: &ExactKey<'_>,
    observed_byte_length_at_least: u64,
) -> O::Error {
    operation.error(
        ExactKeyWriteFailure::key(phase, index, key, CommitCertainty::NotCommitted),
        O::Cause::byte_conflict(byte_length(key.bytes), observed_byte_length_at_least),
    )
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ExistingObject {
    Absent,
    Matching,
}

enum CompareError {
    Read {
        source: opendal::Error,
        observed_byte_length: u64,
    },
    Conflict {
        observed_byte_length_at_least: u64,
    },
}

async fn compare_object(
    operator: &opendal::Operator,
    path: &str,
    expected: &[u8],
) -> Result<ExistingObject, CompareError> {
    let expected_byte_length = byte_length(expected);
    let reader = operator
        .reader(path)
        .await
        .map_err(|source| CompareError::Read {
            source,
            observed_byte_length: 0,
        })?;
    let mut stream = reader
        .into_stream(..)
        .await
        .map_err(|source| CompareError::Read {
            source,
            observed_byte_length: 0,
        })?;
    let mut observed = 0u64;

    while let Some(buffer) = stream.next().await {
        let buffer = buffer.map_err(|source| CompareError::Read {
            source,
            observed_byte_length: observed,
        })?;
        for chunk in buffer {
            for byte in chunk {
                if observed == expected_byte_length {
                    return Err(CompareError::Conflict {
                        observed_byte_length_at_least: expected_byte_length
                            .checked_add(1)
                            .expect("an addressable slice is shorter than u64::MAX bytes"),
                    });
                }
                let index = usize::try_from(observed)
                    .expect("observed bytes fit usize while comparing an addressable slice");
                observed = observed
                    .checked_add(1)
                    .expect("an addressable slice is shorter than u64::MAX bytes");
                if expected[index] != byte {
                    return Err(CompareError::Conflict {
                        observed_byte_length_at_least: observed,
                    });
                }
            }
        }
    }

    if observed != expected_byte_length {
        return Err(CompareError::Conflict {
            observed_byte_length_at_least: observed,
        });
    }
    Ok(ExistingObject::Matching)
}

fn byte_length(bytes: &[u8]) -> u64 {
    u64::try_from(bytes.len()).expect("OpenDAL write supports no 128-bit target")
}

#[cfg(test)]
mod tests {
    use std::convert::Infallible;
    use std::future::Future;
    use std::pin::pin;
    use std::task::{Context, Poll, Waker};

    use opendal::ErrorKind;

    use crate::opendal::scripted_service::{
        DestinationMutation, PendingPoint, WriteCapabilities, WriteCondition,
        WriteDroppedOperation, WriteOperationLogEntry, WriteReadScript, WriteReadStep, WriteScript,
        WriteService, WriteStep,
    };
    use crate::opendal::{OperatorBinding, OperatorResolver};
    use crate::pack_archive::CommitCertainty;
    use crate::{
        CompilationLimits, CompilationOutputSpecification, Pack, PackCompilationRequest,
        SvgOutputSpecification, compile_with_limits,
    };

    use super::{
        CompilationArtifactWriteErrorCause, CompilationArtifactWriteProgress,
        CompilationArtifactWriteRequest, ExactKey, ExactKeyOverwriteCause, ExactKeyWriteCause,
        ExactKeyWriteEntry, ExactKeyWriteFailure, ExactKeyWriteOperation, OpenDalWritePhase,
        PackArchiveWriteEntry, PackArchiveWriteProgress, WriteKeyOutcome, WritePolicy,
        write_compilation_artifacts, write_exact_keys,
    };

    #[test]
    fn empty_write_succeeds_without_resolving_an_operator() {
        let resolver = RejectingResolver;
        let binding = binding();
        let mut completed = Vec::new();
        let receipt = {
            let mut operation = TestWriteOperation::new(&mut completed);
            let mut write = pin!(write_exact_keys(
                &resolver,
                &binding,
                WritePolicy::OverwriteExactKeys,
                &[],
                &mut operation,
            ));
            expect_ready(write.as_mut()).unwrap()
        };

        assert!(receipt.completed().is_empty());
        assert!(completed.is_empty());
    }

    #[test]
    fn invalid_composed_artifact_destination_fails_before_resolution() {
        let result = two_artifact_result();
        let request = CompilationArtifactWriteRequest {
            compilation_result_identity: result.result_identity(),
            destination: "destination:/prefix/".parse().unwrap(),
            artifact_keys: vec!["valid.svg".to_owned(), "../alias.svg".to_owned()],
            policy: WritePolicy::OverwriteExactKeys,
        };
        let mut progress = CompilationArtifactWriteProgress::new();

        let error = expect_ready(pin!(write_compilation_artifacts(
            &RejectingResolver,
            &request,
            &result,
            &mut progress,
        )))
        .unwrap_err();

        assert_eq!(error.phase(), OpenDalWritePhase::DestinationValidation);
        assert_eq!(error.failed_artifact_index(), Some(1));
        assert_eq!(error.failed_key(), Some("../alias.svg"));
        assert_eq!(error.failed_destination_path(), None);
        assert_eq!(error.commit_certainty(), CommitCertainty::NotCommitted);
        assert!(error.progress().completed().is_empty());
        assert!(matches!(
            error.cause(),
            CompilationArtifactWriteErrorCause::InvalidDestinationPath {
                artifact_index: 1,
                key,
            } if key == "../alias.svg"
        ));
    }

    #[test]
    fn overwrite_writes_each_key_once_in_order_without_reading() {
        let service = WriteService::new(
            WriteCapabilities::all(),
            [],
            [],
            [
                WriteScript::new("first.bin", WriteCondition::Direct, []),
                WriteScript::new("second.bin", WriteCondition::Direct, []),
            ],
            16,
        );
        let resolver = ServiceResolver(service.operator());
        let keys = [
            ExactKey::new("first.bin", b"first"),
            ExactKey::new("second.bin", b"second"),
        ];
        let mut completed = Vec::new();

        let receipt = expect_ready(pin!(write_exact_keys(
            &resolver,
            &binding(),
            WritePolicy::OverwriteExactKeys,
            &keys,
            &mut TestWriteOperation::new(&mut completed),
        )))
        .unwrap();

        assert_eq!(
            service.destination().object("first.bin"),
            Some(b"first".as_slice())
        );
        assert_eq!(
            service.destination().object("second.bin"),
            Some(b"second".as_slice())
        );
        assert_eq!(completed, receipt.completed());
        assert_eq!(
            completed
                .iter()
                .map(|entry| (entry.index, entry.outcome))
                .collect::<Vec<_>>(),
            [(0, WriteKeyOutcome::Written), (1, WriteKeyOutcome::Written),]
        );
        assert!(
            service
                .log()
                .entries()
                .iter()
                .all(|entry| !matches!(entry, WriteOperationLogEntry::ReadInvoked { .. }))
        );
    }

    #[test]
    fn create_or_verify_compares_every_key_before_mutation() {
        let service = WriteService::new(
            WriteCapabilities::all(),
            [("conflict.bin".to_owned(), b"wrong".to_vec())],
            [
                WriteReadScript::new(
                    "absent.bin",
                    0,
                    [WriteReadStep::failure(ErrorKind::NotFound)],
                )
                .unwrap(),
                WriteReadScript::new("conflict.bin", 1, [WriteReadStep::chunk(0..5)]).unwrap(),
            ],
            [WriteScript::new(
                "absent.bin",
                WriteCondition::IfNotExists,
                [],
            )],
            32,
        );
        let resolver = ServiceResolver(service.operator());
        let keys = [
            ExactKey::new("absent.bin", b"new"),
            ExactKey::new("conflict.bin", b"right"),
        ];
        let mut completed = Vec::new();

        let error = expect_ready(pin!(write_exact_keys(
            &resolver,
            &binding(),
            WritePolicy::CreateOrVerify,
            &keys,
            &mut TestWriteOperation::new(&mut completed),
        )))
        .unwrap_err();

        assert_eq!(error.phase, OpenDalWritePhase::PreflightRead);
        assert_eq!(error.failed_index, Some(1));
        assert_eq!(error.commit_certainty, CommitCertainty::NotCommitted);
        assert!(matches!(
            error.cause,
            TestWriteErrorCause::ByteConflict {
                expected_byte_length: 5,
                observed_byte_length_at_least: 1,
            }
        ));
        assert!(completed.is_empty());
        assert!(service.destination().object("absent.bin").is_none());
        assert!(
            service
                .log()
                .entries()
                .iter()
                .all(|entry| !matches!(entry, WriteOperationLogEntry::WriteInvoked { .. }))
        );
    }

    #[test]
    fn later_preflight_conflict_retains_the_leading_matching_prefix() {
        let service = WriteService::new(
            WriteCapabilities::all(),
            [
                ("matching.bin".to_owned(), b"matching".to_vec()),
                ("conflict.bin".to_owned(), b"wrong".to_vec()),
            ],
            [
                WriteReadScript::new("matching.bin", 1, [WriteReadStep::chunk(0..8)]).unwrap(),
                WriteReadScript::new("conflict.bin", 1, [WriteReadStep::chunk(0..5)]).unwrap(),
            ],
            [],
            16,
        );
        let resolver = ServiceResolver(service.operator());
        let keys = [
            ExactKey::new("matching.bin", b"matching"),
            ExactKey::new("conflict.bin", b"right"),
        ];
        let mut completed = Vec::new();

        let error = expect_ready(pin!(write_exact_keys(
            &resolver,
            &binding(),
            WritePolicy::CreateOrVerify,
            &keys,
            &mut TestWriteOperation::new(&mut completed),
        )))
        .unwrap_err();

        assert_eq!(error.phase, OpenDalWritePhase::PreflightRead);
        assert_eq!(completed.len(), 1);
        assert_eq!(completed[0].index, 0);
        assert_eq!(completed[0].outcome, WriteKeyOutcome::AlreadyMatching);
    }

    #[test]
    fn mutable_matching_stream_is_read_only_evidence_without_commit_certainty() {
        let service = WriteService::new(
            WriteCapabilities::all(),
            [("mutable.bin".to_owned(), b"abcdef".to_vec())],
            [WriteReadScript::new(
                "mutable.bin",
                2,
                [
                    WriteReadStep::chunk(0..3),
                    WriteReadStep::mutate(DestinationMutation::set("mutable.bin", b"abcXYZ")),
                    WriteReadStep::chunk(3..6),
                ],
            )
            .unwrap()],
            [],
            16,
        );
        let resolver = ServiceResolver(service.operator());
        let keys = [ExactKey::new("mutable.bin", b"abcXYZ")];
        let mut completed = Vec::new();

        let receipt = expect_ready(pin!(write_exact_keys(
            &resolver,
            &binding(),
            WritePolicy::CreateOrVerify,
            &keys,
            &mut TestWriteOperation::new(&mut completed),
        )))
        .unwrap();

        assert_eq!(
            receipt.completed()[0].outcome,
            WriteKeyOutcome::AlreadyMatching
        );
        assert!(
            service
                .log()
                .entries()
                .iter()
                .all(|entry| !matches!(entry, WriteOperationLogEntry::WriteInvoked { .. }))
        );
    }

    #[test]
    fn disappearance_after_a_partial_stream_is_not_treated_as_absence() {
        let service = WriteService::new(
            WriteCapabilities::all(),
            [("unstable.bin".to_owned(), b"planned".to_vec())],
            [WriteReadScript::new(
                "unstable.bin",
                1,
                [
                    WriteReadStep::chunk(0..3),
                    WriteReadStep::failure(ErrorKind::NotFound),
                ],
            )
            .unwrap()],
            [WriteScript::new(
                "unstable.bin",
                WriteCondition::IfNotExists,
                [],
            )],
            16,
        );
        let resolver = ServiceResolver(service.operator());
        let keys = [ExactKey::new("unstable.bin", b"planned")];
        let mut completed = Vec::new();

        let error = expect_ready(pin!(write_exact_keys(
            &resolver,
            &binding(),
            WritePolicy::CreateOrVerify,
            &keys,
            &mut TestWriteOperation::new(&mut completed),
        )))
        .unwrap_err();

        assert_eq!(error.phase, OpenDalWritePhase::PreflightRead);
        assert!(matches!(
            error.cause,
            TestWriteErrorCause::PreflightRead(ref source)
                if source.kind() == ErrorKind::NotFound
        ));
        assert!(completed.is_empty());
        assert!(
            service
                .log()
                .entries()
                .iter()
                .all(|entry| !matches!(entry, WriteOperationLogEntry::WriteInvoked { .. }))
        );
    }

    #[test]
    fn conditional_conflict_performs_one_bounded_verification() {
        let pending = PendingPoint::new();
        let service = WriteService::new(
            WriteCapabilities::all(),
            [],
            [
                WriteReadScript::new("race.bin", 0, [WriteReadStep::failure(ErrorKind::NotFound)])
                    .unwrap(),
                WriteReadScript::new("race.bin", 1, [WriteReadStep::chunk(0..7)]).unwrap(),
            ],
            [WriteScript::new(
                "race.bin",
                WriteCondition::IfNotExists,
                [WriteStep::pending(pending.clone()), WriteStep::commit()],
            )],
            32,
        );
        let resolver = ServiceResolver(service.operator());
        let keys = [ExactKey::new("race.bin", b"planned")];
        let mut completed = Vec::new();
        let binding = binding();
        let receipt = {
            let mut operation = TestWriteOperation::new(&mut completed);
            let mut write = pin!(write_exact_keys(
                &resolver,
                &binding,
                WritePolicy::CreateOrVerify,
                &keys,
                &mut operation,
            ));

            assert!(matches!(poll_once(write.as_mut()), Poll::Pending));
            service.mutate(DestinationMutation::set("race.bin", b"planned"));
            pending.release();
            expect_ready(write.as_mut()).unwrap()
        };

        assert_eq!(
            receipt.completed()[0].outcome,
            WriteKeyOutcome::AlreadyMatching
        );
        assert_eq!(
            service
                .log()
                .entries()
                .iter()
                .filter(|entry| matches!(entry, WriteOperationLogEntry::ReadInvoked { .. }))
                .count(),
            2
        );
        assert_eq!(completed.len(), 1);
    }

    #[test]
    fn appraisal_rejects_capabilities_and_sizes_before_effects() {
        let cases = [
            WriteCapabilities {
                write: false,
                write_can_empty: true,
                write_with_if_not_exists: true,
                read: true,
                write_total_max_size: None,
            },
            WriteCapabilities {
                write: true,
                write_can_empty: false,
                write_with_if_not_exists: true,
                read: true,
                write_total_max_size: None,
            },
            WriteCapabilities {
                write: true,
                write_can_empty: true,
                write_with_if_not_exists: false,
                read: true,
                write_total_max_size: None,
            },
            WriteCapabilities {
                write: true,
                write_can_empty: true,
                write_with_if_not_exists: true,
                read: false,
                write_total_max_size: None,
            },
        ];
        for capabilities in cases {
            let service = WriteService::new(capabilities, [], [], [], 4);
            let resolver = ServiceResolver(service.operator());
            let keys = [ExactKey::new("empty.bin", b"")];
            let mut completed = Vec::new();

            let error = expect_ready(pin!(write_exact_keys(
                &resolver,
                &binding(),
                WritePolicy::CreateOrVerify,
                &keys,
                &mut TestWriteOperation::new(&mut completed),
            )))
            .unwrap_err();

            assert_eq!(error.phase, OpenDalWritePhase::CapabilityAppraisal);
            assert!(matches!(
                error.cause,
                TestWriteErrorCause::UnsupportedPolicy { .. }
            ));
            assert!(service.log().entries().is_empty());
        }

        let service = WriteService::new(
            WriteCapabilities {
                write_total_max_size: Some(3),
                ..WriteCapabilities::all()
            },
            [],
            [],
            [],
            4,
        );
        let resolver = ServiceResolver(service.operator());
        let keys = [ExactKey::new("large.bin", b"four")];
        let mut completed = Vec::new();
        let error = expect_ready(pin!(write_exact_keys(
            &resolver,
            &binding(),
            WritePolicy::OverwriteExactKeys,
            &keys,
            &mut TestWriteOperation::new(&mut completed),
        )))
        .unwrap_err();

        assert!(matches!(
            error.cause,
            TestWriteErrorCause::UnsupportedObjectSize { byte_length: 4 }
        ));
        assert!(service.log().entries().is_empty());
    }

    #[test]
    fn issued_write_failure_is_indeterminate_and_retains_the_completed_prefix() {
        let service = WriteService::new(
            WriteCapabilities::all(),
            [],
            [],
            [
                WriteScript::new("first.bin", WriteCondition::Direct, []),
                WriteScript::write_failure(
                    "second.bin",
                    WriteCondition::Direct,
                    ErrorKind::Unexpected,
                ),
            ],
            16,
        );
        let resolver = ServiceResolver(service.operator());
        let keys = [
            ExactKey::new("first.bin", b"first"),
            ExactKey::new("second.bin", b"second"),
        ];
        let mut completed = Vec::new();

        let error = expect_ready(pin!(write_exact_keys(
            &resolver,
            &binding(),
            WritePolicy::OverwriteExactKeys,
            &keys,
            &mut TestWriteOperation::new(&mut completed),
        )))
        .unwrap_err();

        assert_eq!(error.phase, OpenDalWritePhase::DirectWrite);
        assert_eq!(error.failed_index, Some(1));
        assert_eq!(error.failed_path.as_deref(), Some("second.bin"));
        assert_eq!(error.commit_certainty, CommitCertainty::Indeterminate);
        assert_eq!(completed.len(), 1);
        assert_eq!(completed[0].index, 0);
    }

    #[test]
    fn dropping_a_pending_write_leaves_the_completed_prefix_with_the_caller() {
        let pending = PendingPoint::new();
        let service = WriteService::new(
            WriteCapabilities::all(),
            [],
            [],
            [
                WriteScript::new("first.bin", WriteCondition::Direct, []),
                WriteScript::new(
                    "second.bin",
                    WriteCondition::Direct,
                    [WriteStep::pending(pending.clone())],
                ),
            ],
            16,
        );
        let resolver = ServiceResolver(service.operator());
        let binding = binding();
        let keys = [
            ExactKey::new("first.bin", b"first"),
            ExactKey::new("second.bin", b"second"),
        ];
        let mut completed = Vec::new();
        {
            let mut operation = TestWriteOperation::new(&mut completed);
            let mut write = pin!(write_exact_keys(
                &resolver,
                &binding,
                WritePolicy::OverwriteExactKeys,
                &keys,
                &mut operation,
            ));
            assert!(matches!(poll_once(write.as_mut()), Poll::Pending));
            assert!(pending.was_observed());
        }

        assert_eq!(completed.len(), 1);
        assert_eq!(completed[0].index, 0);
        assert_eq!(
            service.cancellations(),
            [WriteDroppedOperation::Write {
                id: 1,
                path: "second.bin".to_owned(),
                length: 6,
                condition: WriteCondition::Direct,
                issued: true,
            }]
        );
    }

    #[test]
    fn dropping_a_later_preflight_read_retains_the_leading_matching_prefix() {
        let pending = PendingPoint::new();
        let service = WriteService::new(
            WriteCapabilities::all(),
            [("matching.bin".to_owned(), b"matching".to_vec())],
            [
                WriteReadScript::new("matching.bin", 1, [WriteReadStep::chunk(0..8)]).unwrap(),
                WriteReadScript::new("pending.bin", 0, [WriteReadStep::pending(pending.clone())])
                    .unwrap(),
            ],
            [],
            16,
        );
        let resolver = ServiceResolver(service.operator());
        let binding = binding();
        let keys = [
            ExactKey::new("matching.bin", b"matching"),
            ExactKey::new("pending.bin", b"pending"),
        ];
        let mut completed = Vec::new();
        {
            let mut operation = TestWriteOperation::new(&mut completed);
            let mut write = pin!(write_exact_keys(
                &resolver,
                &binding,
                WritePolicy::CreateOrVerify,
                &keys,
                &mut operation,
            ));
            assert!(matches!(poll_once(write.as_mut()), Poll::Pending));
            assert!(pending.was_observed());
        }

        assert_eq!(completed.len(), 1);
        assert_eq!(completed[0].index, 0);
        assert_eq!(completed[0].outcome, WriteKeyOutcome::AlreadyMatching);
    }

    #[test]
    fn workflow_evidence_retains_observed_outcomes() {
        let mut progress = PackArchiveWriteProgress::new();
        progress.push(PackArchiveWriteEntry {
            destination_path: "archive.typk".to_owned(),
            outcome: WriteKeyOutcome::AlreadyMatching,
        });

        assert_eq!(progress.outcome(), Some(WriteKeyOutcome::AlreadyMatching));

        progress.clear();
        progress.push(PackArchiveWriteEntry {
            destination_path: "archive.typk".to_owned(),
            outcome: WriteKeyOutcome::Created,
        });
        assert_eq!(progress.outcome(), Some(WriteKeyOutcome::Created));
    }

    #[derive(Debug)]
    struct TestWriteError {
        phase: OpenDalWritePhase,
        failed_index: Option<usize>,
        failed_path: Option<String>,
        commit_certainty: CommitCertainty,
        cause: TestWriteErrorCause,
    }

    #[derive(Debug)]
    enum TestWriteErrorCause {
        ResolveOperator(crate::opendal::BoxError),
        UnsupportedPolicy {
            policy: WritePolicy,
        },
        UnsupportedObjectSize {
            byte_length: u64,
        },
        PreflightRead(opendal::Error),
        ByteConflict {
            expected_byte_length: u64,
            observed_byte_length_at_least: u64,
        },
        ConditionalCreate(opendal::Error),
        RaceVerification(opendal::Error),
        DirectWrite(opendal::Error),
    }

    impl ExactKeyWriteCause for TestWriteErrorCause {
        fn resolve_operator(source: crate::opendal::BoxError) -> Self {
            Self::ResolveOperator(source)
        }

        fn unsupported_policy(policy: WritePolicy) -> Self {
            Self::UnsupportedPolicy { policy }
        }

        fn unsupported_object_size(_: usize, byte_length: u64) -> Self {
            Self::UnsupportedObjectSize { byte_length }
        }

        fn preflight_read(source: opendal::Error) -> Self {
            Self::PreflightRead(source)
        }

        fn byte_conflict(expected_byte_length: u64, observed_byte_length_at_least: u64) -> Self {
            Self::ByteConflict {
                expected_byte_length,
                observed_byte_length_at_least,
            }
        }

        fn conditional_create(source: opendal::Error) -> Self {
            Self::ConditionalCreate(source)
        }

        fn race_verification(source: opendal::Error) -> Self {
            Self::RaceVerification(source)
        }
    }

    impl ExactKeyOverwriteCause for TestWriteErrorCause {
        fn direct_write(source: opendal::Error) -> Self {
            Self::DirectWrite(source)
        }
    }

    struct TestWriteOperation<'a> {
        completed: &'a mut Vec<ExactKeyWriteEntry>,
    }

    impl<'a> TestWriteOperation<'a> {
        fn new(completed: &'a mut Vec<ExactKeyWriteEntry>) -> Self {
            Self { completed }
        }
    }

    impl ExactKeyWriteOperation for TestWriteOperation<'_> {
        type Error = TestWriteError;
        type Cause = TestWriteErrorCause;

        fn completed_entry(&mut self, entry: ExactKeyWriteEntry) {
            self.completed.push(entry);
        }

        fn error(&self, failure: ExactKeyWriteFailure, cause: Self::Cause) -> Self::Error {
            TestWriteError {
                phase: failure.phase,
                failed_index: failure.failed_index,
                failed_path: failure.failed_path,
                commit_certainty: failure.commit_certainty,
                cause,
            }
        }
    }

    fn expect_ready<F: Future>(future: std::pin::Pin<&mut F>) -> F::Output {
        match poll_once(future) {
            Poll::Ready(output) => output,
            Poll::Pending => panic!("future unexpectedly pending"),
        }
    }

    fn poll_once<F: Future>(future: std::pin::Pin<&mut F>) -> Poll<F::Output> {
        future.poll(&mut Context::from_waker(Waker::noop()))
    }

    fn binding() -> OperatorBinding {
        OperatorBinding::new("destination").unwrap()
    }

    fn two_artifact_result() -> crate::CompilationResult {
        let pack = Pack::builder("main.typ")
            .file(
                "main.typ",
                b"composition validation\n#pagebreak()\nsecond page".to_vec(),
            )
            .unwrap()
            .build()
            .unwrap();
        compile_with_limits(
            PackCompilationRequest::new(
                pack,
                CompilationOutputSpecification::Svg(SvgOutputSpecification::default()),
            ),
            CompilationLimits::reference_v1(),
        )
        .unwrap()
        .result()
        .unwrap()
        .clone()
    }

    struct ServiceResolver(opendal::Operator);

    impl OperatorResolver for ServiceResolver {
        type Error = Infallible;

        fn resolve(&self, _: &OperatorBinding) -> Result<opendal::Operator, Self::Error> {
            Ok(self.0.clone())
        }
    }

    struct RejectingResolver;

    impl OperatorResolver for RejectingResolver {
        type Error = Infallible;

        fn resolve(&self, _: &OperatorBinding) -> Result<opendal::Operator, Self::Error> {
            panic!("an empty write must not resolve an operator")
        }
    }
}