monty-pool 1.5.0

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

mod binary;
mod common;

#[cfg(unix)]
use std::os::unix::fs::symlink;
#[cfg(windows)]
use std::os::windows::fs::symlink_dir;
#[cfg(target_os = "linux")]
use std::{env, ffi::OsStr, os::unix::ffi::OsStrExt};
use std::{
    fmt::Write as _,
    fs,
    future::ready,
    io,
    path::{Path, PathBuf},
    process::Command,
    thread,
    time::Duration,
};

use insta::assert_snapshot;
use monty_pool::{
    Checkout, DEFAULT_MAX_CHECKOUTS_PER_WORKER, MountSpec, MountSpecMode, Pool, PoolConfig, PoolError, PrintFuture,
    ReplConfig, ResumeValue, TurnEvent, on_print_sync,
};
// only the unix-gated raw-path test forges worker frames
#[cfg(unix)]
use monty_proto::{encode_framed_into, pb};
// only the off-Linux CPU rejection test names the clock; Linux CPU tests import their own
#[cfg(not(target_os = "linux"))]
use monty_types::ExecutionClock;
#[cfg(unix)]
use monty_types::SourceRange;
use monty_types::{
    CallArgs, DateTimeSource, ExcType, IMPORT_CALL, IMPORT_STUBS_CALL, ImportArgs, ModuleFile, ModuleRead,
    MontyException, MontyObject, MontyUuid, NameLookupResult, OsPolicy, PrintStream, RandomSeed, RandomStart,
    ResourceLimits, SleepMode, TypeCheckingConfig, TypeCheckingFormat,
    unstable::{self, MontyNode},
};
use tokio::time::sleep;
#[cfg(unix)]
use tokio::time::timeout;

use crate::{binary::monty_binary, common::wait_for_idle};

fn config() -> PoolConfig {
    PoolConfig::subprocess(monty_binary())
}

/// A discard-everything print callback, coercible to `OnPrint` at each callsite.
fn no_print(_: PrintStream, _: &str) -> PrintFuture {
    Box::pin(ready(()))
}

#[track_caller]
fn expect_complete(event: TurnEvent) -> MontyObject {
    match event {
        TurnEvent::Complete(value) => value,
        other => panic!("expected Complete, got {other:?}"),
    }
}

/// Drives a feed the way an auto-answering host does: every `OsCall` is offered
/// to the feed's mounts, returning the first event no mount covers.
///
/// Mount-covered calls surface like any other suspension now, so a test that
/// only cares about the *result* of mounted I/O runs its feed through this.
async fn feed_with_mounts(
    checkout: &mut Checkout,
    result: Result<TurnEvent, PoolError>,
) -> Result<TurnEvent, PoolError> {
    let event = result?;
    let mut event = event;
    loop {
        if !matches!(event, TurnEvent::OsCall { .. }) {
            return Ok(event);
        }
        match checkout.resume_from_mounts(&mut no_print).await? {
            Some(next) => event = next,
            None => return Ok(event),
        }
    }
}

/// Creates a directory symlink, reporting the failure a host without the
/// privilege gives so the caller can skip rather than fail.
fn try_symlink_dir(original: &Path, link: &Path) -> io::Result<()> {
    #[cfg(unix)]
    return symlink(original, link);
    #[cfg(windows)]
    return symlink_dir(original, link);
}

/// Kills a process by pid with SIGKILL — simulates a hard crash.
fn kill_pid(pid: u32) {
    #[cfg(unix)]
    {
        let status = Command::new("kill").args(["-9", &pid.to_string()]).status().unwrap();
        assert!(status.success());
    }
    #[cfg(windows)]
    {
        let status = Command::new("taskkill")
            .args(["/PID", &pid.to_string(), "/F"])
            .status()
            .unwrap();
        assert!(status.success());
    }
}

/// Writes the executable stand-in for `monty` that a test drives, from a child shell rather than
/// this process: a descriptor open for writing here would be inherited by any concurrently
/// forking test, and executing the file while that child still holds it fails with `ETXTBSY`.
#[cfg(unix)]
fn write_fake_monty(dir: &Path, script: &str) -> PathBuf {
    let fake = dir.join("monty");
    let status = Command::new("sh")
        .args(["-c", r#"printf '%s' "$2" > "$1" && chmod 755 "$1""#, "sh"])
        .arg(&fake)
        .arg(script)
        .status()
        .unwrap();
    assert!(status.success(), "writing the stand-in `monty` failed");
    fake
}

// =============================================================================
// Happy path
// =============================================================================

/// Rejected eager answers leave the checkout and worker at the same call.
#[tokio::test]
async fn allow_eager_await_validates_replies_before_sending() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let event = session
        .feed("await f()", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    let TurnEvent::FunctionCall {
        call_id,
        allow_eager_await,
        ..
    } = event
    else {
        panic!("expected function call, got {event:?}")
    };
    assert!(allow_eager_await);
    for results in [
        vec![],
        vec![(call_id + 1, ResumeValue::Return(MontyObject::int(42)))],
        vec![(call_id, ResumeValue::Future)],
        vec![(call_id, ResumeValue::NotFound)],
    ] {
        assert!(matches!(
            session.resume_futures(results, &mut no_print).await,
            Err(PoolError::Protocol(_))
        ));
    }
    let done = session
        .resume_futures(
            vec![(call_id, ResumeValue::Return(MontyObject::int(42)))],
            &mut no_print,
        )
        .await
        .unwrap();
    assert_eq!(expect_complete(done), MontyObject::int(42));
    session.finish().await.unwrap();
}

/// An over-threshold frame round-trips through `decode_event`'s
/// `block_in_place` branch (multi-thread runtime) without corruption.
#[tokio::test(flavor = "multi_thread")]
async fn large_value_roundtrips_through_offloaded_decode() {
    large_value_roundtrip().await;
}

/// The same roundtrip on a current-thread runtime, exercising the inline
/// fallback (`block_in_place` would panic there).
#[tokio::test]
async fn large_value_roundtrips_on_current_thread_runtime() {
    large_value_roundtrip().await;
}

/// Feeds a 2 MB string (over the offload threshold), then a small turn to
/// show the session stayed healthy.
async fn large_value_roundtrip() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let event = session
        .feed("'x' * 2_000_000", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::string("x".repeat(2_000_000)));
    let event = session
        .feed("1 + 1", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(2));
    session.finish().await.unwrap();
}

#[tokio::test]
async fn feed_and_finish_reuses_the_worker() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let first_pid = session.pid().unwrap();
    let first_id = session.worker_id().unwrap();

    let event = session
        .feed("x = 40\nx + 2", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(42));
    // session state persists across feeds on the same checkout
    let event = session
        .feed("x * 2", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(80));
    session.finish().await.unwrap();
    assert_eq!(pool.idle_workers(), 1);

    // the same process serves the next checkout, with a FRESH session:
    // `x` from the previous session must not leak, so reading it suspends
    // at NameLookup and resolving it as undefined raises NameError
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    assert_eq!(session.pid().unwrap(), first_pid);
    assert_eq!(session.worker_id(), Some(first_id));
    let event = session.feed("x", vec![], vec![], false, &mut no_print).await.unwrap();
    assert!(matches!(event, TurnEvent::NameLookup { name, .. } if name == "x"));
    let err = session
        .resume_name_lookup(NameLookupResult::Undefined, &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime, got {err:?}");
    };
    assert_eq!(exc.message(), Some("name 'x' is not defined"));
    session.finish().await.unwrap();
}

/// An `Error` answer to a name lookup is raised inside the sandbox — so the
/// snippet can catch it — and the session stays usable.
#[tokio::test]
async fn name_lookup_error_is_raised_in_the_sandbox() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let event = session
        .feed(
            "try:\n    secret\nexcept PermissionError as e:\n    caught = str(e)\ncaught",
            vec![],
            vec![],
            false,
            &mut no_print,
        )
        .await
        .unwrap();
    assert!(matches!(event, TurnEvent::NameLookup { ref name, .. } if name == "secret"));
    let error = MontyException::new(ExcType::PermissionError, Some("secret is off limits".to_owned()));
    let event = session.resume_name_lookup(error, &mut no_print).await.unwrap();
    assert_eq!(
        expect_complete(event),
        MontyObject::string("secret is off limits".to_owned())
    );
    // uncaught, the error ends the turn as a runtime error with a traceback
    let event = session
        .feed("secret", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert!(matches!(event, TurnEvent::NameLookup { ref name, .. } if name == "secret"));
    let error = MontyException::new(ExcType::PermissionError, Some("still off limits".to_owned()));
    let err = session.resume_name_lookup(error, &mut no_print).await.unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime, got {err:?}");
    };
    assert_eq!(exc.exc_type(), ExcType::PermissionError);
    assert_eq!(exc.message(), Some("still off limits"));
    assert!(
        !exc.traceback().is_empty(),
        "the sandbox frame must be on the traceback"
    );
    let event = session
        .feed("1 + 1", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(2));
    session.finish().await.unwrap();
}

#[tokio::test]
async fn cyclic_return_value_decodes_and_keeps_the_worker_alive() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    // a cyclic dict completes with a `Cycle` placeholder in the payload; the
    // parent must decode it rather than discarding the worker as misbehaving
    let event = session
        .feed("d = {}\nd['self'] = d\nd", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    let value = expect_complete(event);
    let Some(pairs) = value.as_ref().pairs() else {
        panic!("expected Dict");
    };
    assert_eq!(pairs.len(), 1);
    assert_eq!(pairs[0].0, MontyObject::string("self".to_owned()));
    assert!(matches!(unstable::node(pairs[0].1), MontyNode::Cycle(placeholder) if placeholder == "{...}"));
    // the session must still be usable on the same worker
    let event = session
        .feed("1 + 1", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(2));
    session.finish().await.unwrap();
    assert_eq!(pool.idle_workers(), 1);
}

/// The arena has no nesting bound: a lookup answer nested a hundred lists
/// deep crosses the wire and comes back the same shape.
#[tokio::test]
async fn deeply_nested_name_lookup_value_crosses_the_wire() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let event = session
        .feed("missing", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert!(matches!(event, TurnEvent::NameLookup { ref name, .. } if name == "missing"));
    let deep = (0..100).fold(MontyObject::int(1), |inner, _| MontyObject::list([inner]));
    let event = session
        .resume_name_lookup(Some(deep.clone()), &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), deep);
    session.finish().await.unwrap();
}

/// A mount whose host path is not valid UTF-8 works: host paths never cross
/// the wire (the parent services mount I/O itself), so the OS-native path is
/// used as-is. Linux-only: macOS (APFS) rejects non-UTF-8 filenames outright
/// and they cannot be constructed portably elsewhere.
#[cfg(target_os = "linux")]
#[tokio::test]
async fn non_utf8_mount_path_works() {
    let dir = tempfile::tempdir().unwrap();
    let weird_dir = dir.path().join(OsStr::from_bytes(b"weird-\xff"));
    fs::create_dir(&weird_dir).unwrap();
    fs::write(weird_dir.join("data.txt"), "non-utf8 host dir").unwrap();

    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let result = session
        .feed(
            "from pathlib import Path\nPath('/mnt/data/data.txt').read_text()",
            vec![],
            vec![MountSpec::new("/mnt/data", weird_dir, MountSpecMode::ReadOnly).unwrap()],
            false,
            &mut no_print,
        )
        .await;
    let event = feed_with_mounts(&mut session, result).await.unwrap();
    assert_eq!(
        expect_complete(event),
        MontyObject::string("non-utf8 host dir".to_owned())
    );
    session.finish().await.unwrap();
}

/// A mount whose host path does not exist is rejected where the directory is
/// opened — building the [`MountSpec`] — so no feed inherits the failure.
#[tokio::test]
async fn invalid_mount_host_path_is_rejected_cleanly() {
    let err = MountSpec::new(
        "/mnt/data",
        PathBuf::from("/nonexistent/monty/mount/dir"),
        MountSpecMode::ReadOnly,
    )
    .unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime, got {err:?}");
    };
    assert!(
        exc.message().is_some_and(|m| m.contains("cannot open host path")),
        "unexpected message: {:?}",
        exc.message()
    );

    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let event = session
        .feed("1 + 1", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(2));
    session.finish().await.unwrap();
}

/// The sandbox working directory is session state: the first feed sets it
/// (its first mount, else `/`), and later feeds keep it — `os.chdir`
/// included — unless `feed_with_cwd` switches it.
#[tokio::test]
async fn working_directory_persists_across_feeds() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("data.txt"), "relative!").unwrap();
    fs::create_dir(dir.path().join("sub")).unwrap();
    let mount = || vec![MountSpec::new("/mnt", dir.path(), MountSpecMode::ReadOnly).unwrap()];
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();

    // The first feed's mount, so relative paths reach into it; `__file__` is placed under it.
    let code = "\
import os
from pathlib import Path
before = (os.getcwd(), __file__, open('data.txt').read())
os.chdir('sub')
(before, Path.cwd(), Path('..').resolve())";
    let result = session.feed(code, vec![], mount(), false, &mut no_print).await;
    let event = feed_with_mounts(&mut session, result).await.unwrap();
    assert_eq!(
        expect_complete(event),
        MontyObject::tuple([
            MontyObject::tuple([
                MontyObject::string("/mnt".to_owned()),
                MontyObject::string("/mnt/main.py".to_owned()),
                MontyObject::string("relative!".to_owned()),
            ]),
            MontyObject::path("/mnt/sub".to_owned()),
            MontyObject::path("/mnt".to_owned()),
        ])
    );

    // The chdir persists, even into a feed without the mount.
    let event = session
        .feed("os.getcwd()", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::string("/mnt/sub".to_owned()));

    // An explicit cwd switches it, and the switch persists too.
    let result = session
        .feed_with_cwd("os.getcwd()", vec![], mount(), Some("/mnt/"), false, &mut no_print)
        .await;
    let event = feed_with_mounts(&mut session, result).await.unwrap();
    assert_eq!(expect_complete(event), MontyObject::string("/mnt".to_owned()));

    // A relative cwd is refused before anything is sent; the session survives unchanged.
    let err = session
        .feed_with_cwd("1", vec![], vec![], Some("data"), false, &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected a runtime error, got {err:?}");
    };
    assert_eq!(exc.exc_type(), ExcType::ValueError);
    assert_eq!(exc.message().unwrap(), "cwd must be an absolute POSIX path: \"data\"");
    let event = session
        .feed("os.getcwd()", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::string("/mnt".to_owned()));
    session.finish().await.unwrap();

    // A session whose first feed has no mount starts at the root and stays
    // there when a later feed mounts something.
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let event = session
        .feed(
            "import os\n(os.getcwd(), __file__)",
            vec![],
            vec![],
            false,
            &mut no_print,
        )
        .await
        .unwrap();
    assert_eq!(
        expect_complete(event),
        MontyObject::tuple([
            MontyObject::string("/".to_owned()),
            MontyObject::string("/main.py".to_owned())
        ])
    );
    let result = session.feed("os.getcwd()", vec![], mount(), false, &mut no_print).await;
    let event = feed_with_mounts(&mut session, result).await.unwrap();
    assert_eq!(expect_complete(event), MontyObject::string("/".to_owned()));
    session.finish().await.unwrap();
}

