tensorlake 0.5.47

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
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    time::Duration,
};

use base64::{Engine as _, engine::general_purpose::STANDARD};
use docker_credentials_config::DockerConfig;
use ignore::gitignore::{Gitignore, GitignoreBuilder};
use reqwest::{Method, StatusCode};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use shlex::split as shlex_split;
use thiserror::Error;

use crate::{
    Client, ClientBuilder,
    error::SdkError,
    resolve_sandbox_lifecycle_url,
    sandboxes::{
        SandboxProxyClient, SandboxesClient,
        models::{
            CreateSandboxRequest, CreateSandboxResources, MultipartHint, ProcessInfo,
            RunProcessEvent, SandboxInfo, SignBlobOp, SignBlobRequest, SignBlobTarget,
        },
    },
};

type Result<T> = std::result::Result<T, SandboxImageBuildError>;

const DEFAULT_ROOTFS_DISK_MB: u64 = 10 * 1024;
const DEFAULT_SANDBOX_WAIT_TIMEOUT: Duration = Duration::from_secs(120);
const SANDBOX_WAIT_POLL_INTERVAL: Duration = Duration::from_secs(1);
/// Lifetime budget requested for the temporary rootfs-builder sandbox. The
/// builder is short-lived (Dockerfile-defined RUN steps), but it has to outlive
/// long single steps like `dd if=/dev/urandom ...` or large `apt install` runs
/// that produce no client traffic. Setting an explicit value here makes the
/// CLI's behavior independent of whatever default the Platform API hands back
/// today. Paired with the keepalive loop below, which renews this budget while
/// the build is in flight.
const BUILDER_SANDBOX_TIMEOUT_SECS: i64 = 300;
/// Cadence at which the SDK pings the builder sandbox while the offline
/// rootfs builder is running, to keep it from being suspended due to
/// inactivity / lifetime expiry mid-build. Must be shorter than
/// `BUILDER_SANDBOX_TIMEOUT_SECS`.
const BUILDER_SANDBOX_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(120);
const PROCESS_START_ATTEMPTS: usize = 3;
const PROCESS_REATTACH_RETRY_INTERVAL: Duration = Duration::from_secs(1);
const PROCESS_REATTACH_ATTEMPTS: usize = 10;
const PROXY_READY_TIMEOUT: Duration = Duration::from_secs(120);
const PROXY_READY_POLL_INTERVAL: Duration = Duration::from_secs(1);
const REMOTE_BUILD_DIR: &str = "/var/lib/tensorlake/rootfs-builder/build";
const REMOTE_CONTEXT_DIR: &str = "/var/lib/tensorlake/rootfs-builder/build/context";
const REMOTE_SPEC_PATH: &str = "/var/lib/tensorlake/rootfs-builder/build/spec.json";
const REMOTE_METADATA_PATH: &str = "/var/lib/tensorlake/rootfs-builder/build/metadata.json";
const ROOTFS_BUILDER_BIN_DIR: &str = "/usr/local/bin";
const ROOTFS_BUILDER_PATH: &str = "/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";
const ROOTFS_BUILDER_COMMAND: &str = "tl-rootfs-build";
const ROOTFS_BUILDER_PROCESS_USER: &str = "root";
const DIAGNOSTIC_COMMAND_TIMEOUT_SECS: i64 = 5;
const BUILDER_DISK_USAGE_DIAGNOSTIC_THRESHOLD_PERCENT: u8 = 95;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ProcessTerminalStatus {
    code: i64,
    oom_killed: bool,
}

/// Dockerfile instructions that run as usual during the rootfs builder's
/// `docker build`, but have no effect when a sandbox is later run from the
/// image. The builder preserves the built image's OCI config, yet the
/// sandbox runtime only honors `ENV`/`WORKDIR`/`USER`/`ENTRYPOINT`/`CMD`; the
/// rest of the image config is never read at runtime. `ONBUILD` triggers only
/// fire in a downstream build (there is no child build here) and `SHELL` only
/// changes the shell for build-time shell-form `RUN`/`CMD`/`ENTRYPOINT`. We
/// accept all of these and warn, rather than reject, so a Dockerfile that works
/// with `docker build` also works here.
//
// ARG is not in this list; it is accepted at top-level scope so a Dockerfile
// can declare global defaults that Docker resolves at build time, but the SDK
// does not substitute ARG values at parse time.
const IGNORED_DOCKERFILE_INSTRUCTIONS: &[&str] = &[
    "ONBUILD",
    "SHELL",
    "EXPOSE",
    "HEALTHCHECK",
    "LABEL",
    "STOPSIGNAL",
    "VOLUME",
];

