tensorlake 0.5.111

A Rust SDK for interacting with Tensorlake Cloud APIs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
use reqwest::{Method, StatusCode};
use serde::de::DeserializeOwned;
use std::collections::{HashMap, HashSet};
#[cfg(unix)]
use std::path::Path;
use std::sync::Arc;

use crate::{
    client::{Client, Traced},
    error::SdkError,
};

pub mod ingest;
pub mod merge;
pub mod models;
pub mod workspaces;

use models::{
    CreateRepoRequest, GitCredential, ListBranchesResponse, ListOperationsResponse,
    ListRefsResponse, ListReposResponse, MintGitTokenRequest, NativeDirectBlobRequest,
    NativeDirectBlobTargetsRequest, NativeDirectBlobTargetsResponse, NativeDirectFilePathWrite,
    NativeDirectFileWrite, NativeDirectMutation, NativeDirectPathTransfer,
    NativeDirectPublishRequest, NativeDirectPublishResponse, NativeDirectUploadLeaseResponse,
    NativeDirectUploadReceipt, NativeFilesystemFileRead, NativeFilesystemSnapshot,
    NativeFilesystemSnapshotPage, NativeFilesystemSnapshotRetentionResponse, NativeHeadResponse,
    NativeMetadataMutation, NativeMetadataPublishRequest, NativeReadPart, NativeReadPlanPage,
    REPO_KIND_FILESYSTEM, RepoInfo, RepoMetaInfo,
};

type GitCredentialCache = HashMap<(String, Option<String>), GitCredential>;

#[derive(Clone)]
pub struct ArtifactStorageClient {
    api_client: Client,
    git_client: reqwest::Client,
    git_base_url: String,
    git_credentials: Arc<tokio::sync::Mutex<GitCredentialCache>>,
}

#[derive(Clone)]
struct NativeReadIdentity {
    logical_len: u64,
    content_id: String,
    hash_algorithm: String,
}

struct NativeReadPlan {
    identity: NativeReadIdentity,
    inline: Option<Vec<u8>>,
    parts: Vec<NativeReadPart>,
    trace_id: String,
}

enum NativeReadResolution {
    Direct(Traced<NativeFilesystemFileRead>),
    Proxy(NativeReadIdentity),
}

impl ArtifactStorageClient {
    pub fn new(api_client: Client, git_base_url: impl Into<String>) -> Result<Self, SdkError> {
        Ok(Self {
            api_client,
            git_client: reqwest::Client::builder()
                .user_agent(concat!("tensorlake-rust-sdk/", env!("CARGO_PKG_VERSION")))
                .build()?,
            git_base_url: trim_base_url(git_base_url.into()),
            git_credentials: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
        })
    }

    /// Build an Artifact Storage client whose data-plane HTTP connections use
    /// a local Unix socket. Sandbox TLFS uses this for its root-owned relay to
    /// the authenticated dataplane-host system-storage proxy.
    #[cfg(unix)]
    pub fn new_with_unix_socket(
        api_client: Client,
        git_base_url: impl Into<String>,
        socket_path: &Path,
    ) -> Result<Self, SdkError> {
        Ok(Self {
            api_client,
            git_client: reqwest::Client::builder()
                .user_agent(concat!("tensorlake-rust-sdk/", env!("CARGO_PKG_VERSION")))
                .unix_socket(socket_path)
                .build()?,
            git_base_url: trim_base_url(git_base_url.into()),
            git_credentials: Arc::new(tokio::sync::Mutex::new(HashMap::new())),
        })
    }

    pub fn git_base_url(&self) -> &str {
        &self.git_base_url
    }

    pub fn git_repo_url(&self, project_id: &str, repo: &str) -> String {
        format!(
            "{}/{}/{}",
            self.git_base_url,
            encode_path_segment(project_id),
            encode_path_segment(repo)
        )
    }

    pub async fn mint_token(&self, project_id: &str) -> Result<Traced<GitCredential>, SdkError> {
        self.mint_token_for_repo(project_id, None).await
    }

    pub async fn mint_token_for_repo(
        &self,
        project_id: &str,
        repo: Option<&str>,
    ) -> Result<Traced<GitCredential>, SdkError> {
        // Ingress authenticates the bearer token and forwards the authorized project id to Artifact
        // Storage. Callers should build the SDK with `ClientBuilder::scope(...)` when using PATs.
        let _ = project_id;
        let path = "/artifact-storage/v1/token";
        let body = MintGitTokenRequest {
            repo: repo.map(str::to_string),
        };
        let req = self
            .api_client
            .build_post_json_request(Method::POST, path, &body)?;
        self.api_client.execute_json(req).await
    }

    pub fn git_credential_from_env() -> Option<GitCredential> {
        std::env::var("TENSORLAKE_GIT_TOKEN")
            .ok()
            .map(|token| GitCredential {
                token,
                token_type: "bearer".to_string(),
                expires_at: String::new(),
                git_username: std::env::var("TENSORLAKE_GIT_USERNAME")
                    .unwrap_or_else(|_| "t".to_string()),
                repo_pattern: "*".to_string(),
                scopes: Vec::new(),
            })
    }

    /// Resolve the Git credential used by repository helpers.
    ///
    /// `TENSORLAKE_GIT_TOKEN` is honored first for local artifact-storage development; otherwise
    /// the SDK mints a short-lived token scoped to `repo`.
    pub async fn git_credential_for_repo(
        &self,
        project_id: &str,
        repo: &str,
    ) -> Result<GitCredential, SdkError> {
        if let Some(credential) = Self::git_credential_from_env() {
            return Ok(credential);
        }
        let key = (project_id.to_string(), Some(repo.to_string()));
        if let Some(credential) = self.git_credentials.lock().await.get(&key).cloned()
            && git_credential_is_fresh(&credential)
        {
            return Ok(credential);
        }
        let credential = self
            .mint_token_for_repo(project_id, Some(repo))
            .await?
            .into_inner();
        if git_credential_is_fresh(&credential) {
            self.git_credentials
                .lock()
                .await
                .insert(key, credential.clone());
        }
        Ok(credential)
    }

    pub async fn git_credential_for_project(
        &self,
        project_id: &str,
    ) -> Result<GitCredential, SdkError> {
        if let Some(credential) = Self::git_credential_from_env() {
            return Ok(credential);
        }
        let key = (project_id.to_string(), None);
        if let Some(credential) = self.git_credentials.lock().await.get(&key).cloned()
            && git_credential_is_fresh(&credential)
        {
            return Ok(credential);
        }
        let credential = self.mint_token(project_id).await?.into_inner();
        if git_credential_is_fresh(&credential) {
            self.git_credentials
                .lock()
                .await
                .insert(key, credential.clone());
        }
        Ok(credential)
    }

    pub async fn create_repo(
        &self,
        project_id: &str,
        repo: &str,
        default_branch: Option<&str>,
    ) -> Result<Traced<()>, SdkError> {
        self.create_repo_of_kind(project_id, repo, default_branch, None)
            .await
    }

    /// Create a repo of an explicit kind ("repository" | "filesystem"). `None` omits the field
    /// entirely, which pre-kind servers require.
    pub async fn create_repo_of_kind(
        &self,
        project_id: &str,
        repo: &str,
        default_branch: Option<&str>,
        kind: Option<&str>,
    ) -> Result<Traced<()>, SdkError> {
        let credential = self.git_credential_for_project(project_id).await?;
        self.create_repo_with_credential(
            project_id,
            repo,
            default_branch,
            kind,
            &credential.git_username,
            &credential.token,
        )
        .await
    }

    pub async fn create_repo_with_credential(
        &self,
        project_id: &str,
        repo: &str,
        default_branch: Option<&str>,
        kind: Option<&str>,
        git_username: &str,
        git_token: &str,
    ) -> Result<Traced<()>, SdkError> {
        let request = CreateRepoRequest {
            default_branch: default_branch.unwrap_or("main").to_string(),
            kind: kind.map(str::to_string),
        };
        let (request_builder, trace_id) = self.git_request(
            Method::POST,
            project_id,
            repo,
            None,
            git_username,
            git_token,
        )?;
        let response = request_builder.json(&request).send().await?;
        decode_empty(response, trace_id).await
    }

    pub async fn fork_repo(
        &self,
        project_id: &str,
        repo: &str,
        base_repo: &str,
    ) -> Result<Traced<()>, SdkError> {
        let credential = self.git_credential_for_project(project_id).await?;
        self.fork_repo_with_credential(
            project_id,
            repo,
            base_repo,
            &credential.git_username,
            &credential.token,
        )
        .await
    }

    pub async fn fork_repo_with_credential(
        &self,
        project_id: &str,
        repo: &str,
        base_repo: &str,
        git_username: &str,
        git_token: &str,
    ) -> Result<Traced<()>, SdkError> {
        let suffix = format!("fork/{}", encode_path_segment(base_repo));
        let (request, trace_id) = self.git_request(
            Method::POST,
            project_id,
            repo,
            Some(&suffix),
            git_username,
            git_token,
        )?;
        let response = request.send().await?;
        decode_empty(response, trace_id).await
    }

    /// Create a metadata-only filesystem fork at the live head or a selected native snapshot.
    pub async fn fork_filesystem(
        &self,
        project_id: &str,
        filesystem: &str,
        base_filesystem: &str,
        snapshot: Option<&str>,
    ) -> Result<Traced<()>, SdkError> {
        let credential = self.git_credential_for_project(project_id).await?;
        let mut suffix = format!("fork/{}", encode_path_segment(base_filesystem));
        if let Some(snapshot) = snapshot {
            let snapshot = native_snapshot_id(snapshot)?.ok_or_else(|| {
                SdkError::ClientError(
                    "filesystem fork snapshot must be a 64-character snapshot id".to_string(),
                )
            })?;
            suffix.push_str("?snapshot=");
            suffix.push_str(&encode_path_segment(snapshot));
        }
        let (request, trace_id) = self.git_request(
            Method::POST,
            project_id,
            filesystem,
            Some(&suffix),
            &credential.git_username,
            &credential.token,
        )?;
        decode_empty(send_idempotent(request).await?, trace_id).await
    }

    pub async fn delete_repo(&self, project_id: &str, repo: &str) -> Result<Traced<()>, SdkError> {
        // Structural repo management needs the `repo:write` scope, which repo-scoped mints
        // deliberately omit — mint project-wide, like `create_repo`/`fork_repo`.
        let credential = self.git_credential_for_project(project_id).await?;
        self.delete_repo_with_credential(
            project_id,
            repo,
            &credential.git_username,
            &credential.token,
        )
        .await
    }

    pub async fn delete_repo_with_credential(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
    ) -> Result<Traced<()>, SdkError> {
        let (request, trace_id) = self.git_request(
            Method::DELETE,
            project_id,
            repo,
            None,
            git_username,
            git_token,
        )?;
        let response = request.send().await?;
        decode_empty(response, trace_id).await
    }

    pub async fn archive_repo(&self, project_id: &str, repo: &str) -> Result<Traced<()>, SdkError> {
        self.set_repo_status(project_id, repo, "readonly").await
    }

    pub async fn restore_repo(&self, project_id: &str, repo: &str) -> Result<Traced<()>, SdkError> {
        self.set_repo_status(project_id, repo, "active").await
    }

    pub async fn set_repo_status(
        &self,
        project_id: &str,
        repo: &str,
        status: &str,
    ) -> Result<Traced<()>, SdkError> {
        // Archive/restore is structural (`repo:write`), which repo-scoped mints omit.
        let credential = self.git_credential_for_project(project_id).await?;
        self.set_repo_status_with_credential(
            project_id,
            repo,
            status,
            &credential.git_username,
            &credential.token,
        )
        .await
    }

    pub async fn set_repo_status_with_credential(
        &self,
        project_id: &str,
        repo: &str,
        status: &str,
        git_username: &str,
        git_token: &str,
    ) -> Result<Traced<()>, SdkError> {
        let suffix = format!("status?status={}", urlencoding::encode(status));
        let (request, trace_id) = self.git_request(
            Method::PUT,
            project_id,
            repo,
            Some(&suffix),
            git_username,
            git_token,
        )?;
        let response = request.send().await?;
        decode_empty(response, trace_id).await
    }

    pub async fn list_repos(
        &self,
        project_id: &str,
    ) -> Result<Traced<ListReposResponse>, SdkError> {
        self.list_repos_of_kind(project_id, None).await
    }

    /// List repos restricted to one kind ("repository" | "filesystem"). `None` lists all kinds
    /// and sends no filter, which pre-kind servers require.
    pub async fn list_repos_of_kind(
        &self,
        project_id: &str,
        kind: Option<&str>,
    ) -> Result<Traced<ListReposResponse>, SdkError> {
        let credential = self.git_credential_for_project(project_id).await?;
        self.list_repos_with_credential(
            project_id,
            kind,
            &credential.git_username,
            &credential.token,
        )
        .await
    }

    pub async fn list_repos_with_credential(
        &self,
        project_id: &str,
        kind: Option<&str>,
        git_username: &str,
        git_token: &str,
    ) -> Result<Traced<ListReposResponse>, SdkError> {
        let mut repos = Vec::new();
        let mut after = None::<String>;
        let mut seen_after = HashSet::new();
        loop {
            let query = repo_list_query(kind, after.as_deref());
            let url = format!(
                "{}/project/{}/repos?{}",
                self.git_base_url,
                encode_path_segment(project_id),
                query,
            );
            let (request, trace_id) =
                self.git_request_url(Method::GET, url, git_username, git_token);
            let page: Traced<ListReposResponse> =
                decode_json(request.send().await?, trace_id).await?;
            let trace_id = page.trace_id.clone();
            let page = page.into_inner();
            repos.extend(page.repos);
            let Some(next) = page.next_after else {
                return Ok(Traced::new(
                    trace_id,
                    ListReposResponse {
                        project: project_id.to_string(),
                        repos,
                        next_after: None,
                    },
                ));
            };
            after = Some(advance_pagination_cursor(
                &mut seen_after,
                next,
                "repository listing",
            )?);
        }
    }

    /// Authoritative point-read of one repo's meta (kind, default branch, status). 404 =>
    /// SdkError::ServerError with status 404.
    pub async fn repo_meta_with_credential(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
    ) -> Result<Traced<RepoMetaInfo>, SdkError> {
        let (request, trace_id) = self.git_request(
            Method::GET,
            project_id,
            repo,
            Some("meta"),
            git_username,
            git_token,
        )?;
        let response = request.send().await?;
        decode_json(response, trace_id).await
    }

    pub async fn list_refs(
        &self,
        project_id: &str,
        repo: &str,
    ) -> Result<Traced<ListRefsResponse>, SdkError> {
        let credential = self.git_credential_for_repo(project_id, repo).await?;
        self.list_refs_with_credential(
            project_id,
            repo,
            &credential.git_username,
            &credential.token,
        )
        .await
    }