/// A host with no module of an import's name reads its candidate files from
/// the mounts without resuming the worker, then answers with the file found:
/// one `import` call per module, the working directory defaulting to the first mount.
#[tokio::test]
async fn a_module_file_in_a_mount_is_imported() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("helpers.py"), "def double(x):\n    return x * 2\n").unwrap();
    fs::create_dir(dir.path().join("pkg")).unwrap();
    fs::write(dir.path().join("pkg/__init__.py"), "").unwrap();
    fs::write(dir.path().join("pkg/sub.py"), "value = 3\n").unwrap();
    let mount = || vec![MountSpec::new("/mnt", dir.path(), MountSpecMode::ReadOnly).unwrap()];
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();

    let code = "import helpers\nfrom pkg.sub import value\n(helpers.double(value), helpers.__file__)";
    let mut event = session.feed(code, vec![], mount(), false, &mut no_print).await.unwrap();
    let mut asked = Vec::new();
    while matches!(&event, TurnEvent::OsCall { function_name, .. } if function_name == IMPORT_CALL) {
        let args = expect_import_args(event);
        let mut answer = ResumeValue::NotFound;
        for path in args.candidates() {
            if let ModuleRead::Text(source) = session.read_from_mounts(&path).await.unwrap() {
                answer = ResumeValue::ModuleFile(ModuleFile { path, source });
                break;
            }
        }
        asked.push((args.module, args.search_path));
        event = session.resume(answer, &mut no_print).await.unwrap();
    }
    let dirs = |dir: &str| vec![dir.to_owned()];
    assert_eq!(
        asked,
        [
            ("helpers".to_owned(), dirs("/mnt")),
            ("pkg".to_owned(), dirs("/mnt")),
            ("pkg.sub".to_owned(), dirs("/mnt/pkg")),
        ]
    );
    assert_eq!(
        expect_complete(event),
        MontyObject::tuple([MontyObject::int(6), MontyObject::string("/mnt/helpers.py".to_owned())])
    );
    // a mount read answers only a pending import
    let err = session.read_from_mounts("/mnt/helpers.py").await.unwrap_err();
    assert!(matches!(err, PoolError::Protocol(_)), "{err:?}");
    session.finish().await.unwrap();
}

/// A first feed that type checking rejects never reaches the worker's
/// directory switch, so the next feed still establishes the mount default.
#[tokio::test]
async fn working_directory_survives_a_rejected_first_feed() {
    let dir = tempfile::tempdir().unwrap();
    let mount = || vec![MountSpec::new("/mnt", dir.path(), MountSpecMode::ReadOnly).unwrap()];
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool
        .checkout(&ReplConfig {
            type_check: true,
            ..ReplConfig::default()
        })
        .await
        .unwrap();
    let err = session
        .feed("x: int = 'nope'", vec![], mount(), false, &mut no_print)
        .await
        .unwrap_err();
    assert!(matches!(err, PoolError::Typing(_)), "expected Typing, got {err:?}");
    let result = session
        .feed("import os\nos.getcwd()", vec![], mount(), false, &mut no_print)
        .await;
    let event = feed_with_mounts(&mut session, result).await.unwrap();
    assert_eq!(expect_complete(event), MontyObject::string("/mnt".to_owned()));
    session.finish().await.unwrap();
}

/// A first feed rejected as oversize never reaches the worker, so its
/// directory is not established: the next feed still sends the mount default.
#[tokio::test]
async fn working_directory_survives_an_oversize_first_feed() {
    let dir = tempfile::tempdir().unwrap();
    let mount = || vec![MountSpec::new("/mnt", dir.path(), MountSpecMode::ReadOnly).unwrap()];
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    // just over monty_proto's 256 MiB MAX_FRAME_LEN
    let huge = MontyObject::string("x".repeat(257 * 1024 * 1024));
    let err = session
        .feed("data", vec![("data".to_owned(), huge)], mount(), false, &mut no_print)
        .await
        .unwrap_err();
    assert!(matches!(err, PoolError::Runtime(_)), "expected Runtime, got {err:?}");
    let result = session
        .feed("import os\nos.getcwd()", vec![], mount(), false, &mut no_print)
        .await;
    let event = feed_with_mounts(&mut session, result).await.unwrap();
    assert_eq!(expect_complete(event), MontyObject::string("/mnt".to_owned()));
    session.finish().await.unwrap();
}

/// Mount-covered filesystem OS calls are serviced by the parent and never
/// surface to the caller — the feed just completes. Covers read, write,
/// mkdir kwargs, rename, and `open()` + file-handle ops through a mount.
#[tokio::test]
async fn mounted_filesystem_ops_are_serviced_by_the_parent() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("data.txt"), "mounted!").unwrap();

    let mount = || vec![MountSpec::new("/mnt", dir.path(), MountSpecMode::ReadWrite).unwrap()];
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();

    let result = session
        .feed(
            "from pathlib import Path\nPath('/mnt/data.txt').read_text()",
            vec![],
            mount(),
            false,
            &mut no_print,
        )
        .await;
    let event = feed_with_mounts(&mut session, result).await.unwrap();
    assert_eq!(expect_complete(event), MontyObject::string("mounted!".to_owned()));

    let code = "\
Path('/mnt/sub').mkdir(parents=True, exist_ok=True)
Path('/mnt/sub/out.txt').write_text('written')
Path('/mnt/sub/out.txt').rename('/mnt/sub/renamed.txt')
with open('/mnt/sub/renamed.txt') as f:
    body = f.read()
body";
    let result = session.feed(code, vec![], mount(), false, &mut no_print).await;
    let event = feed_with_mounts(&mut session, result).await.unwrap();
    assert_eq!(expect_complete(event), MontyObject::string("written".to_owned()));
    assert_eq!(
        fs::read_to_string(dir.path().join("sub/renamed.txt")).unwrap(),
        "written"
    );
    session.finish().await.unwrap();
}

/// A [`MountSpec`] reused across feeds stays bound to the directory it opened:
/// the sandbox renaming a symlink over that directory's name, from inside a
/// read-write mount of the parent, redirects the *path* and nothing else.
///
/// Skipped where the host cannot create symlinks (Windows without Developer
/// Mode or elevation), since planting the link needs one.
#[tokio::test]
async fn a_reused_mount_spec_survives_a_rename_of_its_host_directory() {
    let base = tempfile::tempdir().unwrap();
    let outside = tempfile::tempdir().unwrap();
    let shared = base.path().join("shared");
    fs::create_dir(&shared).unwrap();
    fs::write(shared.join("inside.txt"), "in-mount").unwrap();
    fs::write(outside.path().join("secret.txt"), "HOST SECRET").unwrap();
    // Host-planted link out of the tree; the sandbox only moves it.
    if try_symlink_dir(outside.path(), &base.path().join("prepared-link")).is_err() {
        eprintln!("skipping: this host cannot create symlinks");
        return;
    }

    // Both built once, as a host holding long-lived mount objects would.
    let child = MountSpec::new("/child", shared, MountSpecMode::ReadOnly).unwrap();
    let parent = MountSpec::new("/parent", base.path(), MountSpecMode::ReadWrite).unwrap();

    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();

    // Feed 1: swap the real directory out and the link in, under one name.
    let code = "\
from pathlib import Path
Path('/parent/shared').rename('/parent/old-shared')
Path('/parent/prepared-link').rename('/parent/shared')
'swapped'";
    let result = session.feed(code, vec![], vec![parent], false, &mut no_print).await;
    match feed_with_mounts(&mut session, result).await {
        Ok(event) => assert_eq!(expect_complete(event), MontyObject::string("swapped".to_owned())),
        // Windows refuses to rename a directory while a handle to it is open,
        // and the child mount holds one — so the swap cannot even be staged
        // there while the mount is alive.
        #[cfg(windows)]
        Err(_) => return,
        #[cfg(not(windows))]
        Err(err) => panic!("staging the swap failed: {err:?}"),
    }

    // Feed 2: the child mount, rebuilt from the same spec, still serves the
    // original directory and cannot see the one the name now points at.
    let code = "\
from pathlib import Path
f\"{Path('/child/inside.txt').read_text()}:{Path('/child/secret.txt').exists()}\"";
    let result = session.feed(code, vec![], vec![child], false, &mut no_print).await;
    let event = feed_with_mounts(&mut session, result).await.unwrap();
    assert_eq!(expect_complete(event), MontyObject::string("in-mount:False".to_owned()));
    session.finish().await.unwrap();
}

/// A write through a read-only mount raises `PermissionError` inside the
/// sandbox (catchable, session-preserving); overlay writes are visible within
/// the feed, never reach the host, and are discarded when the feed ends.
#[tokio::test]
async fn read_only_and_overlay_mount_semantics() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("data.txt"), "original").unwrap();

    let mount = |mode| vec![MountSpec::new("/mnt", dir.path(), mode).unwrap()];
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();

    let result = session
        .feed(
            "from pathlib import Path\nPath('/mnt/new.txt').write_text('x')",
            vec![],
            mount(MountSpecMode::ReadOnly),
            false,
            &mut no_print,
        )
        .await;
    let err = feed_with_mounts(&mut session, result).await.unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime, got {err:?}");
    };
    assert_eq!(exc.exc_type().to_string(), "PermissionError");

    let code = "\
from pathlib import Path
Path('/mnt/data.txt').write_text('changed')
Path('/mnt/data.txt').read_text()";
    let result = session
        .feed(code, vec![], mount(MountSpecMode::Overlay), false, &mut no_print)
        .await;
    let event = feed_with_mounts(&mut session, result).await.unwrap();
    assert_eq!(expect_complete(event), MontyObject::string("changed".to_owned()));
    // the host file is untouched and the overlay does not persist to the next feed
    assert_eq!(fs::read_to_string(dir.path().join("data.txt")).unwrap(), "original");
    let result = session
        .feed(
            "Path('/mnt/data.txt').read_text()",
            vec![],
            mount(MountSpecMode::Overlay),
            false,
            &mut no_print,
        )
        .await;
    let event = feed_with_mounts(&mut session, result).await.unwrap();
    assert_eq!(expect_complete(event), MontyObject::string("original".to_owned()));
    session.finish().await.unwrap();
}

/// The per-mount `write_bytes_limit` is enforced by the parent-side table and
/// surfaces as a catchable `OSError` inside the sandbox.
#[tokio::test]
async fn mount_write_bytes_limit_is_enforced() {
    let dir = tempfile::tempdir().unwrap();
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let code = "\
from pathlib import Path
try:
    Path('/mnt/big.txt').write_text('x' * 100)
except OSError as exc:
    msg = str(exc)
msg";
    let result = session
        .feed(
            code,
            vec![],
            vec![{
                let mut spec = MountSpec::new("/mnt", dir.path(), MountSpecMode::ReadWrite).unwrap();
                spec.write_bytes_limit = Some(10);
                spec
            }],
            false,
            &mut no_print,
        )
        .await;
    let event = feed_with_mounts(&mut session, result).await.unwrap();
    assert_eq!(
        expect_complete(event),
        MontyObject::string("disk write limit of 10 bytes exceeded".to_owned())
    );
    session.finish().await.unwrap();
}

/// A custom `MountSpec::memory_usage_limit` reaches the parent-side table and
/// surfaces as a catchable `MemoryError` inside the sandbox.
#[tokio::test]
async fn mount_memory_usage_limit_is_enforced() {
    let dir = tempfile::tempdir().unwrap();
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    // the retained overlay write and the transient read-back share the budget
    let code = "\
from pathlib import Path
p = Path('/mnt/f.bin')
p.write_bytes(b'a' * 600)
msg = ''
try:
    p.read_bytes()
except MemoryError as exc:
    msg = str(exc)
msg";
    let mut spec = MountSpec::new("/mnt", dir.path(), MountSpecMode::Overlay).unwrap();
    spec.memory_usage_limit = 1_000;
    let result = session.feed(code, vec![], vec![spec], false, &mut no_print).await;
    let event = feed_with_mounts(&mut session, result).await.unwrap();
    assert_eq!(
        expect_complete(event),
        MontyObject::string("mount memory usage limit of 1 KB exceeded".to_owned())
    );
    session.finish().await.unwrap();
}

/// Every OS call surfaces; offering each to the mounts answers the covered
/// one and leaves the uncovered one for the caller.
#[tokio::test]
async fn uncovered_os_calls_surface_alongside_mounted_ones() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("data.txt"), "covered").unwrap();

    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let code = "\
from pathlib import Path
covered = Path('/mnt/data.txt').read_text()
covered + ':' + Path('/elsewhere/file.txt').read_text()";
    let result = session
        .feed(
            code,
            vec![],
            vec![MountSpec::new("/mnt", dir.path(), MountSpecMode::ReadOnly).unwrap()],
            false,
            &mut no_print,
        )
        .await;
    // the covered `/mnt` read is answered by the mount; the `/elsewhere` one
    // is handed back for the caller to answer
    let event = feed_with_mounts(&mut session, result).await.unwrap();
    let TurnEvent::OsCall {
        function_name, args, ..
    } = event
    else {
        panic!("expected OsCall, got {event:?}");
    };
    assert_eq!(function_name, "Path.read_text");
    assert_eq!(
        args,
        CallArgs::from(vec![MontyObject::path("/elsewhere/file.txt".to_owned())])
    );
    let event = session
        .resume(
            ResumeValue::Return(MontyObject::string("uncovered".to_owned())),
            &mut no_print,
        )
        .await
        .unwrap();
    assert_eq!(
        expect_complete(event),
        MontyObject::string("covered:uncovered".to_owned())
    );
    session.finish().await.unwrap();
}