#[derive(Debug, Error)]
pub enum SandboxImageBuildError {
    /// A failure after the builder sandbox was created. Carries the IDs
    /// support needs to find the build: the builder sandbox ID correlates
    /// with dataplane and platform logs, the build ID with platform-api.
    #[error("{source} (builder sandbox: {builder_sandbox_id}, build: {build_id})")]
    BuildFailed {
        builder_sandbox_id: String,
        build_id: String,
        #[source]
        source: Box<SandboxImageBuildError>,
    },
    #[error("{source}\n{messages}")]
    WithDiagnostics {
        #[source]
        source: Box<SandboxImageBuildError>,
        messages: String,
    },
    #[error("{0}")]
    Usage(String),
    #[error("{0}")]
    Auth(String),
    #[error("HTTP request failed: {0}")]
    Http(#[from] reqwest::Error),
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    #[error("{0}")]
    Json(#[from] serde_json::Error),
    #[error("{0}")]
    Sdk(#[from] SdkError),
    #[error("{0}")]
    Other(String),
}

impl SandboxImageBuildError {
    fn usage(message: impl Into<String>) -> Self {
        Self::Usage(message.into())
    }

    fn auth(message: impl Into<String>) -> Self {
        Self::Auth(message.into())
    }

    fn other(message: impl Into<String>) -> Self {
        Self::Other(message.into())
    }
}

/// Auth/context and resource fields shared by every sandbox-image build mode
/// (Dockerfile build and registry import). The mode-specific public option
/// structs (`SandboxImageBuildOptions`, `SandboxImageImportOptions`) each carry
/// their own copy of these and hand them to the shared `run_build_plan` runner.
#[derive(Debug, Clone)]
pub struct CommonBuildOptions {
    pub api_url: String,
    pub bearer_token: String,
    pub use_scope_headers: bool,
    pub organization_id: Option<String>,
    pub project_id: Option<String>,
    pub namespace: String,
    pub registered_name: Option<String>,
    pub disk_mb: Option<u64>,
    pub builder_disk_mb: Option<u64>,
    pub cpus: Option<f64>,
    pub memory_mb: Option<i64>,
    pub is_public: bool,
    pub user_agent: Option<String>,
    pub docker_compat: bool,
}

/// Options for building a sandbox image from a Dockerfile. This is the
/// Dockerfile build path only — to import a registry image directly into a
/// rootfs without a Dockerfile, use [`SandboxImageImportOptions`] /
/// [`import_sandbox_image`] instead. Keeping the two modes in separate structs
/// means a caller cannot construct an ambiguous mix of a Dockerfile and an
/// import reference.
#[derive(Debug, Clone)]
pub struct SandboxImageBuildOptions {
    pub common: CommonBuildOptions,
    pub dockerfile_path: PathBuf,
    pub dockerfile_text: Option<String>,
    pub context_dir: Option<PathBuf>,
}

/// Options for importing a registry image directly into a rootfs (no
/// Dockerfile, no Docker daemon — the builder runs
/// `indexify-rootfs-materialize oci-image-to-ext4`). The reference is always
/// pulled fresh from the registry; it is never resolved against the Tensorlake
/// template registry.
#[derive(Debug, Clone)]
pub struct SandboxImageImportOptions {
    pub common: CommonBuildOptions,
    /// The registry image reference to import, e.g.
    /// `pytorch/pytorch:2.4.1-cuda12.1-cudnn9-runtime` or
    /// `ghcr.io/org/app@sha256:...`.
    pub image_reference: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SandboxImageBuildEvent {
    Status(String),
    BuildLog { stream: String, message: String },
    Warning(String),
}

#[derive(Debug, Clone)]
struct ResolvedBuildContext {
    api_url: String,
    bearer_token: String,
    use_scope_headers: bool,
    organization_id: String,
    project_id: String,
    namespace: String,
    user_agent: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct DockerfileBuildPlan {
    context_dir: PathBuf,
    registered_name: String,
    dockerfile_text: String,
    /// The final-stage FROM image reference — the exact string the user wrote.
    /// Determines the snapshot's lineage parent when it resolves to a
    /// registered Tensorlake template.
    base_image: String,
    /// True when `base_image` matches a stage alias defined earlier in the
    /// Dockerfile (`FROM ubuntu AS base; FROM base`). In that case the
    /// final FROM is an internal reference to an earlier stage and we do
    /// not look it up as an external template.
    base_image_is_internal_stage: bool,
    /// Every external image reference encountered in the Dockerfile other
    /// than `base_image`: earlier-stage FROMs, `COPY --from=<image>`, and
    /// `RUN --mount=type=cache,from=<image>`. Excludes `scratch`, internal
    /// stage names defined by `FROM ... AS <name>` clauses, references
    /// containing `$` variable expansions or `@` digest pins, and the
    /// final-stage FROM itself (which lives in `base_image`). Deduped, in
    /// first-seen order.
    additional_image_references: Vec<String>,
    /// References the SDK could not resolve at planning time and forwarded
    /// to Docker for registry pull at build time. Tagged with a reason so
    /// the caller can emit an appropriate warning.
    unresolvable_image_references: Vec<UnresolvableImageReference>,
    /// Instructions that hit `IGNORED_DOCKERFILE_INSTRUCTIONS` during parse.
    /// Surfaced as warnings by the caller; preserved in `dockerfile_text` and
    /// forwarded to `docker build`.
    ignored_instructions: Vec<(usize, String)>,
    /// When set, this is an image-import build rather than a Dockerfile build:
    /// the builder pulls this registry reference directly into the rootfs with
    /// no Docker daemon. There is no build context to upload and the base is
    /// never resolved against the template registry (import always pulls from
    /// the registry, producing a fresh base rootfs).
    import_image_reference: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct UnresolvableImageReference {
    line_number: usize,
    reference: String,
    reason: UnresolvableImageReferenceReason,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum UnresolvableImageReferenceReason {
    /// Reference contained `$VAR` / `${VAR}` expansion. The SDK does not
    /// resolve build-args at planning time.
    BuildArgExpansion,
    /// Reference carried an `@<digest>` suffix (e.g. `@sha256:...`).
    /// Locally-loaded images cannot match a user-supplied digest, so even if
    /// the name matches a registered template the reference falls through
    /// to a registry pull.
    DigestPin,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct PreparedSandboxTemplateBuild {
    build_id: String,
    snapshot_id: String,
    /// Optional during and after the versioned-response rollout: platform-api
    /// is moving the snapshot location off of a pre-baked `snapshotUri` and
    /// onto `snapshotRelPath` (resolved client-side via
    /// `SandboxProxyClient::sign_blob`). On that new path, the signed upload
    /// response carries the final URI and the CLI copies it into the build
    /// spec before the in-sandbox builder writes `metadata.json`.
    #[serde(default)]
    snapshot_uri: Option<String>,
    rootfs_node_kind: String,
    builder: PreparedRootfsBuilder,
    parent: Option<PreparedRootfsParent>,
    /// New-path marker: when present, platform-api stopped pre-signing S3 and
    /// the CLI must call `SandboxProxyClient::sign_blob` to mint the upload
    /// spec. When absent, the response carries an embedded `upload` block in
    /// the raw passthrough `Value` (legacy path). Apart from the top-level
    /// `snapshotUri` handoff, the prepared spec stays opaque to preserve the
    /// platform-api ↔ in-sandbox-builder forward-compat property.
    #[serde(default)]
    snapshot_rel_path: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct PreparedRootfsBuilder {
    image: String,
    command: String,
    cpus: f64,
    memory_mb: i64,
    disk_mb: u64,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
struct PreparedRootfsParent {
    parent_manifest_uri: String,
    #[serde(default)]
    rootfs_disk_bytes: Option<u64>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct CompleteSandboxTemplateBuildRequest {
    snapshot_id: String,
    snapshot_uri: String,
    snapshot_format_version: String,
    snapshot_size_bytes: u64,
    rootfs_disk_bytes: u64,
    rootfs_node_kind: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    parent_manifest_uri: Option<String>,
}

/// Build a sandbox image from a Dockerfile (path or inline text). To import a
/// registry image directly into a rootfs without a Dockerfile, use
/// [`import_sandbox_image`] instead.
pub async fn build_sandbox_image<F>(options: SandboxImageBuildOptions, mut emit: F) -> Result<Value>
where
    F: FnMut(SandboxImageBuildEvent),
{
    emit(SandboxImageBuildEvent::Status(
        "Loading Dockerfile...".to_string(),
    ));
    let plan = if let Some(dockerfile_text) = &options.dockerfile_text {
        load_dockerfile_text_plan(
            &options.dockerfile_path,
            options.context_dir.as_deref(),
            dockerfile_text.clone(),
            options.common.registered_name.as_deref(),
        )?
    } else {
        load_dockerfile_plan(
            &options.dockerfile_path,
            options.common.registered_name.as_deref(),
        )?
    };
    run_build_plan(plan, options.common, emit).await
}

/// Import a registry image directly into a rootfs (no Dockerfile, no Docker
/// daemon). The reference is always pulled fresh from the registry; it is
/// never resolved against the Tensorlake template registry.
pub async fn import_sandbox_image<F>(
    options: SandboxImageImportOptions,
    mut emit: F,
) -> Result<Value>
where
    F: FnMut(SandboxImageBuildEvent),
{
    emit(SandboxImageBuildEvent::Status(format!(
        "Importing registry image {}...",
        options.image_reference
    )));
    let plan = plan_image_import(
        &options.image_reference,
        options.common.registered_name.as_deref(),
    )?;
    run_build_plan(plan, options.common, emit).await
}

/// Shared build pipeline: provision the rootfs-builder sandbox, materialize the
/// filesystem from `plan`, and register the resulting snapshot. Both the
/// Dockerfile build and registry import paths funnel through here once they
/// have produced a [`DockerfileBuildPlan`].
async fn run_build_plan<F>(
    plan: DockerfileBuildPlan,
    options: CommonBuildOptions,
    mut emit: F,
) -> Result<Value>
where
    F: FnMut(SandboxImageBuildEvent),
{
    emit(SandboxImageBuildEvent::Status(format!(
        "Selected image name: {}",
        plan.registered_name
    )));

    for (_line_number, keyword) in &plan.ignored_instructions {
        emit(SandboxImageBuildEvent::Warning(format!(
            "Dockerfile instruction '{}' is applied during the image build but has no \
             effect when running sandboxes from this image.",
            keyword
        )));
    }
    for unresolvable in &plan.unresolvable_image_references {
        let detail = match unresolvable.reason {
            UnresolvableImageReferenceReason::BuildArgExpansion => {
                "contains a build-arg expansion that the SDK does not resolve at planning time"
            }
            UnresolvableImageReferenceReason::DigestPin => {
                "is pinned to a content digest, which cannot be matched by a locally-loaded image"
            }
        };
        emit(SandboxImageBuildEvent::Warning(format!(
            "line {}: image reference '{}' {}. The build will pull this image from the configured \
             registry instead of using a Tensorlake template. If '{}' was meant to resolve to a \
             Tensorlake template, the resulting build image will be larger than a diff against \
             that template.",
            unresolvable.line_number, unresolvable.reference, detail, unresolvable.reference,
        )));
    }
    if options.docker_compat {
        emit(SandboxImageBuildEvent::Warning(
            "Docker compatibility mode is enabled. This uses Docker/BuildKit export for rootfs \
             materialization, which can be slower and may require a larger builder sandbox disk."
                .to_string(),
        ));
    }

    let ctx = resolve_build_context(options.clone()).await?;

    emit(SandboxImageBuildEvent::Status(
        "Preparing rootfs build...".to_string(),
    ));
    let platform_client = platform_client(&ctx)?;
    let (prepared, mut prepared_spec) =
        prepare_rootfs_build(&ctx, &platform_client, &plan, options.is_public).await?;
    emit(SandboxImageBuildEvent::Status(format!(
        "Build mode: Rootfs{}",
        match prepared.rootfs_node_kind.as_str() {
            "diff" => "Diff",
            _ => "Base",
        }
    )));

    let client = sandbox_lifecycle_client(&ctx)?;
    let sandboxes = SandboxesClient::new(
        client.clone(),
        ctx.namespace.clone(),
        is_localhost(&ctx.api_url),
    );
    let rootfs_disk_bytes = rootfs_disk_bytes(options.disk_mb, &prepared)?;
    let builder_disk_mb = rootfs_disk_bytes_to_mb(rootfs_disk_bytes)?
        .max(options.builder_disk_mb.unwrap_or(prepared.builder.disk_mb));
    let resources = CreateSandboxResources {
        cpus: options.cpus.unwrap_or(prepared.builder.cpus),
        memory_mb: options.memory_mb.unwrap_or(prepared.builder.memory_mb),
        disk_mb: Some(builder_disk_mb),
        gpu_configs: None,
    };

    emit(SandboxImageBuildEvent::Status(format!(
        "Creating rootfs builder sandbox from {}...",
        prepared.builder.image
    )));
    let created = sandboxes
        .create(&CreateSandboxRequest {
            image: Some(prepared.builder.image.clone()),
            resources,
            timeout_secs: Some(BUILDER_SANDBOX_TIMEOUT_SECS),
            entrypoint: None,
            network: None,
            snapshot_id: None,
            name: None,
        })
        .await?;
    let sandbox_id = created.sandbox_id.clone();
    let routing_hint = created.routing_hint.clone();

    let result = async {
        let running_info = wait_for_sandbox_status(
            &sandboxes,
            &sandbox_id,
            "running",
            DEFAULT_SANDBOX_WAIT_TIMEOUT,
        )
        .await?;
        let ingress_endpoint = created
            .ingress_endpoint
            .clone()
            .or_else(|| running_info.ingress_endpoint.clone());
        emit(SandboxImageBuildEvent::Status(format!(
            "Rootfs builder sandbox {sandbox_id} is running"
        )));

        let proxy = sandbox_proxy_client(
            &ctx,
            &client,
            &sandbox_id,
            ingress_endpoint.as_deref(),
            routing_hint,
        )?;
        wait_for_proxy_ready(&proxy).await?;

        let mut builder_failure_diagnostics = BuilderFailureDiagnostics::default();
        let post_proxy_result: Result<Value> = async {
            // Versioned-response bridge: on the new path, platform-api returns
            // `snapshotRelPath` instead of a pre-signed `upload` block, and we
            // ask the sandbox proxy to mint the upload spec. Splice the result
            // into the raw prepared spec so `upload_build_inputs` /
            // `build_rootfs_spec` see an `upload` key regardless of which path
            // produced it — preserving the platform-api ↔ in-sandbox-builder
            // passthrough property.
            //
            // The CLI doesn't know the final snapshot file size until the
            // in-sandbox builder finishes and writes metadata.json, so the
            // provider-neutral upload request includes a capacity hint derived
            // from the rootfs disk budget (`rootfsDiskBytes`). Clamp to
            // [1, MULTIPART_MAX_PARTS] so a 0 MB hint still produces a valid
            // request and absurd inputs don't blow past S3's 10,000-part ceiling.
            //
            // Legacy path: `snapshot_rel_path` is absent, the upload block is
            // already in `prepared_spec`, and we do nothing here.
            let signed_snapshot_uri = if let Some(rel_path) = prepared.snapshot_rel_path.clone() {
                let disk_mb = rootfs_disk_bytes_to_mb(rootfs_disk_bytes)?;
                let parts: u32 = disk_mb
                    .div_ceil(MULTIPART_PART_SIZE_MB)
                    .clamp(1, MULTIPART_MAX_PARTS as u64) as u32;
                let signed = proxy
                    .sign_blob(&SignBlobRequest {
                        target: SignBlobTarget::Artifact { rel_path },
                        op: SignBlobOp::PutArtifact {
                            multipart_hint: Some(MultipartHint {
                                max_parts: parts,
                                part_size_bytes: MULTIPART_PART_SIZE_BYTES,
                            }),
                        },
                    })
                    .await
                    .map_err(SandboxImageBuildError::Sdk)?
                    .into_inner();
                let snapshot_uri = splice_signed_upload(&mut prepared_spec, signed)?;

                if let Some(parent) = prepared.parent.as_ref() {
                    let signed = proxy
                        .sign_blob(&SignBlobRequest {
                            target: SignBlobTarget::Blob {
                                uri: parent.parent_manifest_uri.clone(),
                            },
                            op: SignBlobOp::GetBlob,
                        })
                        .await
                        .map_err(SandboxImageBuildError::Sdk)?
                        .into_inner();
                    prepared_spec
                        .as_object_mut()
                        .ok_or_else(|| {
                            SandboxImageBuildError::other("prepared spec is not a JSON object")
                        })?
                        .get_mut("parent")
                        .and_then(Value::as_object_mut)
                        .ok_or_else(|| {
                            SandboxImageBuildError::other("prepared parent is not a JSON object")
                        })?
                        .insert("download".to_string(), signed);
                }

                Some(snapshot_uri)
            } else {
                None
            };

            upload_build_inputs(
                &proxy,
                &plan,
                &prepared,
                &prepared_spec,
                options.disk_mb,
                options.docker_compat,
                &mut emit,
            )
            .await?;

            emit(SandboxImageBuildEvent::Status(
                "Running offline rootfs builder...".to_string(),
            ));
            // The rootfs builder runs entirely inside the sandbox and can stay
            // silent for minutes at a time (e.g. a single large `RUN dd ...` step
            // in the user's Dockerfile produces no client traffic). Keep the
            // sandbox visibly alive while that step is in flight so the Platform
            // doesn't suspend it out from under us. Aborted as soon as the
            // builder returns, regardless of outcome.
            let keepalive_task = spawn_builder_keepalive(proxy.clone());
            let builder_result =
                run_rootfs_builder(&proxy, &prepared.builder.command, &mut |event| {
                    builder_failure_diagnostics.observe_build_event(&event);
                    emit(event);
                })
                .await;
            keepalive_task.abort();
            builder_result?;

            let metadata = read_build_metadata(&proxy).await?;
            let complete_request = complete_request_from_metadata(
                &prepared,
                &metadata,
                signed_snapshot_uri.as_deref(),
            )?;

            emit(SandboxImageBuildEvent::Status(
                "Completing image registration...".to_string(),
            ));
            let registered = complete_rootfs_build(
                &ctx,
                &platform_client,
                &prepared.build_id,
                &complete_request,
            )
            .await?;
            let template_id = registered.get("id").and_then(Value::as_str).unwrap_or("-");
            emit(SandboxImageBuildEvent::Status(format!(
                "Image '{}' registered ({})",
                plan.registered_name, template_id
            )));
            Ok(registered)
        }
        .await;

        match post_proxy_result {
            Ok(registered) => Ok(registered),
            Err(source) => {
                Err(decorate_builder_failure(&proxy, source, &builder_failure_diagnostics).await)
            }
        }
    }
    .await;

    if let Err(error) = sandboxes.delete(&sandbox_id).await {
        emit(SandboxImageBuildEvent::Warning(format!(
            "Failed to terminate rootfs builder sandbox {} during cleanup: {}",
            sandbox_id, error
        )));
    }

    result.map_err(|source| SandboxImageBuildError::BuildFailed {
        builder_sandbox_id: sandbox_id,
        build_id: prepared.build_id.clone(),
        source: Box::new(source),
    })
}

async fn resolve_build_context(options: CommonBuildOptions) -> Result<ResolvedBuildContext> {
    let client = unscoped_client(&options)?;
    let (organization_id, project_id) = if options.use_scope_headers {
        match (options.organization_id.clone(), options.project_id.clone()) {
            (Some(organization_id), Some(project_id)) => (organization_id, project_id),
            _ => {
                return Err(SandboxImageBuildError::auth(
                    "Organization ID and project ID are required for sandbox image builds with PAT authentication",
                ));
            }
        }
    } else {
        let scope = introspect_scope(&client).await?;
        (scope.organization_id, scope.project_id)
    };

    Ok(ResolvedBuildContext {
        api_url: options.api_url,
        bearer_token: options.bearer_token,
        use_scope_headers: options.use_scope_headers,
        organization_id,
        project_id,
        namespace: options.namespace,
        user_agent: options.user_agent,
    })
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct IntrospectScope {
    organization_id: String,
    project_id: String,
}

async fn introspect_scope(client: &Client) -> Result<IntrospectScope> {
    let request = client
        .request(Method::POST, "/platform/v1/keys/introspect")
        .build()?;
    let response = client.execute_raw(request).await?;
    if !response.status().is_success() {
        let status = response.status();
        let body = response.text().await.unwrap_or_default();
        return Err(SandboxImageBuildError::auth(format!(
            "API key introspection failed (HTTP {}): {}",
            status, body
        )));
    }
    response.json().await.map_err(Into::into)
}

fn unscoped_client(options: &CommonBuildOptions) -> Result<Client> {
    client_builder(
        &options.api_url,
        &options.bearer_token,
        false,
        options.organization_id.as_deref(),
        options.project_id.as_deref(),
        options.user_agent.as_deref(),
    )
    .build()
    .map_err(Into::into)
}

fn platform_client(ctx: &ResolvedBuildContext) -> Result<Client> {
    client_builder(
        &ctx.api_url,
        &ctx.bearer_token,
        ctx.use_scope_headers,
        Some(&ctx.organization_id),
        Some(&ctx.project_id),
        ctx.user_agent.as_deref(),
    )
    .build()
    .map_err(Into::into)
}

fn sandbox_lifecycle_client(ctx: &ResolvedBuildContext) -> Result<Client> {
    let lifecycle_url = resolve_sandbox_lifecycle_url(&ctx.api_url);
    client_builder(
        &lifecycle_url,
        &ctx.bearer_token,
        ctx.use_scope_headers,
        Some(&ctx.organization_id),
        Some(&ctx.project_id),
        ctx.user_agent.as_deref(),
    )
    .build()
    .map_err(Into::into)
}

fn client_builder(
    base_url: &str,
    bearer_token: &str,
    use_scope_headers: bool,
    organization_id: Option<&str>,
    project_id: Option<&str>,
    user_agent: Option<&str>,
) -> ClientBuilder {
    let mut builder = ClientBuilder::new(base_url).bearer_token(bearer_token);
    if let Some(user_agent) = user_agent {
        builder = builder.user_agent(user_agent);
    }
    if use_scope_headers
        && let (Some(organization_id), Some(project_id)) = (organization_id, project_id)
    {
        builder = builder.scope(organization_id, project_id);
    }
    builder
}

async fn wait_for_sandbox_status(
    sandboxes: &SandboxesClient,
    sandbox_id: &str,
    target_status: &str,
    timeout: Duration,
) -> Result<SandboxInfo> {
    let deadline = tokio::time::Instant::now() + timeout;
    loop {
        if tokio::time::Instant::now() > deadline {
            return Err(SandboxImageBuildError::other(format!(
                "Sandbox {} did not reach '{}' within {}s",
                sandbox_id,
                target_status,
                timeout.as_secs()
            )));
        }

        // A sandbox that is still `pending` isn't routable yet, so the
        // lifecycle gateway can return a transient proxy error (502 /
        // "Failed to proxy request") until it starts — in slower environments
        // that window is a minute or two. Treat those as retryable, the same
        // way `wait_for_proxy_ready` does, and let the deadline above bound
        // the total wait. Non-transient errors still fail the build.
        let info = match sandboxes.get(sandbox_id).await {
            Ok(info) => info,
            Err(error) => {
                let error = SandboxImageBuildError::from(error);
                if is_transient_proxy_error(&error) {
                    tokio::time::sleep(SANDBOX_WAIT_POLL_INTERVAL).await;
                    continue;
                }
                return Err(error);
            }
        };
        let current_status = info.status.clone();
        if current_status == target_status {
            return Ok(info.into_inner());
        }
        if current_status == "terminated" && target_status != "terminated" {
            return Err(SandboxImageBuildError::other(format!(
                "Sandbox {} terminated before reaching '{}'",
                sandbox_id, target_status
            )));
        }

        tokio::time::sleep(SANDBOX_WAIT_POLL_INTERVAL).await;
    }
}

/// Look up `reference` as a registered sandbox template and return the
/// JSON entry the prepare endpoint expects for that local-image slot, or
/// `None` if the lookup did not resolve.
///
/// References that resolve but are not usable as a build image (only
/// `durable_archive_v1` base templates are supported by the rootfs builder
/// today) fail with a clear message tied to the offending reference so the
/// user gets feedback on the exact image string that's incompatible.
async fn resolve_template_payload(
    templates: &crate::sandbox_templates::SandboxTemplatesClient,
    reference: &str,
) -> Result<Option<Value>> {
    let Some(found) = templates.find_by_name(reference).await? else {
        return Ok(None);
    };
    let template = found.into_inner();
    let template_id = template.id.clone().ok_or_else(|| {
        SandboxImageBuildError::other(format!(
            "platform returned a template lookup for '{}' without an id",
            reference
        ))
    })?;
    let name = template.name.clone().ok_or_else(|| {
        SandboxImageBuildError::other(format!(
            "platform returned a template lookup for '{}' without a name",
            reference
        ))
    })?;
    let snapshot_id = template.snapshot_id.clone().ok_or_else(|| {
        SandboxImageBuildError::other(format!(
            "platform returned a template lookup for '{}' without a snapshot id",
            reference
        ))
    })?;
    let is_public = template.public.unwrap_or(false);
    if let Some(kind) = template.rootfs_node_kind.as_deref()
        && kind != "base"
    {
        return Err(SandboxImageBuildError::other(format!(
            "template '{}' cannot be used as a build image (only base templates are supported, got rootfsNodeKind='{}'). \
             Build a base image from this template first.",
            reference, kind
        )));
    }
    if let Some(fmt) = template.snapshot_format_version.as_deref()
        && fmt != "durable_archive_v1"
    {
        return Err(SandboxImageBuildError::other(format!(
            "template '{}' uses snapshot format '{}', which the rootfs builder cannot materialize. \
             Re-register the template with durable_archive_v1.",
            reference, fmt
        )));
    }
    Ok(Some(json!({
        "templateId": template_id,
        "name": name,
        "reference": reference,
        "snapshotId": snapshot_id,
        "public": is_public,
    })))
}

async fn prepare_rootfs_build(
    ctx: &ResolvedBuildContext,
    client: &Client,
    plan: &DockerfileBuildPlan,
    is_public: bool,
) -> Result<(PreparedSandboxTemplateBuild, Value)> {
    // Resolve every external image reference against the platform's template
    // registry. The final-stage FROM is treated separately so its resolution
    // becomes the lineage parent; the additional references (earlier stages,
    // COPY --from, RUN --mount=,from) become preload-only local images.
    let templates = crate::sandbox_templates::SandboxTemplatesClient::new(
        client.clone(),
        ctx.organization_id.clone(),
        ctx.project_id.clone(),
    );

    // Skip the lookup when the final-stage FROM is `FROM <stage-alias>` —
    // the value is an internal reference to an earlier-defined stage, not
    // an external image we should resolve as a template. Also skip when
    // the base image contains `$` (build-arg) or `@` (digest pin); those
    // were already recorded as unresolvable and warned about. Import builds
    // never resolve a parent — they always pull a fresh base from the
    // registry, even if the reference happens to match a template name.
    let parent_template_payload = if plan.import_image_reference.is_some()
        || plan.base_image_is_internal_stage
        || plan.base_image.contains('$')
        || plan.base_image.contains('@')
    {
        None
    } else {
        resolve_template_payload(&templates, &plan.base_image).await?
    };
    let mut additional_payload: Vec<Value> =
        Vec::with_capacity(plan.additional_image_references.len());
    for reference in &plan.additional_image_references {
        if let Some(payload) = resolve_template_payload(&templates, reference).await? {
            additional_payload.push(payload);
        }
    }
    let rootfs_node_kind = if parent_template_payload.is_some() {
        "diff"
    } else {
        "base"
    };
    let parent_template_json = parent_template_payload.unwrap_or(Value::Null);

    let request = client
        .request(Method::POST, &sandbox_template_builds_path(ctx))
        .json(&json!({
            "name": plan.registered_name,
            "dockerfile": plan.dockerfile_text,
            "baseImage": plan.base_image,
            "public": is_public,
            "rootfsNodeKind": rootfs_node_kind,
            "parentTemplate": parent_template_json,
            "additionalLocalImages": additional_payload,
        }))
        .build()?;
    let response = client.execute_raw(request).await?;

    if !response.status().is_success() {
        let status = response.status();
        let body = response.text().await.unwrap_or_default();
        return Err(SandboxImageBuildError::other(format!(
            "failed to prepare sandbox image build (HTTP {}): {}",
            status, body
        )));
    }

    let raw: Value = response.json().await?;
    let prepared = serde_json::from_value(raw.clone())?;
    Ok((prepared, raw))
}

async fn complete_rootfs_build(
    ctx: &ResolvedBuildContext,
    client: &Client,
    build_id: &str,
    request: &CompleteSandboxTemplateBuildRequest,
) -> Result<Value> {
    let path = format!(
        "{}/{}/complete",
        sandbox_template_builds_path(ctx),
        build_id
    );
    let request = client.request(Method::POST, &path).json(request).build()?;
    let response = client.execute_raw(request).await?;

    if !response.status().is_success() {
        let status = response.status();
        let body = response.text().await.unwrap_or_default();
        return Err(SandboxImageBuildError::other(format!(
            "failed to complete sandbox image build (HTTP {}): {}",
            status, body
        )));
    }

    response.json().await.map_err(Into::into)
}

fn sandbox_template_builds_path(ctx: &ResolvedBuildContext) -> String {
    format!(
        "/platform/v1/organizations/{}/projects/{}/sandbox-template-builds",
        ctx.organization_id, ctx.project_id
    )
}

fn sandbox_proxy_base(
    api_url: &str,
    sandbox_id: &str,
    ingress_endpoint: Option<&str>,
) -> (String, Option<String>) {
    let proxy_url = ingress_endpoint
        .map(str::to_string)
        .unwrap_or_else(|| resolve_proxy_url(api_url));

    if let Ok(parsed) = url::Url::parse(&proxy_url) {
        let host = parsed.host_str().unwrap_or("");
        if host == "localhost" || host == "127.0.0.1" {
            return (proxy_url, Some(format!("{sandbox_id}.local")));
        }
        let port_part = parsed.port().map(|p| format!(":{p}")).unwrap_or_default();
        let base_url = format!("{}://{host}{port_part}", parsed.scheme());
        return (base_url, None);
    }

    (proxy_url, None)
}

fn resolve_proxy_url(api_url: &str) -> String {
    if let Ok(url) = std::env::var("TENSORLAKE_SANDBOX_PROXY_URL") {
        return url;
    }
    if is_localhost(api_url) {
        return "http://localhost:9443".to_string();
    }
    if let Ok(parsed) = url::Url::parse(api_url) {
        let host = parsed.host_str().unwrap_or("");
        if let Some(rest) = host.strip_prefix("api.") {
            return format!("{}://sandbox.{}", parsed.scheme(), rest);
        }
    }
    "https://sandbox.tensorlake.ai".to_string()
}

fn sandbox_proxy_client(
    ctx: &ResolvedBuildContext,
    client: &Client,
    sandbox_id: &str,
    ingress_endpoint: Option<&str>,
    routing_hint: Option<String>,
) -> Result<SandboxProxyClient> {
    let (proxy_base, host_override) =
        sandbox_proxy_base(&ctx.api_url, sandbox_id, ingress_endpoint);
    Ok(
        SandboxProxyClient::new(client.with_base_url(&proxy_base), host_override)
            .with_sandbox_id(Some(sandbox_id.to_string()))
            .with_routing_hint(routing_hint),
    )
}

async fn wait_for_proxy_ready(proxy: &SandboxProxyClient) -> Result<()> {
    let deadline = tokio::time::Instant::now() + PROXY_READY_TIMEOUT;
    loop {
        let mut emit = |_| {};
        match run_streaming_process(proxy, "/bin/true", Vec::new(), None, None, false, &mut emit)
            .await
        {
            Ok(()) => return Ok(()),
            Err(error) if is_transient_proxy_error(&error) => {
                if tokio::time::Instant::now() > deadline {
                    return Err(error);
                }
                tokio::time::sleep(PROXY_READY_POLL_INTERVAL).await;
            }
            Err(error) => return Err(error),
        }
    }
}

fn is_transient_proxy_error(error: &SandboxImageBuildError) -> bool {
    match error {
        SandboxImageBuildError::Sdk(SdkError::ServerError { status, message }) => {
            matches!(
                *status,
                StatusCode::BAD_GATEWAY
                    | StatusCode::SERVICE_UNAVAILABLE
                    | StatusCode::GATEWAY_TIMEOUT
            ) || (*status == StatusCode::BAD_REQUEST && message.contains("not running"))
                || message.contains("PROXY_ERROR")
                || message.contains("Failed to proxy request")
        }
        SandboxImageBuildError::Http(error) => error.is_timeout() || error.is_connect(),
        _ => false,
    }
}

async fn upload_build_inputs(
    proxy: &SandboxProxyClient,
    plan: &DockerfileBuildPlan,
    prepared: &PreparedSandboxTemplateBuild,
    prepared_spec: &Value,
    disk_mb: Option<u64>,
    docker_compat: bool,
    emit: &mut impl FnMut(SandboxImageBuildEvent),
) -> Result<()> {
    // Pre-create REMOTE_BUILD_DIR with permissive mode as root so the
    // sandbox-user file API can write into it. The path lives under
    // /var/lib/tensorlake/ which is root-owned in the rootfs-builder image,
    // so a plain `mkdir -p` issued as the sandbox user can't traverse and
    // create the leaf. Once the build root is world-writable, the per-file
    // `mkdir -p`s inside `copy_local_path` and the subsequent
    // `PUT /api/v1/files` calls (both running as the sandbox user) succeed
    // without further root involvement.
    ensure_remote_build_root(proxy).await?;
    // Import builds have no local build context — the rootfs comes straight
    // from the registry image — so there is nothing to upload.
    if plan.import_image_reference.is_none() {
        emit(SandboxImageBuildEvent::Status(
            "Uploading build context...".to_string(),
        ));
        copy_local_path(proxy, &plan.context_dir, REMOTE_CONTEXT_DIR).await?;
    }

    let docker_config_json = resolved_docker_config_json().await?;
    let spec = build_rootfs_spec(
        prepared_spec,
        prepared,
        plan,
        disk_mb,
        docker_config_json,
        docker_compat,
    )?;
    ensure_remote_parent_dir(proxy, REMOTE_SPEC_PATH).await?;
    proxy
        .write_file(REMOTE_SPEC_PATH, serde_json::to_vec_pretty(&spec)?)
        .await?;
    Ok(())
}

fn build_rootfs_spec(
    prepared_spec: &Value,
    prepared: &PreparedSandboxTemplateBuild,
    plan: &DockerfileBuildPlan,
    disk_mb: Option<u64>,
    docker_config_json: Option<String>,
    docker_compat: bool,
) -> Result<Value> {
    let mut spec = prepared_spec.clone();
    let object = spec.as_object_mut().ok_or_else(|| {
        SandboxImageBuildError::other("platform API returned a non-object rootfs build spec")
    })?;

    object.insert(
        "dockerfile".to_string(),
        Value::String(plan.dockerfile_text.clone()),
    );
    object.insert(
        "contextDir".to_string(),
        Value::String(REMOTE_CONTEXT_DIR.to_string()),
    );
    object.insert(
        "baseImage".to_string(),
        Value::String(plan.base_image.clone()),
    );
    // Routes the builder to `oci-image-to-ext4` instead of docker build; the
    // builder pulls this reference straight into the rootfs.
    if let Some(import_image_reference) = &plan.import_image_reference {
        object.insert(
            "importImageReference".to_string(),
            Value::String(import_image_reference.clone()),
        );
    }
    object.insert(
        "rootfsDiskBytes".to_string(),
        Value::Number(rootfs_disk_bytes(disk_mb, prepared)?.into()),
    );
    if let Some(docker_config_json) = docker_config_json {
        object.insert(
            "dockerConfigJson".to_string(),
            Value::String(docker_config_json),
        );
    }
    if docker_compat {
        object.insert("dockerCompat".to_string(), Value::Bool(true));
    }

    Ok(spec)
}

fn splice_signed_upload(prepared_spec: &mut Value, signed_upload: Value) -> Result<String> {
    let snapshot_uri = signed_upload
        .get("uri")
        .and_then(Value::as_str)
        .ok_or_else(|| {
            SandboxImageBuildError::other("dataplane signed upload response is missing uri")
        })?
        .to_string();

    let object = prepared_spec
        .as_object_mut()
        .ok_or_else(|| SandboxImageBuildError::other("prepared spec is not a JSON object"))?;
    object.insert(
        "snapshotUri".to_string(),
        Value::String(snapshot_uri.clone()),
    );
    object.insert("upload".to_string(), signed_upload);
    Ok(snapshot_uri)
}

fn rootfs_disk_bytes(disk_mb: Option<u64>, prepared: &PreparedSandboxTemplateBuild) -> Result<u64> {
    if let Some(disk_mb) = disk_mb {
        return disk_mb.checked_mul(1024 * 1024).ok_or_else(|| {
            SandboxImageBuildError::usage("--disk_mb is too large to convert to bytes")
        });
    }

    if let Some(parent) = &prepared.parent {
        return parent.rootfs_disk_bytes.ok_or_else(|| {
            SandboxImageBuildError::other(
                "platform API did not return parent rootfsDiskBytes for diff build; pass --disk_mb explicitly or update Platform API"
            )
        });
    }

    Ok(DEFAULT_ROOTFS_DISK_MB * 1024 * 1024)
}

fn rootfs_disk_bytes_to_mb(rootfs_disk_bytes: u64) -> Result<u64> {
    rootfs_disk_bytes
        .checked_add((1024 * 1024) - 1)
        .ok_or_else(|| {
            SandboxImageBuildError::usage("rootfsDiskBytes is too large to convert to megabytes")
        })
        .map(|bytes| bytes / (1024 * 1024))
}

/// Part size used when the new-path `sign_blob` flow sends an upload capacity
/// hint to the proxy. Used directly by the splice in `build_sandbox_image`.
const MULTIPART_PART_SIZE_MB: u64 = 64;
const MULTIPART_PART_SIZE_BYTES: u64 = MULTIPART_PART_SIZE_MB * 1024 * 1024;

/// S3 caps a multipart upload at 10,000 parts. The dataplane's `sign_blob`
/// endpoint enforces the same ceiling (`MAX_MULTIPART_PARTS` in
/// `indexify/crates/dataplane/src/sign_blob.rs`); keep these in sync.
const MULTIPART_MAX_PARTS: u32 = 10_000;

async fn resolved_docker_config_json() -> Result<Option<String>> {
    let docker_config = DockerConfig::load().await.map_err(|error| {
        SandboxImageBuildError::other(format!("Failed to load Docker config: {error}"))
    })?;
    let credentials = docker_config.all_credentials();
    if credentials.is_empty() {
        return Ok(None);
    }

    docker_config_json_from_credentials(credentials)
        .map(Some)
        .map_err(Into::into)
}

fn docker_config_json_from_credentials(
    credentials: HashMap<String, bollard::auth::DockerCredentials>,
) -> serde_json::Result<String> {
    let mut auths = Map::new();
    for (registry, creds) in credentials {
        let mut entry = Map::new();
        if let Some(identity_token) = creds.identitytoken {
            entry.insert("identitytoken".to_string(), Value::String(identity_token));
        }
        if let (Some(username), Some(password)) = (creds.username, creds.password) {
            let encoded = STANDARD.encode(format!("{username}:{password}"));
            entry.insert("auth".to_string(), Value::String(encoded));
        }
        if !entry.is_empty() {
            auths.insert(registry, Value::Object(entry));
        }
    }

    serde_json::to_string(&json!({ "auths": auths }))
}

/// Spawn a background task that pings the builder sandbox at a fixed cadence
/// to keep it from being suspended due to inactivity / lifetime expiry. The
/// caller MUST `.abort()` the returned handle when the build phase finishes
/// (success or failure) — otherwise the task would outlive the build and keep
/// poking a sandbox we're about to delete.
fn spawn_builder_keepalive(proxy: SandboxProxyClient) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        let mut interval = tokio::time::interval(BUILDER_SANDBOX_KEEPALIVE_INTERVAL);
        // The first tick fires immediately; skip it — we don't need a ping
        // right after the build kicks off, since the upload that just ran
        // already counts as activity.
        interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
        interval.tick().await;
        loop {
            interval.tick().await;
            // Best-effort: a transient error here is uninteresting. If the
            // sandbox is genuinely gone, run_rootfs_builder's streaming
            // process call will surface the real error.
            let _ = proxy.health().await;
        }
    })
}

async fn run_rootfs_builder(
    proxy: &SandboxProxyClient,
    command: &str,
    emit: &mut impl FnMut(SandboxImageBuildEvent),
) -> Result<()> {
    let parts = shlex_split(command).ok_or_else(|| {
        SandboxImageBuildError::other(format!(
            "invalid rootfs builder command returned by platform API: {}",
            command
        ))
    })?;
    let Some((executable, command_args)) = parts.split_first() else {
        return Err(SandboxImageBuildError::other(
            "empty rootfs builder command returned by platform API",
        ));
    };
    let mut args = command_args.to_vec();
    args.extend([
        "--spec".to_string(),
        REMOTE_SPEC_PATH.to_string(),
        "--metadata-out".to_string(),
        REMOTE_METADATA_PATH.to_string(),
    ]);

    let executable = rootfs_builder_executable(executable);
    // The rootfs builder needs root inside the VM to run `docker build`,
    // mount loop devices, write to /var/lib/docker, etc. Everything else
    // (proxy probes, upload-prep `mkdir`) stays on the sandbox user so the
    // file API can write into the directories it creates.
    run_streaming_process(
        proxy,
        &executable,
        args,
        Some(rootfs_builder_env()),
        Some(REMOTE_BUILD_DIR.to_string()),
        true,
        emit,
    )
    .await
}

fn rootfs_builder_executable(executable: &str) -> String {
    if executable == ROOTFS_BUILDER_COMMAND {
        format!("{ROOTFS_BUILDER_BIN_DIR}/{ROOTFS_BUILDER_COMMAND}")
    } else {
        executable.to_string()
    }
}

fn rootfs_builder_env() -> Map<String, Value> {
    let mut env = Map::new();
    env.insert(
        "PATH".to_string(),
        Value::String(ROOTFS_BUILDER_PATH.to_string()),
    );
    env
}

#[derive(Debug, Default, Clone, PartialEq, Eq)]
struct BuilderFailureDiagnostics {
    oom_killed: bool,
    disk_usage_percent: Option<u8>,
    disk_error_output: bool,
}

impl BuilderFailureDiagnostics {
    fn observe_build_event(&mut self, event: &SandboxImageBuildEvent) {
        if let SandboxImageBuildEvent::BuildLog { message, .. } = event
            && contains_disk_space_evidence(message)
        {
            self.disk_error_output = true;
        }
    }

    fn merge(&mut self, other: &BuilderFailureDiagnostics) {
        self.oom_killed |= other.oom_killed;
        self.disk_error_output |= other.disk_error_output;
        self.disk_usage_percent = self.disk_usage_percent.max(other.disk_usage_percent);
    }

    fn advice_messages(&self) -> Vec<&'static str> {
        let mut messages = Vec::new();
        if self.oom_killed {
            messages.push(
                "The builder sandbox ran out of memory. Retry with a larger `memory_mb` / `memoryMb` / `--memory` value.",
            );
        }
        if self
            .disk_usage_percent
            .is_some_and(|usage| usage >= BUILDER_DISK_USAGE_DIAGNOSTIC_THRESHOLD_PERCENT)
            || self.disk_error_output
        {
            messages.push(
                "The builder sandbox ran out of disk space. Retry with a larger `builder_disk_mb` / `builderDiskMb` / `--builder_disk_mb` value.",
            );
        }
        messages
    }
}

async fn decorate_builder_failure(
    proxy: &SandboxProxyClient,
    source: SandboxImageBuildError,
    observed: &BuilderFailureDiagnostics,
) -> SandboxImageBuildError {
    let mut diagnostics = diagnose_builder_failure(proxy, &source.to_string()).await;
    diagnostics.merge(observed);
    let messages = diagnostics.advice_messages();
    if messages.is_empty() {
        return source;
    }

    SandboxImageBuildError::WithDiagnostics {
        source: Box::new(source),
        messages: messages.join("\n"),
    }
}

async fn diagnose_builder_failure(
    proxy: &SandboxProxyClient,
    failure_output: &str,
) -> BuilderFailureDiagnostics {
    let dmesg_output = run_diagnostic_command_stdout(proxy, "dmesg 2>/dev/null || true").await;
    let disk_output = run_diagnostic_command_stdout(
        proxy,
        &format!(
            "for path in '{}' /var/lib/docker /; do if [ -e \"$path\" ]; then df -P \"$path\"; fi; done 2>/dev/null || true",
            REMOTE_BUILD_DIR
        ),
    )
    .await;

    BuilderFailureDiagnostics {
        oom_killed: dmesg_output
            .as_deref()
            .is_some_and(contains_oom_killer_evidence),
        disk_usage_percent: disk_output.as_deref().and_then(parse_df_max_usage_percent),
        disk_error_output: contains_disk_space_evidence(failure_output),
    }
}

async fn run_diagnostic_command_stdout(proxy: &SandboxProxyClient, script: &str) -> Option<String> {
    let mut payload = streaming_process_payload(
        "/bin/sh",
        vec!["-lc".to_string(), script.to_string()],
        None,
        None,
        true,
    );
    payload.as_object_mut()?.insert(
        "timeout".to_string(),
        json!(DIAGNOSTIC_COMMAND_TIMEOUT_SECS),
    );

    let events = proxy.run_process(&payload).await.ok()?.into_inner();
    let mut output = String::new();
    for event in events {
        if let RunProcessEvent::Output(event) = event
            && event.stream.as_deref() != Some("stderr")
        {
            output.push_str(&event.line);
            output.push('\n');
        }
    }
    Some(output)
}

fn contains_oom_killer_evidence(output: &str) -> bool {
    let output = output.to_ascii_lowercase();
    output.contains("out of memory")
        || output.contains("oom-kill")
        || output.contains("killed process")
}

fn contains_disk_space_evidence(output: &str) -> bool {
    let output = output.to_ascii_lowercase();
    output.contains("enospc") || output.contains("no space")
}

fn parse_df_max_usage_percent(output: &str) -> Option<u8> {
    output.lines().filter_map(parse_df_line_usage_percent).max()
}

fn parse_df_line_usage_percent(line: &str) -> Option<u8> {
    let mut fields = line.split_whitespace();
    let _filesystem = fields.next()?;
    let _blocks = fields.next()?;
    let _used = fields.next()?;
    let _available = fields.next()?;
    fields.next()?.strip_suffix('%')?.parse().ok()
}

async fn read_build_metadata(proxy: &SandboxProxyClient) -> Result<Value> {
    let content = proxy.read_file(REMOTE_METADATA_PATH).await?.into_inner();
    serde_json::from_slice(&content).map_err(Into::into)
}

fn complete_request_from_metadata(
    prepared: &PreparedSandboxTemplateBuild,
    metadata: &Value,
    signed_snapshot_uri: Option<&str>,
) -> Result<CompleteSandboxTemplateBuildRequest> {
    let rootfs_node_kind = metadata_string(metadata, "rootfs_node_kind", "rootfsNodeKind")
        .unwrap_or_else(|| prepared.rootfs_node_kind.clone());
    let parent_manifest_uri = metadata_string(metadata, "parent_manifest_uri", "parentManifestUri")
        .or_else(|| {
            (rootfs_node_kind == "diff")
                .then(|| {
                    prepared
                        .parent
                        .as_ref()
                        .map(|parent| parent.parent_manifest_uri.clone())
                })
                .flatten()
        });

    if rootfs_node_kind == "diff" && parent_manifest_uri.is_none() {
        return Err(SandboxImageBuildError::other(
            "rootfs diff build completed without parent_manifest_uri",
        ));
    }

    Ok(CompleteSandboxTemplateBuildRequest {
        snapshot_id: metadata_string(metadata, "snapshot_id", "snapshotId")
            .unwrap_or_else(|| prepared.snapshot_id.clone()),
        snapshot_uri: completion_snapshot_uri(prepared, metadata, signed_snapshot_uri)?,
        snapshot_format_version: required_metadata_string(
            metadata,
            "snapshot_format_version",
            "snapshotFormatVersion",
        )?,
        snapshot_size_bytes: required_metadata_u64(
            metadata,
            "snapshot_size_bytes",
            "snapshotSizeBytes",
        )?,
        rootfs_disk_bytes: required_metadata_u64(metadata, "rootfs_disk_bytes", "rootfsDiskBytes")?,
        rootfs_node_kind,
        parent_manifest_uri,
    })
}

fn completion_snapshot_uri(
    prepared: &PreparedSandboxTemplateBuild,
    metadata: &Value,
    signed_snapshot_uri: Option<&str>,
) -> Result<String> {
    if let Some(signed_snapshot_uri) = signed_snapshot_uri {
        if let Some(metadata_snapshot_uri) =
            metadata_string(metadata, "snapshot_uri", "snapshotUri")
            && metadata_snapshot_uri != signed_snapshot_uri
        {
            return Err(SandboxImageBuildError::other(format!(
                "rootfs builder metadata snapshot_uri {} did not match dataplane signed uri {}",
                metadata_snapshot_uri, signed_snapshot_uri
            )));
        }

        return Ok(signed_snapshot_uri.to_string());
    }

    if let Some(snapshot_uri) = metadata_string(metadata, "snapshot_uri", "snapshotUri") {
        return Ok(snapshot_uri);
    }

    if let Some(snapshot_uri) = prepared.snapshot_uri.clone() {
        return Ok(snapshot_uri);
    }

    Err(SandboxImageBuildError::other(
        "rootfs build completed without snapshot_uri",
    ))
}

fn required_metadata_string(metadata: &Value, snake_key: &str, camel_key: &str) -> Result<String> {
    metadata_string(metadata, snake_key, camel_key).ok_or_else(|| {
        SandboxImageBuildError::other(format!("rootfs builder metadata is missing {}", snake_key))
    })
}

fn metadata_string(metadata: &Value, snake_key: &str, camel_key: &str) -> Option<String> {
    metadata
        .get(snake_key)
        .or_else(|| metadata.get(camel_key))
        .and_then(Value::as_str)
        .map(str::to_string)
}

fn required_metadata_u64(metadata: &Value, snake_key: &str, camel_key: &str) -> Result<u64> {
    metadata
        .get(snake_key)
        .or_else(|| metadata.get(camel_key))
        .and_then(|value| match value {
            Value::Number(number) => number.as_u64(),
            Value::String(value) => value.parse::<u64>().ok(),
            _ => None,
        })
        .ok_or_else(|| {
            SandboxImageBuildError::other(format!(
                "rootfs builder metadata is missing numeric {}",
                snake_key
            ))
        })
}

async fn run_streaming_process(
    proxy: &SandboxProxyClient,
    command: &str,
    args: Vec<String>,
    env: Option<Map<String, Value>>,
    working_dir: Option<String>,
    run_as_root: bool,
    emit: &mut impl FnMut(SandboxImageBuildEvent),
) -> Result<()> {
    let expected_args = args.clone();
    let payload = streaming_process_payload(command, args, env, working_dir, run_as_root);

    let started = start_or_recover_process(proxy, &payload, command, &expected_args, emit).await?;

    let terminal_status = stream_started_process(proxy, started.pid, emit).await?;

    if terminal_status.code != 0 {
        let reason = if terminal_status.oom_killed {
            " (process was killed by the kernel OOM killer)"
        } else {
            ""
        };
        return Err(SandboxImageBuildError::other(format!(
            "Command '{}' failed with exit code {}{}",
            command, terminal_status.code, reason
        )));
    }

    Ok(())
}

async fn start_or_recover_process(
    proxy: &SandboxProxyClient,
    payload: &Value,
    command: &str,
    expected_args: &[String],
    emit: &mut impl FnMut(SandboxImageBuildEvent),
) -> Result<ProcessInfo> {
    let mut last_error = None;

    for attempt in 1..=PROCESS_START_ATTEMPTS {
        match proxy.start_process(payload).await {
            Ok(started) => return Ok(started.into_inner()),
            Err(start_error) => {
                emit(SandboxImageBuildEvent::Status(format!(
                    "Process start attempt {} failed; looking for an already-started process...",
                    attempt
                )));
                match recover_started_process(proxy, command, expected_args).await {
                    Ok(process) => return Ok(process),
                    Err(recover_error) => {
                        last_error = Some(format!(
                            "start failed: {}; recovery failed: {}",
                            start_error, recover_error
                        ));
                    }
                }
            }
        }

        if attempt < PROCESS_START_ATTEMPTS {
            tokio::time::sleep(PROCESS_REATTACH_RETRY_INTERVAL).await;
        }
    }

    Err(SandboxImageBuildError::other(last_error.unwrap_or_else(
        || format!("Failed to start process '{}'", command),
    )))
}

async fn recover_started_process(
    proxy: &SandboxProxyClient,
    command: &str,
    expected_args: &[String],
) -> Result<ProcessInfo> {
    let mut last_error = None;

    for _ in 0..PROCESS_REATTACH_ATTEMPTS {
        match proxy.list_processes().await {
            Ok(processes) => {
                if let Some(process) = processes
                    .into_inner()
                    .into_iter()
                    .filter(|process| process.command == command && process.args == expected_args)
                    .max_by_key(|process| process.pid)
                {
                    return Ok(process);
                }
            }
            Err(error) => {
                last_error = Some(error);
            }
        }
        tokio::time::sleep(PROCESS_REATTACH_RETRY_INTERVAL).await;
    }

    let message = if let Some(error) = last_error {
        format!(
            "No process found for command '{}' after process-list errors: {}",
            command, error
        )
    } else {
        format!("No process found for command '{}'", command)
    };
    Err(SandboxImageBuildError::other(message))
}

async fn stream_started_process(
    proxy: &SandboxProxyClient,
    pid: i64,
    emit: &mut impl FnMut(SandboxImageBuildEvent),
) -> Result<ProcessTerminalStatus> {
    let mut output_events_seen = 0usize;
    let mut attempts = 0usize;

    loop {
        let follow_result = follow_process_output(proxy, pid, &mut output_events_seen, emit).await;

        if let Err(error) = follow_result {
            attempts += 1;
            if let Some(status) =
                get_process_terminal_status_with_retries(proxy, pid, &mut attempts).await?
            {
                return Ok(status);
            }
            if attempts >= PROCESS_REATTACH_ATTEMPTS {
                return Err(error);
            }
            emit(SandboxImageBuildEvent::Status(format!(
                "Process stream interrupted; reattaching to process {}...",
                pid
            )));
            tokio::time::sleep(PROCESS_REATTACH_RETRY_INTERVAL).await;
            continue;
        }

        attempts = 0;
        if let Some(status) =
            get_process_terminal_status_with_retries(proxy, pid, &mut attempts).await?
        {
            return Ok(status);
        }

        emit(SandboxImageBuildEvent::Status(format!(
            "Process output stream ended before process {} exited; reattaching...",
            pid
        )));
        tokio::time::sleep(PROCESS_REATTACH_RETRY_INTERVAL).await;
    }
}

async fn follow_process_output(
    proxy: &SandboxProxyClient,
    pid: i64,
    output_events_seen: &mut usize,
    emit: &mut impl FnMut(SandboxImageBuildEvent),
) -> Result<()> {
    let mut replayed_events_seen = 0usize;
    proxy
        .follow_output_streaming(pid, |output| {
            if replayed_events_seen < *output_events_seen {
                replayed_events_seen += 1;
                return;
            }
            replayed_events_seen += 1;
            *output_events_seen += 1;
            emit(SandboxImageBuildEvent::BuildLog {
                stream: output.stream.unwrap_or_else(|| "stdout".to_string()),
                message: output.line,
            });
        })
        .await?;

    Ok(())
}

async fn get_process_terminal_status_with_retries(
    proxy: &SandboxProxyClient,
    pid: i64,
    attempts: &mut usize,
) -> Result<Option<ProcessTerminalStatus>> {
    loop {
        match proxy.get_process(pid).await {
            Ok(info) => return Ok(process_terminal_status(&info.into_inner())),
            Err(error) => {
                *attempts += 1;
                if *attempts >= PROCESS_REATTACH_ATTEMPTS {
                    return Err(error.into());
                }
                tokio::time::sleep(PROCESS_REATTACH_RETRY_INTERVAL).await;
            }
        }
    }
}

fn process_terminal_status(info: &ProcessInfo) -> Option<ProcessTerminalStatus> {
    let oom_killed = info.oom_killed
        || info.status == "oom_killed"
        || info
            .managed
            .as_ref()
            .and_then(|managed| managed.last_exit.as_ref())
            .is_some_and(|last_exit| last_exit.oom_killed);

    if oom_killed {
        Some(ProcessTerminalStatus {
            code: info
                .signal
                .map(|signal| -signal)
                .or(info.exit_code)
                .unwrap_or(-9),
            oom_killed,
        })
    } else if let Some(code) = info.exit_code {
        Some(ProcessTerminalStatus { code, oom_killed })
    } else if let Some(signal) = info.signal {
        Some(ProcessTerminalStatus {
            code: -signal,
            oom_killed,
        })
    } else if info.status != "running" {
        Some(ProcessTerminalStatus {
            code: 0,
            oom_killed,
        })
    } else {
        None
    }
}

fn streaming_process_payload(
    command: &str,
    args: Vec<String>,
    env: Option<Map<String, Value>>,
    working_dir: Option<String>,
    run_as_root: bool,
) -> Value {
    let mut payload = Map::new();
    payload.insert("command".to_string(), Value::String(command.to_string()));
    payload.insert(
        "args".to_string(),
        Value::Array(args.into_iter().map(Value::String).collect()),
    );
    if let Some(env) = env {
        payload.insert("env".to_string(), Value::Object(env));
    }
    if let Some(working_dir) = working_dir {
        payload.insert("working_dir".to_string(), Value::String(working_dir));
    }
    // Only opt into root for the actual rootfs build command. Daemon-side, the
    // process API runs as the sandbox user by default while the file API
    // performs writes with the sandbox user's fsuid/fsgid (setfsuid/setfsgid
    // in container-daemon's file_manager). If we ran the upload-prep `mkdir`
    // as root we'd end up with directories the file API can't write into
    // and the very first `PUT /api/v1/files` would fail with EACCES (surfaced
    // as 500 "Failed to create file: …"). See the SDK PR description for the
    // dataplane log trace.
    if run_as_root {
        payload.insert(
            "user".to_string(),
            Value::String(ROOTFS_BUILDER_PROCESS_USER.to_string()),
        );
    }

    Value::Object(payload)
}

async fn copy_local_path(
    proxy: &SandboxProxyClient,
    local_path: &Path,
    remote_path: &str,
) -> Result<()> {
    if local_path.is_file() {
        ensure_remote_parent_dir(proxy, remote_path).await?;
        proxy.upload_file(remote_path, local_path).await?;
        return Ok(());
    }

    if local_path.is_dir() {
        for (full_path, relative_path) in collect_dir_files(local_path, local_path)? {
            let remote_destination = join_posix(remote_path, &relative_path);
            ensure_remote_parent_dir(proxy, &remote_destination).await?;
            proxy.upload_file(&remote_destination, &full_path).await?;
        }
        return Ok(());
    }

    Err(SandboxImageBuildError::other(format!(
        "Local path not found: {}",
        local_path.display()
    )))
}

/// Create `REMOTE_BUILD_DIR` as root and chmod it 0777 so subsequent
/// uploads — which run via the file API with the sandbox user's fsuid —
/// can write inside. Must be called once before any per-file
/// `ensure_remote_parent_dir` for paths under `REMOTE_BUILD_DIR`.
async fn ensure_remote_build_root(proxy: &SandboxProxyClient) -> Result<()> {
    let mut emit = |_| {};
    // mkdir as root: needed to traverse the root-owned ancestor
    // /var/lib/tensorlake/rootfs-builder/.
    run_streaming_process(
        proxy,
        "mkdir",
        vec!["-p".to_string(), REMOTE_BUILD_DIR.to_string()],
        None,
        None,
        true,
        &mut emit,
    )
    .await?;
    // chmod as root: open it up so the sandbox user can create the
    // upload-temp files the file API needs. Mode 0777 is fine here because
    // the builder sandbox is single-tenant and ephemeral.
    run_streaming_process(
        proxy,
        "chmod",
        vec!["0777".to_string(), REMOTE_BUILD_DIR.to_string()],
        None,
        None,
        true,
        &mut emit,
    )
    .await
}

async fn ensure_remote_parent_dir(proxy: &SandboxProxyClient, remote_path: &str) -> Result<()> {
    let parent_dir = parent_posix(remote_path);
    let mut emit = |_| {};
    // Stay on the sandbox user. The follow-up `PUT /api/v1/files` writes via
    // the file API, which the container-daemon executes with sandbox fsuid;
    // running `mkdir` as root here would create root-owned directories the
    // file API can't write into.
    run_streaming_process(
        proxy,
        "mkdir",
        vec!["-p".to_string(), parent_dir],
        None,
        None,
        false,
        &mut emit,
    )
    .await
}

fn is_localhost(url: &str) -> bool {
    if let Ok(parsed) = url::Url::parse(url) {
        return matches!(parsed.host_str(), Some("localhost" | "127.0.0.1"));
    }
    false
}

/// Build a plan for importing a registry image directly (no Dockerfile).
/// The stored "dockerfile" is a synthetic `FROM <ref>` so the template
/// registry records a faithful provenance, but the build never runs Docker:
/// the spec's `importImageReference` routes the builder to
/// `oci-image-to-ext4`. Import is always a fresh base from the registry, so
/// the base is not resolved against the template registry.
fn plan_image_import(
    image_ref: &str,
    registered_name: Option<&str>,
) -> Result<DockerfileBuildPlan> {
    let image_ref = image_ref.trim();
    if image_ref.is_empty() {
        return Err(SandboxImageBuildError::usage(
            "image reference to import must not be empty",
        ));
    }
    let registered_name = registered_name
        .map(str::to_string)
        .unwrap_or_else(|| default_registered_name_from_image(image_ref));
    Ok(DockerfileBuildPlan {
        context_dir: PathBuf::new(),
        registered_name,
        dockerfile_text: format!("FROM {image_ref}\n"),
        base_image: image_ref.to_string(),
        base_image_is_internal_stage: false,
        additional_image_references: Vec::new(),
        unresolvable_image_references: Vec::new(),
        ignored_instructions: Vec::new(),
        import_image_reference: Some(image_ref.to_string()),
    })
}

/// Derive a registered name from an image reference: the last path segment
/// with any tag/digest stripped (e.g. `pytorch/pytorch:2.4.1` -> `pytorch`,
/// `ghcr.io/org/app@sha256:...` -> `app`).
fn default_registered_name_from_image(image_ref: &str) -> String {
    let without_digest = image_ref.split('@').next().unwrap_or(image_ref);
    let last_segment = without_digest.rsplit('/').next().unwrap_or(without_digest);
    let name = match last_segment.rsplit_once(':') {
        Some((repo, tag)) if !tag.is_empty() => repo,
        _ => last_segment,
    };
    if name.is_empty() {
        "imported-image".to_string()
    } else {
        name.to_string()
    }
}

fn load_dockerfile_plan(
    dockerfile_path: &Path,
    registered_name: Option<&str>,
) -> Result<DockerfileBuildPlan> {
    let absolute_path = if dockerfile_path.is_absolute() {
        dockerfile_path.to_path_buf()
    } else {
        std::env::current_dir()?.join(dockerfile_path)
    };
    if !absolute_path.is_file() {
        return Err(SandboxImageBuildError::other(format!(
            "Dockerfile not found: {}",
            dockerfile_path.display()
        )));
    }

    let dockerfile_text = std::fs::read_to_string(&absolute_path)?;
    load_dockerfile_text_plan(&absolute_path, None, dockerfile_text, registered_name)
}

fn load_dockerfile_text_plan(
    dockerfile_path: &Path,
    context_dir: Option<&Path>,
    dockerfile_text: String,
    registered_name: Option<&str>,
) -> Result<DockerfileBuildPlan> {
    let absolute_path = if dockerfile_path.is_absolute() {
        dockerfile_path.to_path_buf()
    } else {
        std::env::current_dir()?.join(dockerfile_path)
    };
    let context_dir = if let Some(context_dir) = context_dir {
        if context_dir.is_absolute() {
            context_dir.to_path_buf()
        } else {
            std::env::current_dir()?.join(context_dir)
        }
    } else {
        absolute_path
            .parent()
            .unwrap_or(Path::new("."))
            .to_path_buf()
    };
    // Track stage aliases (`FROM ... AS <name>`) so we can distinguish
    // `COPY --from=<stage>` (internal reference, skip lookup) from
    // `COPY --from=<image>` (external reference, look up as template).
    let mut stage_aliases: Vec<String> = Vec::new();
    // Final-stage FROM image. Each new FROM overwrites this so the last one
    // wins — matches Docker's "the final stage is the resulting image"
    // semantics.
    let mut final_from_image: Option<String> = None;
    // Order-preserving deduped set of additional external image references.
    // We keep insertion order via a separate Vec while tracking membership
    // in a HashSet for O(1) dedup.
    let mut additional_refs: Vec<String> = Vec::new();
    let mut additional_refs_seen: std::collections::HashSet<String> =
        std::collections::HashSet::new();
    let mut unresolvable_image_references: Vec<UnresolvableImageReference> = Vec::new();
    let mut ignored_instructions: Vec<(usize, String)> = Vec::new();

    for (line_number, line) in logical_dockerfile_lines(&dockerfile_text) {
        let (keyword, value) = split_instruction(&line, line_number)?;
        if keyword == "FROM" {
            let (image, alias) = parse_from_value_with_alias(&value, line_number)?;
            // If a prior FROM had set the "final image" candidate, demote it
            // now — it's actually an earlier-stage FROM. Push it to the
            // additional-refs set so the rootfs builder still loads it
            // locally (e.g., for COPY --from referring to it by image name).
            // Skip the demotion when the prior image equals the new final
            // FROM (would duplicate the entry) or is itself unresolvable.
            if let Some(prior) = final_from_image.take()
                && prior != image
                && !prior.eq_ignore_ascii_case("scratch")
                && !prior.contains('$')
                && !prior.contains('@')
                && !stage_aliases.iter().any(|alias| alias == prior.as_str())
                && additional_refs_seen.insert(prior.clone())
            {
                additional_refs.push(prior);
            }
            if image.contains('$') {
                unresolvable_image_references.push(UnresolvableImageReference {
                    line_number,
                    reference: image.clone(),
                    reason: UnresolvableImageReferenceReason::BuildArgExpansion,
                });
            } else if image.contains('@') {
                unresolvable_image_references.push(UnresolvableImageReference {
                    line_number,
                    reference: image.clone(),
                    reason: UnresolvableImageReferenceReason::DigestPin,
                });
            }
            // `scratch`, variable references, and digest-pinned references are
            // tracked but never put in additional_refs — they're either
            // built-ins or unresolvable.
            final_from_image = Some(image);
            if let Some(alias) = alias {
                stage_aliases.push(alias);
            }
            continue;
        }
        if keyword == "COPY" {
            for from_value in copy_from_values(&value) {
                accumulate_side_reference(
                    line_number,
                    from_value,
                    &stage_aliases,
                    &mut additional_refs,
                    &mut additional_refs_seen,
                    &mut unresolvable_image_references,
                );
            }
            continue;
        }
        if keyword == "RUN" {
            for from_value in run_mount_from_values(&value) {
                accumulate_side_reference(
                    line_number,
                    from_value,
                    &stage_aliases,
                    &mut additional_refs,
                    &mut additional_refs_seen,
                    &mut unresolvable_image_references,
                );
            }
            continue;
        }
        if IGNORED_DOCKERFILE_INSTRUCTIONS.contains(&keyword.as_str()) {
            ignored_instructions.push((line_number, keyword));
        }
        let _ = value;
    }

    let base_image = final_from_image.ok_or_else(|| {
        SandboxImageBuildError::other("Dockerfile must contain a FROM instruction")
    })?;
    // Final pass: a side-channel reference (COPY --from / RUN --mount=,from)
    // that happens to name the final-stage image must not appear in both
    // `base_image` and `additional_image_references`. Filter here rather
    // than in the inner loop because the final base isn't known until every
    // FROM has been seen.
    additional_refs.retain(|reference| reference != &base_image);
    // Detect `FROM <stage-alias>` in the final stage. When the final FROM
    // matches an earlier-defined stage alias the value is an internal
    // reference rather than an external image, so we must not look it up
    // as a template.
    let base_image_is_internal_stage = stage_aliases
        .iter()
        .any(|alias| alias == base_image.as_str());

    Ok(DockerfileBuildPlan {
        context_dir,
        registered_name: registered_name
            .map(str::to_string)
            .unwrap_or_else(|| default_registered_name(&absolute_path)),
        dockerfile_text,
        base_image,
        base_image_is_internal_stage,
        additional_image_references: additional_refs,
        unresolvable_image_references,
        ignored_instructions,
        import_image_reference: None,
    })
}

fn default_registered_name(dockerfile_path: &Path) -> String {
    let stem = dockerfile_path
        .file_stem()
        .and_then(|value| value.to_str())
        .unwrap_or_default();
    if stem.eq_ignore_ascii_case("dockerfile") {
        return dockerfile_path
            .parent()
            .and_then(|value| value.file_name())
            .and_then(|value| value.to_str())
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .unwrap_or("sandbox-image")
            .to_string();
    }
    if stem.is_empty() {
        "sandbox-image".to_string()
    } else {
        stem.to_string()
    }
}

fn logical_dockerfile_lines(dockerfile_text: &str) -> Vec<(usize, String)> {
    let mut logical_lines = Vec::new();
    let mut parts = Vec::new();
    let mut start_line = None;

    for (index, raw_line) in dockerfile_text.lines().enumerate() {
        let line_number = index + 1;
        let stripped = raw_line.trim();
        if parts.is_empty() && (stripped.is_empty() || stripped.starts_with('#')) {
            continue;
        }

        if start_line.is_none() {
            start_line = Some(line_number);
        }

        let mut line = raw_line.trim_end().to_string();
        let continued = line.ends_with('\\');
        if continued {
            line.pop();
        }

        let normalized = line.trim();
        if !normalized.is_empty() && !normalized.starts_with('#') {
            parts.push(normalized.to_string());
        }

        if continued {
            continue;
        }

        if !parts.is_empty() {
            logical_lines.push((start_line.unwrap_or(1), parts.join(" ")));
        }
        parts.clear();
        start_line = None;
    }

    if !parts.is_empty() {
        logical_lines.push((start_line.unwrap_or(1), parts.join(" ")));
    }

    logical_lines
}

fn split_instruction(line: &str, line_number: usize) -> Result<(String, String)> {
    let trimmed = line.trim();
    if trimmed.is_empty() {
        return Err(SandboxImageBuildError::other(format!(
            "line {}: empty Dockerfile instruction",
            line_number
        )));
    }
    if let Some(index) = trimmed.find(char::is_whitespace) {
        let keyword = trimmed[..index].to_ascii_uppercase();
        let value = trimmed[index..].trim().to_string();
        Ok((keyword, value))
    } else {
        Ok((trimmed.to_ascii_uppercase(), String::new()))
    }
}

/// Parse a FROM instruction value into `(image, alias)`.
///
/// `value` is the text after the `FROM` keyword (e.g.
/// `--platform=linux/amd64 python:3.12-slim AS builder`). Returns the image
/// reference exactly as the user wrote it, plus any `AS <alias>` stage name.
fn parse_from_value_with_alias(
    value: &str,
    line_number: usize,
) -> Result<(String, Option<String>)> {
    let (_, remainder) = strip_leading_flags(value)?;
    let tokens = shlex_split(&remainder).ok_or_else(|| {
        SandboxImageBuildError::other(format!(
            "line {}: invalid FROM syntax '{}'",
            line_number, value
        ))
    })?;
    if tokens.is_empty() {
        return Err(SandboxImageBuildError::other(format!(
            "line {}: FROM must include a base image",
            line_number
        )));
    }
    let image = tokens[0].clone();
    if tokens.len() == 1 {
        return Ok((image, None));
    }
    if !tokens[1].eq_ignore_ascii_case("as") {
        return Err(SandboxImageBuildError::other(format!(
            "line {}: unsupported FROM syntax '{}'",
            line_number, value
        )));
    }
    if tokens.len() < 3 {
        return Err(SandboxImageBuildError::other(format!(
            "line {}: FROM ... AS must include a stage name",
            line_number
        )));
    }
    Ok((image, Some(tokens[2].clone())))
}

/// Classify a side-channel image reference (COPY --from / RUN --mount=,from)
/// and either accumulate it into the additional-references list or record
/// it as unresolvable (variable / digest-pin / built-in / stage alias).
fn accumulate_side_reference(
    line_number: usize,
    value: String,
    stage_aliases: &[String],
    additional_refs: &mut Vec<String>,
    additional_refs_seen: &mut std::collections::HashSet<String>,
    unresolvable_image_references: &mut Vec<UnresolvableImageReference>,
) {
    if value.eq_ignore_ascii_case("scratch") {
        return;
    }
    if value.contains('$') {
        unresolvable_image_references.push(UnresolvableImageReference {
            line_number,
            reference: value,
            reason: UnresolvableImageReferenceReason::BuildArgExpansion,
        });
        return;
    }
    if value.contains('@') {
        unresolvable_image_references.push(UnresolvableImageReference {
            line_number,
            reference: value,
            reason: UnresolvableImageReferenceReason::DigestPin,
        });
        return;
    }
    if stage_aliases.iter().any(|alias| alias == value.as_str()) {
        return;
    }
    if additional_refs_seen.insert(value.clone()) {
        additional_refs.push(value);
    }
}

/// Extract `--from=<value>` arguments from a COPY instruction's tail.
///
/// COPY supports at most one `--from` flag per instruction. The flag can be
/// written as `--from=<value>` or `--from <value>`. Anything else (the source
/// paths, the destination, other flags) is ignored.
fn copy_from_values(value: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut tokens = value.split_whitespace();
    while let Some(token) = tokens.next() {
        if let Some(v) = token.strip_prefix("--from=") {
            if !v.is_empty() {
                out.push(v.to_string());
            }
        } else if token == "--from"
            && let Some(next) = tokens.next()
        {
            out.push(next.to_string());
        }
    }
    out
}

/// Extract image references from `RUN --mount=type=cache,from=<value>` and
/// `RUN --mount=type=bind,from=<value>` flags.
///
/// BuildKit's mount syntax uses comma-separated key/value pairs after
/// `--mount=`. We pick out the `from=` element and, for the cases where it
/// names an image (rather than a stage), the rootfs builder will need to
/// have that image loaded locally.
fn run_mount_from_values(value: &str) -> Vec<String> {
    let mut out = Vec::new();
    for token in value.split_whitespace() {
        let body = match token.strip_prefix("--mount=") {
            Some(body) => body,
            None => continue,
        };
        for entry in body.split(',') {
            if let Some(v) = entry.strip_prefix("from=")
                && !v.is_empty()
            {
                out.push(v.to_string());
            }
        }
    }
    out
}

fn strip_leading_flags(value: &str) -> Result<(Vec<(String, String)>, String)> {
    let mut flags = Vec::new();
    let mut remaining = value.trim_start().to_string();

    while remaining.starts_with("--") {
        let (token, rest) = match remaining.split_once(' ') {
            Some((token, rest)) => (token.to_string(), rest.trim_start().to_string()),
            None => {
                return Err(SandboxImageBuildError::other(format!(
                    "invalid Dockerfile flag syntax: {}",
                    value
                )));
            }
        };

        let flag_body = &token[2..];
        if let Some((key, flag_value)) = flag_body.split_once('=') {
            flags.push((key.to_string(), flag_value.to_string()));
            remaining = rest;
        } else if let Some((flag_value, tail)) = rest.split_once(' ') {
            flags.push((flag_body.to_string(), flag_value.to_string()));
            remaining = tail.trim_start().to_string();
        } else {
            return Err(SandboxImageBuildError::other(format!(
                "missing value for Dockerfile flag '{}'",
                token
            )));
        }
    }

    Ok((flags, remaining))
}

fn normalize_posix(path: &str) -> String {
    let mut parts = Vec::new();
    for segment in path.split('/') {
        match segment {
            "" | "." => {}
            ".." => {
                parts.pop();
            }
            other => parts.push(other),
        }
    }

    if parts.is_empty() {
        "/".to_string()
    } else {
        format!("/{}", parts.join("/"))
    }
}

fn parent_posix(path: &str) -> String {
    let normalized = normalize_posix(path);
    if normalized == "/" {
        return "/".to_string();
    }
    match normalized.rsplit_once('/') {
        Some(("", _)) | None => "/".to_string(),
        Some((parent, _)) => parent.to_string(),
    }
}

fn join_posix(base: &str, child: &str) -> String {
    normalize_posix(&format!("{}/{}", base.trim_end_matches('/'), child))
}

fn collect_dir_files(root: &Path, current: &Path) -> Result<Vec<(PathBuf, String)>> {
    let mut files = Vec::new();
    let dockerignore = dockerignore_matcher(root)?;
    collect_dir_files_filtered(root, current, dockerignore.as_ref(), &mut files)?;
    Ok(files)
}

fn dockerignore_matcher(root: &Path) -> Result<Option<Gitignore>> {
    let dockerignore_path = root.join(".dockerignore");
    if !dockerignore_path.is_file() {
        return Ok(None);
    }

    let mut builder = GitignoreBuilder::new(root);
    if let Some(error) = builder.add(&dockerignore_path) {
        return Err(SandboxImageBuildError::other(format!(
            "failed to parse {}: {}",
            dockerignore_path.display(),
            error
        )));
    }
    builder
        .build()
        .map(Some)
        .map_err(|error| SandboxImageBuildError::other(error.to_string()))
}

fn collect_dir_files_filtered(
    root: &Path,
    current: &Path,
    dockerignore: Option<&Gitignore>,
    files: &mut Vec<(PathBuf, String)>,
) -> Result<()> {
    for entry in std::fs::read_dir(current)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            if is_dockerignored(root, &path, true, dockerignore) {
                continue;
            }
            collect_dir_files_filtered(root, &path, dockerignore, files)?;
        } else if path.is_file() {
            if is_dockerignored(root, &path, false, dockerignore) {
                continue;
            }
            let relative = path
                .strip_prefix(root)
                .map_err(|error| SandboxImageBuildError::other(error.to_string()))?;
            let relative = relative
                .components()
                .map(|component| component.as_os_str().to_string_lossy())
                .collect::<Vec<_>>()
                .join("/");
            files.push((path, relative));
        }
    }
    Ok(())
}

fn is_dockerignored(
    root: &Path,
    path: &Path,
    is_dir: bool,
    dockerignore: Option<&Gitignore>,
) -> bool {
    let Some(dockerignore) = dockerignore else {
        return false;
    };
    let Ok(relative) = path.strip_prefix(root) else {
        return false;
    };
    if relative.as_os_str().is_empty() {
        return false;
    }
    dockerignore.matched(relative, is_dir).is_ignore()
}

#[cfg(test)]
mod tests {

    #[test]
    fn build_failed_error_names_the_builder_sandbox_and_build() {
        let error = super::SandboxImageBuildError::BuildFailed {
            builder_sandbox_id: "rtmmkcw33uvsbep6hn03u".to_string(),
            build_id: "sandbox_template_build_123".to_string(),
            source: Box::new(super::SandboxImageBuildError::Other(
                "rootfs builder exited with status 1".to_string(),
            )),
        };
        let message = error.to_string();
        assert!(message.contains("builder sandbox: rtmmkcw33uvsbep6hn03u"));
        assert!(message.contains("build: sandbox_template_build_123"));
        assert!(message.contains("rootfs builder exited with status 1"));
    }
    use super::{
        BuilderFailureDiagnostics, CompleteSandboxTemplateBuildRequest, PreparedRootfsBuilder,
        PreparedRootfsParent, PreparedSandboxTemplateBuild, SandboxImageBuildError,
        SandboxImageBuildEvent, build_rootfs_spec, collect_dir_files,
        complete_request_from_metadata, contains_disk_space_evidence, contains_oom_killer_evidence,
        default_registered_name, load_dockerfile_plan, load_dockerfile_text_plan,
        logical_dockerfile_lines, normalize_posix, parse_df_line_usage_percent,
        parse_df_max_usage_percent, process_terminal_status, rootfs_builder_env,
        rootfs_builder_executable, rootfs_disk_bytes, rootfs_disk_bytes_to_mb,
        splice_signed_upload, streaming_process_payload,
    };
    use crate::sandboxes::models::ProcessInfo;
    use serde_json::{Value, json};
    use std::io::Write;

    #[test]
    fn oom_dmesg_parser_detects_kernel_oom_entries() {
        assert!(contains_oom_killer_evidence(
            "[ 123.4] Out of memory: Killed process 99 (python) total-vm:1234kB"
        ));
        assert!(contains_oom_killer_evidence(
            "memory: oom-kill:constraint=CONSTRAINT_MEMCG,nodemask=(null)"
        ));
        assert!(contains_oom_killer_evidence(
            "Killed process 42 (cc1plus), UID 0, total-vm:1234kB"
        ));
    }

    #[test]
    fn oom_dmesg_parser_ignores_unrelated_entries() {
        assert!(!contains_oom_killer_evidence(
            "[ 123.4] eth0: link becomes ready\n[ 124.0] EXT4-fs mounted"
        ));
    }

    #[test]
    fn df_parser_extracts_usage_percent() {
        assert_eq!(
            parse_df_line_usage_percent("/dev/vda1 10485760 9961472 524288 95% /"),
            Some(95)
        );
        assert_eq!(
            parse_df_line_usage_percent(
                "Filesystem 1024-blocks Used Available Capacity Mounted on"
            ),
            None
        );
    }

    #[test]
    fn df_parser_returns_max_usage_across_multiple_filesystems() {
        let output = "\
Filesystem 1024-blocks Used Available Capacity Mounted on
/dev/vda1 10485760 5242880 5242880 50% /
Filesystem 1024-blocks Used Available Capacity Mounted on
/dev/vdb1 10485760 10066329 419431 96% /var/lib/docker
";
        assert_eq!(parse_df_max_usage_percent(output), Some(96));
    }

    #[test]
    fn disk_space_parser_detects_enospc_and_no_space_output() {
        assert!(contains_disk_space_evidence(
            "fallocate: fallocate failed: No space left on device"
        ));
        assert!(contains_disk_space_evidence(
            "failed to write layer: ENOSPC"
        ));
        assert!(!contains_disk_space_evidence(
            "rootfs builder exited with status 1"
        ));
    }

    #[test]
    fn diagnostics_observe_disk_space_build_log_events() {
        let mut diagnostics = BuilderFailureDiagnostics::default();
        diagnostics.observe_build_event(&SandboxImageBuildEvent::BuildLog {
            stream: "stderr".to_string(),
            message: "dd: error writing '/tmp/fill': No space left on device".to_string(),
        });

        assert!(diagnostics.disk_error_output);
        assert!(
            diagnostics
                .advice_messages()
                .iter()
                .any(|message| message.contains("larger `builder_disk_mb`"))
        );
    }

    #[test]
    fn diagnostics_advice_uses_thresholds() {
        assert!(
            BuilderFailureDiagnostics {
                oom_killed: false,
                disk_usage_percent: Some(94),
                disk_error_output: false,
            }
            .advice_messages()
            .is_empty()
        );

        let messages = BuilderFailureDiagnostics {
            oom_killed: true,
            disk_usage_percent: Some(95),
            disk_error_output: false,
        }
        .advice_messages();
        assert_eq!(messages.len(), 2);
        assert!(messages[0].contains("larger `memory_mb`"));
        assert!(messages[1].contains("larger `builder_disk_mb`"));
        assert!(messages[1].contains("--builder_disk_mb"));

        let messages = BuilderFailureDiagnostics {
            oom_killed: false,
            disk_usage_percent: Some(10),
            disk_error_output: true,
        }
        .advice_messages();
        assert_eq!(messages.len(), 1);
        assert!(messages[0].contains("larger `builder_disk_mb`"));
    }

    #[test]
    fn diagnostic_error_wrapper_preserves_source_message() {
        let error = SandboxImageBuildError::WithDiagnostics {
            source: Box::new(SandboxImageBuildError::Other(
                "rootfs builder exited with status 1".to_string(),
            )),
            messages: BuilderFailureDiagnostics {
                oom_killed: true,
                disk_usage_percent: Some(99),
                disk_error_output: false,
            }
            .advice_messages()
            .join("\n"),
        };
        let message = error.to_string();
        assert!(message.contains("rootfs builder exited with status 1"));
        assert!(message.contains("The builder sandbox ran out of memory"));
        assert!(message.contains("The builder sandbox ran out of disk space"));
    }

    #[test]
    fn default_registered_name_uses_parent_for_dockerfile() {
        let path = std::path::Path::new("/tmp/example/Dockerfile");
        assert_eq!(default_registered_name(path), "example");
    }

    #[test]
    fn logical_dockerfile_lines_collapses_continuations() {
        let lines = logical_dockerfile_lines("FROM ubuntu\nRUN echo one \\\n  && echo two\n");
        assert_eq!(
            lines,
            vec![
                (1, "FROM ubuntu".to_string()),
                (2, "RUN echo one && echo two".to_string())
            ]
        );
    }

    #[test]
    fn plan_image_import_synthesizes_from_and_marks_import() {
        let plan = super::plan_image_import("ubuntu:24.04", None).unwrap();
        assert_eq!(plan.dockerfile_text, "FROM ubuntu:24.04\n");
        assert_eq!(plan.base_image, "ubuntu:24.04");
        assert_eq!(plan.import_image_reference.as_deref(), Some("ubuntu:24.04"));
        assert!(plan.additional_image_references.is_empty());
        // Last path segment with the tag stripped.
        assert_eq!(plan.registered_name, "ubuntu");
    }

    #[test]
    fn plan_image_import_honors_explicit_name_and_rejects_empty() {
        let plan = super::plan_image_import("ghcr.io/org/app:v1", Some("my-image")).unwrap();
        assert_eq!(plan.registered_name, "my-image");
        assert!(super::plan_image_import("   ", None).is_err());
    }

    #[test]
    fn default_registered_name_from_image_strips_path_tag_and_digest() {
        assert_eq!(
            super::default_registered_name_from_image("pytorch/pytorch:2.4.1-runtime"),
            "pytorch"
        );
        assert_eq!(
            super::default_registered_name_from_image(&format!(
                "ghcr.io/org/app@sha256:{}",
                "a".repeat(64)
            )),
            "app"
        );
        assert_eq!(
            super::default_registered_name_from_image("ubuntu"),
            "ubuntu"
        );
    }

    #[test]
    fn build_rootfs_spec_sets_import_reference_for_import_plans() {
        let prepared_spec = json!({});
        let prepared: super::PreparedSandboxTemplateBuild = serde_json::from_value(json!({
            "buildId": "build-1",
            "snapshotId": "snap-1",
            "snapshotUri": "s3://bucket/snap-1",
            "rootfsNodeKind": "base",
            "builder": {
                "image": "tensorlake/rootfs-builder",
                "command": "tl-rootfs-build",
                "cpus": 2.0,
                "memoryMb": 2048,
                "diskMb": 20480
            },
            "parent": null
        }))
        .unwrap();
        let plan = super::plan_image_import("ubuntu:24.04", None).unwrap();

        let spec =
            super::build_rootfs_spec(&prepared_spec, &prepared, &plan, Some(10240), None, false)
                .unwrap();
        assert_eq!(spec["importImageReference"], "ubuntu:24.04");
        assert_eq!(spec["baseImage"], "ubuntu:24.04");
        assert_eq!(spec["dockerfile"], "FROM ubuntu:24.04\n");
        assert!(spec.get("dockerCompat").is_none());
    }

    #[test]
    fn load_dockerfile_plan_reads_base_image_and_name() {
        let temp_dir = tempfile::tempdir().unwrap();
        let dockerfile_path = temp_dir.path().join("Dockerfile");
        let mut file = std::fs::File::create(&dockerfile_path).unwrap();
        writeln!(file, "FROM python:3.12-slim\nWORKDIR /app\nRUN echo hi").unwrap();

        let plan = load_dockerfile_plan(&dockerfile_path, None).unwrap();
        assert_eq!(plan.base_image, "python:3.12-slim");
        assert_eq!(
            plan.registered_name,
            temp_dir.path().file_name().unwrap().to_string_lossy()
        );
        assert!(plan.ignored_instructions.is_empty());
    }

    #[test]
    fn load_dockerfile_plan_accepts_onbuild_and_shell() {
        // ONBUILD and SHELL are no longer rejected: they run during the build
        // but have no runtime effect, so they land in the ignored set alongside
        // EXPOSE/LABEL/etc. rather than failing the build.
        for instruction in ["ONBUILD RUN echo", "SHELL [\"/bin/bash\", \"-c\"]"] {
            let temp_dir = tempfile::tempdir().unwrap();
            let dockerfile_path = temp_dir.path().join("Dockerfile");
            std::fs::write(
                &dockerfile_path,
                format!("FROM python:3.12-slim\n{}\n", instruction),
            )
            .unwrap();

            let plan = load_dockerfile_plan(&dockerfile_path, None).unwrap();
            let keyword = instruction.split_whitespace().next().unwrap();
            let keywords: Vec<&str> = plan
                .ignored_instructions
                .iter()
                .map(|(_, kw)| kw.as_str())
                .collect();
            assert_eq!(
                keywords,
                vec![keyword],
                "instruction {instruction}: expected {keyword:?} in the ignored set",
            );
        }
    }

    #[test]
    fn load_dockerfile_plan_accepts_arg_at_top_level() {
        let temp_dir = tempfile::tempdir().unwrap();
        let dockerfile_path = temp_dir.path().join("Dockerfile");
        std::fs::write(
            &dockerfile_path,
            "ARG PY_TAG=3.12-slim\nFROM python:${PY_TAG}\nRUN echo hi\n",
        )
        .unwrap();

        // ARG no longer rejects the build; the variable-bearing FROM is
        // recorded for the warning channel and the lookup is skipped.
        let plan = load_dockerfile_plan(&dockerfile_path, None).unwrap();
        assert_eq!(plan.base_image, "python:${PY_TAG}");
        assert_eq!(plan.unresolvable_image_references.len(), 1);
        assert!(matches!(
            plan.unresolvable_image_references[0].reason,
            super::UnresolvableImageReferenceReason::BuildArgExpansion
        ));
    }

    #[test]
    fn load_dockerfile_plan_warns_on_digest_pinned_from() {
        let temp_dir = tempfile::tempdir().unwrap();
        let dockerfile_path = temp_dir.path().join("Dockerfile");
        std::fs::write(
            &dockerfile_path,
            "FROM python:3.12-slim@sha256:abc\nRUN echo hi\n",
        )
        .unwrap();

        let plan = load_dockerfile_plan(&dockerfile_path, None).unwrap();
        assert_eq!(plan.base_image, "python:3.12-slim@sha256:abc");
        assert_eq!(plan.unresolvable_image_references.len(), 1);
        assert!(matches!(
            plan.unresolvable_image_references[0].reason,
            super::UnresolvableImageReferenceReason::DigestPin
        ));
    }

    #[test]
    fn load_dockerfile_plan_flags_final_from_stage_alias() {
        let temp_dir = tempfile::tempdir().unwrap();
        let dockerfile_path = temp_dir.path().join("Dockerfile");
        std::fs::write(
            &dockerfile_path,
            "FROM ubuntu:24.04 AS base\nRUN make\nFROM base\nRUN ls\n",
        )
        .unwrap();

        let plan = load_dockerfile_plan(&dockerfile_path, None).unwrap();
        // The final FROM is `FROM base`, an internal alias — flagged so
        // it is not looked up as an external template.
        assert_eq!(plan.base_image, "base");
        assert!(plan.base_image_is_internal_stage);
        assert_eq!(plan.additional_image_references, vec!["ubuntu:24.04"]);
    }

    #[test]
    fn load_dockerfile_plan_collects_ignored_instructions() {
        let temp_dir = tempfile::tempdir().unwrap();
        let dockerfile_path = temp_dir.path().join("Dockerfile");
        std::fs::write(
            &dockerfile_path,
            "FROM python:3.12-slim\n\
             ONBUILD RUN echo build\n\
             SHELL [\"/bin/bash\", \"-c\"]\n\
             LABEL maintainer=alice\n\
             EXPOSE 8080\n\
             HEALTHCHECK CMD echo ok\n\
             STOPSIGNAL SIGTERM\n\
             VOLUME /data\n\
             RUN echo hi\n",
        )
        .unwrap();

        let plan = load_dockerfile_plan(&dockerfile_path, None).unwrap();
        let keywords: Vec<&str> = plan
            .ignored_instructions
            .iter()
            .map(|(_, kw)| kw.as_str())
            .collect();
        assert_eq!(
            keywords,
            vec![
                "ONBUILD",
                "SHELL",
                "LABEL",
                "EXPOSE",
                "HEALTHCHECK",
                "STOPSIGNAL",
                "VOLUME",
            ]
        );
        // Dockerfile text is preserved verbatim so the rootfs builder still
        // sees the same instructions.
        assert!(plan.dockerfile_text.contains("EXPOSE 8080"));
    }

    #[test]
    fn load_dockerfile_plan_accepts_user_cmd_entrypoint() {
        let temp_dir = tempfile::tempdir().unwrap();
        let dockerfile_path = temp_dir.path().join("Dockerfile");
        std::fs::write(
            &dockerfile_path,
            "FROM python:3.12-slim\n\
             USER app\n\
             CMD [\"python\", \"-m\", \"http.server\"]\n\
             ENTRYPOINT [\"/usr/bin/env\"]\n\
             RUN echo hi\n",
        )
        .unwrap();

        // USER, CMD, and ENTRYPOINT are now supported: the plan loads without
        // error and none of them land in the ignored set.
        let plan = load_dockerfile_plan(&dockerfile_path, None).unwrap();
        let keywords: Vec<&str> = plan
            .ignored_instructions
            .iter()
            .map(|(_, kw)| kw.as_str())
            .collect();
        assert!(
            keywords.is_empty(),
            "expected no ignored instructions, got {keywords:?}",
        );
    }

    #[test]
    fn load_dockerfile_plan_accepts_multistage_builds() {
        let temp_dir = tempfile::tempdir().unwrap();
        let dockerfile_path = temp_dir.path().join("Dockerfile");
        std::fs::write(
            &dockerfile_path,
            "FROM ubuntu:24.04 AS build\n\
             RUN make\n\
             FROM python:3.12-slim\n\
             COPY --from=build /artifact /artifact\n",
        )
        .unwrap();

        let plan = load_dockerfile_plan(&dockerfile_path, None).unwrap();
        assert_eq!(plan.base_image, "python:3.12-slim");
        assert_eq!(plan.additional_image_references, vec!["ubuntu:24.04"]);
    }

    #[test]
    fn load_dockerfile_plan_collects_copy_from_image_references() {
        let temp_dir = tempfile::tempdir().unwrap();
        let dockerfile_path = temp_dir.path().join("Dockerfile");
        std::fs::write(
            &dockerfile_path,
            "FROM python:3.12-slim\n\
             COPY --from=tensorlake/utility:1.0 /bin/foo /usr/local/bin/foo\n\
             COPY src/ /app/\n",
        )
        .unwrap();

        let plan = load_dockerfile_plan(&dockerfile_path, None).unwrap();
        assert_eq!(plan.base_image, "python:3.12-slim");
        assert_eq!(
            plan.additional_image_references,
            vec!["tensorlake/utility:1.0"]
        );
    }

    #[test]
    fn load_dockerfile_plan_treats_copy_from_stage_as_internal() {
        let temp_dir = tempfile::tempdir().unwrap();
        let dockerfile_path = temp_dir.path().join("Dockerfile");
        std::fs::write(
            &dockerfile_path,
            "FROM ubuntu:24.04 AS build\n\
             FROM python:3.12-slim\n\
             COPY --from=build /artifact /artifact\n",
        )
        .unwrap();

        let plan = load_dockerfile_plan(&dockerfile_path, None).unwrap();
        // `build` matches an earlier stage alias, so the COPY --from is
        // internal; only the demoted earlier-FROM ends up in the additional
        // references list.
        assert_eq!(plan.base_image, "python:3.12-slim");
        assert_eq!(plan.additional_image_references, vec!["ubuntu:24.04"]);
    }

    #[test]
    fn load_dockerfile_plan_dedupes_image_references_across_stages() {
        let temp_dir = tempfile::tempdir().unwrap();
        let dockerfile_path = temp_dir.path().join("Dockerfile");
        std::fs::write(
            &dockerfile_path,
            "FROM python:3.12-slim AS prep\n\
             FROM python:3.12-slim\n\
             COPY --from=python:3.12-slim /tmp/x /tmp/x\n",
        )
        .unwrap();

        let plan = load_dockerfile_plan(&dockerfile_path, None).unwrap();
        // The first FROM and the COPY --from both reference the same image
        // as the final-stage FROM, so additional_image_references is empty.
        assert_eq!(plan.base_image, "python:3.12-slim");
        assert!(
            plan.additional_image_references.is_empty(),
            "got {:?}",
            plan.additional_image_references
        );
    }

    #[test]
    fn load_dockerfile_text_plan_uses_explicit_context_without_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        let context_dir = temp_dir.path().join("context");
        std::fs::create_dir(&context_dir).unwrap();
        let dockerfile_path = context_dir.join("Dockerfile.generated");

        let plan = load_dockerfile_text_plan(
            &dockerfile_path,
            Some(&context_dir),
            "FROM python:3.12-slim\nRUN echo hi\n".to_string(),
            Some("generated"),
        )
        .unwrap();

        assert_eq!(plan.context_dir, context_dir);
        assert_eq!(plan.base_image, "python:3.12-slim");
        assert_eq!(plan.registered_name, "generated");
    }

    #[test]
    fn rootfs_disk_bytes_uses_default_and_validates_overflow() {
        let mut base = prepared_build("base");
        base.parent = None;
        let diff = prepared_build("diff");

        assert_eq!(
            rootfs_disk_bytes(None, &base).unwrap(),
            10 * 1024 * 1024 * 1024
        );
        assert_eq!(
            rootfs_disk_bytes(None, &diff).unwrap(),
            20 * 1024 * 1024 * 1024
        );
        assert_eq!(
            rootfs_disk_bytes(Some(2048), &diff).unwrap(),
            2048 * 1024 * 1024
        );
        assert!(rootfs_disk_bytes(Some(u64::MAX), &base).is_err());
    }

    #[test]
    fn rootfs_disk_bytes_requires_parent_size_for_diff_default() {
        let mut prepared = prepared_build("diff");
        prepared.parent.as_mut().unwrap().rootfs_disk_bytes = None;

        let error = rootfs_disk_bytes(None, &prepared).unwrap_err();
        assert!(
            error.to_string().contains("parent rootfsDiskBytes"),
            "{error}"
        );
    }

    #[test]
    fn rootfs_disk_bytes_to_mb_rounds_up() {
        assert_eq!(rootfs_disk_bytes_to_mb(1024 * 1024).unwrap(), 1);
        assert_eq!(rootfs_disk_bytes_to_mb((1024 * 1024) + 1).unwrap(), 2);
    }

    #[test]
    fn prepared_deserializes_snapshot_rel_path() {
        let with_rel_path: PreparedSandboxTemplateBuild = serde_json::from_value(json!({
            "buildId": "build-1",
            "snapshotId": "snapshot-1",
            "snapshotUri": "s3://bucket/snapshot.tlsnap",
            "snapshotRelPath": "snapshots/abc.tlsnap",
            "rootfsNodeKind": "base",
            "builder": {
                "image": "tensorlake/rootfs-builder",
                "command": "tl-rootfs-build",
                "cpus": 2,
                "memoryMb": 4096,
                "diskMb": 30720
            }
        }))
        .unwrap();
        assert_eq!(
            with_rel_path.snapshot_rel_path.as_deref(),
            Some("snapshots/abc.tlsnap")
        );

        // Legacy-shape fixture (no snapshotRelPath) must still deserialize
        // and default to None — that's how the CLI tells the two paths
        // apart at runtime.
        let without_rel_path: PreparedSandboxTemplateBuild = serde_json::from_value(json!({
            "buildId": "build-1",
            "snapshotId": "snapshot-1",
            "snapshotUri": "s3://bucket/snapshot.tlsnap",
            "rootfsNodeKind": "base",
            "builder": {
                "image": "tensorlake/rootfs-builder",
                "command": "tl-rootfs-build",
                "cpus": 2,
                "memoryMb": 4096,
                "diskMb": 30720
            }
        }))
        .unwrap();
        assert!(without_rel_path.snapshot_rel_path.is_none());
        assert_eq!(
            without_rel_path.snapshot_uri.as_deref(),
            Some("s3://bucket/snapshot.tlsnap")
        );
    }

    #[test]
    fn prepared_deserializes_without_snapshot_uri() {
        // Forward-compat with platform-api dropping `snapshotUri` once the
        // versioned-response rollout finishes: the CLI must still accept
        // the response and fill the final URI from dataplane signing.
        let prepared: PreparedSandboxTemplateBuild = serde_json::from_value(json!({
            "buildId": "build-1",
            "snapshotId": "snapshot-1",
            "snapshotRelPath": "snapshots/abc.tlsnap",
            "rootfsNodeKind": "base",
            "builder": {
                "image": "tensorlake/rootfs-builder",
                "command": "tl-rootfs-build",
                "cpus": 2,
                "memoryMb": 4096,
                "diskMb": 30720
            }
        }))
        .unwrap();
        assert!(prepared.snapshot_uri.is_none());
        assert_eq!(
            prepared.snapshot_rel_path.as_deref(),
            Some("snapshots/abc.tlsnap")
        );
    }

    #[test]
    fn build_rootfs_spec_adds_builder_inputs() {
        let prepared_spec = json!({
            "buildId": "build-1",
            "snapshotId": "snapshot-1",
            "snapshotUri": "s3://bucket/snapshot.tlsnap",
            "rootfsNodeKind": "base",
            "builder": {
                "image": "tensorlake/rootfs-builder",
                "command": "tl-rootfs-build",
                "cpus": 2,
                "memoryMb": 4096,
                "diskMb": 30720
            },
            "upload": {
                "kind": "single_put",
                "method": "PUT",
                "url": "https://example/upload",
                "headers": {},
                "expiresAt": "2026-05-12T00:00:00Z"
            },
            "runtimeContract": {
                "guestRuntimeLayout": "embedded",
                "guestRuntimeDriveFormat": "none",
                "guestBootContract": "supervisor-init-wrapper-v1"
            }
        });
        let prepared: PreparedSandboxTemplateBuild =
            serde_json::from_value(prepared_spec.clone()).unwrap();
        let plan = super::DockerfileBuildPlan {
            context_dir: "/tmp/context".into(),
            registered_name: "child".to_string(),
            dockerfile_text: "FROM alpine\nRUN echo hi\n".to_string(),
            base_image: "alpine".to_string(),
            additional_image_references: Vec::new(),
            base_image_is_internal_stage: false,
            unresolvable_image_references: Vec::new(),
            ignored_instructions: Vec::new(),
            import_image_reference: None,
        };

        let spec = build_rootfs_spec(
            &prepared_spec,
            &prepared,
            &plan,
            Some(2048),
            Some("{}".to_string()),
            true,
        )
        .unwrap();
        assert_eq!(spec["dockerfile"], "FROM alpine\nRUN echo hi\n");
        assert_eq!(
            spec["contextDir"],
            "/var/lib/tensorlake/rootfs-builder/build/context"
        );
        assert_eq!(spec["rootfsDiskBytes"], 2048_u64 * 1024 * 1024);
        assert_eq!(spec["dockerConfigJson"], "{}");
        assert_eq!(spec["dockerCompat"], true);
    }

    #[test]
    fn build_rootfs_spec_defaults_diff_to_parent_rootfs_size() {
        let prepared = prepared_build("diff");
        let prepared_spec = serde_json::to_value(&prepared).unwrap();
        let plan = super::DockerfileBuildPlan {
            context_dir: "/tmp/context".into(),
            registered_name: "child".to_string(),
            dockerfile_text: "FROM parent\nRUN echo hi\n".to_string(),
            base_image: "parent".to_string(),
            additional_image_references: Vec::new(),
            base_image_is_internal_stage: false,
            unresolvable_image_references: Vec::new(),
            ignored_instructions: Vec::new(),
            import_image_reference: None,
        };

        let spec = build_rootfs_spec(&prepared_spec, &prepared, &plan, None, None, false).unwrap();
        assert_eq!(spec["rootfsDiskBytes"], 20_u64 * 1024 * 1024 * 1024);
        assert!(spec.get("dockerCompat").is_none());
    }

    #[test]
    fn splice_signed_upload_uses_dataplane_uri_for_snapshot_uri() {
        let mut prepared_spec = json!({
            "buildId": "build-1",
            "snapshotId": "snapshot-1",
            "snapshotUri": "s3://platform/stale.tlsnap",
            "rootfsNodeKind": "base",
        });
        let signed_upload = json!({
            "kind": "s3_multipart",
            "uri": "s3://dataplane/final.tlsnap",
            "uploadId": "upload-1",
            "partSizeBytes": 67_108_864,
            "partUrls": []
        });

        let snapshot_uri = splice_signed_upload(&mut prepared_spec, signed_upload).unwrap();

        assert_eq!(snapshot_uri, "s3://dataplane/final.tlsnap");
        assert_eq!(prepared_spec["snapshotUri"], "s3://dataplane/final.tlsnap");
        assert_eq!(
            prepared_spec["upload"]["uri"],
            "s3://dataplane/final.tlsnap"
        );
        assert_eq!(prepared_spec["upload"]["uploadId"], "upload-1");
    }

    #[test]
    fn splice_signed_upload_requires_dataplane_uri() {
        let mut prepared_spec = json!({
            "buildId": "build-1",
            "snapshotId": "snapshot-1",
            "rootfsNodeKind": "base",
        });
        let signed_upload = json!({
            "kind": "s3_multipart",
            "uploadId": "upload-1",
            "partSizeBytes": 67_108_864,
            "partUrls": []
        });

        let error = splice_signed_upload(&mut prepared_spec, signed_upload).unwrap_err();
        assert!(
            error.to_string().contains("missing uri"),
            "expected signed upload uri error, got: {error}"
        );
    }

    #[test]
    fn rootfs_builder_command_uses_installed_path_and_tool_path() {
        assert_eq!(
            rootfs_builder_executable("tl-rootfs-build"),
            "/usr/local/bin/tl-rootfs-build"
        );
        assert_eq!(
            rootfs_builder_executable("/custom/tl-rootfs-build"),
            "/custom/tl-rootfs-build"
        );

        let env = rootfs_builder_env();
        assert_eq!(
            env.get("PATH").and_then(Value::as_str),
            Some("/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin")
        );
    }

    #[test]
    fn streaming_process_payload_runs_as_root_when_requested() {
        let payload = streaming_process_payload(
            "tl-rootfs-build",
            vec!["--spec".to_string(), "/tmp/spec.json".to_string()],
            None,
            None,
            true,
        );

        assert_eq!(payload["command"], "tl-rootfs-build");
        assert_eq!(payload["user"], "root");
    }

    #[test]
    fn streaming_process_payload_omits_user_when_not_root() {
        // Upload-prep helpers (mkdir, /bin/true) must NOT request root,
        // otherwise the container-daemon's file API — which writes with the
        // sandbox user's fsuid — can't create temp files inside the resulting
        // root-owned directories. The absence of a `user` field lets the
        // daemon fall back to its default (sandbox user) so the dir and the
        // subsequent uploads share the same fsuid.
        let payload = streaming_process_payload(
            "mkdir",
            vec![
                "-p".to_string(),
                "/var/lib/tensorlake/rootfs-builder".to_string(),
            ],
            None,
            None,
            false,
        );

        assert_eq!(payload["command"], "mkdir");
        assert!(
            payload.get("user").is_none(),
            "non-root callers must not pin a user; got {:?}",
            payload.get("user")
        );
    }

    #[test]
    fn complete_request_maps_snapshotter_metadata_to_platform_api_shape() {
        let prepared = prepared_build("diff");
        let metadata = json!({
            "snapshot_id": "snapshot-1",
            "snapshot_uri": "s3://bucket/child.tlsnap",
            "snapshot_format_version": "durable_archive_v1",
            "snapshot_size_bytes": 1234,
            "rootfs_disk_bytes": 10 * 1024 * 1024 * 1024_u64,
            "rootfs_node_kind": "diff",
            "parent_manifest_uri": "s3://bucket/parent.tlsnap"
        });

        let request = complete_request_from_metadata(&prepared, &metadata, None).unwrap();
        let body = serde_json::to_value(&request).unwrap();
        assert_eq!(body["snapshotId"], "snapshot-1");
        assert_eq!(body["snapshotUri"], "s3://bucket/child.tlsnap");
        assert_eq!(body["snapshotFormatVersion"], "durable_archive_v1");
        assert_eq!(body["snapshotSizeBytes"], 1234);
        assert_eq!(body["rootfsNodeKind"], "diff");
        assert_eq!(body["parentManifestUri"], "s3://bucket/parent.tlsnap");
    }

    #[test]
    fn complete_request_uses_signed_uri_when_provided() {
        let mut prepared = prepared_build("base");
        prepared.parent = None;
        prepared.snapshot_uri = None;
        let metadata = json!({
            "snapshot_uri": "s3://bucket/from-signed.tlsnap",
            "snapshot_format_version": "durable_archive_v1",
            "snapshot_size_bytes": 1234,
            "rootfs_disk_bytes": 10 * 1024 * 1024 * 1024_u64
        });

        let request = complete_request_from_metadata(
            &prepared,
            &metadata,
            Some("s3://bucket/from-signed.tlsnap"),
        )
        .unwrap();
        assert_eq!(request.snapshot_uri, "s3://bucket/from-signed.tlsnap");
    }

    #[test]
    fn complete_request_uses_signed_uri_when_metadata_omits_snapshot_uri() {
        let mut prepared = prepared_build("base");
        prepared.parent = None;
        prepared.snapshot_uri = Some("s3://bucket/stale-prepared.tlsnap".to_string());
        let metadata = json!({
            "snapshot_format_version": "durable_archive_v1",
            "snapshot_size_bytes": 1234,
            "rootfs_disk_bytes": 10 * 1024 * 1024 * 1024_u64
        });

        let request = complete_request_from_metadata(
            &prepared,
            &metadata,
            Some("s3://bucket/from-signed.tlsnap"),
        )
        .unwrap();
        assert_eq!(request.snapshot_uri, "s3://bucket/from-signed.tlsnap");
    }

    #[test]
    fn complete_request_rejects_metadata_uri_mismatch_when_signed_uri_provided() {
        let mut prepared = prepared_build("base");
        prepared.parent = None;
        prepared.snapshot_uri = None;
        let metadata = json!({
            "snapshot_uri": "s3://bucket/from-metadata.tlsnap",
            "snapshot_format_version": "durable_archive_v1",
            "snapshot_size_bytes": 1234,
            "rootfs_disk_bytes": 10 * 1024 * 1024 * 1024_u64
        });

        let error = complete_request_from_metadata(
            &prepared,
            &metadata,
            Some("s3://bucket/from-signed.tlsnap"),
        )
        .unwrap_err();
        assert!(
            error
                .to_string()
                .contains("did not match dataplane signed uri"),
            "expected signed URI mismatch error, got: {error}"
        );
    }

    #[test]
    fn complete_request_errors_when_snapshot_uri_missing_from_both_sources() {
        let mut prepared = prepared_build("base");
        prepared.parent = None;
        prepared.snapshot_uri = None;
        let metadata = json!({
            "snapshot_format_version": "durable_archive_v1",
            "snapshot_size_bytes": 1234,
            "rootfs_disk_bytes": 10 * 1024 * 1024 * 1024_u64
        });

        let error = complete_request_from_metadata(&prepared, &metadata, None).unwrap_err();
        assert!(
            error.to_string().contains("snapshot_uri"),
            "expected snapshot_uri error, got: {error}"
        );
    }

    #[test]
    fn complete_request_uses_prepared_parent_for_diff_when_metadata_omits_it() {
        let prepared = prepared_build("diff");
        let metadata = json!({
            "snapshot_format_version": "durable_archive_v1",
            "snapshot_size_bytes": "1234",
            "rootfs_disk_bytes": 10 * 1024 * 1024 * 1024_u64
        });

        let request = complete_request_from_metadata(&prepared, &metadata, None).unwrap();
        assert_eq!(request.snapshot_id, "snapshot-prepared");
        assert_eq!(request.snapshot_uri, "s3://bucket/prepared.tlsnap");
        assert_eq!(
            request.parent_manifest_uri.as_deref(),
            Some("s3://bucket/parent.tlsnap")
        );
    }

    #[test]
    fn normalize_posix_collapses_dot_segments() {
        assert_eq!(normalize_posix("/a//b/../c"), "/a/c");
    }

    #[test]
    fn collect_dir_files_honors_dockerignore() {
        let temp_dir = tempfile::tempdir().unwrap();
        let root = temp_dir.path();
        std::fs::write(root.join(".dockerignore"), "ignored.txt\ncache/drop.txt\n").unwrap();
        std::fs::write(root.join("included.txt"), "included").unwrap();
        std::fs::write(root.join("ignored.txt"), "ignored").unwrap();
        std::fs::create_dir(root.join("cache")).unwrap();
        std::fs::write(root.join("cache/drop.txt"), "drop").unwrap();
        std::fs::write(root.join("cache/keep.txt"), "keep").unwrap();

        let mut files = collect_dir_files(root, root)
            .unwrap()
            .into_iter()
            .map(|(_, relative)| relative)
            .collect::<Vec<_>>();
        files.sort();

        assert_eq!(
            files,
            vec![".dockerignore", "cache/keep.txt", "included.txt"]
        );
    }

    #[test]
    fn process_terminal_status_detects_oom_killed_process() {
        let info = ProcessInfo {
            handle: Some(1),
            pid: 42,
            status: "oom_killed".to_string(),
            exit_code: None,
            signal: Some(9),
            oom_killed: true,
            stdin_writable: false,
            command: "/usr/local/bin/tl-rootfs-build".to_string(),
            args: Vec::new(),
            started_at: json!(123),
            ended_at: Some(json!(456)),
            managed: None,
        };

        let status = process_terminal_status(&info).unwrap();
        assert_eq!(status.code, -9);
        assert!(status.oom_killed);
    }

    fn prepared_build(rootfs_node_kind: &str) -> PreparedSandboxTemplateBuild {
        PreparedSandboxTemplateBuild {
            build_id: "build-1".to_string(),
            snapshot_id: "snapshot-prepared".to_string(),
            snapshot_uri: Some("s3://bucket/prepared.tlsnap".to_string()),
            rootfs_node_kind: rootfs_node_kind.to_string(),
            builder: PreparedRootfsBuilder {
                image: "tensorlake/rootfs-builder".to_string(),
                command: "tl-rootfs-build".to_string(),
                cpus: 2.0,
                memory_mb: 4096,
                disk_mb: 30720,
            },
            parent: Some(PreparedRootfsParent {
                parent_manifest_uri: "s3://bucket/parent.tlsnap".to_string(),
                rootfs_disk_bytes: Some(20 * 1024 * 1024 * 1024),
            }),
            snapshot_rel_path: None,
        }
    }

    #[allow(dead_code)]
    fn assert_serialize(_: &CompleteSandboxTemplateBuildRequest, _: &Value) {}
}