    pub async fn list_refs_with_credential(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
    ) -> Result<Traced<ListRefsResponse>, SdkError> {
        let (request, trace_id) = self.git_request(
            Method::GET,
            project_id,
            repo,
            Some("refs"),
            git_username,
            git_token,
        )?;
        let response = request.send().await?;
        decode_json(response, trace_id).await
    }

    pub async fn repo_info(
        &self,
        project_id: &str,
        repo: &str,
    ) -> Result<Traced<RepoInfo>, SdkError> {
        let credential = self.git_credential_for_repo(project_id, repo).await?;
        // Independent reads — issue them concurrently.
        let (branches, refs) = tokio::try_join!(
            self.list_branches_with_credential(
                project_id,
                repo,
                &credential.git_username,
                &credential.token,
            ),
            self.list_refs_with_credential(
                project_id,
                repo,
                &credential.git_username,
                &credential.token,
            )
        )?;
        let trace_id = refs.trace_id.clone();
        let branches = branches.into_inner();
        let refs = refs.into_inner();
        Ok(Traced::new(
            trace_id,
            RepoInfo {
                repo: repo.to_string(),
                url: self.git_repo_url(project_id, repo),
                branches: branches.branches,
                refs: refs.refs,
            },
        ))
    }

    pub async fn list_branches(
        &self,
        project_id: &str,
        repo: &str,
    ) -> Result<Traced<ListBranchesResponse>, SdkError> {
        let credential = self.git_credential_for_repo(project_id, repo).await?;
        self.list_branches_with_credential(
            project_id,
            repo,
            &credential.git_username,
            &credential.token,
        )
        .await
    }

    pub async fn list_branches_with_credential(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
    ) -> Result<Traced<ListBranchesResponse>, SdkError> {
        let (request, trace_id) = self.git_request(
            Method::GET,
            project_id,
            repo,
            Some("branches"),
            git_username,
            git_token,
        )?;
        let response = request.send().await?;
        decode_json(response, trace_id).await
    }

    pub async fn delete_branch(
        &self,
        project_id: &str,
        repo: &str,
        branch: &str,
    ) -> Result<Traced<()>, SdkError> {
        let credential = self.git_credential_for_repo(project_id, repo).await?;
        self.delete_branch_with_credential(
            project_id,
            repo,
            branch,
            &credential.git_username,
            &credential.token,
        )
        .await
    }

    pub async fn delete_branch_with_credential(
        &self,
        project_id: &str,
        repo: &str,
        branch: &str,
        git_username: &str,
        git_token: &str,
    ) -> Result<Traced<()>, SdkError> {
        let suffix = format!("branches/{}", encode_path_segment(branch));
        let (request, trace_id) = self.git_request(
            Method::DELETE,
            project_id,
            repo,
            Some(&suffix),
            git_username,
            git_token,
        )?;
        let response = request.send().await?;
        decode_empty(response, trace_id).await
    }

    pub async fn list_operations_with_credential(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
    ) -> Result<Traced<ListOperationsResponse>, SdkError> {
        let mut operations = Vec::new();
        let mut after = None::<String>;
        let mut seen_after = HashSet::new();
        loop {
            let suffix = after.as_ref().map_or_else(
                || "admin/operations?limit=1000".to_string(),
                |after| {
                    format!(
                        "admin/operations?limit=1000&after={}",
                        urlencoding::encode(after)
                    )
                },
            );
            let (request, trace_id) = self.git_request(
                Method::GET,
                project_id,
                repo,
                Some(&suffix),
                git_username,
                git_token,
            )?;
            let page: Traced<ListOperationsResponse> =
                decode_json(request.send().await?, trace_id).await?;
            let trace_id = page.trace_id.clone();
            let page = page.into_inner();
            operations.extend(page.operations);
            let Some(next) = page.next_after else {
                return Ok(Traced::new(
                    trace_id,
                    ListOperationsResponse {
                        repo: format!("{project_id}/{repo}"),
                        operations,
                        next_after: None,
                    },
                ));
            };
            after = Some(advance_pagination_cursor(
                &mut seen_after,
                next,
                "operation listing",
            )?);
        }
    }

    pub async fn list_operations(
        &self,
        project_id: &str,
        repo: &str,
    ) -> Result<Traced<ListOperationsResponse>, SdkError> {
        // The operation log is `project:admin`-gated, which repo-scoped mints omit.
        let credential = self.git_credential_for_project(project_id).await?;
        self.list_operations_with_credential(
            project_id,
            repo,
            &credential.git_username,
            &credential.token,
        )
        .await
    }

    pub async fn native_filesystem_head(
        &self,
        project_id: &str,
        filesystem: &str,
    ) -> Result<Traced<NativeHeadResponse>, SdkError> {
        let credential = self.git_credential_for_repo(project_id, filesystem).await?;
        let (request, trace_id) = self.git_request(
            Method::GET,
            project_id,
            filesystem,
            Some("fs/head"),
            &credential.git_username,
            &credential.token,
        )?;
        decode_json(send_idempotent(request).await?, trace_id).await
    }

    pub async fn read_native_filesystem_file(
        &self,
        project_id: &str,
        filesystem: &str,
        path: &str,
        version: &str,
    ) -> Result<Traced<Vec<u8>>, SdkError> {
        self.read_native_filesystem_file_with_metadata(project_id, filesystem, path, version, None)
            .await
            .map(|read| read.map(|read| read.data))
    }

    pub async fn read_native_filesystem_file_with_metadata(
        &self,
        project_id: &str,
        filesystem: &str,
        path: &str,
        version: &str,
        range: Option<(u64, u64)>,
    ) -> Result<Traced<NativeFilesystemFileRead>, SdkError> {
        if let Some((offset, length)) = range {
            if length == 0 {
                return Err(SdkError::ClientError(
                    "filesystem read range length must be positive".to_string(),
                ));
            }
            offset.checked_add(length - 1).ok_or_else(|| {
                SdkError::ClientError("filesystem read range overflow".to_string())
            })?;
        }
        let snapshot = native_snapshot_id(version)?;
        let path = encode_native_path(path)?;
        let credential = self.git_credential_for_repo(project_id, filesystem).await?;
        let resolution = self
            .read_native_filesystem_file_direct(
                project_id,
                filesystem,
                &path,
                snapshot,
                range,
                &credential,
            )
            .await?;
        match resolution {
            NativeReadResolution::Direct(read) => Ok(read),
            NativeReadResolution::Proxy(identity) => {
                self.read_native_filesystem_file_via_server(
                    project_id,
                    filesystem,
                    &path,
                    snapshot,
                    range,
                    &credential,
                    identity,
                )
                .await
            }
        }
    }

    async fn read_native_filesystem_file_via_server(
        &self,
        project_id: &str,
        filesystem: &str,
        encoded_path: &str,
        snapshot: Option<&str>,
        range: Option<(u64, u64)>,
        credential: &GitCredential,
        identity: NativeReadIdentity,
    ) -> Result<Traced<NativeFilesystemFileRead>, SdkError> {
        let suffix = match snapshot {
            Some(snapshot) => format!("fs/files/{encoded_path}?snapshot={snapshot}"),
            None => format!("fs/files/{encoded_path}"),
        };
        let (request, trace_id) = self.git_request(
            Method::GET,
            project_id,
            filesystem,
            Some(&suffix),
            &credential.git_username,
            &credential.token,
        )?;
        let request = match range {
            Some((offset, length)) => request.header(
                reqwest::header::RANGE,
                format!("bytes={offset}-{}", offset + length - 1),
            ),
            None => request,
        };
        let response = handle_response(send_idempotent(request).await?).await?;
        let response_content_id = response
            .headers()
            .get("x-tensorlake-content-id")
            .and_then(|value| value.to_str().ok())
            .filter(|value| !value.is_empty())
            .ok_or_else(|| {
                native_read_protocol_error("filesystem proxy omitted content identity")
            })?;
        if response_content_id != identity.content_id {
            return Err(native_read_protocol_error(
                "filesystem proxy changed the read-plan content identity",
            ));
        }
        let response_hash_algorithm = response
            .headers()
            .get("x-tensorlake-content-hash-algorithm")
            .and_then(|value| value.to_str().ok())
            .ok_or_else(|| {
                native_read_protocol_error("filesystem proxy omitted its content hash algorithm")
            })?;
        if response_hash_algorithm != identity.hash_algorithm {
            return Err(native_read_protocol_error(
                "filesystem proxy changed the read-plan hash algorithm",
            ));
        }
        let full_size = match response.headers().get(reqwest::header::CONTENT_RANGE) {
            Some(value) => value
                .to_str()
                .ok()
                .and_then(|value| value.rsplit_once('/'))
                .and_then(|(_, total)| total.parse::<u64>().ok()),
            None => response.content_length(),
        }
        .ok_or_else(|| native_read_protocol_error("filesystem proxy omitted total size"))?;
        if full_size != identity.logical_len {
            return Err(native_read_protocol_error(
                "filesystem proxy changed the read-plan logical length",
            ));
        }
        let expected_len = match range {
            Some((offset, length)) => length.min(full_size.saturating_sub(offset)),
            None => full_size,
        };
        let data = read_response_body_exact(response, expected_len)
            .await
            .ok_or_else(|| {
                native_read_protocol_error(
                    "filesystem proxy body did not match the requested logical length",
                )
            })?;
        if range.is_none() {
            verify_native_logical_content(
                &data,
                identity.logical_len,
                &identity.content_id,
                &identity.hash_algorithm,
            )?;
        }
        Ok(Traced::new(
            trace_id,
            NativeFilesystemFileRead {
                data,
                content_id: identity.content_id,
                full_size,
            },
        ))
    }

    /// Resolve immutable content locations through the authenticated service, then fetch only
    /// overlapping payload records straight from the object store. Signed URLs are transport
    /// capabilities: Tensorlake credentials are never attached to those requests.
    async fn read_native_filesystem_file_direct(
        &self,
        project_id: &str,
        filesystem: &str,
        encoded_path: &str,
        snapshot: Option<&str>,
        range: Option<(u64, u64)>,
        credential: &GitCredential,
    ) -> Result<NativeReadResolution, SdkError> {
        use base64::Engine as _;
        use futures::StreamExt as _;

        const PAGE_LIMIT: usize = 4096;
        const MAX_PARTS: usize = 1_000_000;
        const DOWNLOAD_CONCURRENCY: usize = 8;

        let mut after_offset = 0u64;
        let mut parts = Vec::new();
        let mut inline = None;
        let mut identity: Option<(u64, Option<String>, Option<String>)> = None;
        let mut trace_id = None;
        loop {
            let suffix = native_read_plan_suffix(encoded_path, snapshot, after_offset, PAGE_LIMIT);
            let (request, request_trace_id) = self.git_request(
                Method::GET,
                project_id,
                filesystem,
                Some(&suffix),
                &credential.git_username,
                &credential.token,
            )?;
            trace_id.get_or_insert(request_trace_id.clone());
            let page = decode_json::<NativeReadPlanPage>(
                send_idempotent(request).await?,
                request_trace_id,
            )
            .await?
            .into_inner();
            let page_identity = (
                page.logical_len,
                page.content_id.clone(),
                page.hash_algorithm.clone(),
            );
            if identity
                .as_ref()
                .is_some_and(|prior| prior != &page_identity)
            {
                return Err(native_read_protocol_error(
                    "read-plan identity changed between immutable pages",
                ));
            }
            identity.get_or_insert(page_identity);

            if let Some(encoded) = page.inline_base64 {
                if after_offset != 0
                    || page.next_offset.is_some()
                    || !page.parts.is_empty()
                    || inline.is_some()
                {
                    return Err(native_read_protocol_error(
                        "inline read-plan mixed inline bytes with parts or pagination",
                    ));
                }
                let bytes = base64::engine::general_purpose::STANDARD
                    .decode(encoded)
                    .map_err(|error| {
                        native_read_protocol_error(format!(
                            "invalid inline filesystem content: {error}"
                        ))
                    })?;
                verify_native_leaf_content(
                    &bytes,
                    page.logical_len,
                    page.content_id.as_deref(),
                    page.hash_algorithm.as_deref(),
                )?;
                inline = Some(bytes);
            }

            let page_logical_len = page.parts.iter().try_fold(0u64, |total, part| {
                if part.logical_len == 0 || part.stored_len == 0 {
                    return None;
                }
                total.checked_add(part.logical_len)
            });
            let Some(page_logical_len) = page_logical_len else {
                return Err(native_read_protocol_error(
                    "read-plan contains an empty or overflowing part",
                ));
            };
            let described_offset = after_offset
                .checked_add(page_logical_len)
                .ok_or_else(|| native_read_protocol_error("read-plan logical offset overflowed"))?;
            if parts.len().saturating_add(page.parts.len()) > MAX_PARTS {
                return Err(native_read_protocol_error(format!(
                    "read-plan exceeds the {MAX_PARTS} part SDK safety limit"
                )));
            }
            parts.extend(page.parts);
            let Some(next_offset) = page.next_offset else {
                break;
            };
            if next_offset != described_offset || next_offset <= after_offset {
                return Err(native_read_protocol_error(
                    "read-plan pagination cursor did not match its described bytes",
                ));
            }
            after_offset = next_offset;
        }

        let (logical_len, content_id, hash_algorithm) = identity.ok_or_else(|| {
            native_read_protocol_error("read-plan did not describe filesystem content")
        })?;
        let plan = NativeReadPlan {
            identity: NativeReadIdentity {
                logical_len,
                content_id: content_id
                    .ok_or_else(|| native_read_protocol_error("content ID is missing"))?,
                hash_algorithm: hash_algorithm
                    .ok_or_else(|| native_read_protocol_error("hash algorithm is missing"))?,
            },
            inline,
            parts,
            trace_id: trace_id.unwrap_or_default(),
        };
        let requested = match range {
            Some((offset, length)) if offset < plan.identity.logical_len => {
                offset..offset.saturating_add(length).min(plan.identity.logical_len)
            }
            Some(_) => return Ok(NativeReadResolution::Proxy(plan.identity)),
            None => 0..plan.identity.logical_len,
        };

        if let Some(bytes) = plan.inline {
            if !plan.parts.is_empty() || bytes.len() as u64 != plan.identity.logical_len {
                return Err(native_read_protocol_error(
                    "inline read-plan did not exactly cover the file",
                ));
            }
            let start = usize::try_from(requested.start)
                .map_err(|_| native_read_protocol_error("read range exceeds address space"))?;
            let end = usize::try_from(requested.end)
                .map_err(|_| native_read_protocol_error("read range exceeds address space"))?;
            return Ok(NativeReadResolution::Direct(Traced::new(
                plan.trace_id,
                NativeFilesystemFileRead {
                    data: bytes[start..end].to_vec(),
                    content_id: plan.identity.content_id,
                    full_size: plan.identity.logical_len,
                },
            )));
        }

        let mut logical_offset = 0u64;
        let mut selected = Vec::new();
        for part in plan.parts {
            let part_start = logical_offset;
            let part_end = part_start
                .checked_add(part.logical_len)
                .ok_or_else(|| native_read_protocol_error("read-plan logical length overflowed"))?;
            if part_end > requested.start && part_start < requested.end {
                selected.push((part_start, part));
            }
            logical_offset = part_end;
        }
        if logical_offset != plan.identity.logical_len {
            return Err(native_read_protocol_error(
                "read-plan parts do not cover the complete file",
            ));
        }
        if selected.iter().any(|(_, part)| part.url.is_none()) {
            return Ok(NativeReadResolution::Proxy(plan.identity));
        }

        let capacity = usize::try_from(requested.end - requested.start)
            .map_err(|_| native_read_protocol_error("read range exceeds address space"))?;
        let mut output = Vec::new();
        output.try_reserve_exact(capacity).map_err(|_| {
            native_read_protocol_error("filesystem read is too large to materialize")
        })?;
        let mut downloads = futures::stream::iter(selected.into_iter().map(
            |(logical_start, part)| async move {
                self.download_native_read_part(part)
                    .await
                    .map(|bytes| bytes.map(|bytes| (logical_start, bytes)))
            },
        ))
        .buffered(DOWNLOAD_CONCURRENCY);
        while let Some(result) = downloads.next().await {
            let Some((logical_start, bytes)) = result? else {
                return Ok(NativeReadResolution::Proxy(plan.identity));
            };
            let logical_end = logical_start + bytes.len() as u64;
            let start = usize::try_from(requested.start.saturating_sub(logical_start))
                .unwrap_or(usize::MAX)
                .min(bytes.len());
            let end = usize::try_from(requested.end.min(logical_end) - logical_start)
                .unwrap_or(usize::MAX)
                .min(bytes.len());
            output.extend_from_slice(&bytes[start..end]);
        }
        if output.len() != capacity {
            return Err(native_read_protocol_error(format!(
                "direct filesystem read returned {} bytes, expected {capacity}",
                output.len()
            )));
        }
        if requested.start == 0 && requested.end == plan.identity.logical_len {
            verify_native_logical_content(
                &output,
                plan.identity.logical_len,
                &plan.identity.content_id,
                &plan.identity.hash_algorithm,
            )?;
        }
        Ok(NativeReadResolution::Direct(Traced::new(
            plan.trace_id,
            NativeFilesystemFileRead {
                data: output,
                content_id: plan.identity.content_id,
                full_size: plan.identity.logical_len,
            },
        )))
    }