/// A feed suspended mid-OsCall can be dumped and restored elsewhere; the
/// re-supplied mounts service the resumed feed's filesystem calls.
#[tokio::test]
async fn suspended_feed_restores_with_mounts_re_supplied() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("data.txt"), "after resume").unwrap();

    let mount = || vec![MountSpec::new("/mnt", dir.path(), MountSpecMode::ReadOnly).unwrap()];
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    // suspend on an *uncovered* call, dump, and restore into a fresh worker
    let code = "\
from pathlib import Path
external = Path('/external/answer.txt').read_text()
external + ' ' + Path('/mnt/data.txt').read_text()";
    let event = session.feed(code, vec![], mount(), false, &mut no_print).await.unwrap();
    assert!(matches!(event, TurnEvent::OsCall { .. }), "got {event:?}");
    let state = session.dump().await.unwrap();
    drop(session);

    let mut restored = pool.checkout(&ReplConfig::default()).await.unwrap();
    let (event, _) = restored.restore(state, mount(), &mut no_print).await.unwrap();
    // the re-announcement carries the full call payload, so the uncovered
    // call surfaces exactly like a fresh suspension — name and args intact;
    // answering it lets the feed continue, and its remaining mounted read is
    // serviced by the parent
    let Some(TurnEvent::OsCall {
        function_name, args, ..
    }) = &event
    else {
        panic!("expected OsCall, got {event:?}");
    };
    assert_eq!(function_name, "Path.read_text");
    assert_eq!(
        args,
        &CallArgs::from(vec![MontyObject::path("/external/answer.txt".to_owned())])
    );
    let result = restored
        .resume(
            ResumeValue::Return(MontyObject::string("hello".to_owned())),
            &mut no_print,
        )
        .await;
    // the feed's remaining `/mnt` read is answered by the re-supplied mount
    let event = feed_with_mounts(&mut restored, result).await.unwrap();
    assert_eq!(
        expect_complete(event),
        MontyObject::string("hello after resume".to_owned())
    );
    restored.finish().await.unwrap();
}

/// A dump taken while suspended on a mount-coverable OS call re-announces the
/// call in full, so mounts supplied to `restore` can answer it — the payload
/// survives the round trip even though the original feed had no mounts.
#[tokio::test]
async fn restored_os_call_is_serviced_by_restore_mounts() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(dir.path().join("data.txt"), "from mount").unwrap();

    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    // feed with NO mounts: the read surfaces as an uncovered OsCall
    let event = session
        .feed(
            "from pathlib import Path\nPath('/mnt/data.txt').read_text()",
            vec![],
            vec![],
            false,
            &mut no_print,
        )
        .await
        .unwrap();
    assert!(matches!(event, TurnEvent::OsCall { .. }), "got {event:?}");
    let state = session.dump().await.unwrap();
    drop(session);

    // restore WITH the mount: the call is re-announced, and offering it to the
    // now-present mount answers it and runs the feed to completion
    let mut restored = pool.checkout(&ReplConfig::default()).await.unwrap();
    let (event, _) = restored
        .restore(
            state,
            vec![MountSpec::new("/mnt", dir.path(), MountSpecMode::ReadOnly).unwrap()],
            &mut no_print,
        )
        .await
        .unwrap();
    let event = event.expect("suspended dump must re-announce a turn event");
    assert!(matches!(event, TurnEvent::OsCall { .. }), "got {event:?}");
    let event = feed_with_mounts(&mut restored, Ok(event)).await.unwrap();
    assert_eq!(expect_complete(event), MontyObject::string("from mount".to_owned()));
    restored.finish().await.unwrap();
}

/// An over-limit frame must fail as a clean, session-preserving error rather
/// than crashing the worker: `Worker::send` rejects it before writing any
/// bytes, so the stream stays synced. Covers both directions — a request the
/// parent cannot send (a huge input) and a result the worker cannot send
/// back.
///
/// Allocates ~257 MiB (just over the 256 MiB frame limit) in the test process
/// and again in the worker, so it is memory-heavy; disable it if it proves
/// flaky in CI.
#[tokio::test]
async fn oversize_frames_are_rejected_without_killing_the_worker() {
    // just over monty_proto's 256 MiB MAX_FRAME_LEN
    const OVERSIZE: usize = 257 * 1024 * 1024;

    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();

    // (1) parent -> child: an input larger than the frame limit cannot be
    // sent. The worker never receives the request, so the session survives.
    let huge = MontyObject::string("x".repeat(OVERSIZE));
    let err = session
        .feed("data", vec![("data".to_owned(), huge)], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime for oversize input, got {err:?}");
    };
    assert!(
        exc.message()
            .is_some_and(|m| m.contains("request frame") && m.contains("exceeds the maximum")),
        "unexpected message: {:?}",
        exc.message()
    );
    let event = session
        .feed("1 + 1", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(2));

    // (2) child -> parent: a result larger than the frame limit cannot be sent
    // back. The worker answers with a clean error and keeps the session.
    let err = session
        .feed(&format!("'x' * {OVERSIZE}"), vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime for oversize result, got {err:?}");
    };
    assert!(
        exc.message()
            .is_some_and(|m| m.contains("result frame") && m.contains("exceeds the maximum")),
        "unexpected message: {:?}",
        exc.message()
    );
    let event = session
        .feed("1 + 1", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(2));

    // (3) child -> parent suspension: external-call arguments larger than the
    // frame limit cannot be announced to the parent. The child aborts that
    // feed before entering the suspension, so the session remains usable.
    let err = session
        .feed(
            &format!(
                "result = 'not caught'\ntry:\n    fetch('x' * {OVERSIZE})\nexcept RuntimeError:\n    result = 'caught'\nresult"
            ),
            vec![],
            vec![],
            false,
            &mut no_print,
        )
        .await
        .unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime for oversize external-call args, got {err:?}");
    };
    assert!(
        exc.message()
            .is_some_and(|m| m.contains("argument frame") && m.contains("exceeds the maximum")),
        "unexpected message: {:?}",
        exc.message()
    );
    let event = session
        .feed("1 + 1", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(2));

    session.finish().await.unwrap();

    // (4) parent -> child resume: a return value too large to send leaves the
    // suspension *answerable*. The child never saw the oversize frame, so it is
    // still waiting — clearing the pending call here would strand it for ever.
    // A fresh checkout, so the earlier steps' namespace cannot interfere.
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let event = session
        .feed("len(grab())", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert!(matches!(event, TurnEvent::FunctionCall { .. }), "got {event:?}");
    let huge = MontyObject::string("x".repeat(OVERSIZE));
    let err = session
        .resume(ResumeValue::Return(huge), &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime for oversize resume value, got {err:?}");
    };
    assert!(
        exc.message()
            .is_some_and(|m| m.contains("request frame") && m.contains("exceeds the maximum")),
        "unexpected message: {:?}",
        exc.message()
    );
    // the same suspension still answers to a value that fits
    let event = session
        .resume(
            ResumeValue::Return(MontyObject::string("small".to_owned())),
            &mut no_print,
        )
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(5));

    // (5) parent -> child name-lookup resume: same invariant as (4) — the
    // rejected answer leaves the lookup answerable.
    let event = session
        .feed("missing", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert!(matches!(event, TurnEvent::NameLookup { ref name, .. } if name == "missing"));
    let huge = MontyObject::string("x".repeat(OVERSIZE));
    let err = session.resume_name_lookup(Some(huge), &mut no_print).await.unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime for oversize name-lookup value, got {err:?}");
    };
    assert!(
        exc.message()
            .is_some_and(|m| m.contains("request frame") && m.contains("exceeds the maximum")),
        "unexpected message: {:?}",
        exc.message()
    );
    let event = session
        .resume_name_lookup(Some(MontyObject::string("small".to_owned())), &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::string("small".to_owned()));

    // (6) parent -> child future resolution: the pending futures stay
    // resolvable after an oversize result is rejected.
    let code = "import asyncio\nasync def main():\n    return await go()\nasyncio.run(main())";
    let event = session.feed(code, vec![], vec![], false, &mut no_print).await.unwrap();
    let TurnEvent::FunctionCall { call_id, .. } = event else {
        panic!("expected FunctionCall, got {event:?}");
    };
    let event = session.resume(ResumeValue::Future, &mut no_print).await.unwrap();
    assert!(matches!(event, TurnEvent::ResolveFutures { .. }), "got {event:?}");
    let huge = MontyObject::string("x".repeat(OVERSIZE));
    let err = session
        .resume_futures(vec![(call_id, ResumeValue::Return(huge))], &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime for oversize future result, got {err:?}");
    };
    assert!(
        exc.message()
            .is_some_and(|m| m.contains("request frame") && m.contains("exceeds the maximum")),
        "unexpected message: {:?}",
        exc.message()
    );
    let event = session
        .resume_futures(
            vec![(call_id, ResumeValue::Return(MontyObject::int(99)))],
            &mut no_print,
        )
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(99));
    session.finish().await.unwrap();
}

/// A `dump()` too large for the frame limit while the session is *suspended*
/// must fail as a clean, session-preserving error — the suspension already
/// announced its resume point, so the child stays suspended and resumable.
///
/// Allocates ~300 MiB in the worker (plus the dump copy), so it is
/// memory-heavy; disable it if it proves flaky in CI.
#[tokio::test]
async fn oversize_dump_while_suspended_fails_cleanly_and_resumes() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    // a tiny suspension announcement on top of a heap too big to dump
    let code = "data = 'x' * (300 * 1024 * 1024)\nf()\nlen(data)";
    let event = session.feed(code, vec![], vec![], false, &mut no_print).await.unwrap();
    assert!(matches!(event, TurnEvent::FunctionCall { .. }), "got {event:?}");

    let err = session.dump().await.unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime for oversize dump, got {err:?}");
    };
    assert!(
        exc.message()
            .is_some_and(|m| m.contains("result frame") && m.contains("exceeds the maximum")),
        "unexpected message: {:?}",
        exc.message()
    );

    // the suspension is untouched: resuming completes the feed
    let event = session
        .resume(ResumeValue::Return(MontyObject::none()), &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(300 * 1024 * 1024));
    session.finish().await.unwrap();
}

#[tokio::test]
async fn inputs_and_prints() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let mut output = String::new();
    let event = session
        .feed(
            "print('hello', name)\nlen(name)",
            vec![("name".to_owned(), MontyObject::string("monty".to_owned()))],
            vec![],
            false,
            &mut on_print_sync(|_, text: &str| output.push_str(text)),
        )
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(5));
    assert_eq!(output, "hello monty\n");
    session.finish().await.unwrap();
}

/// A loop of small prints must not cost one `Print` event each: the worker
/// batches them by size and elapsed time, which is what keeps the parent's
/// per-event work (telemetry included) proportional to output rather than to
/// how often the sandbox called `print()`.
#[tokio::test]
async fn prints_are_batched_into_few_events() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let mut output = String::new();
    let mut events = 0;
    let event = session
        .feed(
            "for i in range(2000):\n    print(i)",
            vec![],
            vec![],
            false,
            &mut on_print_sync(|_, text: &str| {
                events += 1;
                output.push_str(text);
            }),
        )
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::none());
    let mut expected = String::new();
    for i in 0..2000 {
        writeln!(expected, "{i}").unwrap();
    }
    assert_eq!(output, expected);
    assert!(
        events < 200,
        "expected far fewer than one event per print, got {events}"
    );
    session.finish().await.unwrap();
}

/// The size threshold still bounds a chunk when the interval never expires:
/// one huge write is split into ~8 KiB events rather than buffered whole. This
/// is also what keeps the buffer below the threshold on entry to each write, so
/// its remaining-room arithmetic cannot underflow.
#[tokio::test]
async fn one_huge_write_is_split_at_the_size_threshold() {
    const FLUSH_BYTES: usize = 8 * 1024;
    let pool = Pool::new(config()).await.unwrap();
    // an interval nothing will reach, so only the size threshold can flush
    let repl = ReplConfig {
        print_flush_interval: Some(Duration::from_secs(600)),
        ..ReplConfig::default()
    };
    let mut session = pool.checkout(&repl).await.unwrap();
    let mut chunks: Vec<usize> = Vec::new();
    let mut total = 0;
    session
        .feed(
            "print('x' * 100_000, end='')",
            vec![],
            vec![],
            false,
            &mut on_print_sync(|_, text: &str| {
                chunks.push(text.len());
                total += text.len();
            }),
        )
        .await
        .unwrap();
    assert_eq!(total, 100_000);
    assert!(chunks.len() > 1, "expected the write to be split, got {chunks:?}");
    assert!(
        chunks.iter().all(|len| *len <= FLUSH_BYTES),
        "every chunk must stay within the threshold, got {chunks:?}"
    );
    session.finish().await.unwrap();
}

/// A zero interval turns the timer off and restores line buffering, for a host
/// that wants each completed line delivered on its own.
#[tokio::test]
async fn zero_flush_interval_delivers_one_event_per_line() {
    let pool = Pool::new(config()).await.unwrap();
    let repl = ReplConfig {
        print_flush_interval: Some(Duration::ZERO),
        ..ReplConfig::default()
    };
    let mut session = pool.checkout(&repl).await.unwrap();
    let mut lines = Vec::new();
    session
        .feed(
            "for i in range(20):\n    print(i)",
            vec![],
            vec![],
            false,
            &mut on_print_sync(|_, text: &str| lines.push(text.to_owned())),
        )
        .await
        .unwrap();
    assert_eq!(lines.len(), 20);
    assert_eq!(lines[0], "0\n");
    assert_eq!(lines[19], "19\n");
    session.finish().await.unwrap();
}

/// With the timer off the contract is one event per *completed line*, not one
/// per write: a single `print()` carrying embedded newlines must still arrive
/// as one event per line.
#[tokio::test]
async fn zero_flush_interval_splits_embedded_newlines() {
    let pool = Pool::new(config()).await.unwrap();
    let repl = ReplConfig {
        print_flush_interval: Some(Duration::ZERO),
        ..ReplConfig::default()
    };
    let mut session = pool.checkout(&repl).await.unwrap();
    let mut events = Vec::new();
    session
        .feed(
            r#"print("a\nb")"#,
            vec![],
            vec![],
            false,
            &mut on_print_sync(|_, text: &str| events.push(text.to_owned())),
        )
        .await
        .unwrap();
    assert_eq!(events, vec!["a\n".to_owned(), "b\n".to_owned()]);
    session.finish().await.unwrap();
}

/// Output must not sit in the worker's buffer while the program computes in
/// silence: the interpreter polls the writer at its dispatch checkpoints, so a
/// line printed before a long stretch of quiet work is released on its own
/// rather than waiting for the next print.
#[tokio::test]
async fn silence_releases_buffered_output() {
    let pool = Pool::new(config()).await.unwrap();
    let repl = ReplConfig {
        print_flush_interval: Some(Duration::from_millis(1)),
        ..ReplConfig::default()
    };
    let mut session = pool.checkout(&repl).await.unwrap();
    let mut events: Vec<String> = Vec::new();
    session
        .feed(
            // the loop is far longer than the 1ms interval in any build
            "print('first')\nt = 0\nfor i in range(200_000):\n    t += i\nprint('second')",
            vec![],
            vec![],
            false,
            &mut on_print_sync(|_, text: &str| events.push(text.to_owned())),
        )
        .await
        .unwrap();
    assert_eq!(events.first().map(String::as_str), Some("first\n"));
    assert_eq!(events.concat(), "first\nsecond\n");
    session.finish().await.unwrap();
}

/// Batching must never reorder output against the suspension that follows it:
/// the worker drains its buffer before every turn-ending event, so a print
/// made just before a host call still arrives before the call is announced.
#[tokio::test]
async fn buffered_output_is_flushed_before_a_suspension() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let mut output = String::new();
    let event = session
        .feed(
            "print('before')\nask()",
            vec![],
            vec![],
            false,
            &mut on_print_sync(|_, text: &str| output.push_str(text)),
        )
        .await
        .unwrap();
    assert!(
        matches!(event, TurnEvent::FunctionCall { ref function_name, .. } if function_name == "ask"),
        "expected a call suspension, got {event:?}"
    );
    assert_eq!(output, "before\n");
    session.finish().await.unwrap();
}

#[tokio::test]
async fn external_function_round_trip() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let event = session
        .feed("fetch('https://x') + '!'", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    let TurnEvent::FunctionCall {
        function_name, args, ..
    } = event
    else {
        panic!("expected FunctionCall, got {event:?}");
    };
    assert_eq!(function_name, "fetch");
    assert_eq!(args, CallArgs::from(vec![MontyObject::string("https://x".to_owned())]));
    let event = session
        .resume(
            ResumeValue::Return(MontyObject::string("body".to_owned())),
            &mut no_print,
        )
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::string("body!".to_owned()));
    session.finish().await.unwrap();
}

#[tokio::test]
async fn runtime_error_keeps_session_and_worker() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    assert_eq!(
        expect_complete(
            session
                .feed("kept = 1", vec![], vec![], false, &mut no_print)
                .await
                .unwrap()
        ),
        MontyObject::none()
    );
    let err = session
        .feed("1 / 0", vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime, got {err:?}");
    };
    assert_eq!(exc.message(), Some("division by zero"));
    // session and worker survive
    assert_eq!(
        expect_complete(
            session
                .feed("kept + 41", vec![], vec![], false, &mut no_print)
                .await
                .unwrap()
        ),
        MontyObject::int(42)
    );
    session.finish().await.unwrap();
    assert_eq!(pool.idle_workers(), 1);
}

// =============================================================================
// Crash isolation — the headline feature
// =============================================================================

#[tokio::test]
async fn sigkill_mid_request_is_a_clean_crash_and_the_pool_recovers() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let pid = session.pid().unwrap();

    // kill the worker while it spins forever
    let killer = thread::spawn(move || {
        thread::sleep(Duration::from_millis(300));
        kill_pid(pid);
    });
    let err = session
        .feed("while True:\n    pass", vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    killer.join().unwrap();
    assert!(matches!(err, PoolError::Crashed { .. }), "got {err:?}");

    // the pool spawns a replacement transparently
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    assert_ne!(session.pid().unwrap(), pid);
    assert_eq!(
        expect_complete(
            session
                .feed("1 + 1", vec![], vec![], false, &mut no_print)
                .await
                .unwrap()
        ),
        MontyObject::int(2)
    );
    session.finish().await.unwrap();
}

#[tokio::test]
async fn worker_killed_while_idle_is_replaced_transparently() {
    let pool = Pool::new(config()).await.unwrap();
    let pids = pool.idle_worker_pids();
    assert_eq!(pids.len(), 1);
    kill_pid(pids[0]);
    // give the OS a moment to deliver the kill
    sleep(Duration::from_millis(100)).await;

    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    assert_eq!(
        expect_complete(
            session
                .feed("2 + 2", vec![], vec![], false, &mut no_print)
                .await
                .unwrap()
        ),
        MontyObject::int(4)
    );
    session.finish().await.unwrap();
}

/// A deep postfix spine (`a.x.x.x…`) currently overflows the child's stack
/// (recursive AST handling) — a REAL memory crash, exactly what subprocess
/// isolation exists for. If monty core gains AST-depth protection this
/// becomes a `Runtime`/`Crashed` either way; the invariant under test is
/// that the parent survives and the pool keeps serving.
#[tokio::test]
async fn hard_child_crash_does_not_harm_the_pool() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let mut code = String::with_capacity(300_002);
    code.push('a');
    for _ in 0..150_000 {
        code.push_str(".x");
    }
    let err = session
        .feed(&code, vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    assert!(
        matches!(err, PoolError::Crashed { .. } | PoolError::Runtime(_)),
        "got {err:?}"
    );
    // a stack overflow aborts with SIGABRT, which must never be mistaken for the
    // allocator's dedicated out-of-memory exit — the reason that exit exists
    if let PoolError::Runtime(exc) = &err {
        assert_ne!(
            exc.message(),
            Some("the worker exceeded its memory limit and was terminated")
        );
    }

    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    assert_eq!(
        expect_complete(
            session
                .feed("1 + 1", vec![], vec![], false, &mut no_print)
                .await
                .unwrap()
        ),
        MontyObject::int(2)
    );
    session.finish().await.unwrap();
}

#[tokio::test]
async fn deadline_kills_hung_worker_after_request_timeout() {
    let mut config = config();
    config.request_timeout = Some(Duration::from_secs(1));
    let pool = Pool::new(config).await.unwrap();
    // The checkout's Configure turn shares the pool-wide deadline, and a cold
    // child on a fully loaded test machine has (rarely) missed it — retry so
    // the setup is independent of the deadline actually under test below.
    let mut session = loop {
        match pool.checkout(&ReplConfig::default()).await {
            Ok(session) => break session,
            Err(PoolError::Timeout { .. }) => {}
            Err(err) => panic!("checkout failed: {err:?}"),
        }
    };
    let err = session
        .feed("while True:\n    pass", vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    assert!(matches!(err, PoolError::Timeout { .. }), "got {err:?}");

    // pool still healthy
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    assert_eq!(
        expect_complete(
            session
                .feed("3 + 3", vec![], vec![], false, &mut no_print)
                .await
                .unwrap()
        ),
        MontyObject::int(6)
    );
    session.finish().await.unwrap();
}

#[tokio::test]
async fn child_resource_limits_do_not_kill_the_worker() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool
        .checkout(&ReplConfig {
            limits: Some(ResourceLimits::default().max_feed_duration(Duration::from_millis(100))),
            ..ReplConfig::default()
        })
        .await
        .unwrap();
    let err = session
        .feed("while True:\n    pass", vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    // the SANDBOX limit fired (TimeoutError exception), not the parent-side
    // deadline — the worker process is alive and finishable
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime, got {err:?}");
    };
    assert_eq!(exc.exc_type().to_string(), "TimeoutError");
    session.finish().await.unwrap();
    assert_eq!(pool.idle_workers(), 1);
}

/// A session's `max_memory` must not disturb work that stays inside it.
#[tokio::test]
async fn max_memory_leaves_normal_work_alone() {
    let pool = Pool::new(config()).await.unwrap();
    let repl_config = ReplConfig {
        limits: Some(ResourceLimits::default().max_memory(1024 * 1024)),
        ..ReplConfig::default()
    };
    let mut session = pool.checkout(&repl_config).await.unwrap();
    assert_eq!(
        expect_complete(
            session
                .feed("1 + 1", vec![], vec![], false, &mut no_print)
                .await
                .unwrap()
        ),
        MontyObject::int(2)
    );
    session.finish().await.unwrap();
}

/// Only `OOM_EXIT_CODE` carries a meaning: any other code a worker might return
/// stays an opaque death rather than being read as a memory outcome.
#[cfg(unix)]
#[tokio::test]
async fn unrecognised_exit_code_stays_an_opaque_death() {
    let dir = tempfile::tempdir().unwrap();
    // outlives the parent's first write, so the death is always observed while
    // waiting for the reply rather than racing with `sending a request`
    let fake = write_fake_monty(dir.path(), "#!/bin/sh\nsleep 0.2\nexit 64\n");

    let pool = Pool::new(PoolConfig::subprocess(&fake)).await.unwrap();
    let err = match pool.checkout(&ReplConfig::default()).await {
        Ok(mut session) => session
            .feed("1 + 1", vec![], vec![], false, &mut no_print)
            .await
            .expect_err("expected the stand-in binary to fail the turn"),
        Err(err) => err,
    };
    let PoolError::Crashed { cause, .. } = &err else {
        panic!("expected Crashed, got {err:?}");
    };
    assert!(
        matches!(cause, monty_pool::CrashCause::Vanished { .. }),
        "an unrecognised exit code must not be classified, got {cause:?}"
    );
    // the message says only what the pool was doing and what it reaped — no
    // memory wording, which is what `OOM_EXIT_CODE` alone earns
    assert_snapshot!(err.to_string(), @"monty worker crashed while waiting for a reply (exit status: 64)");
}

/// A local child cannot pass a `ShutdownDump` off as a turn-ender on the raw
/// path: only a serving relay sends one, and accepting it would let a
/// compromised child hand a dump it minted itself out through a relay that
/// signs whatever it forwards.
#[cfg(unix)]
#[tokio::test]
async fn a_subprocess_shutdown_dump_is_refused_on_the_raw_path() {
    let dir = tempfile::tempdir().unwrap();
    // the two frames the stand-in replays, in order: `Ok` answers the
    // `Configure` that establishes the session, then the forged dump
    let mut replies = framed(&child_event(pb::child_event::Kind::Ok(pb::Ok {})));
    replies.extend(framed(&child_event(pb::child_event::Kind::Shutdown(
        pb::ShutdownDump {
            dump: Some(b"a dump the child minted itself".to_vec().into()),
        },
    ))));
    let replies_path = dir.path().join("replies.bin");
    fs::write(&replies_path, &replies).unwrap();

    // both frames are written up front and the process stays alive; the parent
    // reads them in turn as it sends `Configure` and then the raw request
    let fake = write_fake_monty(
        dir.path(),
        &format!("#!/bin/sh\ncat '{}'\nsleep 5\n", replies_path.display()),
    );

    let pool = Pool::new(PoolConfig::subprocess(&fake)).await.unwrap();
    let mut checkout = pool
        .checkout(&ReplConfig::default())
        .await
        .expect("the stand-in answers Configure with Ok");
    let request = pb::ParentRequest {
        kind: Some(pb::parent_request::Kind::Feed(pb::Feed {
            code: "1 + 1".to_owned(),
            inputs: vec![].into(),
            values: None,
            skip_type_check: false,
            cwd: "/".to_owned(),
        })),
        ..pb::ParentRequest::default()
    };
    let mut on_event = |_: &pb::ChildEvent| Box::pin(ready(())) as PrintFuture;
    let err = checkout
        .turn_raw(&request, &mut on_event)
        .await
        .expect_err("a subprocess ShutdownDump must not be accepted");
    assert_snapshot!(
        err.to_string(),
        @"monty worker protocol error: subprocess worker sent a ShutdownDump"
    );
}

/// An event with no `kind` ends no turn on the raw path. Every wire field is
/// optional, so a hostile worker can send one whose oneof is unset — it must
/// not reach the raw driver's client as a successful turn-ender.
#[cfg(unix)]
#[tokio::test]
async fn an_event_with_no_kind_is_refused_on_the_raw_path() {
    let dir = tempfile::tempdir().unwrap();
    // `Ok` answers the establishing `Configure`, then the kindless frame
    let mut replies = framed(&child_event(pb::child_event::Kind::Ok(pb::Ok {})));
    replies.extend(framed(&pb::ChildEvent::default()));
    let replies_path = dir.path().join("replies.bin");
    fs::write(&replies_path, &replies).unwrap();

    let fake = write_fake_monty(
        dir.path(),
        &format!("#!/bin/sh\ncat '{}'\nsleep 5\n", replies_path.display()),
    );

    let pool = Pool::new(PoolConfig::subprocess(&fake)).await.unwrap();
    let mut checkout = pool
        .checkout(&ReplConfig::default())
        .await
        .expect("the stand-in answers Configure with Ok");
    let request = pb::ParentRequest {
        kind: Some(pb::parent_request::Kind::Feed(pb::Feed {
            code: "1 + 1".to_owned(),
            inputs: vec![].into(),
            values: None,
            skip_type_check: false,
            cwd: "/".to_owned(),
        })),
        ..pb::ParentRequest::default()
    };
    let mut on_event = |_: &pb::ChildEvent| Box::pin(ready(())) as PrintFuture;
    let err = checkout
        .turn_raw(&request, &mut on_event)
        .await
        .expect_err("a kindless event must not be accepted as a turn-ender");
    assert_snapshot!(
        err.to_string(),
        @"monty worker protocol error: worker sent an event with no kind"
    );
}

/// A `FatalError` ends a raw turn *and* the worker behind it: the frame is
/// handed back for the driver to forward, but the dead child is reaped and
/// discarded rather than holding its pool slot until the next failure.
#[cfg(unix)]
#[tokio::test]
async fn a_fatal_error_on_the_raw_path_discards_the_worker() {
    let dir = tempfile::tempdir().unwrap();
    // `Ok` answers the establishing `Configure`, then the fatal frame
    let mut replies = framed(&child_event(pb::child_event::Kind::Ok(pb::Ok {})));
    replies.extend(framed(&child_event(pb::child_event::Kind::FatalError(
        pb::FatalError {
            message: "the child is done".to_owned(),
        },
    ))));
    let replies_path = dir.path().join("replies.bin");
    fs::write(&replies_path, &replies).unwrap();

    let fake = write_fake_monty(
        dir.path(),
        &format!("#!/bin/sh\ncat '{}'\nsleep 5\n", replies_path.display()),
    );

    let pool = Pool::new(PoolConfig::subprocess(&fake)).await.unwrap();
    let mut checkout = pool
        .checkout(&ReplConfig::default())
        .await
        .expect("the stand-in answers Configure with Ok");
    let request = pb::ParentRequest {
        kind: Some(pb::parent_request::Kind::Feed(pb::Feed {
            code: "1 + 1".to_owned(),
            inputs: vec![].into(),
            values: None,
            skip_type_check: false,
            cwd: "/".to_owned(),
        })),
        ..pb::ParentRequest::default()
    };
    let mut on_event = |_: &pb::ChildEvent| Box::pin(ready(())) as PrintFuture;
    let event = checkout
        .turn_raw(&request, &mut on_event)
        .await
        .expect("the fatal frame is the turn-ender");
    let Some(pb::child_event::Kind::FatalError(fatal)) = event.kind else {
        panic!("expected the FatalError frame back, got {:?}", event.kind);
    };
    assert_eq!(fatal.message, "the child is done");
    // the worker was discarded with the frame, not kept until the next failure
    let err = checkout.turn_raw(&request, &mut on_event).await.unwrap_err();
    assert!(matches!(err, PoolError::Finished), "got {err:?}");
}

/// Length-prefixes one event exactly as a worker writes it.
#[cfg(unix)]
fn framed(event: &pb::ChildEvent) -> Vec<u8> {
    let mut buf = Vec::new();
    encode_framed_into(event, &mut buf).expect("encode");
    buf
}

/// A `ChildEvent` carrying `kind` and nothing else.
#[cfg(unix)]
fn child_event(kind: pb::child_event::Kind) -> pb::ChildEvent {
    pb::ChildEvent {
        kind: Some(kind),
        ..pb::ChildEvent::default()
    }
}