    /// `Ok(None)` selects the authenticated service proxy. Malformed ranges, decompression bombs,
    /// and checksum mismatches fail closed instead of silently trusting the fallback.
    async fn download_native_read_part(
        &self,
        part: NativeReadPart,
    ) -> Result<Option<Vec<u8>>, SdkError> {
        let url = part
            .url
            .as_deref()
            .expect("caller checked every read-plan URL");
        validate_signed_blob_url(url)?;
        let end = part
            .offset
            .checked_add(part.stored_len)
            .and_then(|end| end.checked_sub(1))
            .ok_or_else(|| {
                native_read_protocol_error("read-plan returned an invalid byte range")
            })?;
        let response = match send_signed_read(self.git_client.get(url).header(
            reqwest::header::RANGE,
            format!("bytes={}-{end}", part.offset),
        ))
        .await
        {
            Some(response) => response,
            None => return Ok(None),
        };
        let whole_object = response.status() == StatusCode::OK;
        if whole_object
            && (part.offset != 0
                || response
                    .content_length()
                    .is_some_and(|length| length != part.stored_len))
        {
            return Ok(None);
        }
        if !whole_object && response.status() != StatusCode::PARTIAL_CONTENT {
            return Ok(None);
        }
        let stored = match read_response_body_exact(response, part.stored_len).await {
            Some(bytes) => bytes,
            None => return Ok(None),
        };
        if let Some(expected) = part.stored_checksum_sha256.as_deref()
            && sha256_hex(&stored) != expected
        {
            return Err(native_read_protocol_error(
                "stored filesystem content checksum mismatch",
            ));
        }
        let logical = decode_native_read_part(&part, stored).await?;
        verify_native_leaf_content(
            &logical,
            part.logical_len,
            Some(&part.content_id),
            Some(&part.hash_algorithm),
        )?;
        Ok(Some(logical))
    }

    pub async fn list_native_filesystem_entries_page(
        &self,
        project_id: &str,
        filesystem: &str,
        path: &str,
        version: &str,
        after: Option<&str>,
        limit: usize,
    ) -> Result<Traced<workspaces::TreePage>, SdkError> {
        if !path.is_empty() {
            validate_native_direct_path(path)?;
        }
        let suffix = native_entries_suffix(path, native_snapshot_id(version)?, after, limit);
        let credential = self.git_credential_for_repo(project_id, filesystem).await?;
        let (request, trace_id) = self.git_request(
            Method::GET,
            project_id,
            filesystem,
            Some(&suffix),
            &credential.git_username,
            &credential.token,
        )?;
        decode_json(send_idempotent(request).await?, trace_id).await
    }

    /// Permanently retain the current filesystem head with a user-visible message. This publishes
    /// no content or directory metadata: it changes only the snapshot's retention class.
    pub async fn retain_current_native_filesystem_snapshot(
        &self,
        project_id: &str,
        filesystem: &str,
        message: String,
        request_id: String,
    ) -> Result<Traced<NativeFilesystemSnapshotRetentionResponse>, SdkError> {
        let credential = self.git_credential_for_repo(project_id, filesystem).await?;
        let (request, trace_id) = self.git_request(
            Method::POST,
            project_id,
            filesystem,
            Some("fs/snapshots"),
            &credential.git_username,
            &credential.token,
        )?;
        let body = serde_json::json!({ "message": message, "request_id": request_id });
        decode_json(send_idempotent(request.json(&body)).await?, trace_id).await
    }

    /// List every explicitly retained native snapshot in newest-first history order.
    pub async fn list_native_filesystem_snapshots(
        &self,
        project_id: &str,
        filesystem: &str,
    ) -> Result<Traced<Vec<NativeFilesystemSnapshot>>, SdkError> {
        let credential = self.git_credential_for_repo(project_id, filesystem).await?;
        let mut snapshots = Vec::new();
        let mut after: Option<String> = None;
        let mut seen = HashSet::new();
        let trace_id = loop {
            let suffix = match after.as_deref() {
                Some(after) => format!(
                    "fs/snapshots?limit=1000&after={}",
                    encode_path_segment(after)
                ),
                None => "fs/snapshots?limit=1000".to_string(),
            };
            let (request, request_trace_id) = self.git_request(
                Method::GET,
                project_id,
                filesystem,
                Some(&suffix),
                &credential.git_username,
                &credential.token,
            )?;
            let page = decode_json::<NativeFilesystemSnapshotPage>(
                send_idempotent(request).await?,
                request_trace_id,
            )
            .await?;
            snapshots.extend(
                page.snapshots
                    .iter()
                    .filter(|snapshot| snapshot.snapshot_class == "permanent_snapshot")
                    .cloned(),
            );
            match page.next_after.clone() {
                Some(next) if !next.is_empty() && seen.insert(next.clone()) => after = Some(next),
                Some(_) => {
                    return Err(SdkError::ClientError(
                        "native snapshot history returned a repeated or empty cursor".to_string(),
                    ));
                }
                None => break page.trace_id.clone(),
            }
        };
        Ok(Traced::new(trace_id, snapshots))
    }

    /// Drop one permanent snapshot retention root. Content still reachable from a head, fork, or
    /// another snapshot remains durable.
    pub async fn delete_native_filesystem_snapshot(
        &self,
        project_id: &str,
        filesystem: &str,
        snapshot: &str,
    ) -> Result<Traced<()>, SdkError> {
        let snapshot = native_snapshot_id(snapshot)?.ok_or_else(|| {
            SdkError::ClientError(
                "filesystem snapshot must be a 64-character snapshot id".to_string(),
            )
        })?;
        let credential = self.git_credential_for_repo(project_id, filesystem).await?;
        let snapshot_suffix = format!("fs/snapshots/{}", encode_path_segment(snapshot));
        let (snapshot_request, _) = self.git_request(
            Method::GET,
            project_id,
            filesystem,
            Some(&snapshot_suffix),
            &credential.git_username,
            &credential.token,
        )?;
        let current = decode_json::<NativeFilesystemSnapshot>(
            send_idempotent(snapshot_request).await?,
            String::new(),
        )
        .await?
        .into_inner();
        let suffix = format!(
            "{snapshot_suffix}?expected_permanence_epoch={}",
            current.permanence_epoch
        );
        let (request, trace_id) = self.git_request(
            Method::DELETE,
            project_id,
            filesystem,
            Some(&suffix),
            &credential.git_username,
            &credential.token,
        )?;
        decode_empty(send_idempotent(request).await?, trace_id).await
    }

    /// Publish complete files through the native SDK path: SHA-256 locally, upload missing bytes
    /// directly to checksum-bound object-store targets, then atomically publish logical mutations.
    /// Payload bytes never traverse Artifact Storage.
    pub async fn publish_filesystem_files(
        &self,
        project_id: &str,
        filesystem: &str,
        files: Vec<NativeDirectFileWrite>,
        deletes: Vec<String>,
        moves: Vec<NativeDirectPathTransfer>,
        copies: Vec<NativeDirectPathTransfer>,
        message: String,
        operation_id: String,
    ) -> Result<Traced<NativeDirectPublishResponse>, SdkError> {
        let credential = self.git_credential_for_repo(project_id, filesystem).await?;
        self.push_native_files_direct_with_credential(
            project_id,
            filesystem,
            files,
            Vec::new(),
            deletes,
            moves,
            copies,
            message,
            operation_id,
            &credential.git_username,
            &credential.token,
        )
        .await
    }

    /// Publish complete files from local paths without retaining their payloads in SDK memory.
    /// Each source is hashed and streamed in bounded direct-to-object-store parts.
    pub async fn publish_filesystem_paths(
        &self,
        project_id: &str,
        filesystem: &str,
        files: Vec<NativeDirectFilePathWrite>,
        message: String,
        operation_id: String,
    ) -> Result<Traced<NativeDirectPublishResponse>, SdkError> {
        let credential = self.git_credential_for_repo(project_id, filesystem).await?;
        self.push_native_files_direct_with_credential(
            project_id,
            filesystem,
            Vec::new(),
            files,
            Vec::new(),
            Vec::new(),
            Vec::new(),
            message,
            operation_id,
            &credential.git_username,
            &credential.token,
        )
        .await
    }