/// A refused allocation is the one `Runtime` error whose worker is already
/// dead: it reports `MemoryError` (the worker's dedicated exit code, not an
/// unclassifiable `SIGABRT`), the checkout is finished, and the pool recovers.
/// Needs no limit: 1 EiB dwarfs the usable address space on any 64-bit host,
/// so the allocator refuses it regardless of overcommit policy.
#[tokio::test]
async fn refused_allocation_is_a_memory_error_and_the_pool_recovers() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    // no `max_memory`, so the sandbox tracker allows this outright
    let err = session
        .feed("x = ' ' * (1 << 60)", vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime, got {err:?}");
    };
    assert_eq!(exc.exc_type().to_string(), "MemoryError");
    assert_eq!(
        exc.message(),
        Some("the worker exceeded its memory limit and was terminated")
    );
    // unlike an in-sandbox exception, the worker is gone with it
    assert!(matches!(session.finish().await, Err(PoolError::Finished)));

    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    assert_eq!(
        expect_complete(
            session
                .feed("3 + 3", vec![], vec![], false, &mut no_print)
                .await
                .unwrap()
        ),
        MontyObject::int(6)
    );
    session.finish().await.unwrap();
}

#[cfg(unix)]
#[tokio::test]
async fn special_files_in_mounts_are_rejected_without_blocking() {
    // Mount I/O runs on the parent task servicing the sandbox, so reading a
    // FIFO must fail fast (a real read would block until a writer appears —
    // with no deadline able to rescue the parent). The sandbox sees a
    // catchable PermissionError and the session stays usable.
    let dir = tempfile::tempdir().unwrap();
    let status = Command::new("mkfifo").arg(dir.path().join("pipe")).status().unwrap();
    assert!(status.success(), "mkfifo failed");

    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let result = session
        .feed(
            "from pathlib import Path\nPath('/mnt/pipe').read_text()",
            vec![],
            vec![MountSpec::new("/mnt", dir.path(), MountSpecMode::ReadOnly).unwrap()],
            false,
            &mut no_print,
        )
        .await;
    let err = feed_with_mounts(&mut session, result).await.unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime, got {err:?}");
    };
    assert_eq!(exc.exc_type().to_string(), "PermissionError");
    session.finish().await.unwrap();
}

#[tokio::test]
async fn suspension_time_does_not_consume_the_duration_budget() {
    // `max_feed_duration` measures sandbox execution time; the worker reports
    // it on every turn and its clock is paused while suspended. The host
    // staying away for twice the entire budget must therefore not time the
    // feed out.
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool
        .checkout(&ReplConfig {
            limits: Some(ResourceLimits::default().max_feed_duration(Duration::from_millis(300))),
            ..ReplConfig::default()
        })
        .await
        .unwrap();
    let event = session
        .feed("fetch('https://x') + '!'", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert!(matches!(event, TurnEvent::FunctionCall { .. }));

    sleep(Duration::from_millis(600)).await;

    let event = session
        .resume(
            ResumeValue::Return(MontyObject::string("body".to_owned())),
            &mut no_print,
        )
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::string("body!".to_owned()));
    session.finish().await.unwrap();
}

/// Clock and entropy requests cost no turns; system sleeps reach the caller capped.
/// Fixed clocks and seeds survive `Configure` unchanged.
#[tokio::test]
async fn os_policy_are_answered_in_the_worker() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool
        .checkout(&ReplConfig {
            os_policy: OsPolicy {
                sleep: SleepMode::System(Duration::from_millis(10)),
                ..OsPolicy::default()
            },
            ..ReplConfig::default()
        })
        .await
        .unwrap();
    let code = "import asyncio, random, time\nfrom datetime import date\nt = time.time()\ntime.sleep(3600)\n\
                (date.today().year >= 2026, time.time() >= t + 0.01, \
                asyncio.run(asyncio.sleep(3600, 'woken')), 0 <= random.random() < 1)";
    let mut event = session.feed(code, vec![], vec![], false, &mut no_print).await.unwrap();
    let mut slept = vec![];
    while let TurnEvent::OsCall {
        function_name,
        system_sleep,
        ..
    } = &event
    {
        let delay = system_sleep.expect("only the sleeps reach the caller");
        slept.push((function_name.clone(), delay));
        sleep(delay).await;
        event = session
            .resume(ResumeValue::Return(MontyObject::none()), &mut no_print)
            .await
            .unwrap();
    }
    assert_eq!(
        slept,
        vec![
            ("system.sleep".to_owned(), Duration::from_millis(10)),
            ("system.async_sleep".to_owned(), Duration::from_millis(10)),
        ]
    );
    assert_eq!(
        expect_complete(event),
        MontyObject::tuple([
            MontyObject::bool(true),
            MontyObject::bool(true),
            MontyObject::string("woken"),
            MontyObject::bool(true),
        ])
    );
    session.finish().await.unwrap();

    let mut session = pool
        .checkout(&ReplConfig {
            os_policy: OsPolicy {
                datetime: DateTimeSource::Fixed {
                    unix_seconds: 1_700_000_000,
                    microsecond: 0,
                },
                sleep: SleepMode::Zero,
                random_start: RandomStart::Seed(RandomSeed::Int(42.into())),
                ..OsPolicy::default()
            },
            ..ReplConfig::default()
        })
        .await
        .unwrap();
    // CPython: random.seed(42); random.random()
    let code = "import random, time\ntime.sleep(3600)\n(time.time(), random.random())";
    let event = session.feed(code, vec![], vec![], false, &mut no_print).await.unwrap();
    assert_eq!(
        expect_complete(event),
        MontyObject::tuple([
            MontyObject::float(1_700_000_000.0),
            MontyObject::float(0.639_426_798_457_883_7),
        ])
    );
    session.finish().await.unwrap();
}

/// A checkout pinned to a fixed clock at `unix_seconds`.
fn fixed_clock(unix_seconds: i64) -> ReplConfig {
    ReplConfig {
        os_policy: OsPolicy {
            datetime: DateTimeSource::Fixed {
                unix_seconds,
                microsecond: 0,
            },
            ..OsPolicy::default()
        },
        ..ReplConfig::default()
    }
}

/// A restored session answers clock calls with the restoring checkout's policy,
/// both when idle and when resumed from a suspension dumped under another policy.
#[tokio::test]
async fn restored_session_takes_the_checkouts_os_policy() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&fixed_clock(1_000)).await.unwrap();
    let event = session
        .feed("import time\ntime.time()", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::float(1_000.0));
    let idle = session.dump().await.unwrap();
    let event = session
        .feed("fetch('x')\ntime.time()", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert!(matches!(event, TurnEvent::FunctionCall { .. }), "got {event:?}");
    let suspended = session.dump().await.unwrap();
    drop(session);

    let mut restored = pool.checkout(&fixed_clock(2_000)).await.unwrap();
    let (event, _script_name) = restored.restore(idle, vec![], &mut no_print).await.unwrap();
    assert!(event.is_none(), "idle dump should restore without a suspension");
    let event = restored
        .feed("time.time()", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::float(2_000.0));
    restored.finish().await.unwrap();

    let mut restored = pool.checkout(&fixed_clock(3_000)).await.unwrap();
    let (event, _script_name) = restored.restore(suspended, vec![], &mut no_print).await.unwrap();
    assert!(matches!(event, Some(TurnEvent::FunctionCall { .. })), "got {event:?}");
    let event = restored
        .resume(ResumeValue::Return(MontyObject::none()), &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::float(3_000.0));
    restored.finish().await.unwrap();

    // every other suspension kind resumes under the restoring policy too
    let (event, mut restored) = restore_under_new_clock(&pool, "import os\nos.getenv('X')\ntime.time()").await;
    assert!(matches!(event, Some(TurnEvent::OsCall { .. })), "got {event:?}");
    let event = restored
        .resume(ResumeValue::Return(MontyObject::none()), &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::float(4_000.0));
    restored.finish().await.unwrap();

    let (event, mut restored) = restore_under_new_clock(&pool, "missing\ntime.time()").await;
    assert!(matches!(event, Some(TurnEvent::NameLookup { .. })), "got {event:?}");
    let event = restored
        .resume_name_lookup(Some(MontyObject::none()), &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::float(4_000.0));
    restored.finish().await.unwrap();

    let code = "import asyncio\nasync def main():\n    await go()\n    return time.time()\nasyncio.run(main())";
    let (event, mut restored) = restore_under_new_clock(&pool, code).await;
    let Some(TurnEvent::ResolveFutures { pending_call_ids, .. }) = event else {
        panic!("expected ResolveFutures, got {event:?}");
    };
    let results = pending_call_ids
        .into_iter()
        .map(|id| (id, ResumeValue::Return(MontyObject::none())))
        .collect();
    let event = restored.resume_futures(results, &mut no_print).await.unwrap();
    assert_eq!(expect_complete(event), MontyObject::float(4_000.0));
    restored.finish().await.unwrap();
}

/// Feeds `code` under a clock fixed at 1000 until it suspends (answering an
/// external call with a future), dumps it, and restores it under a clock fixed at 4000.
async fn restore_under_new_clock(pool: &Pool, code: &str) -> (Option<TurnEvent>, Checkout) {
    let mut session = pool.checkout(&fixed_clock(1_000)).await.unwrap();
    session
        .feed("import time", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    let mut event = session.feed(code, vec![], vec![], false, &mut no_print).await.unwrap();
    if matches!(event, TurnEvent::FunctionCall { .. }) {
        event = session.resume(ResumeValue::Future, &mut no_print).await.unwrap();
    }
    assert!(
        !matches!(event, TurnEvent::Complete(_)),
        "expected a suspension, got {event:?}"
    );
    let state = session.dump().await.unwrap();
    drop(session);
    let mut restored = pool.checkout(&fixed_clock(4_000)).await.unwrap();
    let (event, _script_name) = restored.restore(state, vec![], &mut no_print).await.unwrap();
    (event, restored)
}

#[tokio::test]
async fn call_host_delivers_clock_and_sleeps_as_os_calls() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool
        .checkout(&ReplConfig {
            os_policy: OsPolicy {
                datetime: DateTimeSource::CallHost,
                sleep: SleepMode::CallHost,
                ..OsPolicy::default()
            },
            ..ReplConfig::default()
        })
        .await
        .unwrap();
    let code = "import time
time.sleep(1.5)
time.time()";
    let event = session.feed(code, vec![], vec![], false, &mut no_print).await.unwrap();
    let TurnEvent::OsCall {
        function_name, args, ..
    } = event
    else {
        panic!("expected OsCall, got {event:?}");
    };
    assert_eq!(function_name, "time.sleep");
    assert_eq!(args, CallArgs::from(vec![MontyObject::float(1.5)]));
    let event = session
        .resume(ResumeValue::Return(MontyObject::none()), &mut no_print)
        .await
        .unwrap();
    let TurnEvent::OsCall { function_name, .. } = event else {
        panic!("expected OsCall, got {event:?}");
    };
    assert_eq!(function_name, "time.time");
    let event = session
        .resume(ResumeValue::Return(MontyObject::float(7.5)), &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::float(7.5));
    session.finish().await.unwrap();
}

/// The pool aborts the first suspension past the limit uncatchably. The
/// session remains usable, but its suspension budget stays spent.
#[tokio::test]
async fn suspension_limit_aborts_the_feed() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool
        .checkout(&ReplConfig {
            limits: Some(ResourceLimits::default().max_suspensions(3)),
            ..ReplConfig::default()
        })
        .await
        .unwrap();
    let code = "n = 0\nwhile True:\n    try:\n        open('/etc/passwd')\n    except Exception:\n        n += 1";
    let mut event = session.feed(code, vec![], vec![], false, &mut no_print).await.unwrap();
    for _ in 0..2 {
        assert!(matches!(event, TurnEvent::OsCall { .. }), "got {event:?}");
        event = session.resume(ResumeValue::NotHandled, &mut no_print).await.unwrap();
    }
    assert!(matches!(event, TurnEvent::OsCall { .. }), "got {event:?}");
    let err = session
        .resume(ResumeValue::NotHandled, &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime, got {err:?}");
    };
    assert_eq!(exc.exc_type().to_string(), "RuntimeError");
    assert_eq!(exc.message(), Some("suspension limit 3 exceeded"));
    // three refusals were caught before the fourth suspension was aborted
    let event = session.feed("n", vec![], vec![], false, &mut no_print).await.unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(3));
    // the budget stays spent: a fresh feed's first suspension is aborted too
    let err = session
        .feed("fetch('x')", vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime, got {err:?}");
    };
    assert_eq!(exc.message(), Some("suspension limit 3 exceeded"));
    session.finish().await.unwrap();
}

/// The `max_suspensions` budget travels in the dump and is re-adopted on
/// restore, but the count is parent state and restarts at zero.
#[tokio::test]
async fn restored_session_readopts_its_suspension_limit() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool
        .checkout(&ReplConfig {
            limits: Some(ResourceLimits::default().max_suspensions(1)),
            ..ReplConfig::default()
        })
        .await
        .unwrap();
    let event = session
        .feed("fetch('x')", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert!(matches!(event, TurnEvent::FunctionCall { .. }));
    let state = session.dump().await.unwrap();
    drop(session);

    let mut restored = pool.checkout(&ReplConfig::default()).await.unwrap();
    let (event, _script_name) = restored.restore(state, vec![], &mut no_print).await.unwrap();
    // the re-announced suspension is the restored checkout's first
    assert!(matches!(event, Some(TurnEvent::FunctionCall { .. })), "got {event:?}");
    let event = restored
        .resume(ResumeValue::Return(MontyObject::int(1)), &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(1));
    // the dump's limit of one applies to the next suspension
    let err = restored
        .feed("fetch('y')", vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime, got {err:?}");
    };
    assert_eq!(exc.message(), Some("suspension limit 1 exceeded"));
    restored.finish().await.unwrap();
}

#[tokio::test]
async fn loaded_session_keeps_its_duration_budget() {
    // The `max_feed_duration` budget travels inside the dump — a session
    // restored via `restore` keeps the original limits even though the parent
    // never saw the original `ReplConfig`.
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool
        .checkout(&ReplConfig {
            limits: Some(ResourceLimits::default().max_feed_duration(Duration::from_millis(100))),
            ..ReplConfig::default()
        })
        .await
        .unwrap();
    let state = session.dump().await.unwrap();
    drop(session);

    let mut restored = pool.checkout(&ReplConfig::default()).await.unwrap();
    let (event, _script_name) = restored.restore(state, vec![], &mut no_print).await.unwrap();
    assert!(event.is_none(), "idle dump should restore without a suspension");
    let err = restored
        .feed("while True:\n    pass", vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime, got {err:?}");
    };
    assert_eq!(exc.exc_type().to_string(), "TimeoutError");
    restored.finish().await.unwrap();
}

/// A real subprocess cannot import a larger snapshot budget into a stricter checkout.
#[tokio::test]
async fn restored_session_cannot_raise_the_destination_memory_budget() {
    let pool = Pool::new(config()).await.unwrap();
    let destination = ReplConfig {
        limits: Some(ResourceLimits::default().max_memory(10 * 1024 * 1024)),
        ..ReplConfig::default()
    };
    let allocation = "large = b'a' * (12 * 1024 * 1024)\nlen(large)";
    let mut fresh = pool.checkout(&destination).await.unwrap();
    assert_eq!(
        expect_complete(fresh.feed("6 * 7", vec![], vec![], false, &mut no_print).await.unwrap()),
        MontyObject::int(42)
    );
    let error = fresh
        .feed(allocation, vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    assert!(matches!(error, PoolError::Runtime(ref exc) if exc.exc_type() == ExcType::MemoryError));
    drop(fresh);
    for suspended in [false, true] {
        let mut source = pool
            .checkout(&ReplConfig {
                limits: Some(ResourceLimits::default().max_memory(64 * 1024 * 1024)),
                ..ReplConfig::default()
            })
            .await
            .unwrap();
        source
            .feed(
                if suspended { "x = 42\nfetch('x')" } else { "x = 42" },
                vec![],
                vec![],
                false,
                &mut no_print,
            )
            .await
            .unwrap();
        let state = source.dump().await.unwrap();
        drop(source);
        let mut restored = pool.checkout(&destination).await.unwrap();
        let (event, _) = restored.restore(state, vec![], &mut no_print).await.unwrap();
        if suspended {
            assert!(matches!(event, Some(TurnEvent::FunctionCall { .. })));
            restored
                .resume(ResumeValue::Return(MontyObject::none()), &mut no_print)
                .await
                .unwrap();
        } else {
            assert!(event.is_none());
        }
        assert_eq!(
            expect_complete(restored.feed("x", vec![], vec![], false, &mut no_print).await.unwrap()),
            MontyObject::int(42)
        );
        let error = restored
            .feed(allocation, vec![], vec![], false, &mut no_print)
            .await
            .unwrap_err();
        assert!(matches!(error, PoolError::Runtime(ref exc) if exc.exc_type() == ExcType::MemoryError));
        drop(restored);
    }
    let mut sibling = pool.checkout(&destination).await.unwrap();
    assert_eq!(
        expect_complete(
            sibling
                .feed("6 * 7", vec![], vec![], false, &mut no_print)
                .await
                .unwrap()
        ),
        MontyObject::int(42)
    );
    sibling.finish().await.unwrap();
}

// =============================================================================
// Lifecycle
// =============================================================================

#[tokio::test]
async fn elastic_growth_up_to_max_then_exhausted() {
    let mut config = config();
    config.min_processes = 1;
    config.max_processes = 2;
    config.checkout_timeout = Some(Duration::from_millis(200));
    let pool = Pool::new(config).await.unwrap();

    let one = pool.checkout(&ReplConfig::default()).await.unwrap();
    let two = pool.checkout(&ReplConfig::default()).await.unwrap(); // grows beyond min
    let Err(err) = pool.checkout(&ReplConfig::default()).await else {
        panic!("expected Exhausted");
    };
    assert!(matches!(err, PoolError::Exhausted), "got {err:?}");

    one.finish().await.unwrap();
    let three = pool.checkout(&ReplConfig::default()).await.unwrap(); // reuses one's worker
    three.finish().await.unwrap();
    two.finish().await.unwrap();
    assert_eq!(pool.idle_workers(), 2);
}

#[tokio::test]
async fn dropping_a_checkout_kills_the_worker_but_frees_capacity() {
    let mut config = config();
    config.max_processes = 1;
    let pool = Pool::new(config).await.unwrap();

    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let pid = session.pid().unwrap();
    let _ = session
        .feed("x = 1", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    drop(session); // abandoned mid-session: worker killed, capacity released

    // with max_processes=1 this checkout only succeeds if capacity was freed
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    assert_ne!(session.pid().unwrap(), pid);
    assert_eq!(
        expect_complete(
            session
                .feed("5 + 5", vec![], vec![], false, &mut no_print)
                .await
                .unwrap()
        ),
        MontyObject::int(10)
    );
    session.finish().await.unwrap();
}

#[tokio::test]
async fn workers_are_recycled_after_max_checkouts() {
    let mut config = config();
    config.max_checkouts_per_worker = Some(1);
    let pool = Pool::new(config).await.unwrap();

    let session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let first_pid = session.pid().unwrap();
    let first_id = session.worker_id().unwrap();
    session.finish().await.unwrap();
    // retired, not pooled: the idle worker is a background replacement
    wait_for_idle(&pool, 1).await;
    assert_ne!(pool.idle_worker_pids(), vec![first_pid]);

    let session = pool.checkout(&ReplConfig::default()).await.unwrap();
    assert_ne!(session.pid().unwrap(), first_pid);
    assert_ne!(session.worker_id().unwrap(), first_id);
    session.finish().await.unwrap();
}

/// Without an explicit setting a worker serves `DEFAULT_MAX_CHECKOUTS_PER_WORKER`
/// sessions, then is retired so no child outlives that many tenants.
#[tokio::test]
async fn workers_are_recycled_after_the_default_checkout_count() {
    let mut config = config();
    config.max_processes = 1;
    assert_eq!(config.max_checkouts_per_worker, Some(DEFAULT_MAX_CHECKOUTS_PER_WORKER));
    let pool = Pool::new(config).await.unwrap();

    let mut first_id = None;
    for _ in 0..DEFAULT_MAX_CHECKOUTS_PER_WORKER {
        let session = pool.checkout(&ReplConfig::default()).await.unwrap();
        let id = session.worker_id().unwrap();
        assert_eq!(*first_id.get_or_insert(id), id);
        session.finish().await.unwrap();
    }
    let session = pool.checkout(&ReplConfig::default()).await.unwrap();
    assert_ne!(session.worker_id(), first_id);
    session.finish().await.unwrap();
}

/// `None` opts out of recycling: one worker serves past the default count.
#[tokio::test]
async fn no_recycle_limit_keeps_the_worker() {
    let mut config = config();
    config.max_processes = 1;
    config.max_checkouts_per_worker = None;
    let pool = Pool::new(config).await.unwrap();

    let session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let first_id = session.worker_id();
    session.finish().await.unwrap();
    for _ in 0..DEFAULT_MAX_CHECKOUTS_PER_WORKER {
        let session = pool.checkout(&ReplConfig::default()).await.unwrap();
        assert_eq!(session.worker_id(), first_id);
        session.finish().await.unwrap();
    }
}

/// With one checkout per process, every session gets a fresh worker, and the
/// pool refills to `min_processes` after each so the next one is warm.
#[tokio::test]
async fn recycled_workers_are_replaced_in_the_background() {
    let mut config = config();
    config.min_processes = 2;
    config.max_processes = 2;
    config.max_checkouts_per_worker = Some(1);
    let pool = Pool::new(config).await.unwrap();

    let mut seen = pool.idle_worker_pids();
    for _ in 0..3 {
        let session = pool.checkout(&ReplConfig::default()).await.unwrap();
        let pid = session.pid().unwrap();
        session.finish().await.unwrap();
        wait_for_idle(&pool, 2).await;
        for idle in pool.idle_worker_pids() {
            if !seen.contains(&idle) {
                seen.push(idle);
            }
        }
        assert!(seen.contains(&pid));
    }
    // two prewarmed plus one refill per session, never a PID reused
    assert_eq!(seen.len(), 5);
}

/// Workers lost to a crash or an abandoned checkout are replaced too.
#[tokio::test]
async fn crashed_and_dropped_workers_are_replaced() {
    let pool = Pool::new(config()).await.unwrap();

    let session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let dropped_pid = session.pid().unwrap();
    drop(session);
    wait_for_idle(&pool, 1).await;
    assert_ne!(pool.idle_worker_pids(), vec![dropped_pid]);

    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let crashed_pid = session.pid().unwrap();
    kill_pid(crashed_pid);
    let err = session
        .feed("1 + 1", vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    assert!(matches!(err, PoolError::Crashed { .. }), "got {err:?}");
    drop(session);
    wait_for_idle(&pool, 1).await;
    assert_ne!(pool.idle_worker_pids(), vec![crashed_pid]);
}

/// A refill reserves its slot before spawning, so it never takes the pool
/// past `max_processes`: a checkout racing it waits for the refilled worker.
#[tokio::test]
async fn refill_never_exceeds_max_processes() {
    let mut config = config();
    config.min_processes = 2;
    config.max_processes = 2;
    config.max_checkouts_per_worker = Some(1);
    config.checkout_timeout = Some(Duration::from_secs(1));
    let pool = Pool::new(config).await.unwrap();

    let first = pool.checkout(&ReplConfig::default()).await.unwrap();
    let held = pool.checkout(&ReplConfig::default()).await.unwrap();
    let first_pid = first.pid().unwrap();
    first.finish().await.unwrap();

    let refilled = pool.checkout(&ReplConfig::default()).await.unwrap();
    assert_ne!(refilled.pid().unwrap(), first_pid);
    assert_eq!(pool.idle_workers(), 0);
    let blocked = pool.checkout(&ReplConfig::default()).await.err();
    assert!(matches!(blocked, Some(PoolError::Exhausted)), "{blocked:?}");

    drop(held);
    drop(refilled);
    wait_for_idle(&pool, 2).await;
}

/// `min_processes` floors live workers, not idle ones: a reuse pool that ran
/// more sessions than its floor keeps exactly the workers its load spawned.
#[tokio::test]
async fn reuse_pool_does_not_grow_past_its_load() {
    let mut config = config();
    config.max_processes = 3;
    let pool = Pool::new(config).await.unwrap();

    let repl = ReplConfig::default();
    let (a, b, c) = tokio::join!(pool.checkout(&repl), pool.checkout(&repl), pool.checkout(&repl));
    for session in [a, b, c] {
        session.unwrap().finish().await.unwrap();
    }
    assert_eq!(pool.idle_workers(), 3);
    sleep(Duration::from_millis(100)).await;
    assert_eq!(pool.idle_workers(), 3);
}

#[tokio::test]
async fn concurrent_checkouts_run_in_parallel() {
    let mut config = config();
    config.min_processes = 2;
    config.max_processes = 2;
    let pool = Pool::new(config).await.unwrap();

    let run_one = async {
        let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
        let event = session
            .feed("sum(range(1000))", vec![], vec![], false, &mut no_print)
            .await
            .unwrap();
        assert_eq!(expect_complete(event), MontyObject::int(499_500));
        session.finish().await.unwrap();
    };
    tokio::join!(run_one, async {
        let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
        let event = session
            .feed("sum(range(1000))", vec![], vec![], false, &mut no_print)
            .await
            .unwrap();
        assert_eq!(expect_complete(event), MontyObject::int(499_500));
        session.finish().await.unwrap();
    });
    assert_eq!(pool.idle_workers(), 2);
}

#[tokio::test]
async fn typing_error_via_pool() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool
        .checkout(&ReplConfig {
            type_check: true,
            ..ReplConfig::default()
        })
        .await
        .unwrap();
    let err = session
        .feed("x: int = 'nope'", vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Typing(diagnostics) = err else {
        panic!("expected Typing, got {err:?}");
    };
    assert!(diagnostics.contains("invalid-assignment"), "{diagnostics}");
    // the session survives a typing rejection
    assert_eq!(
        expect_complete(
            session
                .feed("1 + 1", vec![], vec![], false, &mut no_print)
                .await
                .unwrap()
        ),
        MontyObject::int(2)
    );
    session.finish().await.unwrap();
}

/// Security-critical: a reused worker's type checker must not let one
/// session's files (script or stubs) influence the next session's checks.
/// The same pid is asserted so this cannot pass vacuously on a fresh worker —
/// the exact regression a broken `Reset`-time scrub would cause.
#[tokio::test]
async fn type_check_state_is_scrubbed_between_checkouts_on_the_same_worker() {
    let concise = TypeCheckingConfig {
        format: TypeCheckingFormat::Concise,
        color: false,
    };
    let pool = Pool::new(config()).await.unwrap();

    // Session A: commits a module-level name into `a.py` and carries stubs.
    let mut session = pool
        .checkout(&ReplConfig {
            script_name: "a.py".to_owned(),
            type_check: true,
            type_check_stubs: Some("STUB_SECRET: str = 'from-stubs'".to_owned()),
            type_check_config: concise,
            ..ReplConfig::default()
        })
        .await
        .unwrap();
    let first_pid = session.pid().unwrap();
    let event = session
        .feed("SECRET = 'hunter2'", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::none());
    session.finish().await.unwrap();
    assert_eq!(pool.idle_workers(), 1);

    // Session B runs in the SAME process; A's files must be gone.
    let mut session = pool
        .checkout(&ReplConfig {
            script_name: "b.py".to_owned(),
            type_check: true,
            type_check_config: concise,
            ..ReplConfig::default()
        })
        .await
        .unwrap();
    assert_eq!(
        session.pid().unwrap(),
        first_pid,
        "worker was not reused — test is vacuous"
    );

    let mut probe = async |code: &str| {
        let fed = match session.feed(code, vec![], vec![], false, &mut no_print).await {
            // a host module's stubs are asked for first; this host offers none
            Ok(TurnEvent::OsCall { function_name, .. }) if function_name == IMPORT_STUBS_CALL => {
                session.resume(ResumeValue::NotHandled, &mut no_print).await
            }
            other => other,
        };
        match fed {
            Err(PoolError::Typing(diagnostics)) => diagnostics,
            other => panic!("expected a typing rejection for {code:?}, got {other:?}"),
        }
    };
    assert_eq!(
        probe("from a import SECRET").await,
        "b.py:1:6: error[unresolved-import] Cannot resolve imported module `a`\n"
    );
    assert_eq!(
        probe("from repl_type_stubs import STUB_SECRET").await,
        "b.py:1:6: error[unresolved-import] Cannot resolve imported module `repl_type_stubs`\n"
    );
    assert_eq!(
        probe("x = STUB_SECRET").await,
        "b.py:1:5: error[unresolved-reference] Name `STUB_SECRET` used when not defined\n"
    );
    // and the scrub did not damage the checker itself
    let event = session
        .feed("x: int = 1\nx", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(1));
    session.finish().await.unwrap();
}

// =============================================================================
// Cancellation
// =============================================================================

/// Explicit termination reaps the owned process before it reports completion.
#[tokio::test]
async fn termination_reaps_a_cancelled_turn_and_preserves_pool_capacity() {
    let mut settings = config();
    settings.max_processes = 1;
    let pool = Pool::new(settings).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let worker = session.worker_id().unwrap();
    {
        let mut printer = no_print;
        tokio::select! {
            result = session.feed("while True:\n    pass", vec![], vec![], false, &mut printer) => panic!("the controlled turn cannot finish: {result:?}"),
            () = sleep(Duration::from_millis(10)) => {}
        }
    }
    assert!(session.terminate().await.is_some());
    let mut next = pool.checkout(&ReplConfig::default()).await.unwrap();
    assert_ne!(next.worker_id(), Some(worker));
    assert_eq!(
        expect_complete(next.feed("6 * 7", vec![], vec![], false, &mut no_print).await.unwrap()),
        MontyObject::int(42)
    );
    next.finish().await.unwrap();
}

/// An idle process is killed rather than returned to the reusable pool.
#[tokio::test]
async fn termination_reaps_an_idle_checkout() {
    let pool = Pool::new(config()).await.unwrap();
    let session = pool.checkout(&ReplConfig::default()).await.unwrap();
    assert!(session.terminate().await.is_some());
}

/// A worker discarded by an earlier protocol failure has no retained exit proof.
#[tokio::test]
async fn termination_without_an_owned_worker_does_not_confirm_exit() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    {
        let mut printer = no_print;
        tokio::select! {
            result = session.feed("while True:\n    pass", vec![], vec![], false, &mut printer) => panic!("the controlled turn cannot finish: {result:?}"),
            () = sleep(Duration::from_millis(10)) => {}
        }
    }
    assert!(matches!(
        session.feed("6 * 7", vec![], vec![], false, &mut no_print).await,
        Err(PoolError::Protocol(_))
    ));
    assert!(session.terminate().await.is_none());
}

/// A turn future dropped mid-flight leaves the protocol state unknowable: the
/// next call on the checkout must discard the worker and fail cleanly, and
/// the pool must stay healthy.
#[tokio::test]
async fn cancelled_turn_discards_the_worker_on_next_use() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();

    {
        // race the feed against a short sleep: the snippet never terminates,
        // so the sleep deterministically wins and the feed is cancelled while
        // awaiting the worker's reply
        let mut printer = no_print;
        let feed = session.feed("while True:\n    pass", vec![], vec![], false, &mut printer);
        tokio::select! {
            _result = feed => panic!("the feed cannot complete"),
            () = sleep(Duration::from_millis(10)) => {}
        }
    }

    let err = session
        .feed("1 + 1", vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Protocol(message) = err else {
        panic!("expected Protocol, got {err:?}");
    };
    assert_eq!(
        message,
        "a previous protocol turn was cancelled mid-flight; the worker was discarded"
    );

    // the worker was discarded and the pool serves a fresh one
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let event = session
        .feed("1 + 1", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(2));
    session.finish().await.unwrap();
}

/// A cancellation condemns the worker on *any* next call: `resume_from_mounts`
/// must hit the cancellation check before its own pending-state validation
/// and report the discard, not a state error.
#[tokio::test]
async fn cancelled_turn_discards_the_worker_on_resume_from_mounts() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    {
        let mut printer = no_print;
        let feed = session.feed("while True:\n    pass", vec![], vec![], false, &mut printer);
        tokio::select! {
            _result = feed => panic!("the feed cannot complete"),
            () = sleep(Duration::from_millis(10)) => {}
        }
    }

    let err = session.resume_from_mounts(&mut no_print).await.unwrap_err();
    let PoolError::Protocol(message) = err else {
        panic!("expected Protocol, got {err:?}");
    };
    assert_eq!(
        message,
        "a previous protocol turn was cancelled mid-flight; the worker was discarded"
    );

    // the discard already happened: every later call reports the dead checkout
    let err = session
        .resume(ResumeValue::Return(MontyObject::none()), &mut no_print)
        .await
        .unwrap_err();
    assert!(matches!(err, PoolError::Finished), "got {err:?}");
}

// =============================================================================
// Dump / load across workers
// =============================================================================

#[tokio::test]
async fn dump_survives_worker_death_and_loads_elsewhere() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    assert_eq!(
        expect_complete(
            session
                .feed("base = 40", vec![], vec![], false, &mut no_print)
                .await
                .unwrap()
        ),
        MontyObject::none()
    );
    let event = session
        .feed("base + ext()", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    let TurnEvent::FunctionCall {
        call_id: _,
        ref function_name,
        ..
    } = event
    else {
        panic!("expected FunctionCall, got {event:?}");
    };
    assert_eq!(function_name, "ext");

    let state = session.dump().await.unwrap();
    drop(session); // kill the original worker outright

    // restore into a fresh worker by loading over its empty session
    let mut restored = pool.checkout(&ReplConfig::default()).await.unwrap();
    let (event, script_name) = restored.restore(state, vec![], &mut no_print).await.unwrap();
    // the worker echoes the dump's adopted script name back to the parent
    assert_eq!(script_name.as_deref(), Some("main.py"));
    let Some(TurnEvent::FunctionCall { ref function_name, .. }) = event else {
        panic!("expected re-announced FunctionCall, got {event:?}");
    };
    assert_eq!(function_name, "ext");
    let event = restored
        .resume(ResumeValue::Return(MontyObject::int(2)), &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(42));
    restored.finish().await.unwrap();
}

/// Zero is the explicit line-buffering sentinel, so a positive interval must
/// never round down into it. 100 prints would arrive as 100 events if the
/// sub-millisecond interval had truncated to zero; any batching at all proves
/// the timer is still on.
#[tokio::test]
async fn a_sub_millisecond_interval_does_not_become_line_buffering() {
    let pool = Pool::new(config()).await.unwrap();
    let repl = ReplConfig {
        print_flush_interval: Some(Duration::from_micros(400)),
        ..ReplConfig::default()
    };
    let mut session = pool.checkout(&repl).await.unwrap();
    let mut events = 0usize;
    session
        .feed(
            "for i in range(100):\n    print(i)",
            vec![],
            vec![],
            false,
            &mut on_print_sync(|_, _: &str| events += 1),
        )
        .await
        .unwrap();
    assert!(events < 100, "expected batching, got one event per line ({events})");
    session.finish().await.unwrap();
}

/// A `Load` restores the repl without materializing the checkout's stored
/// `Configure`, so the print flush interval has to be adopted when that config
/// arrives — otherwise a restored session silently falls back to the default
/// and ignores the line buffering its host asked for.
#[tokio::test]
async fn a_restored_session_honors_its_checkout_flush_interval() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    session
        .feed("base = 1", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    let state = session.dump().await.unwrap();
    drop(session);

    let repl = ReplConfig {
        print_flush_interval: Some(Duration::ZERO),
        ..ReplConfig::default()
    };
    let mut restored = pool.checkout(&repl).await.unwrap();
    restored.restore(state, vec![], &mut no_print).await.unwrap();
    let mut lines = Vec::new();
    restored
        .feed(
            "for i in range(20):\n    print(base + i)",
            vec![],
            vec![],
            false,
            &mut on_print_sync(|_, text: &str| lines.push(text.to_owned())),
        )
        .await
        .unwrap();
    assert_eq!(lines.len(), 20);
    assert_eq!(lines[0], "1\n");
    assert_eq!(lines[19], "20\n");
    restored.finish().await.unwrap();
}

// =============================================================================
// Environment isolation
// =============================================================================

/// Workers must be spawned with an empty environment: host secrets must never
/// be in a worker's memory, where a sandbox escape or memory disclosure could
/// reach them. Linux-only because it observes the child via /proc.
#[cfg(target_os = "linux")]
#[tokio::test]
async fn worker_environment_is_empty() {
    // The test process itself always carries variables (PATH, CARGO, ...),
    // so an empty child environ proves nothing was inherited.
    assert!(env::var("PATH").is_ok(), "test process should have PATH set");

    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let environ = fs::read(format!("/proc/{}/environ", session.pid().unwrap())).unwrap();
    assert!(
        environ.is_empty(),
        "worker environment should be empty, got: {}",
        String::from_utf8_lossy(&environ).replace('\0', " ")
    );

    // The worker is fully functional without an environment.
    let event = session
        .feed("1 + 1", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(2));
    session.finish().await.unwrap();
}

/// The per-feed budget restarts at each feed, so a session survives any number
/// of short feeds and the worker is never killed — the sandbox raises
/// `TimeoutError` well inside `feed_duration_limit_grace`.
#[tokio::test]
async fn max_feed_duration_bounds_each_feed_without_killing_the_worker() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool
        .checkout(&ReplConfig {
            limits: Some(ResourceLimits::default().max_feed_duration(Duration::from_millis(100))),
            ..ReplConfig::default()
        })
        .await
        .unwrap();
    for _ in 0..3 {
        let event = session
            .feed("1 + 1", vec![], vec![], false, &mut no_print)
            .await
            .unwrap();
        assert_eq!(expect_complete(event), MontyObject::int(2));
    }
    let err = session
        .feed("while True:\n    pass", vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime, got {err:?}");
    };
    assert_eq!(exc.exc_type().to_string(), "TimeoutError");
    // The session survived, so the budget really did restart.
    let event = session
        .feed("2 + 2", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(4));
    session.finish().await.unwrap();
    assert_eq!(pool.idle_workers(), 1);
}