    /// Credential-explicit form used by callers that already cache or manage a repository token.
    #[allow(clippy::too_many_arguments)]
    pub async fn push_native_files_direct_with_credential(
        &self,
        project_id: &str,
        filesystem: &str,
        files: Vec<NativeDirectFileWrite>,
        path_files: Vec<NativeDirectFilePathWrite>,
        deletes: Vec<String>,
        moves: Vec<NativeDirectPathTransfer>,
        copies: Vec<NativeDirectPathTransfer>,
        message: String,
        operation_id: String,
        git_username: &str,
        git_token: &str,
    ) -> Result<Traced<NativeDirectPublishResponse>, SdkError> {
        use futures::StreamExt;
        if files.is_empty()
            && path_files.is_empty()
            && deletes.is_empty()
            && moves.is_empty()
            && copies.is_empty()
        {
            return Err(SdkError::ClientError(
                "nothing to publish: no writes, deletions, moves, or copies given".to_string(),
            ));
        }
        for file in &files {
            validate_native_direct_path(&file.path)?;
        }
        for file in &path_files {
            validate_native_direct_path(&file.path)?;
        }
        for path in &deletes {
            validate_native_direct_path(path)?;
        }
        for transfer in moves.iter().chain(&copies) {
            validate_native_direct_path(&transfer.from)?;
            validate_native_direct_path(&transfer.to)?;
        }
        if files.is_empty() && path_files.is_empty() {
            let mut mutations = Vec::with_capacity(deletes.len() + moves.len() + copies.len());
            mutations.extend(
                deletes
                    .into_iter()
                    .map(|path| NativeMetadataMutation::Delete { path }),
            );
            mutations.extend(
                moves
                    .into_iter()
                    .map(|transfer| NativeMetadataMutation::Move {
                        from: transfer.from,
                        to: transfer.to,
                    }),
            );
            mutations.extend(
                copies
                    .into_iter()
                    .map(|transfer| NativeMetadataMutation::Copy {
                        from: transfer.from,
                        to: transfer.to,
                    }),
            );
            if mutations.len() > 128 {
                return Err(SdkError::ClientError(format!(
                    "metadata-only publication contains {} mutations; the low-latency limit is 128",
                    mutations.len()
                )));
            }
            let publish = NativeMetadataPublishRequest {
                operation_id,
                message,
                mutations,
            };
            let (request, trace_id) = self.git_request(
                Method::POST,
                project_id,
                filesystem,
                Some("fs/mutations"),
                git_username,
                git_token,
            )?;
            return decode_json(send_idempotent(request.json(&publish)).await?, trace_id).await;
        }
        const DIRECT_PART_BYTES: usize = 64 * 1024 * 1024;
        let prepare = tokio::task::spawn_blocking(move || {
            prepare_native_direct_publication(
                files,
                path_files,
                deletes,
                moves,
                copies,
                DIRECT_PART_BYTES,
            )
        });

        // The head read runs concurrently with the prepare-then-lease chain: the lease request
        // waits only on SHA-256 preparation (it DECLARES the prepared blob identities so the
        // server folds the first target batch into the lease response), never on the head. A
        // small publication is therefore two sequential control round trips — lease+targets,
        // then publish after the parallel direct PUTs — with the head read hidden under them.
        // An older server ignores the declaration and returns no `targets`, selecting the
        // standalone batched target requests below (three round trips, exactly the old flow).
        let head_request = send_idempotent(
            self.git_request(
                Method::GET,
                project_id,
                filesystem,
                Some("fs/head"),
                git_username,
                git_token,
            )?
            .0,
        );
        let head = async {
            decode_json::<NativeHeadResponse>(head_request.await?, String::new())
                .await
                .map(Traced::into_inner)
        };
        let (lease_request, _lease_trace) = self.git_request(
            Method::POST,
            project_id,
            filesystem,
            Some("fs/upload-leases"),
            git_username,
            git_token,
        )?;
        // Mirrors the server's fixed per-request target ceiling; the lease response's
        // `max_targets_per_request` arrives too late to size the declaration.
        const LEASE_DECLARED_TARGETS_MAX: usize = 256;
        let bare_lease_request = lease_request
            .try_clone()
            .map(|request| request.json(&serde_json::json!({})));
        let prepared_then_lease = async {
            let (mutations, unique_blobs) = prepare.await.map_err(|error| {
                SdkError::ClientError(format!(
                    "native direct publication preparation failed: {error}"
                ))
            })??;
            let blob_requests = unique_blobs
                .iter()
                .map(|(blob_id, data)| NativeDirectBlobRequest {
                    blob_id: blob_id.clone(),
                    logical_len: data.logical_len(),
                })
                .collect::<Vec<_>>();
            let declared = blob_requests.len().min(LEASE_DECLARED_TARGETS_MAX);
            let declared_response = decode_json::<NativeDirectUploadLeaseResponse>(
                send_idempotent(lease_request.json(&NativeDirectBlobTargetsRequest {
                    blobs: blob_requests[..declared].to_vec(),
                }))
                .await?,
                String::new(),
            )
            .await;
            let lease = match declared_response {
                Ok(lease) => lease.into_inner(),
                // The declaration is an optimization, never a dependency: a server that rejects
                // it (a per-request target ceiling lowered below this client's mirror of it, a
                // stricter future validator) must not fail the publication while the standalone
                // flow would have worked. One bare-lease retry selects that flow; if the bare
                // lease fails too, ITS error is the real one.
                Err(_) if declared > 0 => match bare_lease_request {
                    Some(bare) => decode_json::<NativeDirectUploadLeaseResponse>(
                        send_idempotent(bare).await?,
                        String::new(),
                    )
                    .await?
                    .into_inner(),
                    None => {
                        return Err(SdkError::ClientError(
                            "direct upload lease request cannot be retried".to_string(),
                        ));
                    }
                },
                Err(error) => return Err(error),
            };
            Ok::<_, SdkError>((lease, mutations, unique_blobs, blob_requests))
        };
        let (head, (mut lease, mutations, unique_blobs, blob_requests)) =
            tokio::try_join!(head, prepared_then_lease)?;
        if head.snapshot_id.is_none()
            && mutations
                .iter()
                .all(|mutation| matches!(mutation, NativeDirectMutation::Delete { .. }))
        {
            return Err(SdkError::ClientError(
                "cannot delete from an empty filesystem".to_string(),
            ));
        }
        if lease.transport != "checksum_presigned_put" || lease.checksum_algorithm != "sha256" {
            return Err(SdkError::ClientError(format!(
                "server returned unsupported direct upload transport {:?} with checksum {:?}",
                lease.transport, lease.checksum_algorithm
            )));
        }
        if lease.max_targets_per_request == 0 || lease.max_parts_per_file == 0 {
            return Err(SdkError::ClientError(
                "server returned a zero direct-upload batching limit".to_string(),
            ));
        }
        if lease.max_blob_bytes < DIRECT_PART_BYTES as u64 {
            return Err(SdkError::ClientError(format!(
                "server direct-upload part limit {} is smaller than the SDK's {} byte part size",
                lease.max_blob_bytes, DIRECT_PART_BYTES
            )));
        }
        if let Some(part_count) = mutations.iter().find_map(|mutation| match mutation {
            NativeDirectMutation::Put { blobs, .. } if blobs.len() > lease.max_parts_per_file => {
                Some(blobs.len())
            }
            _ => None,
        }) {
            return Err(SdkError::ClientError(format!(
                "native file has {part_count} parts, exceeding the server's {} part limit",
                lease.max_parts_per_file
            )));
        }
        if let Some((blob_id, data)) = unique_blobs
            .iter()
            .find(|(_, data)| data.logical_len() > lease.max_blob_bytes)
        {
            return Err(SdkError::ClientError(format!(
                "native blob {blob_id} has {} bytes, exceeding the server's {} byte direct-upload limit",
                data.logical_len(),
                lease.max_blob_bytes
            )));
        }

        let mut targets = NativeDirectBlobTargetsResponse {
            targets: Vec::with_capacity(blob_requests.len()),
        };
        let mut remaining: Vec<NativeDirectBlobRequest> = blob_requests.clone();
        if let Some(inline) = lease.targets.take() {
            // The server minted targets with the lease: only blobs its response did not cover
            // (undeclared overflow past the ceiling — or, defensively, anything a future server
            // sheds from the fold) take the standalone round trip. Coverage is computed from
            // the returned ids rather than assumed from the declared count, so a partial or
            // empty fold degrades to the old flow instead of failing the publication.
            let covered: std::collections::HashSet<&str> = inline
                .iter()
                .map(|target| target.blob_id.as_str())
                .collect();
            remaining.retain(|request| !covered.contains(request.blob_id.as_str()));
            targets.targets.extend(inline);
        }
        let mut target_requests = Vec::new();
        for batch in remaining.chunks(lease.max_targets_per_request) {
            let targets_path = format!(
                "fs/upload-leases/{}/targets",
                encode_path_segment(&lease.lease_id)
            );
            let (request, trace_id) = self.git_request(
                Method::POST,
                project_id,
                filesystem,
                Some(&targets_path),
                git_username,
                git_token,
            )?;
            let body = NativeDirectBlobTargetsRequest {
                blobs: batch.to_vec(),
            };
            target_requests.push(async move {
                decode_json::<NativeDirectBlobTargetsResponse>(
                    send_idempotent(request.json(&body)).await?,
                    trace_id,
                )
                .await
                .map(Traced::into_inner)
            });
        }
        let target_results = futures::stream::iter(target_requests)
            .buffer_unordered(4)
            .collect::<Vec<_>>()
            .await;
        for result in target_results {
            targets.targets.extend(result?.targets);
        }
        validate_native_direct_targets(&blob_requests, &targets.targets)?;

        let mut receipts = Vec::new();
        let mut uploads = Vec::new();
        for target in targets.targets {
            if target.already_present {
                continue;
            }
            let data = unique_blobs.get(&target.blob_id).cloned().ok_or_else(|| {
                SdkError::ClientError(format!(
                    "server returned an unknown native blob target {}",
                    target.blob_id
                ))
            })?;
            let url = target.url.ok_or_else(|| {
                SdkError::ClientError("direct upload target omitted URL".to_string())
            })?;
            let checksum = target.checksum_sha256.ok_or_else(|| {
                SdkError::ClientError("direct upload target omitted SHA-256 header".to_string())
            })?;
            receipts.push(NativeDirectUploadReceipt {
                blob_id: target.blob_id,
                logical_len: target.logical_len,
            });
            let client = self.git_client.clone();
            uploads.push(async move {
                let response = upload_native_direct_source(&client, &url, &checksum, &data).await?;
                if response.status().is_success() {
                    Ok::<(), SdkError>(())
                } else {
                    Err(SdkError::ServerError {
                        status: response.status(),
                        message: body_message(response).await,
                    })
                }
            });
        }
        let results = futures::stream::iter(uploads)
            .buffer_unordered(8)
            .collect::<Vec<_>>()
            .await;
        for result in results {
            result?;
        }

        let publish = NativeDirectPublishRequest {
            operation_id,
            message,
            expected_version_id: head.snapshot_id,
            lease_id: lease.lease_id,
            uploads: receipts,
            mutations,
            retain_as_snapshot: false,
        };
        let (publish_request, trace_id) = self.git_request(
            Method::POST,
            project_id,
            filesystem,
            Some("fs/publish"),
            git_username,
            git_token,
        )?;
        decode_json(
            send_idempotent(publish_request.json(&publish)).await?,
            trace_id,
        )
        .await
    }

    fn git_request(
        &self,
        method: Method,
        project_id: &str,
        repo: &str,
        suffix: Option<&str>,
        git_username: &str,
        git_token: &str,
    ) -> Result<(reqwest::RequestBuilder, String), SdkError> {
        let base = format!(
            "{}/project/{}/repos/{}",
            self.git_base_url,
            encode_path_segment(project_id),
            encode_path_segment(repo)
        );
        let path = match suffix {
            Some(suffix) => format!("{base}/{suffix}"),
            None => base,
        };
        Ok(self.git_request_url(method, path, git_username, git_token))
    }

    /// A project-scope request (`/project/{project}/{suffix}`) with a git credential —
    /// the URL shape for endpoints that span repos, like the workspace fleet.
    fn project_git_request(
        &self,
        method: Method,
        project_id: &str,
        suffix: &str,
        git_username: &str,
        git_token: &str,
    ) -> (reqwest::RequestBuilder, String) {
        let url = format!(
            "{}/project/{}/{}",
            self.git_base_url,
            encode_path_segment(project_id),
            suffix
        );
        self.git_request_url(method, url, git_username, git_token)
    }

    fn git_request_url(
        &self,
        method: Method,
        url: String,
        git_username: &str,
        git_token: &str,
    ) -> (reqwest::RequestBuilder, String) {
        let (traceparent, trace_id) = traceparent();
        (
            self.git_client
                .request(method, url)
                .basic_auth(git_username, Some(git_token))
                .header("traceparent", traceparent),
            trace_id,
        )
    }
}

type NativeDirectPrepared = (
    Vec<NativeDirectMutation>,
    std::collections::BTreeMap<String, NativeDirectUploadSource>,
);

#[derive(Clone, Debug)]
enum NativeDirectUploadSource {
    Bytes(bytes::Bytes),
    FileRange {
        path: std::sync::Arc<std::path::PathBuf>,
        offset: u64,
        logical_len: u64,
    },
}

impl NativeDirectUploadSource {
    fn logical_len(&self) -> u64 {
        match self {
            Self::Bytes(bytes) => bytes.len() as u64,
            Self::FileRange { logical_len, .. } => *logical_len,
        }
    }
}

fn prepare_native_direct_publication(
    files: Vec<NativeDirectFileWrite>,
    path_files: Vec<NativeDirectFilePathWrite>,
    deletes: Vec<String>,
    moves: Vec<NativeDirectPathTransfer>,
    copies: Vec<NativeDirectPathTransfer>,
    part_bytes: usize,
) -> Result<NativeDirectPrepared, SdkError> {
    use rayon::prelude::*;
    use sha2::{Digest, Sha256};

    if part_bytes == 0 {
        return Err(SdkError::ClientError(
            "native direct-upload part size must be non-zero".to_string(),
        ));
    }
    let mut mutations = Vec::with_capacity(
        files.len() + path_files.len() + deletes.len() + moves.len() + copies.len(),
    );
    let mut unique_blobs = std::collections::BTreeMap::<String, NativeDirectUploadSource>::new();
    for file in files {
        let content = bytes::Bytes::from(file.data);
        let parts = if content.is_empty() {
            vec![(hex::encode(Sha256::digest([])), bytes::Bytes::new())]
        } else {
            (0..content.len())
                .step_by(part_bytes)
                .map(|start| content.slice(start..(start + part_bytes).min(content.len())))
                .collect::<Vec<_>>()
                .into_par_iter()
                .map(|part| (hex::encode(Sha256::digest(&part)), part))
                .collect()
        };
        let mut blobs = Vec::with_capacity(parts.len());
        for (blob_id, part) in parts {
            blobs.push(NativeDirectBlobRequest {
                blob_id: blob_id.clone(),
                logical_len: part.len() as u64,
            });
            if !part.is_empty() {
                unique_blobs
                    .entry(blob_id)
                    .or_insert(NativeDirectUploadSource::Bytes(part));
            }
        }
        mutations.push(NativeDirectMutation::Put {
            path: file.path,
            blobs,
        });
    }
    for file in path_files {
        use std::io::Read;

        let source_path = std::sync::Arc::new(file.source_path);
        let mut source = std::fs::File::open(source_path.as_ref()).map_err(|error| {
            SdkError::ClientError(format!(
                "opening native publication source {}: {error}",
                source_path.display()
            ))
        })?;
        let logical_len = source
            .metadata()
            .map_err(|error| {
                SdkError::ClientError(format!(
                    "reading native publication source metadata {}: {error}",
                    source_path.display()
                ))
            })?
            .len();
        let mut blobs = Vec::new();
        if logical_len == 0 {
            blobs.push(NativeDirectBlobRequest {
                blob_id: hex::encode(Sha256::digest([])),
                logical_len: 0,
            });
        } else {
            let mut offset = 0u64;
            let mut buffer = vec![0u8; part_bytes];
            while offset < logical_len {
                let part_len = usize::try_from(
                    (logical_len - offset).min(u64::try_from(part_bytes).unwrap_or(u64::MAX)),
                )
                .map_err(|_| {
                    SdkError::ClientError("native publication part length overflow".to_string())
                })?;
                source
                    .read_exact(&mut buffer[..part_len])
                    .map_err(|error| {
                        SdkError::ClientError(format!(
                            "reading native publication source {}: {error}",
                            source_path.display()
                        ))
                    })?;
                let blob_id = hex::encode(Sha256::digest(&buffer[..part_len]));
                blobs.push(NativeDirectBlobRequest {
                    blob_id: blob_id.clone(),
                    logical_len: part_len as u64,
                });
                unique_blobs.entry(blob_id).or_insert_with(|| {
                    NativeDirectUploadSource::FileRange {
                        path: source_path.clone(),
                        offset,
                        logical_len: part_len as u64,
                    }
                });
                offset += part_len as u64;
            }
        }
        mutations.push(NativeDirectMutation::Put {
            path: file.path,
            blobs,
        });
    }
    mutations.extend(
        deletes
            .into_iter()
            .map(|path| NativeDirectMutation::Delete { path }),
    );
    mutations.extend(
        moves
            .into_iter()
            .map(|transfer| NativeDirectMutation::Move {
                from: transfer.from,
                to: transfer.to,
            }),
    );
    mutations.extend(
        copies
            .into_iter()
            .map(|transfer| NativeDirectMutation::Copy {
                from: transfer.from,
                to: transfer.to,
            }),
    );
    if unique_blobs.len() > 4_096 {
        return Err(SdkError::ClientError(format!(
            "native publication contains {} unique non-empty parts; the maximum is 4096",
            unique_blobs.len()
        )));
    }
    Ok((mutations, unique_blobs))
}

fn native_read_protocol_error(message: impl Into<String>) -> SdkError {
    SdkError::ClientError(format!(
        "invalid native filesystem read response: {}",
        message.into()
    ))
}

fn validate_signed_blob_url(url: &str) -> Result<(), SdkError> {
    let parsed = url::Url::parse(url)
        .map_err(|_| native_read_protocol_error("server returned an invalid signed blob URL"))?;
    if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {
        return Err(native_read_protocol_error(
            "server returned an unsupported signed blob URL",
        ));
    }
    Ok(())
}

fn sha256_hex(bytes: &[u8]) -> String {
    use sha2::Digest as _;
    hex::encode(sha2::Sha256::digest(bytes))
}

fn native_file_content_id(bytes: &[u8]) -> String {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"tensorlake.fs.file-content.v1\0");
    hasher.update(bytes);
    hex::encode(hasher.finalize().as_bytes())
}

fn verify_native_logical_content(
    bytes: &[u8],
    logical_len: u64,
    content_id: &str,
    hash_algorithm: &str,
) -> Result<(), SdkError> {
    if bytes.len() as u64 != logical_len {
        return Err(native_read_protocol_error(format!(
            "logical content is {} bytes, expected {logical_len}",
            bytes.len()
        )));
    }
    let actual = match hash_algorithm {
        "blake3" => native_file_content_id(bytes),
        "sha256" => sha256_hex(bytes),
        // A recipe root commits to the ordered, individually verified leaves rather than the
        // concatenated bytes. Every downloaded leaf has already been checked.
        "native-merkle-v1" => return Ok(()),
        other => {
            return Err(native_read_protocol_error(format!(
                "unsupported content hash algorithm {other:?}"
            )));
        }
    };
    if actual != content_id {
        return Err(native_read_protocol_error(
            "logical filesystem content checksum mismatch",
        ));
    }
    Ok(())
}

fn verify_native_leaf_content(
    bytes: &[u8],
    logical_len: u64,
    content_id: Option<&str>,
    hash_algorithm: Option<&str>,
) -> Result<(), SdkError> {
    let content_id =
        content_id.ok_or_else(|| native_read_protocol_error("content ID is missing"))?;
    let hash_algorithm =
        hash_algorithm.ok_or_else(|| native_read_protocol_error("hash algorithm is missing"))?;
    if hash_algorithm == "native-merkle-v1" {
        return Err(native_read_protocol_error(
            "a leaf read-plan entry used a recipe-root hash algorithm",
        ));
    }
    verify_native_logical_content(bytes, logical_len, content_id, hash_algorithm)
}

async fn decode_native_read_part(
    part: &NativeReadPart,
    stored: Vec<u8>,
) -> Result<Vec<u8>, SdkError> {
    match part.compression.as_str() {
        "raw" => Ok(stored),
        "zstd" => {
            let logical_len = part.logical_len;
            tokio::task::spawn_blocking(move || {
                use std::io::Read as _;

                let decoder =
                    zstd::stream::read::Decoder::new(stored.as_slice()).map_err(|error| {
                        native_read_protocol_error(format!(
                            "invalid zstd filesystem content: {error}"
                        ))
                    })?;
                let limit = logical_len.checked_add(1).ok_or_else(|| {
                    native_read_protocol_error("decompressed length limit overflowed")
                })?;
                let mut logical = Vec::with_capacity(
                    usize::try_from(logical_len)
                        .unwrap_or(usize::MAX)
                        .min(8 * 1024 * 1024),
                );
                decoder
                    .take(limit)
                    .read_to_end(&mut logical)
                    .map_err(|error| {
                        native_read_protocol_error(format!(
                            "failed to decompress filesystem content: {error}"
                        ))
                    })?;
                if logical.len() as u64 != logical_len {
                    return Err(native_read_protocol_error(format!(
                        "zstd filesystem content expands to {} bytes, expected {logical_len}",
                        logical.len()
                    )));
                }
                Ok(logical)
            })
            .await
            .map_err(|error| {
                native_read_protocol_error(format!(
                    "filesystem decompression worker failed: {error}"
                ))
            })?
        }
        other => Err(native_read_protocol_error(format!(
            "unsupported filesystem compression {other:?}"
        ))),
    }
}

async fn send_signed_read(request: reqwest::RequestBuilder) -> Option<reqwest::Response> {
    const ATTEMPTS: usize = 3;
    for attempt in 0..ATTEMPTS {
        let current = request.try_clone()?;
        match current.send().await {
            Ok(response)
                if attempt + 1 < ATTEMPTS
                    && (response.status().is_server_error()
                        || response.status() == StatusCode::TOO_MANY_REQUESTS) => {}
            Ok(response) if response.status().is_success() => return Some(response),
            Ok(_) => return None,
            Err(_) if attempt + 1 < ATTEMPTS => {}
            Err(_) => return None,
        }
        tokio::time::sleep(std::time::Duration::from_millis(25 << attempt)).await;
    }
    None
}

async fn read_response_body_exact(
    response: reqwest::Response,
    expected_len: u64,
) -> Option<Vec<u8>> {
    use futures::StreamExt as _;

    if response
        .content_length()
        .is_some_and(|length| length != expected_len)
    {
        return None;
    }
    let capacity = usize::try_from(expected_len).ok()?;
    let mut body = Vec::new();
    body.try_reserve_exact(capacity).ok()?;
    let mut stream = response.bytes_stream();
    while let Some(chunk) = stream.next().await {
        let chunk = chunk.ok()?;
        let next_len = body.len().checked_add(chunk.len())?;
        if next_len > capacity {
            return None;
        }
        body.extend_from_slice(&chunk);
    }
    (body.len() == capacity).then_some(body)
}

fn validate_native_direct_path(path: &str) -> Result<(), SdkError> {
    if path.is_empty()
        || path.starts_with('/')
        || path.ends_with('/')
        || path.contains('\\')
        || path.contains('\0')
        || path.split('/').any(|component| {
            component.is_empty() || component == "." || component == ".." || component.contains(':')
        })
    {
        return Err(SdkError::ClientError(format!(
            "invalid native filesystem path {path:?}"
        )));
    }
    Ok(())
}

fn validate_native_direct_targets(
    requested: &[NativeDirectBlobRequest],
    targets: &[models::NativeDirectBlobTarget],
) -> Result<(), SdkError> {
    use base64::Engine;

    let expected = requested
        .iter()
        .map(|blob| (blob.blob_id.as_str(), blob.logical_len))
        .collect::<std::collections::HashMap<_, _>>();
    let mut seen = std::collections::HashSet::with_capacity(targets.len());
    for target in targets {
        let Some(expected_len) = expected.get(target.blob_id.as_str()) else {
            return Err(SdkError::ClientError(format!(
                "server returned an unrequested native blob target {}",
                target.blob_id
            )));
        };
        if !seen.insert(target.blob_id.as_str()) {
            return Err(SdkError::ClientError(format!(
                "server returned native blob target {} more than once",
                target.blob_id
            )));
        }
        if target.logical_len != *expected_len {
            return Err(SdkError::ClientError(format!(
                "server returned native blob target {} with length {}, expected {}",
                target.blob_id, target.logical_len, expected_len
            )));
        }
        if !target.already_present {
            let checksum = target.checksum_sha256.as_deref().ok_or_else(|| {
                SdkError::ClientError("direct upload target omitted SHA-256 header".to_string())
            })?;
            let digest = hex::decode(&target.blob_id).map_err(|error| {
                SdkError::ClientError(format!(
                    "server returned invalid native blob identity {}: {error}",
                    target.blob_id
                ))
            })?;
            let expected_checksum = base64::engine::general_purpose::STANDARD.encode(digest);
            if checksum != expected_checksum {
                return Err(SdkError::ClientError(format!(
                    "server returned a checksum that does not match native blob target {}",
                    target.blob_id
                )));
            }
            let url = target.url.as_deref().ok_or_else(|| {
                SdkError::ClientError("direct upload target omitted URL".to_string())
            })?;
            validate_signed_blob_url(url)?;
        }
    }
    if seen.len() != expected.len() {
        let missing = expected
            .keys()
            .filter(|blob_id| !seen.contains(**blob_id))
            .copied()
            .collect::<Vec<_>>();
        return Err(SdkError::ClientError(format!(
            "server omitted native blob target(s): {}",
            missing.join(", ")
        )));
    }
    Ok(())
}

fn encode_native_path(path: &str) -> Result<String, SdkError> {
    validate_native_direct_path(path)?;
    Ok(path
        .split('/')
        .map(encode_path_segment)
        .collect::<Vec<_>>()
        .join("/"))
}

fn native_snapshot_id(version: &str) -> Result<Option<&str>, SdkError> {
    match version {
        "" | "main" | "refs/heads/main" => Ok(None),
        snapshot
            if snapshot.len() == 64 && snapshot.bytes().all(|byte| byte.is_ascii_hexdigit()) =>
        {
            Ok(Some(snapshot))
        }
        _ => Err(SdkError::ClientError(format!(
            "native filesystems support the current head or a 64-character snapshot id, not {version:?}"
        ))),
    }
}

fn native_entries_suffix(
    path: &str,
    snapshot: Option<&str>,
    after: Option<&str>,
    limit: usize,
) -> String {
    let mut query = url::form_urlencoded::Serializer::new(String::new());
    if let Some(snapshot) = snapshot {
        query.append_pair("snapshot", snapshot);
    }
    query.append_pair("path", path);
    if let Some(after) = after {
        query.append_pair("after", after);
    }
    query.append_pair("limit", &limit.clamp(1, 10_000).to_string());
    format!("fs/entries?{}", query.finish())
}

fn native_read_plan_suffix(
    encoded_path: &str,
    snapshot: Option<&str>,
    after_offset: u64,
    limit: usize,
) -> String {
    // Keep the non-Send form serializer inside this synchronous helper so native-binding futures
    // never retain it across an await.
    let mut query = url::form_urlencoded::Serializer::new(String::new());
    if let Some(snapshot) = snapshot {
        query.append_pair("snapshot", snapshot);
    }
    query.append_pair("after_offset", &after_offset.to_string());
    query.append_pair("limit", &limit.clamp(1, 4096).to_string());
    format!("fs/read-plan/{encoded_path}?{}", query.finish())
}

fn repo_list_query(kind: Option<&str>, after: Option<&str>) -> String {
    // `form_urlencoded::Serializer` contains a non-Send callback reference. Keep it in this
    // synchronous helper so napi/tonic callers can carry the async request future across workers.
    let mut params = url::form_urlencoded::Serializer::new(String::new());
    if let Some(kind) = kind {
        params.append_pair("kind", kind);
        // Every filesystem page carries a synchronous cache-generation fence. Project inventory
        // routes have no repository affinity, so consecutive requests may land on different
        // server pods; fencing only page one could splice a fresh first page to a stale later page
        // and omit a just-created filesystem after the first cursor.
        if kind == REPO_KIND_FILESYSTEM {
            params.append_pair("fresh", "true");
        }
    }
    if let Some(after) = after {
        params.append_pair("after", after);
    }
    params.append_pair("limit", "1000");
    params.finish()
}

pub fn resolve_artifact_storage_url(api_url: &str) -> String {
    if let Ok(parsed) = url::Url::parse(api_url) {
        let host = parsed.host_str().unwrap_or("");
        if host == "localhost" || host == "127.0.0.1" {
            return api_url.to_string();
        }
        if let Some(rest) = host.strip_prefix("api.") {
            return format!("{}://git.{}", parsed.scheme(), rest);
        }
    }
    "https://git.tensorlake.ai".to_string()
}

fn trim_base_url(url: String) -> String {
    url.trim_end_matches('/').to_string()
}

fn encode_path_segment(segment: &str) -> String {
    urlencoding::encode(segment).into_owned()
}

fn git_credential_is_fresh(credential: &GitCredential) -> bool {
    chrono::DateTime::parse_from_rfc3339(&credential.expires_at)
        .map(|expires_at| {
            expires_at.timestamp_millis()
                > chrono::Utc::now().timestamp_millis().saturating_add(30_000)
        })
        .unwrap_or(false)
}

/// A paged collection must always make forward progress. Treat an empty or repeated cursor as a
/// malformed server response rather than spinning forever in an SDK call.
fn advance_pagination_cursor(
    seen: &mut HashSet<String>,
    next: String,
    surface: &str,
) -> Result<String, SdkError> {
    if next.is_empty() || !seen.insert(next.clone()) {
        return Err(SdkError::ClientError(format!(
            "{surface} returned an empty or repeated pagination cursor"
        )));
    }
    Ok(next)
}

fn traceparent() -> (String, String) {
    let trace_id = hex::encode(rand::random::<[u8; 16]>());
    let span_id = hex::encode(rand::random::<[u8; 8]>());
    (format!("00-{trace_id}-{span_id}-01"), trace_id)
}

async fn decode_empty(
    response: reqwest::Response,
    trace_id: String,
) -> Result<Traced<()>, SdkError> {
    handle_response(response).await?;
    Ok(Traced::new(trace_id, ()))
}

async fn native_direct_request_body(
    source: &NativeDirectUploadSource,
) -> Result<reqwest::Body, SdkError> {
    match source {
        NativeDirectUploadSource::Bytes(bytes) => Ok(reqwest::Body::from(bytes.clone())),
        NativeDirectUploadSource::FileRange {
            path,
            offset,
            logical_len,
        } => {
            use tokio::io::{AsyncReadExt, AsyncSeekExt};

            let mut file = tokio::fs::File::open(path.as_ref()).await?;
            file.seek(std::io::SeekFrom::Start(*offset)).await?;
            // ReaderStream's small default allocation creates excessive body frames for 64 MiB
            // parts. A 1 MiB transport buffer keeps eight concurrent uploads memory-bounded while
            // reaching object-store line rate with far less scheduler and HTTP framing overhead.
            let stream =
                tokio_util::io::ReaderStream::with_capacity(file.take(*logical_len), 1024 * 1024);
            Ok(reqwest::Body::wrap_stream(stream))
        }
    }
}

/// Upload a replayable source. File-backed parts reopen and seek the source for each transport
/// attempt, avoiding both whole-file memory and reqwest's non-cloneable streaming-body
/// limitation. The retry budget matches `send_idempotent` — the direct PUT is the
/// highest-volume request of a publication and object stores shed load with the same
/// 503-plus-`Retry-After` shape (S3 SlowDown) the control plane does.
async fn upload_native_direct_source(
    client: &reqwest::Client,
    url: &str,
    checksum: &str,
    source: &NativeDirectUploadSource,
) -> Result<reqwest::Response, SdkError> {
    const ATTEMPTS: usize = 5;
    for attempt in 0..ATTEMPTS {
        let body = native_direct_request_body(source).await?;
        let hinted = match client
            .put(url)
            .header(
                reqwest::header::CONTENT_LENGTH,
                source.logical_len().to_string(),
            )
            .header("x-amz-checksum-sha256", checksum)
            .body(body)
            .send()
            .await
        {
            Ok(response)
                if attempt + 1 < ATTEMPTS
                    && (response.status().is_server_error()
                        || response.status() == StatusCode::TOO_MANY_REQUESTS) =>
            {
                let hinted = retry_after_hint(&response);
                // Drain the (small) error body so the pooled connection is reusable across
                // retries; see send_idempotent.
                let _ = response.bytes().await;
                hinted
            }
            Ok(response) => return Ok(response),
            Err(_) if attempt + 1 < ATTEMPTS => None,
            Err(error) => return Err(error.into()),
        };
        tokio::time::sleep(retry_delay(attempt, hinted)).await;
    }
    unreachable!("the final direct upload attempt always returns")
}