/// The per-turn budget is enforced in the sandbox too, and likewise leaves the
/// session usable.
#[tokio::test]
async fn max_turn_duration_bounds_a_runaway_turn() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool
        .checkout(&ReplConfig {
            limits: Some(ResourceLimits::default().max_turn_duration(Duration::from_millis(100))),
            ..ReplConfig::default()
        })
        .await
        .unwrap();
    let err = session
        .feed("while True:\n    pass", vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime, got {err:?}");
    };
    assert_eq!(exc.exc_type().to_string(), "TimeoutError");
    session.finish().await.unwrap();
    assert_eq!(pool.idle_workers(), 1);
}

/// Budgets near `Duration::MAX` must not overflow the parent's backstop
/// arithmetic (remaining budget plus grace), in either scope.
#[tokio::test]
async fn huge_feed_and_turn_budgets_do_not_overflow_the_backstop() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool
        .checkout(&ReplConfig {
            limits: Some(
                ResourceLimits::default()
                    .max_feed_duration(Duration::MAX)
                    .max_turn_duration(Duration::MAX),
            ),
            ..ReplConfig::default()
        })
        .await
        .unwrap();
    let event = session
        .feed("1 + 1", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(2));
}

/// A worker that reports less feed time than it already reported cannot rewind
/// the parent's feed backstop.
///
/// The stand-in spends the whole 60s budget on its first suspension, then
/// claims zero on the second and goes quiet. The ratchet keeps the spent
/// figure, so the next turn is armed with the grace alone — without it the
/// parent would hand a hostile worker the budget back, every turn, for free.
#[cfg(unix)]
#[tokio::test]
async fn a_rewound_feed_clock_cannot_loosen_the_feed_backstop() {
    let dir = tempfile::tempdir().unwrap();
    let suspension = |feed_execution_micros| pb::ChildEvent {
        feed_execution_micros,
        ..child_event(pb::child_event::Kind::NameLookup(pb::NameLookup {
            name: "x".to_owned(),
            object_id: None,
            position: Some(position()),
        }))
    };
    // `Ok` answers Configure, then the honest suspension and the rewound one.
    // Nothing answers the third request: that is the turn the backstop must end.
    let mut replies = framed(&child_event(pb::child_event::Kind::Ok(pb::Ok {})));
    replies.extend(framed(&suspension(60_000_000)));
    replies.extend(framed(&suspension(0)));
    let replies_path = dir.path().join("replies.bin");
    fs::write(&replies_path, &replies).unwrap();
    let fake = write_fake_monty(
        dir.path(),
        &format!("#!/bin/sh\ncat '{}'\nsleep 30\n", replies_path.display()),
    );

    let grace = Duration::from_millis(100);
    let mut config = PoolConfig::subprocess(&fake);
    config.feed_duration_limit_grace = Some(grace);
    // The feed backstop must be what fires, not a blanket per-turn deadline.
    config.request_timeout = None;
    let pool = Pool::new(config).await.unwrap();
    let mut checkout = pool
        .checkout(&ReplConfig {
            limits: Some(ResourceLimits::default().max_feed_duration(Duration::from_secs(60))),
            ..ReplConfig::default()
        })
        .await
        .expect("the stand-in answers Configure with Ok");

    let feed = pb::ParentRequest {
        kind: Some(pb::parent_request::Kind::Feed(pb::Feed {
            code: "x".to_owned(),
            inputs: vec![].into(),
            values: None,
            skip_type_check: false,
            cwd: "/".to_owned(),
        })),
        ..pb::ParentRequest::default()
    };
    let resume = pb::ParentRequest {
        kind: Some(pb::parent_request::Kind::ResumeNameLookup(pb::ResumeNameLookup {
            kind: Some(pb::resume_name_lookup::Kind::Undefined(pb::Unit {})),
            values: None,
        })),
        ..pb::ParentRequest::default()
    };
    let mut on_event = |_: &pb::ChildEvent| Box::pin(ready(())) as PrintFuture;
    checkout.turn_raw(&feed, &mut on_event).await.unwrap();
    checkout.turn_raw(&resume, &mut on_event).await.unwrap();

    // Bounded so a regression fails here rather than waiting out the 60s
    // budget the rewind would have restored.
    let outcome = timeout(Duration::from_secs(5), checkout.turn_raw(&resume, &mut on_event)).await;
    let Ok(Err(PoolError::Timeout { timeout })) = outcome else {
        panic!("the spent feed budget must still backstop the next turn, got {outcome:?}");
    };
    assert_eq!(timeout, grace);
}

/// A child that predates the position field announces suspensions without
/// it; the parent reports an unknown range rather than rejecting them.
#[cfg(unix)]
#[tokio::test]
async fn a_suspension_without_a_position_reads_as_unknown() {
    let dir = tempfile::tempdir().unwrap();
    let mut replies = framed(&child_event(pb::child_event::Kind::Ok(pb::Ok {})));
    replies.extend(framed(&child_event(pb::child_event::Kind::NameLookup(
        pb::NameLookup {
            name: "x".to_owned(),
            object_id: None,
            position: None,
        },
    ))));
    let replies_path = dir.path().join("replies.bin");
    fs::write(&replies_path, &replies).unwrap();
    let fake = write_fake_monty(
        dir.path(),
        &format!("#!/bin/sh\ncat '{}'\nsleep 30\n", replies_path.display()),
    );

    let pool = Pool::new(PoolConfig::subprocess(&fake)).await.unwrap();
    let mut checkout = pool
        .checkout(&ReplConfig::default())
        .await
        .expect("the stand-in answers Configure with Ok");
    let event = checkout.feed("x", vec![], vec![], false, &mut no_print).await.unwrap();
    let TurnEvent::NameLookup { name, position, .. } = event else {
        panic!("expected a name lookup, got {event:?}");
    };
    assert_eq!(name, "x");
    assert_eq!(position, SourceRange::unknown());
}