/// Send an idempotent direct-publication step with a bounded transport retry budget. Every
/// caller either uses a read, a lease/target allocation that reattaches by server key, an
/// immutable PUT, or the operation-id-fenced publish endpoint.
///
/// Capacity rejections (429/503) carry a `Retry-After` hint that this backoff honors up to a
/// 2s-per-wait ceiling — enough for the admission layer's one-second burst shedding (the
/// 2026-08-14 storage-benchmark failures were three sub-100ms retries spent inside a single
/// 2.5s 503 storm) while keeping the worst-case in-call blocking bounded for callers with
/// their own deadlines; storms the server prices above the whole budget are surfaced rather
/// than waited out. Transport errors and hint-less server errors keep a fast exponential
/// fallback.
async fn send_idempotent(request: reqwest::RequestBuilder) -> Result<reqwest::Response, SdkError> {
    const ATTEMPTS: usize = 5;
    for attempt in 0..ATTEMPTS {
        let current = request.try_clone().ok_or_else(|| {
            SdkError::ClientError("direct upload request body cannot be retried".to_string())
        })?;
        let hinted = match current.send().await {
            Ok(response)
                if attempt + 1 < ATTEMPTS
                    && (response.status().is_server_error()
                        || response.status() == StatusCode::TOO_MANY_REQUESTS) =>
            {
                let hinted = retry_after_hint(&response);
                // Drain the (small) error body so the pooled connection is reusable; dropping
                // it unread closes the socket and every retry pays a fresh handshake during
                // exactly the overload window.
                let _ = response.bytes().await;
                hinted
            }
            Ok(response) => return Ok(response),
            Err(error) if attempt + 1 < ATTEMPTS => {
                let _ = error;
                None
            }
            Err(error) => return Err(error.into()),
        };
        tokio::time::sleep(retry_delay(attempt, hinted)).await;
    }
    unreachable!("the final direct request attempt always returns")
}

/// Backoff for one failed idempotent attempt. A `Retry-After` hint is honored — capped so the
/// whole budget stays bounded for callers with their own deadlines, and FLOORED at the
/// exponential fallback so a `Retry-After: 0` (a shape some proxies shed with) cannot strip all
/// backoff and reintroduce the burn-the-budget-inside-one-burst failure.
fn retry_delay(attempt: usize, hinted: Option<std::time::Duration>) -> std::time::Duration {
    const MAX_RETRY_AFTER: std::time::Duration = std::time::Duration::from_secs(2);
    let fallback = std::time::Duration::from_millis(50 << attempt);
    match hinted {
        // max-then-min rather than clamp: clamp panics when the floor exceeds the ceiling,
        // which is one ATTEMPTS bump away (50ms << 6 > 2s) from a retry-path panic.
        Some(hint) => hint.max(fallback).min(MAX_RETRY_AFTER),
        None => fallback,
    }
}

/// The server's `Retry-After` delay, when present as whole seconds (the only shape our
/// admission layer emits). HTTP-date forms are ignored rather than parsed.
fn retry_after_hint(response: &reqwest::Response) -> Option<std::time::Duration> {
    response
        .headers()
        .get(reqwest::header::RETRY_AFTER)?
        .to_str()
        .ok()?
        .trim()
        .parse::<u64>()
        .ok()
        .map(std::time::Duration::from_secs)
}

async fn decode_json<T: DeserializeOwned>(
    response: reqwest::Response,
    trace_id: String,
) -> Result<Traced<T>, SdkError> {
    let response = handle_response(response).await?;
    let bytes = response.bytes().await?;
    let jd = &mut serde_json::Deserializer::from_slice(bytes.as_ref());
    let value = serde_path_to_error::deserialize(jd)?;
    Ok(Traced::new(trace_id, value))
}

async fn handle_response(response: reqwest::Response) -> Result<reqwest::Response, SdkError> {
    let status = response.status();
    match status {
        StatusCode::UNAUTHORIZED => Err(SdkError::Authentication(body_message(response).await)),
        StatusCode::FORBIDDEN => Err(SdkError::Authorization(body_message(response).await)),
        status if !status.is_success() => Err(SdkError::ServerError {
            status,
            message: body_message(response).await,
        }),
        _ => Ok(response),
    }
}