/// A second raw `Feed` restarts the parent's feed clock, as `Checkout::feed`
/// does — the previous feed's total must not shorten the new feed's backstop.
///
/// The deadline is read off the `Timeout` error rather than timed, so the
/// assertion is exact: `begin_feed` gives the whole budget back, and without
/// it the second feed would be armed with the grace alone.
#[cfg(unix)]
#[tokio::test]
async fn a_raw_feed_restarts_the_parent_feed_clock() {
    let dir = tempfile::tempdir().unwrap();
    let budget = Duration::from_millis(300);
    let grace = Duration::from_millis(100);
    // `Ok` answers Configure; the suspension ends the first feed having spent
    // the whole budget. The second feed goes unanswered.
    let mut replies = framed(&child_event(pb::child_event::Kind::Ok(pb::Ok {})));
    replies.extend(framed(&pb::ChildEvent {
        feed_execution_micros: u64::try_from(budget.as_micros()).unwrap(),
        ..child_event(pb::child_event::Kind::NameLookup(pb::NameLookup {
            name: "x".to_owned(),
            object_id: None,
            position: Some(position()),
        }))
    }));
    let replies_path = dir.path().join("replies.bin");
    fs::write(&replies_path, &replies).unwrap();
    let fake = write_fake_monty(
        dir.path(),
        &format!("#!/bin/sh\ncat '{}'\nsleep 30\n", replies_path.display()),
    );

    let mut config = PoolConfig::subprocess(&fake);
    config.feed_duration_limit_grace = Some(grace);
    config.request_timeout = None;
    let pool = Pool::new(config).await.unwrap();
    let mut checkout = pool
        .checkout(&ReplConfig {
            limits: Some(ResourceLimits::default().max_feed_duration(budget)),
            ..ReplConfig::default()
        })
        .await
        .expect("the stand-in answers Configure with Ok");

    let feed = pb::ParentRequest {
        kind: Some(pb::parent_request::Kind::Feed(pb::Feed {
            code: "x".to_owned(),
            inputs: vec![].into(),
            values: None,
            skip_type_check: false,
            cwd: "/".to_owned(),
        })),
        ..pb::ParentRequest::default()
    };
    let mut on_event = |_: &pb::ChildEvent| Box::pin(ready(())) as PrintFuture;
    checkout.turn_raw(&feed, &mut on_event).await.unwrap();
    let err = checkout
        .turn_raw(&feed, &mut on_event)
        .await
        .expect_err("the stand-in never answers the second feed");
    let PoolError::Timeout { timeout } = err else {
        panic!("expected the feed backstop to fire, got {err:?}");
    };
    assert_eq!(timeout, budget + grace);
}

/// A `Load` reply claiming a looser feed budget than the checkout's cannot
/// loosen the parent's feed backstop: the configured budget stays the ceiling.
#[cfg(unix)]
#[tokio::test]
async fn a_load_reply_cannot_loosen_the_feed_backstop() {
    let dir = tempfile::tempdir().unwrap();
    let budget = Duration::from_millis(300);
    let grace = Duration::from_millis(100);
    // `Ok` answers Configure, then the Load, claiming an hour's feed budget.
    // The feed after it goes unanswered.
    let mut replies = framed(&child_event(pb::child_event::Kind::Ok(pb::Ok {})));
    replies.extend(framed(&pb::ChildEvent {
        max_feed_duration_micros: Some(3_600_000_000),
        ..child_event(pb::child_event::Kind::Ok(pb::Ok {}))
    }));
    let replies_path = dir.path().join("replies.bin");
    fs::write(&replies_path, &replies).unwrap();
    let fake = write_fake_monty(
        dir.path(),
        &format!("#!/bin/sh\ncat '{}'\nsleep 30\n", replies_path.display()),
    );

    let mut config = PoolConfig::subprocess(&fake);
    config.feed_duration_limit_grace = Some(grace);
    config.request_timeout = None;
    let pool = Pool::new(config).await.unwrap();
    let mut checkout = pool
        .checkout(&ReplConfig {
            limits: Some(ResourceLimits::default().max_feed_duration(budget)),
            ..ReplConfig::default()
        })
        .await
        .expect("the stand-in answers Configure with Ok");
    let (event, _) = checkout.restore(vec![0], vec![], &mut no_print).await.unwrap();
    assert!(event.is_none());

    // Bounded so a regression fails here rather than waiting out the stand-in.
    let outcome = timeout(
        Duration::from_secs(5),
        checkout.feed("x", vec![], vec![], false, &mut no_print),
    )
    .await;
    let Ok(Err(PoolError::Timeout { timeout })) = outcome else {
        panic!("the configured feed budget must backstop the restored feed, got {outcome:?}");
    };
    assert_eq!(timeout, budget + grace);
}

/// With the grace turned off the parent does not backstop that budget at all,
/// so the sandbox's own `TimeoutError` is what ends the feed — the worker must
/// still come back alive.
#[tokio::test]
async fn a_disabled_grace_leaves_the_sandbox_limit_in_charge() {
    let mut pool_config = config();
    pool_config.feed_duration_limit_grace = None;
    pool_config.turn_duration_limit_grace = None;
    let pool = Pool::new(pool_config).await.unwrap();
    let mut session = pool
        .checkout(&ReplConfig {
            limits: Some(ResourceLimits::default().max_feed_duration(Duration::from_millis(100))),
            ..ReplConfig::default()
        })
        .await
        .unwrap();
    let err = session
        .feed("while True:\n    pass", vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime, got {err:?}");
    };
    assert_eq!(exc.exc_type().to_string(), "TimeoutError");
    session.finish().await.unwrap();
    assert_eq!(pool.idle_workers(), 1);
}

/// The suspension position every hand-built event carries; only the
/// unix-gated forged-frame tests build events.
#[cfg(unix)]
fn position() -> pb::SourceRange {
    pb::SourceRange {
        filename: "main.py".to_owned(),
        start: 0,
        end: 1,
    }
}

// ---- host-provided modules ---------------------------------------------------

/// The host module an import is answered with, under a fixed id.
fn host_module(name: &str, attrs: Vec<(&str, MontyObject)>) -> MontyObject {
    MontyObject::module(
        name,
        MontyUuid::from_u128(2),
        attrs.into_iter().map(|(k, v)| (MontyObject::string(k), v)),
    )
}

fn expect_import(event: TurnEvent) -> String {
    expect_import_args(event).module
}

/// The arguments of the `import` call `event` suspended on.
fn expect_import_args(event: TurnEvent) -> ImportArgs {
    let TurnEvent::OsCall {
        function_name, args, ..
    } = event
    else {
        panic!("expected the import to suspend, got {event:?}");
    };
    assert_eq!(function_name, IMPORT_CALL);
    ImportArgs::from_call_args(&args).expect("well-formed import arguments")
}

fn expect_import_stubs(event: TurnEvent) -> Vec<String> {
    let TurnEvent::OsCall {
        function_name, args, ..
    } = event
    else {
        panic!("expected the stubs ask, got {event:?}");
    };
    assert_eq!(function_name, IMPORT_STUBS_CALL);
    let names: Vec<_> = args.args().map(|arg| arg.to_owned()).collect();
    let [names] = names.as_slice() else {
        panic!("expected one list of names, got {names:?}");
    };
    names
        .as_ref()
        .items()
        .expect("a list")
        .iter()
        .map(|name| name.as_str().expect("a module name").to_owned())
        .collect()
}

fn tools_stubs(source: &str) -> ResumeValue {
    ResumeValue::Return(MontyObject::dict([(
        MontyObject::string("tools"),
        MontyObject::string(source),
    )]))
}

/// Functions on the returned module dispatch as ordinary host functions.
#[tokio::test]
async fn an_import_is_answered_by_the_host() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let event = session
        .feed("import tools\ntools.add(1, 2)", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_import(event), "tools");
    let tools = host_module("tools", vec![("add", MontyObject::function("add", None))]);
    let event = session.resume(ResumeValue::Return(tools), &mut no_print).await.unwrap();
    let TurnEvent::FunctionCall {
        function_name, args, ..
    } = event
    else {
        panic!("expected the tool call, got {event:?}");
    };
    assert_eq!(function_name, "add");
    let summands: Vec<_> = args.args().map(|arg| arg.to_owned()).collect();
    assert_eq!(summands, vec![MontyObject::int(1), MontyObject::int(2)]);
    let event = session
        .resume(ResumeValue::Return(MontyObject::int(3)), &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::int(3));

    let event = session
        .feed("import nope", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_import(event), "nope");
    let err = session.resume(ResumeValue::NotFound, &mut no_print).await.unwrap_err();
    let PoolError::Runtime(exc) = err else {
        panic!("expected Runtime, got {err:?}");
    };
    assert_snapshot!(exc.to_string(), @r#"
    Traceback (most recent call last):
      File "<python-input-1>", line 1, in <module>
        import nope
    ModuleNotFoundError: No module named 'nope'
    "#);
    session.finish().await.unwrap();
}

/// Host stubs are requested once per module per session, before type checking.
#[tokio::test]
async fn module_stubs_type_check_imports() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&type_checked()).await.unwrap();
    let event = session
        .feed(
            "from tools import add\nadd('x', 2)",
            vec![],
            vec![],
            false,
            &mut no_print,
        )
        .await
        .unwrap();
    assert_eq!(expect_import_stubs(event), vec!["tools".to_owned()]);
    let err = session
        .resume(tools_stubs("def add(a: int, b: int) -> int: ...\n"), &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Typing(diagnostics) = err else {
        panic!("expected Typing, got {err:?}");
    };
    assert_snapshot!(diagnostics, @r#"main.py:2:5: error[invalid-argument-type] Argument to function `add` is incorrect: Expected `int`, found `Literal["x"]`"#);
    // an import in one feed is still bound for the next feed's check
    let event = session
        .feed("import math as m", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_complete(event), MontyObject::none());
    let err = session
        .feed("m.sqrt('4')", vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    assert!(matches!(err, PoolError::Typing(_)), "expected Typing, got {err:?}");
    // the stub is kept: the next feed importing the module does not ask again
    let event = session
        .feed("import tools", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_import(event), "tools");
    session.finish().await.unwrap();
}

fn type_checked() -> ReplConfig {
    ReplConfig {
        type_check: true,
        type_check_config: TypeCheckingConfig {
            format: TypeCheckingFormat::Concise,
            color: false,
        },
        ..ReplConfig::default()
    }
}

/// Retained stubs would expose one tenant's module types to the next session.
#[tokio::test]
async fn module_stubs_do_not_outlive_their_session_on_a_reused_worker() {
    let pool = Pool::new(config()).await.unwrap();
    let mut session = pool.checkout(&type_checked()).await.unwrap();
    let first_id = session.worker_id().unwrap();
    let event = session
        .feed("import tools", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_import_stubs(event), vec!["tools".to_owned()]);
    let event = session
        .resume(tools_stubs("def add(a: int, b: int) -> int: ...\n"), &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_import(event), "tools");
    let tools = host_module("tools", vec![]);
    let event = session.resume(ResumeValue::Return(tools), &mut no_print).await.unwrap();
    assert_eq!(expect_complete(event), MontyObject::none());
    session.finish().await.unwrap();

    // the same worker, a session answering with no stubs: the import must not resolve
    let mut session = pool.checkout(&type_checked()).await.unwrap();
    assert_eq!(session.worker_id(), Some(first_id));
    let event = session
        .feed("import tools", vec![], vec![], false, &mut no_print)
        .await
        .unwrap();
    assert_eq!(expect_import_stubs(event), vec!["tools".to_owned()]);
    let err = session
        .resume(ResumeValue::NotHandled, &mut no_print)
        .await
        .unwrap_err();
    let PoolError::Typing(diagnostics) = err else {
        panic!("expected Typing, got {err:?}");
    };
    assert_snapshot!(diagnostics, @"main.py:1:8: error[unresolved-import] Cannot resolve imported module `tools`");
    session.finish().await.unwrap();
}

#[tokio::test]
async fn invalid_stub_answers_without_cpu_supervision_remain_resumable() {
    let pool = Pool::new(config()).await.unwrap();
    for answer in [ResumeValue::Future, ResumeValue::Return(MontyObject::int(42))] {
        let mut session = pool
            .checkout(&ReplConfig {
                type_check: true,
                ..ReplConfig::default()
            })
            .await
            .unwrap();
        let event = session
            .feed("import tools", vec![], vec![], false, &mut no_print)
            .await
            .unwrap();
        assert_eq!(expect_import_stubs(event), vec!["tools".to_owned()]);
        assert!(matches!(
            session.resume(answer, &mut no_print).await,
            Err(PoolError::Protocol(_))
        ));
        let error = MontyException::new(ExcType::RuntimeError, Some("stub provider failed".to_owned()));
        let result = session.resume(ResumeValue::Error(error), &mut no_print).await;
        assert!(
            matches!(result, Err(PoolError::Runtime(ref error)) if error.message() == Some("stub provider failed"))
        );
        let event = session
            .feed("1 + 1", vec![], vec![], false, &mut no_print)
            .await
            .unwrap();
        assert_eq!(expect_complete(event), MontyObject::int(2));
        session.finish().await.unwrap();
    }
    pool.close().await;
}

#[cfg(target_os = "linux")]
#[path = "support/cpu_limits.rs"]
mod cpu_limits;

/// CPU supervision is Linux-only, so other platforms refuse CPU mode before spawning a worker.
#[cfg(not(target_os = "linux"))]
#[tokio::test]
async fn cpu_clock_is_rejected_off_linux() {
    let mut config = config();
    config.execution_clock = ExecutionClock::Cpu;
    config.request_timeout = Some(Duration::from_secs(2));
    let Err(error) = Pool::new(config).await else {
        panic!("CPU pool must be rejected off Linux");
    };
    assert_eq!(
        error.to_string(),
        "failed to spawn monty worker: CPU execution clock is only supported for subprocess workers on Linux"
    );
}

/// An oversized result discards the worker; the next checkout still succeeds.
#[tokio::test]
async fn a_host_decode_budget_rejects_a_subprocess_result() {
    let mut config = config();
    config.max_decode_bytes = 4096;
    let pool = Pool::new(config).await.unwrap();
    let mut session = pool.checkout(&ReplConfig::default()).await.unwrap();
    let result = session.feed("42", vec![], vec![], false, &mut no_print).await.unwrap();
    assert_eq!(expect_complete(result), MontyObject::int(42));
    let error = session
        .feed("[0] * 100_000", vec![], vec![], false, &mut no_print)
        .await
        .unwrap_err();
    assert!(matches!(error, PoolError::Protocol(_)));
    assert!(session.worker_id().is_none());
    drop(session);
    let mut next = pool.checkout(&ReplConfig::default()).await.unwrap();
    let result = next.feed("42", vec![], vec![], false, &mut no_print).await.unwrap();
    assert_eq!(expect_complete(result), MontyObject::int(42));
    next.finish().await.unwrap();
}