async fn body_message(response: reqwest::Response) -> String {
    response.text().await.unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;
    use std::sync::{Arc, Mutex};

    use base64::Engine;
    use sha2::{Digest, Sha256};
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    use super::{
        ArtifactStorageClient, advance_pagination_cursor, encode_path_segment,
        git_credential_is_fresh, native_file_content_id, prepare_native_direct_publication,
        repo_list_query, resolve_artifact_storage_url, sha256_hex, validate_native_direct_targets,
        validate_signed_blob_url, verify_native_leaf_content,
    };
    use crate::ClientBuilder;
    use crate::artifact_storage::models::{
        GitCredential, NativeDirectBlobRequest, NativeDirectBlobTarget, NativeDirectFilePathWrite,
        NativeDirectFileWrite, NativeDirectMutation, NativeDirectPathTransfer,
        REPO_KIND_FILESYSTEM,
    };

    #[test]
    fn resolves_git_url_from_api_url() {
        assert_eq!(
            resolve_artifact_storage_url("https://api.tensorlake.ai"),
            "https://git.tensorlake.ai"
        );
        assert_eq!(
            resolve_artifact_storage_url("https://api.tensorlake.dev"),
            "https://git.tensorlake.dev"
        );
        assert_eq!(
            resolve_artifact_storage_url("http://localhost:3000"),
            "http://localhost:3000"
        );
    }

    #[test]
    fn encodes_path_segments() {
        assert_eq!(encode_path_segment("project_123"), "project_123");
        assert_eq!(encode_path_segment("repo/name"), "repo%2Fname");
    }

    #[test]
    fn signed_blob_urls_are_http_urls_with_hosts() {
        assert!(validate_signed_blob_url("https://store.example/object?signature=x").is_ok());
        assert!(validate_signed_blob_url("http://127.0.0.1:9000/object").is_ok());
        assert!(validate_signed_blob_url("file:///tmp/object").is_err());
        assert!(validate_signed_blob_url("https:///").is_err());
    }

    #[test]
    fn native_read_leaf_hashes_fail_closed() {
        let bytes = b"verified filesystem bytes";
        assert!(
            verify_native_leaf_content(
                bytes,
                bytes.len() as u64,
                Some(&sha256_hex(bytes)),
                Some("sha256"),
            )
            .is_ok()
        );
        assert!(
            verify_native_leaf_content(
                bytes,
                bytes.len() as u64,
                Some(&native_file_content_id(bytes)),
                Some("blake3"),
            )
            .is_ok()
        );
        assert!(
            verify_native_leaf_content(
                bytes,
                bytes.len() as u64,
                Some(&sha256_hex(b"different")),
                Some("sha256"),
            )
            .is_err()
        );
        assert!(
            verify_native_leaf_content(
                bytes,
                bytes.len() as u64,
                Some(&native_file_content_id(bytes)),
                Some("native-merkle-v1"),
            )
            .is_err()
        );
    }

    #[test]
    fn direct_publication_splits_memory_and_file_sources_into_bounded_parts() {
        let temp = tempfile::tempdir().unwrap();
        let source_path = temp.path().join("large.bin");
        std::fs::write(&source_path, b"abcdefgh").unwrap();
        let (mutations, unique) = prepare_native_direct_publication(
            vec![NativeDirectFileWrite {
                path: "memory.bin".into(),
                data: b"abcdefgh".to_vec(),
            }],
            vec![NativeDirectFilePathWrite {
                path: "disk.bin".into(),
                source_path,
            }],
            Vec::new(),
            Vec::new(),
            Vec::new(),
            3,
        )
        .unwrap();

        assert_eq!(mutations.len(), 2);
        for mutation in mutations {
            let NativeDirectMutation::Put { blobs, .. } = mutation else {
                panic!("expected put mutation");
            };
            assert_eq!(
                blobs
                    .iter()
                    .map(|blob| blob.logical_len)
                    .collect::<Vec<_>>(),
                vec![3, 3, 2]
            );
        }
        // Identical memory/file content deduplicates to one source per part identity.
        assert_eq!(unique.len(), 3);
    }

    #[test]
    fn direct_upload_targets_must_exactly_match_the_request() {
        use base64::Engine;

        let blob_id = hex::encode(Sha256::digest(b"payload"));
        let checksum = base64::engine::general_purpose::STANDARD.encode(Sha256::digest(b"payload"));
        let request = NativeDirectBlobRequest {
            blob_id: blob_id.clone(),
            logical_len: 7,
        };
        let target = NativeDirectBlobTarget {
            blob_id: blob_id.clone(),
            logical_len: 7,
            already_present: false,
            url: Some("https://objects.example/upload".to_string()),
            checksum_sha256: Some(checksum),
        };
        assert!(
            validate_native_direct_targets(
                std::slice::from_ref(&request),
                std::slice::from_ref(&target)
            )
            .is_ok()
        );

        let mut wrong_len = target.clone();
        wrong_len.logical_len += 1;
        assert!(
            validate_native_direct_targets(std::slice::from_ref(&request), &[wrong_len]).is_err()
        );
        assert!(
            validate_native_direct_targets(
                std::slice::from_ref(&request),
                &[target.clone(), target.clone()]
            )
            .is_err()
        );
        assert!(validate_native_direct_targets(std::slice::from_ref(&request), &[]).is_err());

        let mut wrong_checksum = target;
        wrong_checksum.checksum_sha256 = Some("not-the-content-digest".to_string());
        assert!(
            validate_native_direct_targets(std::slice::from_ref(&request), &[wrong_checksum])
                .is_err()
        );
    }

    #[test]
    fn git_repo_url_uses_git_root_project_repo_shape() {
        let api_client = ClientBuilder::new("https://api.tensorlake.ai")
            .bearer_token("token")
            .build()
            .unwrap();
        let client = ArtifactStorageClient::new(api_client, "https://git.tensorlake.ai/").unwrap();

        assert_eq!(
            client.git_repo_url("project_123", "myrepo"),
            "https://git.tensorlake.ai/project_123/myrepo"
        );
    }

    #[test]
    fn pagination_cursor_must_make_progress() {
        let mut seen = HashSet::new();
        assert_eq!(
            advance_pagination_cursor(&mut seen, "page-2".to_string(), "test").unwrap(),
            "page-2"
        );
        assert!(advance_pagination_cursor(&mut seen, "page-2".to_string(), "test").is_err());
        assert!(advance_pagination_cursor(&mut seen, String::new(), "test").is_err());
    }

    #[test]
    fn repository_credential_cache_keeps_an_expiry_safety_margin() {
        let credential = |expires_at: String| GitCredential {
            token: "token".to_string(),
            token_type: "bearer".to_string(),
            expires_at,
            git_username: "user".to_string(),
            repo_pattern: "filesystem".to_string(),
            scopes: vec!["fs:write".to_string()],
        };
        assert!(git_credential_is_fresh(&credential(
            (chrono::Utc::now() + chrono::Duration::minutes(5)).to_rfc3339()
        )));
        assert!(!git_credential_is_fresh(&credential(
            (chrono::Utc::now() + chrono::Duration::seconds(10)).to_rfc3339()
        )));
        assert!(!git_credential_is_fresh(&credential(String::new())));
    }

    #[tokio::test]
    async fn project_credential_reuses_the_shared_expiry_checked_cache() {
        let api_client = ClientBuilder::new("http://127.0.0.1:1").build().unwrap();
        let client = ArtifactStorageClient::new(api_client, "http://127.0.0.1:1").unwrap();
        let cached = GitCredential {
            token: "cached-project-token".to_string(),
            token_type: "bearer".to_string(),
            expires_at: (chrono::Utc::now() + chrono::Duration::minutes(5)).to_rfc3339(),
            git_username: "project-user".to_string(),
            repo_pattern: "*".to_string(),
            scopes: vec!["project:admin".to_string()],
        };
        client
            .git_credentials
            .lock()
            .await
            .insert(("project".to_string(), None), cached.clone());

        assert_eq!(
            client.git_credential_for_project("project").await.unwrap(),
            cached,
            "a cached project credential must avoid another control-plane mint"
        );
    }

    #[test]
    fn filesystem_inventory_fences_every_page() {
        assert_eq!(
            repo_list_query(Some(REPO_KIND_FILESYSTEM), None),
            "kind=filesystem&fresh=true&limit=1000"
        );
        assert_eq!(
            repo_list_query(Some(REPO_KIND_FILESYSTEM), Some("project/repo")),
            "kind=filesystem&fresh=true&after=project%2Frepo&limit=1000"
        );
        assert_eq!(
            repo_list_query(Some("repository"), None),
            "kind=repository&limit=1000"
        );
    }

    #[tokio::test]
    async fn native_reads_download_signed_ranges_without_forwarding_credentials() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let payload = b"signed object-store bytes for a direct filesystem read".to_vec();
        let content_id = sha256_hex(&payload);
        let requests = Arc::new(Mutex::new(Vec::<(String, String, String)>::new()));
        let captured = requests.clone();
        let server_base = base.clone();
        let server_payload = payload.clone();
        let server_content_id = content_id.clone();
        let server = tokio::spawn(async move {
            for _ in 0..5 {
                let (mut stream, _) = listener.accept().await.unwrap();
                let mut bytes = Vec::new();
                let header_end = loop {
                    let mut chunk = [0u8; 4096];
                    let read = stream.read(&mut chunk).await.unwrap();
                    assert_ne!(read, 0, "request ended before its headers");
                    bytes.extend_from_slice(&chunk[..read]);
                    if let Some(offset) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
                        break offset + 4;
                    }
                };
                let headers = String::from_utf8(bytes[..header_end].to_vec()).unwrap();
                let request_line = headers.lines().next().unwrap();
                let mut request_parts = request_line.split_whitespace();
                let method = request_parts.next().unwrap().to_string();
                let path = request_parts.next().unwrap().to_string();
                captured
                    .lock()
                    .unwrap()
                    .push((method.clone(), path.clone(), headers.clone()));

                let response_body = match (method.as_str(), path.as_str()) {
                    ("POST", "/artifact-storage/v1/token") => {
                        serde_json::to_vec(&serde_json::json!({
                            "token": "repo-token",
                            "tokenType": "bearer",
                            "expiresAt": "2099-01-01T00:00:00Z",
                            "gitUsername": "repo-user",
                            "repoPattern": "filesystem",
                            "scopes": ["fs:read"],
                        }))
                        .unwrap()
                    }
                    (
                        "GET",
                        "/project/project/repos/filesystem/fs/read-plan/data.bin?after_offset=0&limit=4096",
                    ) => serde_json::to_vec(&serde_json::json!({
                        "inline_base64": null,
                        "parts": [{
                            "segment_id": server_content_id,
                            "offset": 0,
                            "stored_len": server_payload.len(),
                            "logical_len": server_payload.len(),
                            "compression": "raw",
                            "content_id": server_content_id,
                            "hash_algorithm": "sha256",
                            "stored_checksum_sha256": server_content_id,
                            "url": format!("{server_base}/object-store/data"),
                        }],
                        "logical_len": server_payload.len(),
                        "content_id": server_content_id,
                        "hash_algorithm": "sha256",
                        "next_offset": null,
                        "proxy_path": "/project/project/repos/filesystem/fs/files/data.bin",
                    }))
                    .unwrap(),
                    ("GET", "/object-store/data") => server_payload.clone(),
                    other => panic!("unexpected request: {other:?}"),
                };
                let status = if path == "/object-store/data" {
                    "206 Partial Content"
                } else {
                    "200 OK"
                };
                let content_type = if path == "/object-store/data" {
                    "application/octet-stream"
                } else {
                    "application/json"
                };
                let response = format!(
                    "HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                    response_body.len()
                );
                stream.write_all(response.as_bytes()).await.unwrap();
                stream.write_all(&response_body).await.unwrap();
            }
        });

        let api_client = ClientBuilder::new(&base).build().unwrap();
        let client = ArtifactStorageClient::new(api_client, &base).unwrap();
        let full = client
            .read_native_filesystem_file_with_metadata(
                "project",
                "filesystem",
                "data.bin",
                "main",
                None,
            )
            .await
            .unwrap();
        assert_eq!(full.data, payload);
        assert_eq!(full.content_id, content_id);
        assert_eq!(full.full_size, payload.len() as u64);

        let ranged = client
            .read_native_filesystem_file_with_metadata(
                "project",
                "filesystem",
                "data.bin",
                "main",
                Some((7, 12)),
            )
            .await
            .unwrap();
        assert_eq!(ranged.data, payload[7..19]);
        assert_eq!(ranged.content_id, content_id);
        assert_eq!(ranged.full_size, payload.len() as u64);
        server.await.unwrap();

        let requests = requests.lock().unwrap();
        assert_eq!(
            requests
                .iter()
                .filter(|(_, path, _)| path == "/artifact-storage/v1/token")
                .count(),
            1,
            "the repo credential should be reused between direct reads"
        );
        for (_, path, headers) in requests
            .iter()
            .filter(|(_, path, _)| path == "/object-store/data")
        {
            assert!(
                !headers.to_ascii_lowercase().contains("authorization:"),
                "Tensorlake credentials leaked to signed blob URL {path}"
            );
            assert!(
                headers
                    .to_ascii_lowercase()
                    .contains(&format!("range: bytes=0-{}", payload.len() - 1)),
                "SDK did not request the exact stored range"
            );
        }
    }

    #[tokio::test]
    async fn direct_native_push_uploads_payload_only_to_the_presigned_target() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let payload = b"payload goes straight to object storage".to_vec();
        let blob_id = hex::encode(Sha256::digest(&payload));
        let checksum = base64::engine::general_purpose::STANDARD.encode(Sha256::digest(&payload));
        let requests = Arc::new(Mutex::new(Vec::<(String, String, Vec<u8>)>::new()));
        let captured = requests.clone();
        let server_base = base.clone();
        let server_blob_id = blob_id.clone();
        let server_payload = payload.clone();
        let server = tokio::spawn(async move {
            for _ in 0..11 {
                let (mut stream, _) = listener.accept().await.unwrap();
                let mut bytes = Vec::new();
                let header_end = loop {
                    let mut chunk = [0u8; 4096];
                    let read = stream.read(&mut chunk).await.unwrap();
                    assert_ne!(read, 0, "request ended before its headers");
                    bytes.extend_from_slice(&chunk[..read]);
                    if let Some(offset) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
                        break offset + 4;
                    }
                };
                let headers = String::from_utf8(bytes[..header_end].to_vec()).unwrap();
                let content_len = headers
                    .lines()
                    .find_map(|line| {
                        let (name, value) = line.split_once(':')?;
                        name.eq_ignore_ascii_case("content-length")
                            .then(|| value.trim().parse::<usize>().unwrap())
                    })
                    .unwrap_or(0);
                while bytes.len() < header_end + content_len {
                    let mut chunk = [0u8; 4096];
                    let read = stream.read(&mut chunk).await.unwrap();
                    assert_ne!(read, 0, "request ended before its body");
                    bytes.extend_from_slice(&chunk[..read]);
                }
                let request_line = headers.lines().next().unwrap();
                let mut request_parts = request_line.split_whitespace();
                let method = request_parts.next().unwrap().to_string();
                let path = request_parts.next().unwrap().to_string();
                let body = bytes[header_end..header_end + content_len].to_vec();
                captured
                    .lock()
                    .unwrap()
                    .push((method.clone(), path.clone(), body));

                let response_body = match (method.as_str(), path.as_str()) {
                    ("POST", "/artifact-storage/v1/token") => {
                        serde_json::to_vec(&serde_json::json!({
                            "token": "repo-token",
                            "tokenType": "bearer",
                            "expiresAt": "2099-01-01T00:00:00Z",
                            "gitUsername": "repo-user",
                            "repoPattern": "filesystem",
                            "scopes": ["fs:read", "fs:write"],
                        }))
                        .unwrap()
                    }
                    ("GET", "/project/project/repos/filesystem/fs/head") => {
                        serde_json::to_vec(
                            &serde_json::json!({"snapshot_id": null, "generation": 0}),
                        )
                        .unwrap()
                    }
                    ("POST", "/project/project/repos/filesystem/fs/upload-leases") => {
                        serde_json::to_vec(&serde_json::json!({
                            "lease_id": "lease-1",
                            "expires_at_ms": 9_999_999_999_999_u64,
                            "max_blob_bytes": 268_435_456_u64,
                            "max_targets_per_request": 256,
                            "max_parts_per_file": 4096,
                            "transport": "checksum_presigned_put",
                            "checksum_algorithm": "sha256",
                        }))
                        .unwrap()
                    }
                    (
                        "POST",
                        "/project/project/repos/filesystem/fs/upload-leases/lease-1/targets",
                    ) => serde_json::to_vec(&serde_json::json!({
                        "targets": [{
                            "blob_id": server_blob_id,
                            "logical_len": server_payload.len(),
                            "already_present": false,
                            "url": format!("{server_base}/object-store/stage-1"),
                            "checksum_sha256": checksum,
                        }],
                    }))
                    .unwrap(),
                    ("PUT", "/object-store/stage-1") => b"{}".to_vec(),
                    ("POST", "/project/project/repos/filesystem/fs/publish") => {
                        serde_json::to_vec(&serde_json::json!({
                            "version_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                            "previous_version_id": null,
                        }))
                        .unwrap()
                    }
                    ("POST", "/project/project/repos/filesystem/fs/snapshots") => {
                        serde_json::to_vec(&serde_json::json!({
                            "snapshot_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                            "snapshot_class": "permanent_snapshot",
                            "message": "retained by SDK",
                        }))
                        .unwrap()
                    }
                    ("GET", "/project/project/repos/filesystem/fs/snapshots?limit=1000") => {
                        serde_json::to_vec(&serde_json::json!({
                            "snapshots": [{
                                "snapshot_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                                "created_at_ms": 1234,
                                "message": "retained by SDK",
                                "snapshot_class": "permanent_snapshot",
                            }],
                            "next_after": null,
                        }))
                        .unwrap()
                    }
                    (
                        "GET",
                        "/project/project/repos/filesystem/fs/snapshots/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                    ) => serde_json::to_vec(&serde_json::json!({
                        "snapshot_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                        "created_at_ms": 1234,
                        "message": "retained by SDK",
                        "snapshot_class": "permanent_snapshot",
                        "permanence_epoch": 7,
                    }))
                    .unwrap(),
                    (
                        "DELETE",
                        "/project/project/repos/filesystem/fs/snapshots/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa?expected_permanence_epoch=7",
                    ) => Vec::new(),
                    ("GET", path) if path.starts_with(
                        "/project/project/repos/filesystem/fs/entries?path=data&limit=1000",
                    ) => serde_json::to_vec(&serde_json::json!({
                        "entries": [{
                            "name": "probe.bin",
                            "oid": server_blob_id,
                            "mode": 33188,
                            "size": server_payload.len(),
                        }],
                        "truncated": false,
                        "next_after": null,
                    }))
                    .unwrap(),
                    other => panic!("unexpected request: {other:?}"),
                };
                let response = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                    response_body.len()
                );
                stream.write_all(response.as_bytes()).await.unwrap();
                stream.write_all(&response_body).await.unwrap();
            }
        });

        let api_client = ClientBuilder::new(&base).build().unwrap();
        let client = ArtifactStorageClient::new(api_client, &base).unwrap();
        let result = client
            .publish_filesystem_files(
                "project",
                "filesystem",
                vec![
                    NativeDirectFileWrite {
                        path: "data/probe.bin".to_string(),
                        data: payload.clone(),
                    },
                    NativeDirectFileWrite {
                        path: "data/empty.txt".to_string(),
                        data: Vec::new(),
                    },
                ],
                vec!["old.txt".to_string()],
                Vec::new(),
                Vec::new(),
                "SDK publication".to_string(),
                "operation-1".to_string(),
            )
            .await
            .unwrap();
        assert_eq!(
            result.version_id,
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
        );
        let entries = client
            .list_native_filesystem_entries_page(
                "project",
                "filesystem",
                "data",
                "main",
                None,
                1000,
            )
            .await
            .unwrap();
        assert_eq!(entries.entries.len(), 1);
        assert_eq!(entries.entries[0].name, "probe.bin");
        let retained = client
            .retain_current_native_filesystem_snapshot(
                "project",
                "filesystem",
                "retained by SDK".to_string(),
                "retain-1".to_string(),
            )
            .await
            .unwrap();
        assert_eq!(retained.snapshot_class, "permanent_snapshot");
        let snapshots = client
            .list_native_filesystem_snapshots("project", "filesystem")
            .await
            .unwrap();
        assert_eq!(snapshots.len(), 1);
        client
            .delete_native_filesystem_snapshot(
                "project",
                "filesystem",
                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            )
            .await
            .unwrap();
        server.await.unwrap();

        let requests = requests.lock().unwrap();
        let upload = requests
            .iter()
            .find(|(method, path, _)| method == "PUT" && path == "/object-store/stage-1")
            .unwrap();
        assert_eq!(upload.2, payload);
        let targets = requests
            .iter()
            .find(|(_, path, _)| path.ends_with("/targets"))
            .unwrap();
        let targets: serde_json::Value = serde_json::from_slice(&targets.2).unwrap();
        assert_eq!(targets["blobs"].as_array().unwrap().len(), 1);
        assert_eq!(targets["blobs"][0]["blob_id"], blob_id);
        let publish = requests
            .iter()
            .find(|(_, path, _)| path.ends_with("/publish"))
            .unwrap();
        assert!(
            !String::from_utf8_lossy(&publish.2).contains("payload goes straight"),
            "control-plane publish body must not contain file payload bytes"
        );
        let publish: serde_json::Value = serde_json::from_slice(&publish.2).unwrap();
        assert_eq!(publish["operation_id"], "operation-1");
        assert_eq!(publish["message"], "SDK publication");
        assert_eq!(publish["retain_as_snapshot"], false);
        assert_eq!(publish["uploads"].as_array().unwrap().len(), 1);
        assert_eq!(publish["mutations"].as_array().unwrap().len(), 3);
        let retain = requests
            .iter()
            .find(|(method, path, _)| method == "POST" && path.ends_with("/fs/snapshots"))
            .unwrap();
        let retain: serde_json::Value = serde_json::from_slice(&retain.2).unwrap();
        assert_eq!(retain["request_id"], "retain-1");
        assert!(
            requests.iter().any(|(method, path, _)| {
                method == "DELETE" && path.ends_with("expected_permanence_epoch=7")
            }),
            "snapshot deletion must fence the server-observed permanence epoch"
        );
        assert_eq!(
            requests
                .iter()
                .filter(|(_, path, _)| path == "/artifact-storage/v1/token")
                .count(),
            1,
            "the repository credential should be reused across write and reads"
        );
    }

    /// A server that supports the combined flow folds the declared blobs' targets into the
    /// lease response; the SDK must consume them and issue NO standalone targets request. The
    /// sibling test above keeps the old-server shape (no `targets` in the lease response) and
    /// proves the standalone fallback stays byte-identical.
    #[tokio::test]
    async fn direct_native_push_consumes_targets_folded_into_the_lease() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let payload = b"combined lease and targets payload".to_vec();
        let blob_id = hex::encode(Sha256::digest(&payload));
        let checksum = base64::engine::general_purpose::STANDARD.encode(Sha256::digest(&payload));
        let requests = Arc::new(Mutex::new(Vec::<(String, String, Vec<u8>)>::new()));
        let captured = requests.clone();
        let server_base = base.clone();
        let server_blob_id = blob_id.clone();
        let server_payload = payload.clone();
        let server = tokio::spawn(async move {
            for _ in 0..5 {
                let (mut stream, _) = listener.accept().await.unwrap();
                let mut bytes = Vec::new();
                let header_end = loop {
                    let mut chunk = [0u8; 4096];
                    let read = stream.read(&mut chunk).await.unwrap();
                    assert_ne!(read, 0, "request ended before its headers");
                    bytes.extend_from_slice(&chunk[..read]);
                    if let Some(offset) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
                        break offset + 4;
                    }
                };
                let headers = String::from_utf8(bytes[..header_end].to_vec()).unwrap();
                let content_len = headers
                    .lines()
                    .find_map(|line| {
                        let (name, value) = line.split_once(':')?;
                        name.eq_ignore_ascii_case("content-length")
                            .then(|| value.trim().parse::<usize>().unwrap())
                    })
                    .unwrap_or(0);
                while bytes.len() < header_end + content_len {
                    let mut chunk = [0u8; 4096];
                    let read = stream.read(&mut chunk).await.unwrap();
                    assert_ne!(read, 0, "request ended before its body");
                    bytes.extend_from_slice(&chunk[..read]);
                }
                let request_line = headers.lines().next().unwrap();
                let mut request_parts = request_line.split_whitespace();
                let method = request_parts.next().unwrap().to_string();
                let path = request_parts.next().unwrap().to_string();
                let body = bytes[header_end..header_end + content_len].to_vec();
                captured
                    .lock()
                    .unwrap()
                    .push((method.clone(), path.clone(), body));

                let response_body = match (method.as_str(), path.as_str()) {
                    ("POST", "/artifact-storage/v1/token") => {
                        serde_json::to_vec(&serde_json::json!({
                            "token": "repo-token",
                            "tokenType": "bearer",
                            "expiresAt": "2099-01-01T00:00:00Z",
                            "gitUsername": "repo-user",
                            "repoPattern": "filesystem",
                            "scopes": ["fs:read", "fs:write"],
                        }))
                        .unwrap()
                    }
                    ("GET", "/project/project/repos/filesystem/fs/head") => {
                        serde_json::to_vec(
                            &serde_json::json!({"snapshot_id": null, "generation": 0}),
                        )
                        .unwrap()
                    }
                    ("POST", "/project/project/repos/filesystem/fs/upload-leases") => {
                        serde_json::to_vec(&serde_json::json!({
                            "lease_id": "lease-1",
                            "expires_at_ms": 9_999_999_999_999_u64,
                            "max_blob_bytes": 268_435_456_u64,
                            "max_targets_per_request": 256,
                            "max_parts_per_file": 4096,
                            "transport": "checksum_presigned_put",
                            "checksum_algorithm": "sha256",
                            "targets": [{
                                "blob_id": server_blob_id,
                                "logical_len": server_payload.len(),
                                "already_present": false,
                                "url": format!("{server_base}/object-store/stage-1"),
                                "checksum_sha256": checksum,
                            }],
                        }))
                        .unwrap()
                    }
                    ("PUT", "/object-store/stage-1") => b"{}".to_vec(),
                    ("POST", "/project/project/repos/filesystem/fs/publish") => {
                        serde_json::to_vec(&serde_json::json!({
                            "version_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                            "previous_version_id": null,
                        }))
                        .unwrap()
                    }
                    other => panic!("unexpected request (a combined-flow client must not issue a standalone targets request): {other:?}"),
                };
                let response = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                    response_body.len()
                );
                stream.write_all(response.as_bytes()).await.unwrap();
                stream.write_all(&response_body).await.unwrap();
            }
        });

        let api_client = ClientBuilder::new(&base).build().unwrap();
        let client = ArtifactStorageClient::new(api_client, &base).unwrap();
        let result = client
            .publish_filesystem_files(
                "project",
                "filesystem",
                vec![NativeDirectFileWrite {
                    path: "data/probe.bin".to_string(),
                    data: payload.clone(),
                }],
                Vec::new(),
                Vec::new(),
                Vec::new(),
                "combined publication".to_string(),
                "operation-combined".to_string(),
            )
            .await
            .unwrap();
        assert_eq!(
            result.version_id,
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
        );
        server.await.unwrap();

        let requests = requests.lock().unwrap();
        assert!(
            !requests
                .iter()
                .any(|(_, path, _)| path.contains("/targets")),
            "folded targets must remove the standalone negotiation round trip"
        );
        let lease = requests
            .iter()
            .find(|(method, path, _)| method == "POST" && path.ends_with("/fs/upload-leases"))
            .unwrap();
        let lease: serde_json::Value = serde_json::from_slice(&lease.2).unwrap();
        assert_eq!(
            lease["blobs"].as_array().unwrap().len(),
            1,
            "the lease request declares the prepared blob identities"
        );
        assert_eq!(lease["blobs"][0]["blob_id"], blob_id);
        let upload = requests
            .iter()
            .find(|(method, path, _)| method == "PUT" && path == "/object-store/stage-1")
            .unwrap();
        assert_eq!(upload.2, payload);
    }

    /// A server that rejects the blob declaration itself (a lowered per-request target ceiling,
    /// a stricter future validator) must not fail the publication: the declaration is an
    /// optimization, and one bare-lease retry selects the standalone-targets flow that would
    /// have worked.
    #[tokio::test]
    async fn direct_native_push_falls_back_to_a_bare_lease_when_the_declaration_is_rejected() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let payload = b"declaration rejected, bare lease accepted".to_vec();
        let blob_id = hex::encode(Sha256::digest(&payload));
        let checksum = base64::engine::general_purpose::STANDARD.encode(Sha256::digest(&payload));
        let requests = Arc::new(Mutex::new(Vec::<(String, String, Vec<u8>)>::new()));
        let captured = requests.clone();
        let server_base = base.clone();
        let server_blob_id = blob_id.clone();
        let server_payload = payload.clone();
        let server = tokio::spawn(async move {
            for _ in 0..7 {
                let (mut stream, _) = listener.accept().await.unwrap();
                let mut bytes = Vec::new();
                let header_end = loop {
                    let mut chunk = [0u8; 4096];
                    let read = stream.read(&mut chunk).await.unwrap();
                    assert_ne!(read, 0, "request ended before its headers");
                    bytes.extend_from_slice(&chunk[..read]);
                    if let Some(offset) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
                        break offset + 4;
                    }
                };
                let headers = String::from_utf8(bytes[..header_end].to_vec()).unwrap();
                let content_len = headers
                    .lines()
                    .find_map(|line| {
                        let (name, value) = line.split_once(':')?;
                        name.eq_ignore_ascii_case("content-length")
                            .then(|| value.trim().parse::<usize>().unwrap())
                    })
                    .unwrap_or(0);
                while bytes.len() < header_end + content_len {
                    let mut chunk = [0u8; 4096];
                    let read = stream.read(&mut chunk).await.unwrap();
                    assert_ne!(read, 0, "request ended before its body");
                    bytes.extend_from_slice(&chunk[..read]);
                }
                let request_line = headers.lines().next().unwrap();
                let mut request_parts = request_line.split_whitespace();
                let method = request_parts.next().unwrap().to_string();
                let path = request_parts.next().unwrap().to_string();
                let body = bytes[header_end..header_end + content_len].to_vec();
                captured
                    .lock()
                    .unwrap()
                    .push((method.clone(), path.clone(), body.clone()));

                let (status_line, response_body) = match (method.as_str(), path.as_str()) {
                    ("POST", "/artifact-storage/v1/token") => (
                        "HTTP/1.1 200 OK",
                        serde_json::to_vec(&serde_json::json!({
                            "token": "repo-token",
                            "tokenType": "bearer",
                            "expiresAt": "2099-01-01T00:00:00Z",
                            "gitUsername": "repo-user",
                            "repoPattern": "filesystem",
                            "scopes": ["fs:read", "fs:write"],
                        }))
                        .unwrap(),
                    ),
                    ("GET", "/project/project/repos/filesystem/fs/head") => (
                        "HTTP/1.1 200 OK",
                        serde_json::to_vec(
                            &serde_json::json!({"snapshot_id": null, "generation": 0}),
                        )
                        .unwrap(),
                    ),
                    ("POST", "/project/project/repos/filesystem/fs/upload-leases") => {
                        let parsed: serde_json::Value = serde_json::from_slice(&body).unwrap();
                        let declared = parsed
                            .get("blobs")
                            .and_then(|blobs| blobs.as_array())
                            .is_some_and(|blobs| !blobs.is_empty());
                        if declared {
                            (
                                "HTTP/1.1 400 Bad Request",
                                b"direct upload target request takes 1..=8 blobs".to_vec(),
                            )
                        } else {
                            (
                                "HTTP/1.1 200 OK",
                                serde_json::to_vec(&serde_json::json!({
                                    "lease_id": "lease-1",
                                    "expires_at_ms": 9_999_999_999_999_u64,
                                    "max_blob_bytes": 268_435_456_u64,
                                    "max_targets_per_request": 256,
                                    "max_parts_per_file": 4096,
                                    "transport": "checksum_presigned_put",
                                    "checksum_algorithm": "sha256",
                                }))
                                .unwrap(),
                            )
                        }
                    }
                    (
                        "POST",
                        "/project/project/repos/filesystem/fs/upload-leases/lease-1/targets",
                    ) => (
                        "HTTP/1.1 200 OK",
                        serde_json::to_vec(&serde_json::json!({
                            "targets": [{
                                "blob_id": server_blob_id,
                                "logical_len": server_payload.len(),
                                "already_present": false,
                                "url": format!("{server_base}/object-store/stage-1"),
                                "checksum_sha256": checksum,
                            }],
                        }))
                        .unwrap(),
                    ),
                    ("PUT", "/object-store/stage-1") => ("HTTP/1.1 200 OK", b"{}".to_vec()),
                    ("POST", "/project/project/repos/filesystem/fs/publish") => (
                        "HTTP/1.1 200 OK",
                        serde_json::to_vec(&serde_json::json!({
                            "version_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                            "previous_version_id": null,
                        }))
                        .unwrap(),
                    ),
                    other => panic!("unexpected request: {other:?}"),
                };
                let response = format!(
                    "{status_line}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                    response_body.len()
                );
                stream.write_all(response.as_bytes()).await.unwrap();
                stream.write_all(&response_body).await.unwrap();
            }
        });

        let api_client = ClientBuilder::new(&base).build().unwrap();
        let client = ArtifactStorageClient::new(api_client, &base).unwrap();
        let result = client
            .publish_filesystem_files(
                "project",
                "filesystem",
                vec![NativeDirectFileWrite {
                    path: "data/probe.bin".to_string(),
                    data: payload.clone(),
                }],
                Vec::new(),
                Vec::new(),
                Vec::new(),
                "fallback publication".to_string(),
                "operation-fallback".to_string(),
            )
            .await
            .unwrap();
        assert_eq!(
            result.version_id,
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
        );
        server.await.unwrap();

        let requests = requests.lock().unwrap();
        let leases: Vec<_> = requests
            .iter()
            .filter(|(method, path, _)| method == "POST" && path.ends_with("/fs/upload-leases"))
            .collect();
        assert_eq!(leases.len(), 2, "one declared attempt, one bare retry");
        assert!(
            requests
                .iter()
                .any(|(_, path, _)| path.contains("/targets")),
            "the bare-lease retry selects the standalone targets flow"
        );
        let upload = requests
            .iter()
            .find(|(method, path, _)| method == "PUT" && path == "/object-store/stage-1")
            .unwrap();
        assert_eq!(upload.2, payload);
    }

    /// Capacity rejections carry a `Retry-After` the server means literally; the retry budget
    /// must survive a burst longer than its exponential fallback would (the 2026-08-14 storage
    /// benchmark lost 5% of its publications to sub-100ms retries inside one 2.5s 503 storm).
    #[tokio::test]
    async fn send_idempotent_honors_retry_after_on_capacity_rejections() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let hits = Arc::new(Mutex::new(0usize));
        let counted = hits.clone();
        let server = tokio::spawn(async move {
            for attempt in 0..3 {
                let (mut stream, _) = listener.accept().await.unwrap();
                let mut bytes = Vec::new();
                loop {
                    let mut chunk = [0u8; 4096];
                    let read = stream.read(&mut chunk).await.unwrap();
                    assert_ne!(read, 0);
                    bytes.extend_from_slice(&chunk[..read]);
                    if bytes.windows(4).any(|part| part == b"\r\n\r\n") {
                        break;
                    }
                }
                *counted.lock().unwrap() += 1;
                let response = if attempt < 2 {
                    "HTTP/1.1 503 Service Unavailable\r\nRetry-After: 1\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
                        .to_string()
                } else {
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}"
                        .to_string()
                };
                stream.write_all(response.as_bytes()).await.unwrap();
            }
        });
        // The SDK ClientBuilder installs the process-wide rustls provider; a bare reqwest
        // client in an isolated test run must install it itself (AlreadyInstalled is fine).
        let _ = rustls::crypto::ring::default_provider().install_default();
        let started = std::time::Instant::now();
        let response = super::send_idempotent(reqwest::Client::new().get(&base))
            .await
            .unwrap();
        assert_eq!(response.status(), reqwest::StatusCode::OK);
        assert!(
            started.elapsed() >= std::time::Duration::from_millis(1900),
            "two Retry-After: 1 hints must be honored, waited {:?}",
            started.elapsed()
        );
        server.await.unwrap();
        assert_eq!(*hits.lock().unwrap(), 3);
    }

    #[tokio::test]
    async fn metadata_only_publication_is_one_data_plane_request_without_a_lease() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let server = tokio::spawn(async move {
            let (mut stream, _) = listener.accept().await.unwrap();
            let mut bytes = Vec::new();
            let header_end = loop {
                let mut chunk = [0u8; 4096];
                let read = stream.read(&mut chunk).await.unwrap();
                assert_ne!(read, 0, "request ended before its headers");
                bytes.extend_from_slice(&chunk[..read]);
                if let Some(offset) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
                    break offset + 4;
                }
            };
            let headers = String::from_utf8(bytes[..header_end].to_vec()).unwrap();
            let content_len = headers
                .lines()
                .find_map(|line| {
                    let (name, value) = line.split_once(':')?;
                    name.eq_ignore_ascii_case("content-length")
                        .then(|| value.trim().parse::<usize>().unwrap())
                })
                .unwrap();
            while bytes.len() < header_end + content_len {
                let mut chunk = [0u8; 4096];
                let read = stream.read(&mut chunk).await.unwrap();
                assert_ne!(read, 0, "request ended before its body");
                bytes.extend_from_slice(&chunk[..read]);
            }
            assert_eq!(
                headers.lines().next().unwrap(),
                "POST /project/project/repos/filesystem/fs/mutations HTTP/1.1"
            );
            let body: serde_json::Value =
                serde_json::from_slice(&bytes[header_end..header_end + content_len]).unwrap();
            assert_eq!(
                body,
                serde_json::json!({
                    "operation_id": "metadata-1",
                    "message": "rearrange paths",
                    "mutations": [
                        {"type": "delete", "path": "old.txt"},
                        {"type": "move", "from": "data.bin", "to": "archive/data.bin"},
                        {"type": "copy", "from": "model.bin", "to": "copies/model.bin"},
                    ],
                })
            );
            let response_body = serde_json::to_vec(&serde_json::json!({
                "version_id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                "previous_version_id": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
            }))
            .unwrap();
            let response = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                response_body.len(),
            );
            stream.write_all(response.as_bytes()).await.unwrap();
            stream.write_all(&response_body).await.unwrap();
        });

        let api_client = ClientBuilder::new(&base).build().unwrap();
        let client = ArtifactStorageClient::new(api_client, &base).unwrap();
        let published = client
            .push_native_files_direct_with_credential(
                "project",
                "filesystem",
                Vec::new(),
                Vec::new(),
                vec!["old.txt".into()],
                vec![NativeDirectPathTransfer {
                    from: "data.bin".into(),
                    to: "archive/data.bin".into(),
                }],
                vec![NativeDirectPathTransfer {
                    from: "model.bin".into(),
                    to: "copies/model.bin".into(),
                }],
                "rearrange paths".into(),
                "metadata-1".into(),
                "repo-user",
                "repo-token",
            )
            .await
            .unwrap();
        assert_eq!(
            published.version_id,
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
        );
        server.await.unwrap();
    }

    #[tokio::test]
    async fn metadata_only_publication_rejects_oversized_batches_before_network_io() {
        let api_client = ClientBuilder::new("http://127.0.0.1:1").build().unwrap();
        let client = ArtifactStorageClient::new(api_client, "http://127.0.0.1:1").unwrap();
        let error = client
            .push_native_files_direct_with_credential(
                "project",
                "filesystem",
                Vec::new(),
                Vec::new(),
                (0..129).map(|index| format!("old-{index}.txt")).collect(),
                Vec::new(),
                Vec::new(),
                "oversized metadata batch".into(),
                "metadata-oversized".into(),
                "repo-user",
                "repo-token",
            )
            .await
            .unwrap_err()
            .to_string();
        assert!(
            error.contains("129 mutations") && error.contains("128"),
            "{error}"
        );
    }
}