autumn-web 0.9.0

An opinionated, convention-over-configuration web framework for 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
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
//! The sandbox host: a `wasmi` interpreter plus a deny-by-default WASI shim.
//!
//! # The sandbox *is* this file's import list
//!
//! A WebAssembly guest can do exactly two things on its own: compute, and call
//! a function the host gave it. It has no syscalls, no ambient file
//! descriptors and no way to name anything outside its own linear memory. So
//! the entire authority a sandboxed plugin holds is the list of host functions
//! `define_wasi_shim` registers — which is why they are all in one function,
//! in one place, readable top to bottom.
//!
//! Every one of them either serves the request dialogue or says no:
//!
//! | Import | Behaviour |
//! | --- | --- |
//! | `fd_read` (fd 0) | the next bytes of the request frame |
//! | `fd_write` (fd 1) | the response frame, one NDJSON line (charged per byte parsed) |
//! | `fd_write` (fd 2) | captured as diagnostics, surfaced in the failure detail |
//! | `random_get` | a fixed-seed PRNG — entropy is not authority, but it is not ambient either |
//! | `clock_time_get` | a fixed instant |
//! | `sched_yield`, `fd_close`, `fd_fdstat_get`, `fd_seek`, `fd_tell` | inert |
//! | `environ_*`, `args_*` | **empty, and each call recorded as a denial** |
//! | every `path_*`, every `fd_*` on an unknown descriptor | **`ENOTCAPABLE`/`EBADF`, recorded** |
//! | every `sock_*`, `poll_oneoff`, `proc_raise` | **`ENOTCAPABLE`, recorded** |
//! | `proc_exit` | ends the guest, never the host |
//!
//! There is no `path_open` that opens, no `fd_prestat_get` that resolves, and
//! no socket that connects. A capability is not "off by default" here — for
//! everything but request handling, there is no implementation to turn on.
//!
//! # The world is closed
//!
//! Anything the module imports that this shim does not define is refused at
//! **load**, before the artifact can run once, and the refusal names the
//! import. That is what makes a bespoke seam — `autumn_db::query`,
//! `env::system` — a non-starter rather than a runtime error a guest could
//! catch and retry.
//!
//! # Everything a guest does wrong is a value, never a process event
//!
//! A trap (what a Rust panic compiles to on wasm), a `proc_exit`, fuel
//! exhaustion, a refused allocation, a malformed frame, a guest that never
//! answers: all of them come back as [`SandboxFailure`] inside an
//! [`SandboxOutcome`]. Nothing in this module can abort, exit or panic the host
//! process.
// autumn-panic-gate: request-path module — production code path must be panic-free.
// See CONTRIBUTING.md "Request-path panic gate". Justify exceptions with
// #[allow(clippy::<lint>, reason = "…")] at the narrowest scope.
#![cfg_attr(
    not(test),
    deny(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::panic,
        clippy::unreachable,
        clippy::todo,
        clippy::unimplemented,
        clippy::indexing_slicing,
        clippy::string_slice,
        clippy::arithmetic_side_effects,
    )
)]

use std::collections::VecDeque;
use std::fmt;

use tokio::sync::Semaphore;
use wasmi::{Caller, Config, Engine, Linker, Module, Store};

use super::artifact::SandboxArtifact;
use super::manifest::{ResourceLimits, SandboxManifest};
use super::wire::{
    GuestFrame, HostFrame, SandboxRequest, SandboxResponse, from_guest_line, to_exact_line, to_line,
};

/// The WASI module name every import in the shim lives under.
const WASI: &str = "wasi_snapshot_preview1";

/// WASI `errno` values this shim returns.
mod errno {
    pub(super) const SUCCESS: i32 = 0;
    /// Bad file descriptor.
    pub(super) const BADF: i32 = 8;
    /// Invalid argument.
    pub(super) const INVAL: i32 = 28;
    /// Seek on a pipe.
    pub(super) const SPIPE: i32 = 70;
    /// Capability insufficient — the sandbox's universal "no".
    pub(super) const NOTCAPABLE: i32 = 76;
}

/// Bytes in one WebAssembly page.
const WASM_PAGE_BYTES: u64 = 64 * 1024;

/// The size of one WASI `iovec` (two `u32`s: pointer and length).
const IOVEC_SIZE: usize = 8;

/// Size of a WASI `fdstat` struct.
const FDSTAT_SIZE: usize = 24;

/// Scratch-buffer size for host-side copies of guest-supplied ranges (64 KiB).
///
/// An in-bounds iovec can legitimately span the guest's whole linear memory,
/// but the host must never mirror one in a single allocation — a few concurrent
/// requests doing so would exhaust host memory that no guest-side limit
/// accounts for. Copies run through a buffer of this size, and the output
/// budget is applied per chunk, so a runaway write fails long before its full
/// length is copied.
const HOST_IO_CHUNK_BYTES: usize = 64 * 1024;

/// Cap on accumulated guest stderr, in bytes (64 KiB).
const STDERR_BUDGET_BYTES: usize = 64 * 1024;

/// Largest `iovec` array the shim will walk in one call.
///
/// Real WASI callers pass a handful; an array of millions is a guest asking the
/// host to do a million times the work of one call. Bounding the array bounds
/// the per-call amplification factor, which the fuel charge below then prices.
const MAX_IOVECS: i32 = 64;

/// The largest number of table elements one instance may hold, across all of
/// its tables.
///
/// A table holds function references, not bytes, but it is still per-instance
/// host storage: at four tables of 65,536 entries each it would be megabytes an
/// instance, multiplied by `max_concurrency`, that
/// [`ResourceLimits::request_footprint_bytes`](crate::plugin_sandbox::ResourceLimits::request_footprint_bytes)
/// never counted. Bounded here to a number small enough that the footprint can
/// carry it as a constant, and generous enough for any real guest's
/// indirect-call table.
pub const MAX_TABLE_ELEMENTS: u32 = 16_384;

/// The most tables one instance may have.
///
/// The store limiter refuses the fifth at instantiation, which is per request,
/// so the count has to be a load-time verdict too — a module with five empty
/// tables clears the *element* ceiling for free. Defined once and read by both,
/// so the number the limiter enforces and the number the loader admits cannot
/// drift apart.
pub const MAX_TABLES: usize = 4;

/// The most linear memories a module may declare.
///
/// The `MemoryLimiter` reports one, so wasmi refuses to create a second at
/// instantiation — which is per request, as a gateway error, on an artifact
/// `autumn plugin inspect` said was fine. wasmi's own `Config` enables the
/// multi-memory proposal by default, so `Module::new` accepts such a module
/// and only the limiter objects, and the limiter runs too late to tell anyone
/// useful. The one export named `memory` is what the shim reads and writes, so
/// a second is authority the wire could not describe even if it were created.
///
/// Said once at load, like the table ceiling beside it, rather than once per
/// request forever.
pub const MAX_MEMORIES: usize = 1;

/// The most globals a module may declare.
///
/// Every instance allocates and initialises its own copy of each, and an
/// instance is per request — so globals are per-request storage and per-request
/// work in exactly the way tables and segments are. The aggregate declared-entry
/// ceiling is far too generous to bound them on its own: a module can sit well
/// under a million total entries and still carry hundreds of thousands of
/// globals, which no fuel charge priced and no footprint counted.
pub const MAX_GLOBALS: usize = 4096;

/// The most functions a module may define.
///
/// Every instance allocates an entry per defined function, so functions are
/// per-instance storage and per-instance work exactly as globals and tables
/// are. Neither general ceiling bounds them: half a million tiny functions sit
/// under both the aggregate declared-entry cap and the code-section byte cap,
/// because each one is a couple of bytes of body and one byte of type index.
/// Generous against real output — a whole Rust web application compiles to a
/// few tens of thousands of functions.
pub const MAX_FUNCTIONS: usize = 65_536;

/// The most bytes a module's code section may occupy.
///
/// The declaration counts bound how many *things* a module names; they say
/// nothing about how much instruction stream sits inside one of them. A single
/// function whose body fills the file allowance declares exactly one entry and
/// still hands `Module::new` tens of megabytes to translate into wasmi's larger
/// internal representation, which is the allocation amplification the file
/// ceiling was never a bound on. Generous against real output — a whole Rust
/// web application compiles to a few megabytes of code — and far under what a
/// 64 MiB artifact can carry.
pub const MAX_CODE_BYTES: usize = 16 * 1024 * 1024;

/// The largest total data + element section a module may carry (16 MiB).
///
/// Every request instantiates a **fresh** module — that is what makes "no state
/// survives a request" true — and instantiation copies the module's data and
/// element segments before the first guest instruction runs. wasmi does not
/// meter that phase, so the only real bound on it is a bound on the segments
/// themselves, checked once at load. A hello-world Rust guest carries tens of
/// kilobytes here; a large one, a few megabytes.
pub const MAX_INIT_SECTION_BYTES: usize = 16 * 1024 * 1024;

/// The largest number of data + element segments a module may declare.
///
/// Bytes alone do not bound the work: a segment costs a bounds check and a
/// copy set-up regardless of its length, so a module of a million empty
/// segments is small on disk and expensive to instantiate. Both are capped
/// because instantiation cost is a function of both.
pub const MAX_INIT_SEGMENTS: usize = 4096;

/// Bytes of host-side copying one unit of fuel buys.
///
/// wasmi meters the guest's own instructions, and a host call costs a handful
/// of units no matter how much the host then copies on the guest's behalf.
/// Without a charge here, a guest could buy gigabytes of `memcpy` for single
/// digits of fuel — a spin *inside the host* rather than inside the
/// interpreter, which the CPU ceiling would never see and no deadline exists to
/// catch. The rate matches the order of wasmi's own pricing for bulk memory
/// operations, so byte-work and instruction-work share one budget and the
/// ceiling means what the manifest says it means.
const BYTES_PER_FUEL: u64 = 64;

/// Characters of stderr echoed into a failure detail.
const STDERR_EXCERPT: usize = 512;

/// Characters of a guest-influenced string kept for a log line or an error.
///
/// Every `String` a [`SandboxFailure`] carries came, directly or by way of an
/// interpreter message quoting one, from an artifact nobody audited. It is
/// evidence, so it has to survive; it is also attacker-controlled text on its
/// way into a log the operator trusts, so it cannot survive intact.
const DETAIL_EXCERPT: usize = 512;

/// What a bounded excerpt says when it had to leave something out.
///
/// Named because two places append it — [`bounded_guest_text`], which meets the
/// bound while walking, and `stderr_excerpt`, which is handed a string already
/// at it — and an excerpt that says it was cut in two different ways is worse
/// than one that never says so.
pub(super) const TRUNCATION_MARKER: &str = " … (truncated)";

/// Bound and neutralise a string the guest influenced.
///
/// Two hazards, and the fix for one is not the fix for the other. *Length*: a
/// detail can be as large as the stdout budget — megabytes at the maximum
/// response ceiling — and a plugin that fails in a loop writes one per request,
/// which is a log-storage exhaustion with no guest instruction spent on it.
/// *Content*: a newline ends the host's record and starts one the operator did
/// not write, and an ANSI escape repaints records already on screen; either
/// turns "the log says" into something a plugin controls.
///
/// Control characters are escaped rather than dropped, so a detail that was
/// trying to forge a line reads as one that tried. Real text is kept, including
/// non-ASCII: an author debugging a plugin that writes error text in their own
/// language should be able to read it.
///
/// `is_control` alone is not the line between those two, because it covers the
/// C0/C1 codes and stops there. The Unicode formatting characters do the same
/// job by other means — U+202E reverses the run that follows it, so a guest can
/// make a denial record *display* as something other than what was recorded,
/// which is the same forgery a newline attempts and just as available. They are
/// escaped by the same predicate the consent screen refuses them with, so the
/// two surfaces cannot disagree about what counts as display-altering.
///
/// Escaped rather than refused, unlike a route path: a path must mean exactly
/// one thing, but a failure detail is evidence, and evidence that tried
/// something is worth keeping in a legible form.
pub(super) fn guest_text(text: &str) -> String {
    bounded_guest_text(text.chars(), text.len())
}

/// The bound-and-escape rule itself, over characters rather than a `&str`.
///
/// Taking a `&str` means the whole string already exists, which is fine when it
/// does and is the entire problem when it does not: an import's operation is
/// `module::name`, and joining those two before bounding them copies a name an
/// artifact may have spent most of its 64 MiB on, in order to say it is
/// refused. `hint` is only a capacity, and it is capped, so a caller cannot
/// turn it into the allocation this exists to avoid.
fn bounded_guest_text(chars: impl Iterator<Item = char>, hint: usize) -> String {
    let mut out = String::with_capacity(hint.min(DETAIL_EXCERPT));
    for (kept, ch) in chars.enumerate() {
        if kept == DETAIL_EXCERPT {
            out.push_str(TRUNCATION_MARKER);
            break;
        }
        if ch.is_control() || is_line_separator(ch) || super::manifest::is_display_reordering(ch) {
            out.extend(ch.escape_debug());
        } else {
            out.push(ch);
        }
    }
    out
}

/// The two characters Unicode calls line breaks that are not control characters.
///
/// C0/C1 gets escaped by `is_control`, and the invisible and bidi characters by
/// [`is_display_reordering`](super::manifest::is_display_reordering) — and
/// U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR fall between the two.
/// They are general category Zl and Zp: not `Cc`, so `is_control` says no, and
/// neither format nor default-ignorable, so the other predicate says no either.
/// Yet a plain-text log consumer that splits on Unicode line breaks renders
/// them as exactly the newline the escaping exists to deny, which puts a guest
/// back in the business of writing its own operator-facing record — the whole
/// point of escaping C0 in the first place.
///
/// A route path needs nothing here: `validate_route_path` refuses
/// `char::is_whitespace`, and both of these are `White_Space`. The gap is only
/// in a detail, which is escaped rather than refused.
const fn is_line_separator(ch: char) -> bool {
    matches!(ch, '\u{2028}' | '\u{2029}')
}

/// The characters of a lossy UTF-8 decode, without decoding all of it first.
///
/// `String::from_utf8_lossy` answers the same question by building the whole
/// replacement string, which is the one thing a caller keeping a bounded
/// excerpt of guest bytes must not do. `utf8_chunks` yields each maximal
/// invalid subpart separately, which is exactly the grouping `from_utf8_lossy`
/// replaces one-for-one, so this produces the same characters lazily.
fn lossy_chars(bytes: &[u8]) -> impl Iterator<Item = char> + '_ {
    bytes.utf8_chunks().flat_map(|chunk| {
        chunk
            .valid()
            .chars()
            .chain((!chunk.invalid().is_empty()).then_some(char::REPLACEMENT_CHARACTER))
    })
}

/// An import's `module::name`, bounded and escaped without ever being joined.
///
/// Written down here rather than left to the review surface. The surface does
/// excerpt it — but that excerpt runs after this string exists, and the copy is
/// the cost, not the printing. `MAX_IMPORTS` bounds how many names a module may
/// declare and nothing bounded how long one may be, so a single import was
/// enough to make refusing an artifact as expensive as accepting it.
fn import_operation(module: &str, name: &str) -> String {
    bounded_guest_text(
        module.chars().chain("::".chars()).chain(name.chars()),
        module.len().saturating_add(name.len()).saturating_add(2),
    )
}

/// What one recorded denial can hold, at its worst.
///
/// [`guest_text`] bounds a detail at `DETAIL_EXCERPT` *characters*, and
/// escaping is where characters become bytes: `escape_debug` writes an
/// unprintable scalar as `\u{10ffff}`, ten bytes for one character. So the byte
/// bound is ten times the character bound, with room beside it for the
/// truncation marker and the operation and capability names.
const DENIAL_RECORD_BYTES: usize = DETAIL_EXCERPT * 10 + 256;

/// Host buffers a request holds no matter what its manifest declares.
///
/// [`ResourceLimits::request_footprint_bytes`](crate::plugin_sandbox::manifest::ResourceLimits::request_footprint_bytes)
/// scales every other term with a ceiling the manifest names. These do not
/// scale with anything, which is why they were missed: the stderr budget the
/// state holds for the whole request, the scratch buffer an `fd_write` or
/// `fd_read` allocates while that budget is still resident, and the denial
/// ledger beside them. Fixed per request is still per request, and multiplied
/// by a concurrency near the product ceiling it is tens of megabytes the
/// advertised bound did not know about.
pub const FIXED_HOST_BUFFER_BYTES: usize = STDERR_BUDGET_BYTES
    .saturating_add(HOST_IO_CHUNK_BYTES)
    .saturating_add(MAX_DENIALS.saturating_mul(DENIAL_RECORD_BYTES))
    // Capability replies the guest has queued and not yet read, and the ledger
    // of what it asked for. Both are bounded by their own constants below and
    // both are held for the whole request, so they belong in the same term as
    // the stderr budget rather than in the manifest's scaling ones.
    .saturating_add(MAX_QUEUED_REPLY_BYTES)
    .saturating_add(
        crate::plugin_sandbox::capability::MAX_EVENTS.saturating_mul(CAPABILITY_EVENT_BYTES),
    )
    // Slack for the bookkeeping around them — the frame's own scalars, the
    // outcome struct, the excerpt built from the stderr budget when it is read.
    .saturating_add(4096);

/// Host bytes one capability call's reply may hold, unread, in the guest's
/// stdin queue.
///
/// A guest is free to write a call frame and never read the answer — nothing
/// obliges it to, and a buggy one will. Every unread reply stays in the queue,
/// so without a ceiling the `calls` quota (128 by default) multiplied by the
/// largest reply (an outbound response, up to that quota's own byte ceiling)
/// would be tens of megabytes of host memory per in-flight request, at a
/// concurrency the footprint validator approved on other grounds.
///
/// Crossing it ends the request rather than dropping the reply: a guest that is
/// not reading its answers is one that will not notice a dropped one either,
/// and quietly losing a reply is how a plugin comes to believe a write happened.
///
/// It bounds what is **resident**, not what has been sent: `take_stdin` gives
/// the budget back as the guest drains it, so a guest that reads each answer
/// before making the next call never approaches it however many calls it makes.
/// Counting cumulatively instead killed a well-behaved plugin at its 63rd
/// `kv-get` — inside the quotas its own operator had approved — and told it it
/// had a bug it did not have.
///
/// One MiB rather than four: the resident set is one reply at a time for any
/// honest guest, the largest single reply is bounded by the
/// `outbound_response_bytes` quota, and every byte here is charged against
/// [`FIXED_HOST_BUFFER_BYTES`] for *every* plugin — including one granted no
/// capability that can produce a reply. Four MiB moved the largest admissible
/// `max_concurrency` for an otherwise-default manifest from 16 to 15, which is a
/// load-time break for a manifest that used to be fine.
pub const MAX_QUEUED_REPLY_BYTES: usize = 1024 * 1024;

/// Host bytes one capability-ledger entry may hold, for the footprint term.
///
/// An event carries a capability, a `&'static str` operation, its outcome, and a
/// target the guest chose. The target is the term that has to be priced
/// carefully, and at the right rate: it is bounded at
/// [`MAX_TARGET_CHARS`](crate::plugin_sandbox::capability::MAX_TARGET_CHARS)
/// *characters*, and `guest_text` escapes a hostile character to as many as ten
/// bytes — the same `× 10` [`DENIAL_RECORD_BYTES`] already applies for the same
/// reason. Pricing it at the character count understated the ledger eightfold.
const CAPABILITY_EVENT_BYTES: usize =
    crate::plugin_sandbox::capability::MAX_TARGET_CHARS * 10 + 256;

/// Fuel one capability call costs before its reply is priced by the byte.
///
/// A call is host work the guest chose to cause: a lock, a lookup, a frame
/// encoded and queued. Priced like an imported call rather than like a copy,
/// because that is what it is, and priced at all because a plugin with a
/// generous fuel budget would otherwise get its quota's worth of host work for
/// the cost of writing a few hundred bytes to stdout.
const CAPABILITY_CALL_FUEL: u64 = 2_000;

/// Fuel a guest keeps after a call's reply is priced, so it can write its
/// answer.
///
/// The host reserves it before dispatching: a call whose reply the budget could
/// pay for but whose guest could not then finish would commit and then end the
/// request as `FuelExhausted`. A call that commits also keeps
/// [`GUEST_READ_FUEL_PER_BYTE`] to read its reply.
const FINISH_ALLOWANCE_FUEL: u64 = 100_000;

/// Fuel per reply byte that a guest keeps to read the reply of a call that
/// commits (#2523).
///
/// Measured: a Rust guest that reads the line and parses it with `serde_json`
/// spent 6 fuel per byte on plain text, 77 on escaped NULs and 106 on escaped
/// quotes. A JSON body is escape-heavy, so the rate covers the worst case.
///
/// Only for a call that commits. A read that fails changed nothing, so the
/// host does not refuse it for this fuel.
const GUEST_READ_FUEL_PER_BYTE: u64 = 128;

/// Refuse a request whose body is over the manifest's declared ceiling.
///
/// The ceiling is enforced here, not only in the Axum adapter. The adapter
/// applies it while reading, so an oversized body never gets buffered on that
/// path — but [`SandboxHost::run`] is public, and an embedder calling it
/// directly hands over a `SandboxRequest` that has already been built. Without
/// this the body is cloned into the frame and base64-expanded regardless of the
/// ceiling, and the footprint the manifest advertises — which counts the body
/// at `4 × max_request_body_bytes` — stops bounding anything.
///
/// The encoding price charged below it is a real bound, but only against a
/// manifest whose fuel is small relative to its body ceiling; a generous fuel
/// budget buys an arbitrarily large host-side copy. So the ceiling is checked
/// first, before the request is priced or walked at all.
pub const MAX_REQUEST_METADATA_BYTES: usize = 256 * 1024;

/// Every byte of a request that is not its body, summed — or the first running
/// total to cross [`MAX_REQUEST_METADATA_BYTES`], whichever comes first.
///
/// One definition, used by both the ceiling below and [`encoding_fuel`], so the
/// bytes that are refused and the bytes that are charged for cannot drift apart
/// as fields are added to the frame.
///
/// The walk stops at the ceiling rather than finishing and reporting a true
/// total. Charging every entry made an oversized list *fail*; it did not bound
/// the work of discovering that it fails, and that discovery happens before the
/// permit is taken — so an unbounded list still bought an unbounded scan, per
/// concurrent caller, from a ceiling meant to refuse it cheaply. Past the
/// ceiling the answer cannot change, because the total only grows, so the
/// entries after it have nothing left to establish.
///
/// The cost of stopping is that a value over the ceiling is a floor rather than
/// a total. Only the refusal ever sees one: `encoding_fuel` prices requests that
/// were already admitted, and an admitted request finished the walk.
/// What one metadata pair costs, contents plus the structure around them.
///
/// Two 24-byte `String` headers in the vector, and the `["",""],` the serialiser
/// writes around them. Counting only the *contents* would leave a list of a
/// million empty pairs summing to zero — past a byte ceiling for free, then
/// cloned and expanded into real syntax anyway.
///
/// Public to the crate so the adapter can charge a header the same way before
/// deciding to clone it. One definition, so the early refusal and the ceiling
/// cannot disagree about what a pair costs.
pub(crate) const fn metadata_pair_bytes(name: &str, value: &str) -> usize {
    /// Two `String` headers plus the `["",""],` around them.
    const ENTRY: usize = 56;
    name.len().saturating_add(value.len()).saturating_add(ENTRY)
}

/// What a metadata pair the frame will discard still costs.
///
/// Not its contents. Those never cross, and charging them refused requests
/// that cost the guest nothing — a 256 KiB `Cookie` turning a confidentiality
/// promise into an availability one. But the pair sits in a list the host
/// walks three times before the guest starts: once for the ceiling, once to
/// price the encoding, once to filter it back out. That walk is per entry and
/// is not priced by fuel, which the guest has not begun to spend, nor bounded
/// by `max_concurrency`, which limits guests and not the work done to reach
/// one. So the entry is charged even when nothing in it is.
///
/// At 56 bytes an entry this caps a request at a few thousand headers, which
/// is far above what any HTTP client sends and far below what costs anything
/// to walk.
pub(crate) const DROPPED_PAIR_BYTES: usize = metadata_pair_bytes("", "");

fn request_metadata_bytes(request: &SandboxRequest) -> usize {
    let mut total = request
        .method
        .len()
        .saturating_add(request.path.len())
        .saturating_add(request.query.len())
        .saturating_add(request.route.len());
    if total > MAX_REQUEST_METADATA_BYTES {
        return total;
    }
    for (name, value) in &request.headers {
        // Contents only for the headers that will actually cross.
        // `HostFrame::request` filters through the same allowlist, so a
        // `Cookie` or `Authorization` a direct `run` caller happens to be
        // holding is dropped before the frame is built and never reaches the
        // guest — counting its bytes here refused a request that would have
        // cost nothing, and made the public API stricter than the adapter that
        // is merely its politest caller. The entry itself is still charged;
        // see `DROPPED_PAIR_BYTES` for why the two halves separate.
        total = total.saturating_add(if super::wire::request_header_allowed(name) {
            metadata_pair_bytes(name, value)
        } else {
            DROPPED_PAIR_BYTES
        });
        if total > MAX_REQUEST_METADATA_BYTES {
            return total;
        }
    }
    for (name, value) in &request.path_params {
        total = total.saturating_add(metadata_pair_bytes(name, value));
        if total > MAX_REQUEST_METADATA_BYTES {
            return total;
        }
    }
    total
}

fn refuse_oversized_request(
    request: &SandboxRequest,
    limits: ResourceLimits,
) -> Option<SandboxOutcome> {
    if request.body.len() > limits.max_request_body_bytes {
        return Some(SandboxOutcome::refused(
            SandboxFailure::RequestBudget {
                max: limits.max_request_body_bytes,
                len: request.body.len(),
            },
            0,
        ));
    }
    // The body ceiling is the manifest's; this one is the host's, because no
    // manifest declares a query or header budget. `run` is public and the adapter's
    // own limits do not reach it, so an embedder building a `SandboxRequest` by hand
    // could hand over a gigabyte of query string — cloned into the frame and
    // serialised into the NDJSON line before the guest starts, against a footprint
    // that budgets for the body alone. The encoding charge prices those bytes, but
    // pricing is not a bound: at the manifest's maximum fuel it permits more than a
    // terabyte. The ceiling is what keeps `request_footprint_bytes` honest.
    let metadata = request_metadata_bytes(request);
    (metadata > MAX_REQUEST_METADATA_BYTES).then(|| {
        SandboxOutcome::refused(
            SandboxFailure::RequestMetadataBudget {
                max: MAX_REQUEST_METADATA_BYTES,
                len: metadata,
            },
            0,
        )
    })
}

/// Imports listed on a review surface before it stops enumerating them.
///
/// The names themselves are excerpted where they are rendered, but the *count*
/// is a separate amplification: a legal 64 MiB module can carry millions of
/// tiny import entries, and formatting each into its own `String` turns the
/// artifact into hundreds of megabytes in the process that is trying to refuse
/// it. A review surface needs enough to recognise what a module reaches for,
/// not every repetition of it.
/// The most imports a module may declare.
///
/// A structural ceiling, checked before anything walks the import table. Every
/// import is resolved and retained *per instance*, and an instance is per
/// request, so a module repeating one allowlisted import a million times makes
/// every request pay for a million resolutions and hold the results — work no
/// fuel charge priced and storage `request_footprint_bytes` never counted.
/// Refusing the shape at load is what keeps that footprint the real bound.
///
/// It is checked *first* for a second reason: `forbidden_imports` builds one
/// owned denial per offending import, so an unbounded import table amplifies
/// through the refusal path too — including under `autumn plugin inspect`,
/// which runs it on artifacts nobody has audited. This ceiling does not weaken
/// that gate: a module hiding one forbidden import behind a million decoys is
/// still refused at load, now for its shape rather than its contents.
/// The most entries a module's sections may declare between them.
///
/// Checked from the section headers before the module is compiled, because
/// compilation is itself the allocation that needs bounding. Generous against
/// real output — a large Rust module declares tens of thousands of functions
/// and types — and far below what a 64 MiB file of one-byte declarations can
/// claim.
pub const MAX_DECLARED_ENTRIES: usize = 1_000_000;

/// The most sections a module may carry, custom ones included.
///
/// Every other shape ceiling is read from a section's leading count, which is
/// what makes reading them cheap. A custom section has no such count — its body
/// is a name and opaque bytes — so it contributes to nothing, and an empty one
/// encodes in three bytes. A 64 MiB artifact of those is roughly 22 million
/// section headers walked to reach a verdict this loop exists to reach cheaply.
///
/// So the headers are counted too, and the walk stops at the ceiling rather
/// than running to the end and refusing afterwards: here the iteration *is* the
/// cost, unlike the per-entry walks below it, where refusing on the count alone
/// is enough. A real module carries a dozen sections; a toolchain that emits
/// names, producers and debug info carries a few dozen.
pub const MAX_SECTIONS: usize = 1_024;

pub const MAX_IMPORTS: usize = 1024;

const MAX_REPORTED_IMPORTS: usize = 256;

/// Format a module's imports for review, bounded in number and in length.
///
/// The total is still reported honestly — an operator must not read a truncated
/// list as the whole of what an artifact imports — but only the first
/// [`MAX_REPORTED_IMPORTS`] are allocated. Counting the rest costs nothing: the
/// import table is already parsed, and walking it without formatting allocates
/// nothing per entry.
///
/// Each entry is built with [`import_operation`], the same bounded formatter
/// the denial path uses, so the *length* is capped where the string is made
/// rather than where it is rendered. A count-only bound left 256 names each as
/// long as an artifact cared to make them, and the review surface's own excerpt
/// runs afterwards — which is one copy too late to matter.
///
/// This bounds the *review* surface only. The load gate checks every import
/// against the shim's allowlist with no cap, because a module that hides a
/// forbidden import behind a million decoys must still be refused.
fn reported_imports<'a>(imports: impl Iterator<Item = wasmi::ImportType<'a>>) -> Vec<String> {
    let mut names: Vec<String> = Vec::new();
    let mut total: usize = 0;
    for import in imports {
        total = total.saturating_add(1);
        if names.len() < MAX_REPORTED_IMPORTS {
            names.push(import_operation(import.module(), import.name()));
        }
    }
    if let Some(hidden) = total.checked_sub(names.len()).filter(|more| *more > 0) {
        names.push(format!("… and {hidden} more (truncated)"));
    }
    names
}

/// What encoding one request's frame costs, in fuel.
///
/// Priced off the request's own bytes at [`BYTES_PER_FUEL`], the rate every
/// other host-side copy pays, multiplied by the number of times those bytes are
/// walked on the way to the guest's stdin.
///
/// A flat multiplier over the *raw* input was the wrong shape, because the
/// passes are not all over the raw input. The body is base64-encoded, which
/// expands it by 4/3, and every walk after that is over the expansion.
/// Metadata is JSON-escaped, and `serde_json` writes a control character as
/// `\u0000` — six bytes for one — so a direct caller filling a header value
/// with them expands it sixfold. Then [`HostState::seed_from`] reads the
/// finished line end to end, so the largest single walk is over the expanded
/// form, not the raw one. Charging four times the raw bytes let a request buy
/// host work the ceiling never saw.
///
/// So body and metadata are priced separately, each at its own worst-case
/// expansion:
///
/// | | raw passes | expanded passes | charged |
/// |---|---|---|---|
/// | body | clone, encode-read, sizing read | encode-write and escape-scan in both passes, seed scan | `3 + 5 × 4/3 = 9 2/3`, charged as 10 |
/// | metadata | clone, escape-read, sizing read | escape-write, sizing write, seed scan | `3 + 3 × 6 = 21` |
///
/// The sizing walks are `to_line`'s first pass, which counts the line so the
/// second pass can write into an exact buffer.
///
/// Both are upper bounds rather than measurements, because this runs *before*
/// the line exists — that is the point of it. The expansion factors are the
/// same ones [`ResourceLimits::request_footprint_bytes`](crate::plugin_sandbox::manifest::ResourceLimits::request_footprint_bytes)
/// budgets memory at, so the two describe the same request.
fn encoding_fuel(request: &SandboxRequest) -> u64 {
    /// Raw-equivalent walks of the body: three over the raw bytes, five over the
    /// base64 expansion of them, which is 4/3. `3 + 5 × 4/3` is 9 2/3, so 10.
    const BODY_PASSES: u64 = 10;
    /// Raw-equivalent walks of the metadata: three over the raw bytes, three
    /// over a JSON escaping that can reach six bytes per byte.
    const METADATA_PASSES: u64 = 21;

    let charge = |bytes: usize, passes: u64| {
        u64::try_from(bytes)
            .unwrap_or(u64::MAX)
            .saturating_mul(passes)
    };

    charge(request.body.len(), BODY_PASSES)
        .saturating_add(charge(request_metadata_bytes(request), METADATA_PASSES))
        .checked_div(BYTES_PER_FUEL)
        .unwrap_or(u64::MAX)
        .saturating_add(1)
}

/// Largest number of distinct denials recorded for one request.
///
/// The ledger is a diagnostic, and a guest that calls a denied import in a
/// loop must not be able to grow one. Denials are deduplicated by
/// `(capability, operation)` first, so hitting this bound at all means a guest
/// found more distinct refusals than the shim has functions.
const MAX_DENIALS: usize = 64;

// ── Denials ──────────────────────────────────────────────────────────────

/// The class of authority a guest reached for and did not get.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DeniedCapability {
    /// Reading, writing, opening or discovering anything on a filesystem.
    Filesystem,
    /// Any outbound socket operation.
    Network,
    /// Environment variables and process arguments.
    Environment,
    /// Signalling, blocking or otherwise steering the host process.
    ProcessControl,
    /// An allocation over the plugin's declared memory ceiling.
    Memory,
    /// A response header a plugin is not allowed to set.
    ResponseHeader,
    /// An import no host function defines. Refused at load.
    UnknownImport,
}

impl DeniedCapability {
    /// Stable lowercase tag used in logs and reports.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Filesystem => "filesystem",
            Self::Network => "network",
            Self::Environment => "environment",
            Self::ProcessControl => "process-control",
            Self::Memory => "memory",
            Self::ResponseHeader => "response-header",
            Self::UnknownImport => "unknown-import",
        }
    }
}

impl fmt::Display for DeniedCapability {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// One thing a guest reached for and was refused.
///
/// Denials are the *observable* half of deny-by-default: without them, a
/// sandbox that silently swallows a `path_open` and one that has a bug look
/// exactly alike from outside.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CapabilityDenial {
    /// Which class of authority was refused.
    pub capability: DeniedCapability,
    /// The guest-visible operation, e.g. `path_open` or `autumn_db::query`.
    pub operation: String,
    /// What the guest was told, for the log.
    pub detail: String,
}

impl fmt::Display for CapabilityDenial {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{capability}: {operation} — {detail}",
            capability = self.capability,
            operation = self.operation,
            detail = self.detail
        )
    }
}

// ── Failures ─────────────────────────────────────────────────────────────

/// Why a request produced no answer from the plugin.
///
/// Almost every variant is a *plugin* failure — none of those is a host
/// failure, and none can be anything other than a 5xx on the plugin's own
/// prefix. [`RequestBudget`](Self::RequestBudget) and
/// [`RequestMetadataBudget`](Self::RequestMetadataBudget) are the exceptions:
/// it is the *caller's* request that was refused, before the plugin was asked
/// anything, so they answer 413 the way the ceiling does everywhere else.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SandboxFailure {
    /// The module could not be instantiated for this request.
    Instantiation(String),
    /// The guest burned its whole fuel budget without answering.
    FuelExhausted {
        /// The budget it was given.
        budget: u64,
    },
    /// The guest trapped.
    Trap(String),
    /// The guest called `proc_exit`.
    Exited(i32),
    /// The guest returned without answering.
    NoAnswer,
    /// The guest wrote what may well be a complete frame but never ended the
    /// line, so the host never saw one.
    PartialFrame,
    /// The guest wrote something that is not a frame this version knows.
    MalformedFrame(String),
    /// The guest reported its own failure.
    GuestError(String),
    /// The guest answered, but with something HTTP or the manifest refuses.
    ResponseRefused(String),
    /// The guest wrote more than its response ceiling without ending a line.
    OutputBudget {
        /// The ceiling it blew through.
        max: usize,
    },
    /// The plugin already has `max_concurrency` requests executing, so this
    /// one was not started.
    AtCapacity {
        /// The ceiling it ran into.
        max: usize,
    },
    /// The request handed to [`SandboxHost::run`] carried a body over the
    /// manifest's declared ceiling. The guest was never started.
    RequestBudget {
        /// The ceiling it blew through.
        max: usize,
        /// What the caller actually handed over.
        len: usize,
    },
    /// The request handed to [`SandboxHost::run`] carried more metadata — path,
    /// query, route, headers, path parameters — than the host's ceiling allows.
    /// The guest was never started.
    RequestMetadataBudget {
        /// The ceiling it blew through.
        max: usize,
        /// How much metadata the caller handed over — at least this much.
        ///
        /// A floor rather than a total: the walk stops as soon as it knows the
        /// answer, so the entries past the ceiling are never counted. Bounding
        /// the work of refusing costs the exact figure, and the exact figure is
        /// not what the refusal turns on.
        len: usize,
    },
}

impl SandboxFailure {
    /// The status this failure serves on the plugin's prefix.
    ///
    /// A budget exhaustion is a 504: the plugin was given a deadline and missed
    /// it. An oversized request is a 413, the same answer the adapter gives
    /// before it ever gets here — one condition must not have two statuses
    /// depending on which door the request came through. Everything else is a
    /// 502: the plugin answered badly or not at all, which is exactly what a
    /// bad gateway is.
    #[must_use]
    pub const fn status(&self) -> http::StatusCode {
        match self {
            Self::FuelExhausted { .. } | Self::OutputBudget { .. } => {
                http::StatusCode::GATEWAY_TIMEOUT
            }
            Self::RequestBudget { .. } | Self::RequestMetadataBudget { .. } => {
                http::StatusCode::PAYLOAD_TOO_LARGE
            }
            Self::AtCapacity { .. } => http::StatusCode::SERVICE_UNAVAILABLE,
            _ => http::StatusCode::BAD_GATEWAY,
        }
    }
}

impl fmt::Display for SandboxFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Instantiation(detail) => {
                write!(f, "the plugin could not be instantiated: {detail}")
            }
            Self::FuelExhausted { budget } => write!(
                f,
                "the plugin exhausted its {budget}-unit CPU budget without answering"
            ),
            Self::Trap(detail) => write!(f, "the plugin trapped: {detail}"),
            Self::Exited(code) => write!(f, "the plugin called proc_exit({code})"),
            Self::NoAnswer => write!(f, "the plugin returned without answering"),
            Self::PartialFrame => write!(
                f,
                "the plugin wrote a partial frame with no terminating newline; a frame is one \
                 NDJSON line, so it must end with `\\n` (use `println!`, not `print!`)"
            ),
            Self::MalformedFrame(detail) => {
                write!(f, "the plugin wrote a malformed frame: {detail}")
            }
            Self::GuestError(detail) => write!(f, "the plugin reported a failure: {detail}"),
            Self::ResponseRefused(detail) => {
                write!(f, "the plugin's answer was refused: {detail}")
            }
            Self::OutputBudget { max } => write!(
                f,
                "the plugin wrote more than its {max}-byte response ceiling without ending a frame"
            ),
            Self::AtCapacity { max } => write!(
                f,
                "the plugin already has its {max} permitted requests executing"
            ),
            Self::RequestBudget { max, len } => write!(
                f,
                "the request body is {len} bytes, over the plugin's {max}-byte request ceiling"
            ),
            Self::RequestMetadataBudget { max, len } => write!(
                f,
                "the request's path, query, headers and parameters are {len} bytes, over the \
                 host's {max}-byte ceiling"
            ),
        }
    }
}

impl std::error::Error for SandboxFailure {}

/// Why an artifact could not be loaded at all.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SandboxLoadError {
    /// The manifest handed to [`SandboxHost::from_module`] does not satisfy the
    /// rules parsing enforces — it was built or mutated rather than parsed.
    InvalidManifest(String),
    /// The bytes are not a WebAssembly module this engine can compile.
    Wasm(String),
    /// The module imports something no host function defines.
    ForbiddenImports(Vec<CapabilityDenial>),
    /// The manifest's fuel budget cannot cover what every request must spend
    /// before the guest runs at all, so no route it declares could ever answer.
    FuelBelowFixedCharges {
        /// The budget the manifest declares.
        fuel: u64,
        /// What instantiating this module costs, every request, before `_start`.
        instantiation: u64,
    },
    /// The module's data or element segments would make every request's
    /// instantiation expensive, in host work no fuel budget prices.
    InstantiationTooExpensive {
        /// What was counted.
        what: &'static str,
        /// How many the module carries.
        found: usize,
        /// The ceiling.
        max: usize,
    },
    /// The module is larger than [`MAX_MODULE_BYTES`](super::MAX_MODULE_BYTES).
    ///
    /// The container reader applies this to a module it unpacks; this applies
    /// it to one handed straight to [`SandboxHost::from_module`] or
    /// [`SandboxHost::imports_of`], which never passed through that reader.
    ModuleTooLarge {
        /// The module's length.
        found: usize,
        /// The ceiling.
        max: usize,
    },
    /// The module exports no `_start` of type `() -> ()`.
    MissingStart,
    /// The module exports no linear memory named `memory`.
    MissingMemory,
    /// The module carries a WebAssembly `start` section.
    ///
    /// Guest code that runs at instantiation, before any request and outside
    /// the `_start` the shim calls. If it traps, every instantiation fails and
    /// the plugin can never answer; and running it at load to find out would
    /// mean executing an unaudited artifact's code just to inspect it.
    StartSectionForbidden,
    /// An active data segment does not fit the module's own initial memory.
    ///
    /// Copied in during instantiation, which is per request — so a segment
    /// past the end compiles clean and then fails every instantiation the
    /// artifact is ever given.
    SegmentOutOfBounds {
        /// Which store the segment writes into, for the message.
        what: &'static str,
        /// One past the segment's furthest write.
        end: u64,
        /// What the module starts that store with.
        capacity: u64,
    },
    /// The module's *initial* linear memory is already over the manifest's
    /// ceiling, so no request could ever instantiate it.
    MemoryTooLarge {
        /// The module's initial memory, in bytes.
        found: u64,
        /// The manifest's ceiling.
        max: usize,
    },
    /// The engine could not be configured.
    Engine(String),
}

impl fmt::Display for SandboxLoadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidManifest(detail) => {
                write!(f, "the manifest is not one this host will serve: {detail}")
            }
            Self::Wasm(detail) => write!(f, "the plugin module could not be loaded: {detail}"),
            Self::ForbiddenImports(denials) => {
                // Written straight through rather than cloned into a `Vec` and
                // joined. Each operation is already bounded, so the clone was
                // not unbounded — but it was a second full copy of every name
                // on the path that exists to refuse the artifact cheaply, and
                // the joined string was a third.
                write!(
                    f,
                    "the plugin imports {count} host function(s) the sandbox does not provide, \
                     so it is refused before it runs: ",
                    count = denials.len(),
                )?;
                for (written, denial) in denials.iter().enumerate() {
                    if written > 0 {
                        f.write_str(", ")?;
                    }
                    f.write_str(&denial.operation)?;
                }
                Ok(())
            }
            Self::FuelBelowFixedCharges {
                fuel,
                instantiation,
            } => write!(
                f,
                "the plugin's {fuel}-unit fuel budget cannot cover the {instantiation} units \
                 instantiating this module costs before `_start` runs, so every request would \
                 exhaust the budget without the guest executing an instruction"
            ),
            Self::ModuleTooLarge { found, max } => write!(
                f,
                "sandboxed plugin module is {found} bytes, over the {max}-byte ceiling"
            ),
            Self::InstantiationTooExpensive { what, found, max } => write!(
                f,
                "the plugin declares {found} {what}, over the {max} ceiling: every request \
                 re-instantiates the module, and that work happens before the first guest \
                 instruction — so it is bounded here rather than priced per request"
            ),
            Self::MissingStart => write!(
                f,
                "the plugin exports no `_start` of type `() -> ()`; it must be built as a \
                 wasm32-wasip1 *command*"
            ),
            Self::MissingMemory => write!(
                f,
                "the plugin exports no linear memory named `memory`; every host function reads \
                 and writes through it, so a plugin without one can never answer"
            ),
            Self::MemoryTooLarge { found, max } => write!(
                f,
                "the plugin's initial linear memory is {found} bytes, over the manifest's \
                 {max}-byte ceiling; no request could instantiate it"
            ),
            Self::StartSectionForbidden => write!(
                f,
                "the plugin carries a WebAssembly `start` section; a sandboxed plugin answers \
                 through its exported `_start` and runs no code at instantiation"
            ),
            Self::SegmentOutOfBounds {
                what,
                end,
                capacity,
            } => write!(
                f,
                "an active segment writes up to {end} of the plugin's {what}, past the \
                 {capacity} it starts with; every instantiation would fail on it"
            ),
            Self::Engine(detail) => write!(f, "the sandbox engine could not be built: {detail}"),
        }
    }
}

impl std::error::Error for SandboxLoadError {}

// ── The outcome ──────────────────────────────────────────────────────────

/// Everything one request produced: the answer or the failure, plus the
/// evidence.
#[derive(Debug)]
#[non_exhaustive]
pub struct SandboxOutcome {
    /// The plugin's answer, or why there is none.
    pub result: Result<SandboxResponse, SandboxFailure>,
    /// Everything the guest reached for and did not get.
    pub denials: Vec<CapabilityDenial>,
    /// Fuel the guest consumed.
    pub fuel_used: u64,
    /// The high-water mark of the guest's linear memory, in bytes.
    pub peak_memory_bytes: usize,
    /// What the guest wrote to stderr, truncated.
    pub stderr: String,
    /// Every capability call this request made, allowed or refused (#1632).
    ///
    /// The operator audit surface is built from these; see
    /// [`capability::audit`](crate::plugin_sandbox::capability::audit).
    pub activity: Vec<crate::plugin_sandbox::capability::CapabilityEvent>,
    /// Capability calls this request made that the bounded ledger could not
    /// hold, so `activity` is a floor rather than a count.
    ///
    /// Has no times. Ingest [`dropped_calls`](Self::dropped_calls) instead.
    pub dropped_activity: u64,
    /// The same calls, with when they occurred. `None` when none was dropped.
    ///
    /// Give it to
    /// [`PluginActivityLog::ingest_dropped_calls`](crate::plugin_sandbox::PluginActivityLog::ingest_dropped_calls).
    pub dropped_calls: Option<crate::plugin_sandbox::capability::DroppedCalls>,
}

impl SandboxOutcome {
    /// A request refused before the guest produced anything: no denials, no
    /// peak, no stderr, because nothing of the guest's ever ran.
    ///
    /// `fuel_used` is what the *host* had already committed on its behalf — the
    /// whole budget when a charge could not be covered, zero when the request
    /// was turned away before it was priced.
    const fn refused(failure: SandboxFailure, fuel_used: u64) -> Self {
        Self {
            result: Err(failure),
            denials: Vec::new(),
            fuel_used,
            peak_memory_bytes: 0,
            stderr: String::new(),
            activity: Vec::new(),
            dropped_activity: 0,
            dropped_calls: None,
        }
    }
}

/// Everything one render-slot call produced (#1632).
///
/// Separate from [`SandboxOutcome`] rather than a variant of it: the two carry
/// different answers, and a caller filling a slot on a page has a different
/// failure posture — it omits the fragment and serves the page — from one
/// serving a request, which returns a status.
#[derive(Debug)]
#[non_exhaustive]
pub struct SandboxRenderOutcome {
    /// The rendered HTML fragment, or why there is none.
    ///
    /// Every `Err` here means the same thing to a caller: leave the slot empty.
    pub fragment: Result<String, SandboxFailure>,
    /// Everything the guest reached for and did not get.
    pub denials: Vec<CapabilityDenial>,
    /// Fuel the guest consumed.
    pub fuel_used: u64,
    /// What the guest wrote to stderr, truncated.
    pub stderr: String,
    /// The high-water mark of the guest's linear memory, in bytes.
    pub peak_memory_bytes: usize,
    /// Every capability call the hook made.
    pub activity: Vec<crate::plugin_sandbox::capability::CapabilityEvent>,
    /// Calls the bounded ledger could not hold.
    ///
    /// Has no times. Ingest [`dropped_calls`](Self::dropped_calls) instead.
    pub dropped_events: u64,
    /// The same calls, with when they occurred. `None` when none was dropped.
    ///
    /// Give it to
    /// [`PluginActivityLog::ingest_dropped_calls`](crate::plugin_sandbox::PluginActivityLog::ingest_dropped_calls).
    pub dropped_calls: Option<crate::plugin_sandbox::capability::DroppedCalls>,
}

// ── The host ─────────────────────────────────────────────────────────────

/// A compiled sandboxed plugin, ready to serve requests.
///
/// Compilation happens once in [`load`](SandboxHost::load); every call to
/// [`run`](SandboxHost::run) builds a *fresh* store and instance, so no state
/// survives a request and one request's misbehaviour cannot reach the next.
pub struct SandboxHost {
    engine: Engine,
    module: Module,
    /// One permit per concurrently-executing request.
    ///
    /// `SandboxedPlugin::serve` has a semaphore of its own, which it holds
    /// across the body read as well as the run, so the declared footprint
    /// bounds the whole request rather than only the part a guest is running.
    /// This one is narrower and lives here because [`run`](SandboxHost::run)
    /// is public: an embedder calling it directly never passes through
    /// `serve`, and `request_footprint_bytes() × max_concurrency` is the
    /// premise the manifest validator accepts limits on.
    ///
    /// The two never fight. At most `max_concurrency` requests are in `serve`
    /// at once, so they can hold at most that many of these — this semaphore
    /// is only ever the binding constraint on a direct caller, which is the
    /// one it exists for.
    permits: Semaphore,
    /// The sealed digest of the whole artifact, when this host came from one.
    /// Stamped on every job the plugin enqueues.
    artifact_sha256: Option<String>,
    /// The paths this plugin declared, as the router matches them.
    ///
    /// Built once here because a redirect may only name a route the plugin
    /// serves, and rebuilding the matcher per response would be a per-request
    /// allocation for a set fixed at load. See [`OwnedRoutes`].
    owned_routes: super::wire::OwnedRoutes,
    /// What one instantiation of this module costs, in fuel. Bounded at load by
    /// [`MAX_INIT_SEGMENTS`] and [`MAX_INIT_SECTION_BYTES`]; charged per request
    /// so the declared CPU ceiling prices it — see [`SandboxHost::run`].
    instantiation_fuel: u64,
    manifest: SandboxManifest,
}

impl fmt::Debug for SandboxHost {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SandboxHost")
            .field("plugin", &self.manifest.name)
            .field("prefix", &self.manifest.prefix)
            .finish_non_exhaustive()
    }
}

/// What one context entry costs beyond its bytes: two `String` headers, a
/// tuple, and the JSON punctuation it becomes on the wire.
///
/// Counted in both the ceiling and the fuel charge, so a thousand empty pairs
/// are neither free to hold nor free to encode.
pub const RENDER_CONTEXT_ENTRY_OVERHEAD: usize = 64;

/// The most context entries one render hook is handed.
///
/// A slot's context is a handful of values a panel needs — an id, a locale, a
/// count. Far above that, and far below anything that could matter.
pub const MAX_RENDER_CONTEXT_ENTRIES: usize = 32;

/// The most bytes one render hook's context may carry across all its entries.
pub const MAX_RENDER_CONTEXT_BYTES: usize = 16 * 1024;

/// Take as much of `context` as the ceilings above allow.
///
/// Applied by [`SandboxHost::render`] itself, not only by the wrapper: the
/// entry point is public, an embedder may call it with context built from a
/// row or a query string, and a ceiling that only one of two callers reaches is
/// a ceiling the other does not have.
///
/// Per-entry overhead is counted, not just the strings: a thousand empty pairs
/// cost real allocation and real serialization, and a budget measured only in
/// string length prices them at nothing.
#[must_use]
pub fn bounded_context(context: &[(String, String)]) -> Vec<(String, String)> {
    let mut out = Vec::with_capacity(context.len().min(MAX_RENDER_CONTEXT_ENTRIES));
    let mut total = 0_usize;
    for (name, value) in context {
        if out.len() >= MAX_RENDER_CONTEXT_ENTRIES {
            break;
        }
        let weight = name
            .len()
            .saturating_add(value.len())
            .saturating_add(RENDER_CONTEXT_ENTRY_OVERHEAD);
        if total.saturating_add(weight) > MAX_RENDER_CONTEXT_BYTES {
            break;
        }
        total = total.saturating_add(weight);
        out.push((name.clone(), value.clone()));
    }
    out
}

impl SandboxHost {
    /// Compile a verified artifact into a runnable host.
    ///
    /// # Errors
    ///
    /// Returns [`SandboxLoadError`] if the module does not compile, imports
    /// something the sandbox does not provide, or exports no `_start`.
    pub fn load(artifact: &SandboxArtifact) -> Result<Self, SandboxLoadError> {
        // The whole container's digest, kept here so a direct `run` stamps jobs
        // with it too, not only a host built through `SandboxedPlugin`.
        let digest = artifact
            .artifact_digest()
            .map_err(|err| SandboxLoadError::InvalidManifest(err.to_string()))?;
        Ok(
            Self::from_module(artifact.manifest().clone(), artifact.module())?
                .with_artifact_sha256(digest),
        )
    }

    /// Compile a module against a manifest.
    ///
    /// Prefer [`load`](Self::load), which also proves the manifest describes
    /// *these* bytes.
    ///
    /// The manifest is re-validated here rather than trusted. Parsing is where
    /// a manifest's rules are enforced, but [`SandboxManifest`]'s fields are
    /// public and this constructor is too, so "it was parsed once" is an
    /// invariant a caller can step around by building or editing one. The
    /// values that matter are the ones something downstream would *panic* on
    /// rather than merely misbehave over — a `max_concurrency` past the
    /// semaphore's ceiling, a route path axum refuses to build — and this crate
    /// does not panic on plugin input.
    ///
    /// # Errors
    ///
    /// See [`load`](Self::load), plus
    /// [`InvalidManifest`](SandboxLoadError::InvalidManifest) if the manifest
    /// does not satisfy the rules parsing enforces.
    pub fn from_module(manifest: SandboxManifest, wasm: &[u8]) -> Result<Self, SandboxLoadError> {
        manifest
            .validate()
            .map_err(|err| SandboxLoadError::InvalidManifest(err.to_string()))?;

        // Before `Module::new`, deliberately: compiling is what allocates a
        // representation of every declaration, so a ceiling checked afterwards
        // is a ceiling checked too late.
        let shape = refuse_unbounded_shape(wasm)?;

        let mut config = Config::default();
        // Fuel metering is what turns "a plugin might loop forever" into "a
        // plugin gets a bounded number of instructions". It must be on before
        // the module is compiled, because the counting is compiled in.
        config.consume_fuel(true);
        let engine = Engine::new(&config);
        let module =
            Module::new(&engine, wasm).map_err(|err| SandboxLoadError::Wasm(err.to_string()))?;

        let import_count = module.imports().count();
        if import_count > MAX_IMPORTS {
            return Err(SandboxLoadError::InstantiationTooExpensive {
                what: "imports",
                found: import_count,
                max: MAX_IMPORTS,
            });
        }

        let forbidden = forbidden_imports(&module);
        if !forbidden.is_empty() {
            return Err(SandboxLoadError::ForbiddenImports(forbidden));
        }

        // Every shim function reads and writes through an export named
        // `memory`; without one they all answer `EINVAL` and the plugin can
        // never serve a request. And a module whose *initial* memory is already
        // over the manifest's ceiling is refused by the limiter at
        // instantiation — per request, as a gateway error, when it could have
        // been said once here.
        let memory = module
            .exports()
            .find(|export| export.name() == "memory")
            .and_then(|export| export.ty().memory().copied());
        let Some(memory) = memory else {
            return Err(SandboxLoadError::MissingMemory);
        };
        let initial_bytes =
            u64::from(u32::from(memory.initial_pages())).saturating_mul(WASM_PAGE_BYTES);
        if initial_bytes > manifest.limits.memory_bytes as u64 {
            return Err(SandboxLoadError::MemoryTooLarge {
                found: initial_bytes,
                max: manifest.limits.memory_bytes,
            });
        }

        // Both ceilings are enforced by `refuse_unbounded_shape` above, before
        // `Module::new` rather than after it.
        let (segments, init_bytes) = (shape.segments, shape.init_bytes);
        // A budget that cannot cover instantiation is a manifest whose every route is
        // already broken: the charge is unavoidable and paid before `_start`, so the
        // guest never executes an instruction. Refusing at load is what makes `autumn
        // plugin inspect` mean something — a passing verdict on an artifact that can
        // only answer 504 is worse than no verdict, because an operator installs on
        // the strength of it. Compared against instantiation alone rather than the
        // whole per-request cost: the frame encoding varies with the request, so there
        // is no single number to check it against, while this charge is fixed by the
        // module and known now.
        let instantiation = instantiation_fuel(
            segments,
            init_bytes,
            import_count,
            shape.global_count,
            initial_bytes,
            shape.table_elements,
        )
        .saturating_add(u64::try_from(shape.function_count).unwrap_or(u64::MAX));
        if manifest.limits.fuel <= instantiation {
            return Err(SandboxLoadError::FuelBelowFixedCharges {
                fuel: manifest.limits.fuel,
                instantiation,
            });
        }

        // Not merely "some function called `_start`": the host looks it up as
        // `() -> ()`, so a `_start` with parameters or results is a module that
        // loads and then fails on every request.
        let start_is_callable = module.exports().any(|export| {
            export.name() == "_start"
                && export
                    .ty()
                    .func()
                    .is_some_and(|ty| ty.params().is_empty() && ty.results().is_empty())
        });
        if !start_is_callable {
            return Err(SandboxLoadError::MissingStart);
        }

        refuse_unrunnable_shape(&shape, initial_bytes)?;

        Ok(Self {
            engine,
            module,
            permits: Semaphore::new(manifest.limits.max_concurrency),
            artifact_sha256: None,
            instantiation_fuel: instantiation,
            owned_routes: super::wire::OwnedRoutes::from_routes(
                manifest
                    .routes
                    .iter()
                    .map(|route| (route.method.as_str(), route.path.as_str())),
            ),
            manifest,
        })
    }

    /// Record the sealed digest of the artifact this host came from.
    #[must_use]
    pub(super) fn with_artifact_sha256(mut self, digest: String) -> Self {
        self.artifact_sha256 = Some(digest);
        self
    }

    /// The manifest this host enforces.
    #[must_use]
    pub const fn manifest(&self) -> &SandboxManifest {
        &self.manifest
    }

    /// Every import a module declares, as `module::name`, without loading it.
    ///
    /// The review surface for an artifact the sandbox *refuses*: what it wanted
    /// is the whole reason it was refused, so a consent screen must be able to
    /// show it.
    ///
    /// # Errors
    ///
    /// Returns [`SandboxLoadError::Wasm`] if the bytes are not a module.
    pub fn imports_of(wasm: &[u8]) -> Result<Vec<String>, SandboxLoadError> {
        // `inspect` calls this on artifacts nobody has audited, and on the ones
        // the sandbox is about to refuse — so the review surface must not be
        // the way an artifact exhausts the process reviewing it.
        refuse_unbounded_shape(wasm)?;
        let engine = Engine::default();
        let module =
            Module::new(&engine, wasm).map_err(|err| SandboxLoadError::Wasm(err.to_string()))?;
        Ok(reported_imports(module.imports()))
    }

    /// What one request pays, in fuel, just to instantiate this module.
    ///
    /// Bounded at load; charged per request. Surfaced so a packaging tool can
    /// show an author what their module costs before it costs anyone else.
    #[must_use]
    pub const fn instantiation_fuel(&self) -> u64 {
        self.instantiation_fuel
    }

    /// Every import the module declares, as `module::name`, for review.
    #[must_use]
    pub fn imports(&self) -> Vec<String> {
        reported_imports(self.module.imports())
    }

    /// Serve one request, with no capability backends wired.
    ///
    /// This is synchronous and CPU-bound by design — it is an interpreter loop.
    /// Callers on an async runtime must dispatch it to a blocking worker; the
    /// [`plugin`](super::plugin) module does exactly that.
    ///
    /// Never panics and never fails: a plugin that misbehaves in any way
    /// produces an [`SandboxOutcome`] whose `result` is `Err`.
    ///
    /// A plugin granted `kv`, `db`, `http-outbound` or `jobs` still *runs* here
    /// — its calls are answered [`unavailable`](crate::plugin_sandbox::DenialReason::Unavailable)
    /// and recorded. Wire the backends with [`run_with`](Self::run_with).
    #[must_use]
    pub fn run(&self, request: &SandboxRequest) -> SandboxOutcome {
        self.run_with(request, crate::plugin_sandbox::CapabilityServices::none())
    }

    /// Serve one request against `services` (issue #1632).
    ///
    /// The services are per-call rather than per-host because the tenant is:
    /// one compiled plugin serves every tenant's requests, and the scoping that
    /// makes that safe comes from `services.tenant` being the *request's*
    /// tenant. A host that held the services would hold one tenant.
    #[must_use]
    pub fn run_with(
        &self,
        request: &SandboxRequest,
        services: crate::plugin_sandbox::CapabilityServices,
    ) -> SandboxOutcome {
        let limits = self.manifest.limits;
        // Bounds where the response may redirect a client; see `sanitize`.
        let rules = ResponseRules {
            prefix: self.manifest.prefix.as_str(),
            owned: &self.owned_routes,
            requested: &request.method,
        };

        if let Some(refusal) = refuse_oversized_request(request, limits) {
            return refusal;
        }

        // Borrowed, not cloned: `HostFrame::request` reads the grants to decide
        // what the guest is told it may do and never keeps them, so copying the
        // vector on every request bought nothing. Validation refuses a repeated
        // grant, so this list is at most one entry per capability this build
        // understands.
        // The frame is *built* inside `execute`, not here. Encoding it clones
        // the body and base64-expands it, which is the host work
        // `encoding_fuel` exists to price and `max_concurrency` exists to
        // bound — so doing it before admission and before the charge undid
        // both: a manifest with a 64 MiB body ceiling and almost no fuel would
        // expand every request in full and only then answer `FuelExhausted`,
        // once per request, for as long as a client cared to ask.
        let capabilities = &self.manifest.capabilities;
        match self.execute(
            || HostFrame::request(request, capabilities),
            encoding_fuel(request),
            Exchange::Request,
            services,
        ) {
            Execution::Refused(failure, fuel_used) => SandboxOutcome::refused(failure, fuel_used),
            Execution::Ran(store, permit, result) => {
                // The permit is still held, and dropped only once `finish` has
                // drained the store: sanitising and size-checking the response
                // clones up to `max_response_bytes`, which is the term
                // `request_footprint_bytes` charges to `max_concurrency`.
                let outcome = finish(store, limits, &rules, result);
                drop(permit);
                outcome
            }
        }
    }

    /// Fill one render slot (issue #1632).
    ///
    /// `context` is whatever the host chose to tell the plugin about the page —
    /// an order id, a locale. It is the host's to decide and the plugin's to
    /// read; nothing about the request, the session or the user crosses unless
    /// the host put it here.
    ///
    /// Every failure produces an `Err` fragment and nothing else: a slow hook, a
    /// trapping one, a fragment carrying a tag this build will not emit, one
    /// over the `render_bytes` quota. A caller omits the fragment and serves the
    /// page — see [`SandboxRenderOutcome`].
    #[must_use]
    pub fn render(
        &self,
        slot: &str,
        context: &[(String, String)],
        services: crate::plugin_sandbox::CapabilityServices,
    ) -> SandboxRenderOutcome {
        let limits = self.manifest.limits;
        let refused = |failure, fuel_used| SandboxRenderOutcome {
            fragment: Err(failure),
            denials: Vec::new(),
            fuel_used,
            peak_memory_bytes: 0,
            stderr: String::new(),
            activity: Vec::new(),
            dropped_events: 0,
            dropped_calls: None,
        };

        // Checked here rather than left to the guest: a plugin that was not
        // granted the slot must not run at all for it, because running is what
        // costs the page its latency.
        if !self
            .manifest
            .is_granted(super::manifest::SandboxCapability::Render)
            || !self
                .manifest
                .grants
                .allows(super::manifest::SandboxCapability::Render, slot)
        {
            return refused(
                SandboxFailure::GuestError(format!(
                    "this plugin was not granted the render slot {slot:?}",
                    slot = super::manifest::rejected(slot)
                )),
                0,
            );
        }

        // Bounded here, at the public entry point, rather than only in
        // `SandboxedPlugin::render_slot`. An embedder may call this directly
        // with context built from a row or a query string, and a ceiling only
        // one of two callers reaches is a ceiling the other does not have.
        let context = &bounded_context(context);

        // The context is the host's own text rather than a client's body, so it
        // is priced by its length the same way an encoded request is. Measured
        // from the parts rather than from the encoded frame, because encoding
        // it is the work being priced. Per-entry overhead is included, so a
        // context of many empty pairs is not charged nothing for allocation and
        // serialization it really costs.
        let encoding = context
            .iter()
            .map(|(name, value)| {
                u64::try_from(
                    name.len()
                        .saturating_add(value.len())
                        .saturating_add(RENDER_CONTEXT_ENTRY_OVERHEAD),
                )
                .unwrap_or(u64::MAX)
            })
            .fold(
                u64::try_from(slot.len()).unwrap_or(u64::MAX),
                u64::saturating_add,
            )
            / BYTES_PER_FUEL;

        let capabilities = &self.manifest.capabilities;
        match self.execute(
            || HostFrame::render(slot, context, capabilities),
            encoding,
            Exchange::Render,
            services,
        ) {
            Execution::Refused(failure, fuel_used) => refused(failure, fuel_used),
            Execution::Ran(store, permit, result) => {
                let fuel_used = store
                    .get_fuel()
                    .map_or(limits.fuel, |left| limits.fuel.saturating_sub(left));
                let mut state = store.into_data();
                // The same drain `finish` performs, and for the same reason: a
                // hook that kept hitting its memory ceiling is the likeliest
                // cause of an omitted fragment, and an operator reading an empty
                // denial list would be reading silence rather than evidence.
                let peak_memory_bytes = record_limiter_refusals(&mut state, limits);
                let activity = state.runtime.take_events();
                let dropped_events = state.runtime.dropped_events();
                let dropped_calls = state.runtime.dropped_calls();
                let max_bytes = state.runtime.quotas().render_bytes as usize;
                let fragment = match result {
                    Ok(GuestAnswer::Fragment(nodes)) => {
                        super::capability::render::render(&nodes, max_bytes).map_err(|err| {
                            SandboxFailure::ResponseRefused(guest_text(&err.to_string()))
                        })
                    }
                    Ok(GuestAnswer::Response(_)) => Err(SandboxFailure::MalformedFrame(
                        "a render slot is answered with a `fragment` frame, not a `response`"
                            .to_owned(),
                    )),
                    Err(failure) => Err(failure),
                };
                let stderr = state.stderr_excerpt();
                drop(permit);
                SandboxRenderOutcome {
                    fragment,
                    denials: state.denials,
                    fuel_used,
                    peak_memory_bytes,
                    stderr,
                    activity,
                    dropped_events,
                    dropped_calls,
                }
            }
        }
    }

    /// Instantiate the module and run it to its first terminal frame.
    ///
    /// The half `run_with` and `render` share: everything from admission to the
    /// `_start` call is identical between them, and a second copy of it would be
    /// a second place for one of these ceilings to go missing.
    fn execute(
        &self,
        frame: impl FnOnce() -> HostFrame,
        encoding: u64,
        exchange: Exchange,
        services: crate::plugin_sandbox::CapabilityServices,
    ) -> Execution<'_> {
        let limits = self.manifest.limits;

        // Admission, before a single buffer is built. `serve` holds a permit of
        // its own across the whole request, so this is never what stops an
        // ordinary HTTP request — it is here for the embedder who calls the
        // public entry points directly and would otherwise start as many
        // instances as it liked, against a footprint the manifest validator
        // accepted on the premise that `max_concurrency` bounds them.
        //
        // Held for the body of the run: dropping the guard on the way out is
        // what makes the permit mean "executing now".
        let Ok(permit) = self.permits.try_acquire() else {
            return Execution::Refused(
                SandboxFailure::AtCapacity {
                    max: limits.max_concurrency,
                },
                0,
            );
        };

        // Building the guest's stdin is host work proportional to the frame:
        // the body is cloned into it and base64-expanded into the NDJSON line,
        // all of it before a single guest instruction runs. Unpriced, that is
        // megabytes of host CPU per request for a manifest that declares a
        // large body ceiling and almost no fuel — and a client can repeat it
        // for as long as it likes.
        //
        // So it is charged at the same rate as every other host-side copy, and
        // charged *before* the copies happen: a budget that cannot cover the
        // encoding refuses without doing it. The guest then starts on what is
        // left, which is the same arrangement instantiation already has.
        let Some(after_encoding) = limits.fuel.checked_sub(encoding) else {
            return Execution::Refused(
                SandboxFailure::FuelExhausted {
                    budget: limits.fuel,
                },
                limits.fuel,
            );
        };

        // Built and encoded here, after admission and after the charge above —
        // see the note in `run_with`. The frame's bytes are then *moved* into
        // the queue rather than copied into it: `VecDeque::from(Vec<u8>)`
        // reuses the allocation, and the `String` is gone afterwards. For a
        // plugin with a large body ceiling that is a whole base64-expanded copy
        // of the request that no longer exists at the same time as the others.
        let frame = frame();
        // Only the request frame is large, and only its encoding is priced for
        // the second pass above. Render frames keep the single pass.
        let line = match if matches!(frame, HostFrame::Request { .. }) {
            to_exact_line(&frame)
        } else {
            to_line(&frame)
        } {
            Ok(line) => line,
            Err(err) => {
                // The host could not encode its own frame. Reported as a
                // plugin-prefix failure rather than propagating: the rest of
                // the application is unaffected either way.
                return Execution::Refused(
                    SandboxFailure::Instantiation(guest_text(&err.to_string())),
                    0,
                );
            }
        };

        let mut state = HostState::new(
            self.manifest.name.clone(),
            limits,
            line.as_bytes(),
            exchange,
            crate::plugin_sandbox::capability::CapabilityRuntime::new(&self.manifest, services)
                .with_artifact_sha256(
                    self.artifact_sha256
                        .clone()
                        .unwrap_or_else(|| self.manifest.sha256.clone()),
                ),
        );
        state.stdin = VecDeque::from(line.into_bytes());

        let mut store = Store::new(&self.engine, state);
        store.limiter(|state| &mut state.limiter);
        // Set before instantiation, so the budget is in place the moment the
        // first guest instruction runs.
        if let Err(err) = store.set_fuel(after_encoding) {
            return Execution::Refused(
                SandboxFailure::Instantiation(guest_text(&err.to_string())),
                0,
            );
        }

        // wasmi does not meter instantiation: every request copies the module's
        // data and element segments before `_start` runs. Two things bound it,
        // and it needs both. The *ceiling* is at load — a module whose segments
        // are structurally expensive is refused outright, because a per-request
        // charge cannot stop work that has already been admitted. The *price* is
        // here, so the work that is admitted still comes out of the budget the
        // manifest declared rather than being free.
        let Some(left) = after_encoding.checked_sub(self.instantiation_fuel) else {
            return Execution::Ran(
                store,
                permit,
                Err(SandboxFailure::FuelExhausted {
                    budget: limits.fuel,
                }),
            );
        };
        if let Err(err) = store.set_fuel(left) {
            return Execution::Refused(
                SandboxFailure::Instantiation(guest_text(&err.to_string())),
                0,
            );
        }

        let mut linker = <Linker<HostState>>::new(&self.engine);
        if let Err(err) = define_wasi_shim(&mut linker) {
            return Execution::Refused(
                SandboxFailure::Instantiation(guest_text(&err.to_string())),
                0,
            );
        }

        let started = linker
            .instantiate(&mut store, &self.module)
            .and_then(|pre| pre.start(&mut store));
        let instance = match started {
            Ok(instance) => instance,
            Err(err) => {
                return Execution::Ran(store, permit, Err(instantiation_failure(&err, limits)));
            }
        };

        let Ok(start) = instance.get_typed_func::<(), ()>(&store, "_start") else {
            // `from_module` already refused a module without `_start`; reaching
            // here would mean the export changed shape, which is still the
            // plugin's problem and not the host's.
            return Execution::Ran(store, permit, Err(SandboxFailure::NoAnswer));
        };

        let trap = start.call(&mut store, ()).err();
        let partial = !store.data().stdout_line.is_empty();
        let result = match (store.data().answer.clone(), trap) {
            // A guest that answered and *then* trapped still answered: the
            // first frame is the answer, and everything after it — including
            // the host's own `AnswerComplete` unwind — is noise after the fact.
            (Some(answer), _) => answer,
            (None, Some(err)) => Err(guest_failure(&err, limits)),
            (None, None) if partial => Err(SandboxFailure::PartialFrame),
            (None, None) => Err(SandboxFailure::NoAnswer),
        };
        Execution::Ran(store, permit, result)
    }
}

/// What one instantiation-and-run produced.
///
/// `Refused` is a request that never reached a guest instruction — at capacity,
/// or a budget that could not cover its own fixed charges — and carries no
/// store, because there is none. `Ran` carries the store so the caller can drain
/// the evidence: fuel, memory peak, denials, stderr and the capability ledger.
#[allow(
    clippy::large_enum_variant,
    reason = "`Ran` carries the wasmi `Store` itself, which is large by construction and is the \
              common path; boxing it would add an allocation per request without shrinking the \
              store, and this value is a return value moved once, never held in a collection"
)]
enum Execution<'a> {
    /// Turned away before a store existed.
    Refused(SandboxFailure, u64),
    /// Ran to a terminal frame, or failed trying.
    ///
    /// The permit comes back out with the store rather than being dropped at
    /// the end of `execute`: draining the store is where the response is
    /// sanitised, size-checked and cloned, which is the `5 ×
    /// max_response_bytes` term `max_concurrency` is validated against. A
    /// permit released before that work happens bounds the interpreter and not
    /// the request.
    Ran(
        Store<HostState>,
        tokio::sync::SemaphorePermit<'a>,
        Result<GuestAnswer, SandboxFailure>,
    ),
}

/// Drain the store into an outcome, applying the response sanitation and the
/// size ceiling that only the host can enforce.
/// What a response may carry, gathered because the three travel together.
///
/// A `Location` is judged against all of them at once: it must stay under the
/// prefix, name a route the plugin actually serves — an application route may
/// sit under the prefix — and land on that route under the method the client
/// will replay, which the status and the request's own method decide between
/// them. Passing them as one argument keeps `run`'s exits readable.
struct ResponseRules<'a> {
    prefix: &'a str,
    owned: &'a super::wire::OwnedRoutes,
    requested: &'a str,
}

fn finish(
    store: Store<HostState>,
    limits: ResourceLimits,
    rules: &ResponseRules<'_>,
    result: Result<GuestAnswer, SandboxFailure>,
) -> SandboxOutcome {
    let fuel_used = store
        .get_fuel()
        .map_or(limits.fuel, |left| limits.fuel.saturating_sub(left));
    let mut state = store.into_data();
    let peak_memory_bytes = record_limiter_refusals(&mut state, limits);

    let activity = state.runtime.take_events();
    let dropped_activity = state.runtime.dropped_events();
    let dropped_calls = state.runtime.dropped_calls();
    let result = match result {
        Ok(GuestAnswer::Fragment(_)) => Err(SandboxFailure::MalformedFrame(
            "a request is answered with a `response` frame, not a `fragment`".to_owned(),
        )),
        Ok(GuestAnswer::Response(response)) => {
            let (response, denied) = response.sanitize(rules.prefix, rules.owned, rules.requested);
            for name in denied {
                // The name is the guest's, so it is as long and as hostile as
                // the guest cares to make it — bounded only by the stdout line
                // ceiling. `deny` clones it into the ledger and logs it, and a
                // name is not validated before it gets here (that it is invalid
                // is often *why* it was denied), so it can carry newlines and
                // terminal escapes too. Same treatment as every other
                // guest-influenced string that reaches a log.
                state.deny(
                    DeniedCapability::ResponseHeader,
                    &guest_text(&name),
                    "a sandboxed plugin may not set this response header",
                );
            }
            response.refused_content_type().map_or_else(
                || {
                    response
                        .validate()
                        .and_then(|()| response.check_size(limits.max_response_bytes))
                        .map_or_else(
                            |err| {
                                Err(SandboxFailure::ResponseRefused(guest_text(
                                    &err.to_string(),
                                )))
                            },
                            |()| Ok(response.clone()),
                        )
                },
                |essence| {
                    // `refused_content_type` returns everything before the
                    // first `;`, so a guest that writes no parameter hands back
                    // its whole header value — bounded only by the stdout
                    // ceiling, which is megabytes. Both strings built here are
                    // logged, the denial by `deny` and the failure by `serve`,
                    // so the guest's text gets the same cap and control-escaping
                    // every other guest-influenced string gets. The branch beside
                    // this one already did; this one did not.
                    let essence = guest_text(&essence);
                    let detail = format!(
                        "a sandboxed plugin may not serve `{essence}`: a document or a script \
                         from the host's own origin would carry the host's authority"
                    );
                    state.deny(DeniedCapability::ResponseHeader, "content-type", &detail);
                    Err(SandboxFailure::ResponseRefused(
                        super::wire::WireError::UnsupportedContentType(essence).to_string(),
                    ))
                },
            )
        }
        Err(failure) => Err(failure),
    };

    let stderr = state.stderr_excerpt();
    SandboxOutcome {
        result,
        denials: state.denials,
        fuel_used,
        peak_memory_bytes,
        stderr,
        activity,
        dropped_activity,
        dropped_calls,
    }
}

/// Turn the memory limiter's refusal counts into denials, and report the peak.
///
/// Shared by `finish` and by the render path. Two exits that both drain a store
/// are two places for one of these to be forgotten — and the render path did
/// forget them, so a hook that died against its memory ceiling reported an empty
/// denial list, which reads as "nothing was refused" rather than as the answer.
fn record_limiter_refusals(state: &mut HostState, limits: ResourceLimits) -> usize {
    let peak_memory_bytes = state.limiter.peak;
    let (memory_refusals, table_refusals) =
        (state.limiter.memory_refusals, state.limiter.table_refusals);
    if memory_refusals > 0 {
        let detail = format!(
            "{memory_refusals} allocation(s) over the plugin's {max}-byte memory ceiling were refused",
            max = limits.memory_bytes,
        );
        state.deny(DeniedCapability::Memory, "memory.grow", &detail);
    }
    // Its own operation and its own ceiling. `deny` deduplicates by
    // `(capability, operation)`, so this is a second entry beside the byte one
    // rather than a collision with it, and a guest that hit both is recorded as
    // having hit both.
    if table_refusals > 0 {
        let detail = format!(
            "{table_refusals} table growth(s) over the sandbox's {MAX_TABLE_ELEMENTS}-element table ceiling were refused",
        );
        state.deny(DeniedCapability::Memory, "table.grow", &detail);
    }
    peak_memory_bytes
}

fn instantiation_failure(err: &wasmi::Error, limits: ResourceLimits) -> SandboxFailure {
    if err.as_trap_code() == Some(wasmi::core::TrapCode::OutOfFuel) {
        SandboxFailure::FuelExhausted {
            budget: limits.fuel,
        }
    } else {
        SandboxFailure::Instantiation(guest_text(&err.to_string()))
    }
}

fn guest_failure(err: &wasmi::Error, limits: ResourceLimits) -> SandboxFailure {
    if let Some(code) = err.i32_exit_status() {
        return SandboxFailure::Exited(code);
    }
    if err.as_trap_code() == Some(wasmi::core::TrapCode::OutOfFuel) {
        return SandboxFailure::FuelExhausted {
            budget: limits.fuel,
        };
    }
    if err.downcast_ref::<OutputBudgetExhausted>().is_some() {
        return SandboxFailure::OutputBudget {
            max: limits.max_response_bytes,
        };
    }
    SandboxFailure::Trap(guest_text(&err.to_string()))
}

/// What a module's section headers declare, without compiling it.
///
/// Walks the top-level sections directly. wasmi's public API does not expose
/// segments, and these are the numbers that have to be bounded at load: the
/// alternative is discovering them per request, in host work no budget prices.
///
/// Returns `None` for bytes that are not a well-formed section stream. This now
/// runs *before* wasmi compiles the module, so malformed bytes reach it — and
/// refusing them is the right answer.
#[derive(Debug, Clone, Copy)]
struct ModuleShape {
    /// How many linear memories the module declares for itself.
    memory_count: usize,
    /// Section headers the module carries, custom ones included.
    ///
    /// Counted because a custom section contributes to no other ceiling and
    /// costs three bytes to encode; see `MAX_SECTIONS`.
    sections: usize,
    /// Data and element segments, which every instantiation copies.
    segments: usize,
    /// Bytes those sections hold.
    init_bytes: usize,
    /// Entries every section *declares*, summed.
    ///
    /// Read from each section's leading count, so this costs one LEB128 per
    /// section rather than a walk over the entries themselves — the point is to
    /// know the shape before anything allocates per entry.
    declared_entries: usize,
    /// The first active element segment that writes past its table, as
    /// (one past its furthest write, what the table starts with).
    element_overflow: Option<(u64, u64)>,
    /// The furthest byte any active data segment writes to.
    ///
    /// Zero when the module has none, or when the offsets are not constants
    /// this walk can evaluate.
    data_end: u64,
    /// How many imports the module declares.
    ///
    /// `MAX_IMPORTS` was enforced from `module.imports().count()`, which is
    /// only available *after* `Module::new` has already built a representation
    /// of every one of them — the ceiling ran after the allocation it exists to
    /// prevent. Read from the section header here, so it can run before.
    import_count: usize,
    /// How many functions the module defines.
    function_count: usize,
    /// Whether the module carries a `start` section.
    has_start: bool,
    /// Bytes of instruction stream in the code section.
    code_bytes: usize,
    /// How many globals the module declares.
    global_count: usize,
    /// Bytes of instruction stream in the global section.
    ///
    /// A global's initializer is a constant expression, and the extended-const
    /// proposal lets that expression run to arbitrary length — one global can
    /// carry most of the module. Those bytes are instruction volume, the same
    /// thing the code-section ceiling measures, so they share it rather than
    /// hiding behind the entry count.
    global_bytes: usize,
    /// How many tables the module declares.
    ///
    /// Sizes and count are separate ceilings: five empty tables cost no
    /// elements at all and still exceed what the store will build.
    table_count: usize,
    /// Elements the module's own tables declare as their *initial* size.
    ///
    /// The limiter enforces `MAX_TABLE_ELEMENTS` at instantiation, which is
    /// per request; knowing the declared total at load is what turns "every
    /// request fails" into "this artifact does not load".
    table_elements: u64,
}

/// What an element section declares, and whether it writes past a table.
struct ElementSectionShape {
    /// The first active segment that writes past its table, as (one past its
    /// furthest write, what the table starts with).
    overflow: Option<(u64, u64)>,
    /// Items the section's segments declare between them.
    ///
    /// Read from each segment's leading count rather than by counting the
    /// items walked, which is what lets the walk stop at the ceiling instead
    /// of reaching it one entry at a time.
    items: usize,
}

/// What the element section declares, and whether any *active* segment writes
/// past the table it targets.
///
/// `None` when the section cannot be read — the same restraint the data walk
/// uses: an offset this cannot evaluate is left to the engine rather than
/// guessed at.
fn element_section_shape(
    wasm: &[u8],
    start: usize,
    section_end: usize,
    table_minimums: &[u64],
) -> Option<ElementSectionShape> {
    let (count, mut at) = leb128(wasm, start)?;
    let mut overflow = None;
    let mut declared = 0usize;
    for _ in 0..count {
        let (flags, next) = leb128(wasm, at)?;
        at = next;
        // Only an active segment is written at instantiation; passive (1, 5)
        // and declarative (3, 7) ones are not.
        let active = matches!(flags, 0 | 2 | 4 | 6);
        let mut table_index = 0usize;
        if flags == 2 || flags == 6 {
            let (index, next) = leb128(wasm, at)?;
            table_index = index;
            at = next;
        }
        let mut offset = None;
        if active {
            let (value, next) = const_i32(wasm, at, section_end)?;
            offset = value;
            at = next;
        }
        // Every form but 0 and 4 carries an elemkind or reftype byte.
        if !matches!(flags, 0 | 4) {
            at = at.checked_add(1)?;
        }
        let (items, next) = leb128(wasm, at)?;
        at = next;
        // The segment's own count, before a single item is read. Nothing else sees it:
        // `declared_entries` sums each section's leading count, so one segment holding
        // millions of indices adds one, and `MAX_TABLE_ELEMENTS` bounds only what a
        // table starts with, which a passive segment never touches. The ceiling that
        // exists to bound declarations before anything allocates per declaration was
        // therefore blind to the one place a declaration is nested. Return here rather
        // than walk on: past the ceiling the module is refused whatever the remaining
        // segments hold, so reading them is work an artifact chose for this process —
        // the same rule the section-count walk follows, one level down.
        declared = declared.saturating_add(items);
        if declared > MAX_DECLARED_ENTRIES {
            return Some(ElementSectionShape {
                overflow,
                items: declared,
            });
        }
        if flags >= 4 {
            // `vec(expr)`: each element is a constant expression.
            for _ in 0..items {
                at = skip_const_expr(wasm, at, section_end)?;
            }
        } else {
            // `vec(funcidx)`: each element is one LEB128.
            for _ in 0..items {
                let (_, next) = leb128(wasm, at)?;
                at = next;
            }
        }
        if at > section_end {
            return None;
        }
        // The same rule the data section walk reaches by way of
        // `DataSectionEnd::ActiveUnevaluable`: an active segment is written at
        // instantiation whether or not this can work out where, so an offset it
        // cannot evaluate is treated as one that cannot fit. Skipping it left
        // the bounds check silently not running — the defect this walk exists
        // to prevent, in the sibling of the walk where it was just fixed.
        if active {
            let capacity = table_minimums.get(table_index).copied().unwrap_or(0);
            let end = match offset {
                Some(offset) => offset.checked_add(items as u64)?,
                None => u64::MAX,
            };
            if end > capacity && overflow.is_none() {
                overflow = Some((end, capacity));
            }
        }
    }
    Some(ElementSectionShape {
        overflow,
        items: declared,
    })
}

/// Skip one constant expression, returning the offset just past its `end`.
///
/// Scanning for the `0x0b` terminator instead of decoding is wrong, and quietly
/// so: `ref.func 11` encodes its immediate as `0x0b`, so a scan stops on the
/// operand and every following byte is read at the wrong offset. That desync
/// made the walk bail and silently drop the bounds check it exists to perform.
/// Only the instructions a constant expression may contain are decoded; an
/// unknown opcode returns `None`, which leaves the module to the engine rather
/// than to a guess.
fn skip_const_expr(wasm: &[u8], mut at: usize, limit: usize) -> Option<usize> {
    loop {
        if at > limit {
            return None;
        }
        let opcode = *wasm.get(at)?;
        at = at.checked_add(1)?;
        match opcode {
            // end
            0x0b => return Some(at),
            // i32.const / i64.const: one signed LEB128. `ref.null` (0xd0)
            // takes the same step: the format writes a heap type as a signed
            // LEB too. Every heap type this engine accepts fits one byte —
            // `funcref` is 0x70, `externref` 0x6f, and wasmi enables neither
            // function-references nor the GC proposal's concrete type
            // references, so a type index cannot appear here — which makes
            // reading the LEB identical to reading the byte today, and keeps
            // this walk in step if that ever stops being true.
            0x41 | 0x42 | 0xd0 => at = sleb128(wasm, at)?.1,
            // f32.const / f64.const: raw little-endian bits
            0x43 => at = at.checked_add(4)?,
            0x44 => at = at.checked_add(8)?,
            // ref.func / global.get: one unsigned LEB128
            0xd2 | 0x23 => at = leb128(wasm, at)?.1,
            // extended-const arithmetic: no immediates. wasmi enables the
            // proposal by default, so these appear in offsets the engine
            // accepts and this walk has to keep step with.
            0x6a..=0x6c | 0x7c..=0x7e => {}
            _ => return None,
        }
    }
}

/// The `i32` value a constant expression evaluates to, if this can tell.
///
/// Returns the offset past the expression either way, so a caller can keep
/// walking past an expression it cannot evaluate.
///
/// Reading only a bare `i32.const` was not enough, and the gap was a fail-open.
/// wasmi enables the extended-const proposal by default, so
/// `i32.const 65535; i32.const 2; i32.add` is a legal active data offset that
/// the engine compiles happily. Against the bare-form reader it was not merely
/// unevaluable: `skip_const_expr` did not know `i32.add` either, so the whole
/// data section's walk returned `None`, the caller dropped it, and `data_end`
/// stayed at zero. The bounds check did not run at all, and packaging approved
/// an artifact whose every request would then fail at instantiation — the one
/// outcome the load-time check exists to prevent.
///
/// So the arithmetic is evaluated. Everything else a constant expression may
/// contain is still stepped over and reported as unevaluable rather than
/// guessed at: `global.get` reads a global this walk has not tracked, and the
/// float and reference forms are not offsets at all.
fn const_i32(wasm: &[u8], at: usize, limit: usize) -> Option<(Option<u64>, usize)> {
    // The proposal's grammar is a fold over constants, so a handful of slots is
    // more than any real offset needs; a deeper expression is reported as
    // unevaluable rather than growing a stack for an untrusted module.
    let mut stack = [0i32; 16];
    let mut depth = 0usize;
    let mut evaluable = true;
    let mut at = at;
    loop {
        if at > limit {
            return None;
        }
        let opcode = *wasm.get(at)?;
        at = at.checked_add(1)?;
        match opcode {
            // end
            0x0b => break,
            // i32.const
            0x41 => {
                let (value, next) = sleb128(wasm, at)?;
                at = next;
                match (i32::try_from(value), stack.get_mut(depth)) {
                    (Ok(narrow), Some(slot)) => {
                        *slot = narrow;
                        depth = depth.saturating_add(1);
                    }
                    _ => evaluable = false,
                }
            }
            // i32.add / i32.sub / i32.mul, which wrap in wasm as they do here.
            0x6a..=0x6c => {
                // Folded through `checked_sub` and `get` rather than indexing:
                // this module is in the request-path panic-gate manifest, and
                // the depth these run against comes out of an untrusted module.
                let folded = depth.checked_sub(2).and_then(|left_at| {
                    let right = *stack.get(depth.checked_sub(1)?)?;
                    let left = *stack.get(left_at)?;
                    let value = match opcode {
                        0x6a => left.wrapping_add(right),
                        0x6b => left.wrapping_sub(right),
                        _ => left.wrapping_mul(right),
                    };
                    Some((left_at, value))
                });
                match folded {
                    Some((left_at, value)) => {
                        if let Some(slot) = stack.get_mut(left_at) {
                            *slot = value;
                        }
                        depth = left_at.saturating_add(1);
                    }
                    None => evaluable = false,
                }
            }
            // i64.const, and the i64 arithmetic: stepped over, not evaluated —
            // a memory or table offset is an `i32`, so an expression built from
            // these is not one this caller is asking about.
            0x42 => {
                at = sleb128(wasm, at)?.1;
                evaluable = false;
            }
            0x7c..=0x7e => evaluable = false,
            // f32.const / f64.const: raw little-endian bits, never an offset.
            0x43 => {
                at = at.checked_add(4)?;
                evaluable = false;
            }
            0x44 => {
                at = at.checked_add(8)?;
                evaluable = false;
            }
            // ref.null: one heap type byte.
            0xd0 => {
                at = at.checked_add(1)?;
                evaluable = false;
            }
            // ref.func / global.get: one unsigned LEB128.
            0xd2 | 0x23 => {
                at = leb128(wasm, at)?.1;
                evaluable = false;
            }
            _ => return None,
        }
    }
    if let (true, 1, Some(&result)) = (evaluable, depth, stack.first()) {
        // A wasm offset is a `u32`, so `i32.const -1` addresses 4294967295 —
        // past the end of any memory or table the sandbox will admit. Dropping
        // a negative as "unevaluable" was a fail-open: the one class of offset
        // that is *certainly* out of bounds was the one recorded as unknown.
        let unsigned = u64::from(u32::from_ne_bytes(result.to_ne_bytes()));
        return Some((Some(unsigned), at));
    }
    Some((None, at))
}

/// Read an unsigned LEB128 at `at`, returning the value and the next offset.
fn leb128(wasm: &[u8], at: usize) -> Option<(usize, usize)> {
    let mut value: usize = 0;
    let mut shift: u32 = 0;
    let mut cursor = at;
    loop {
        let byte = *wasm.get(cursor)?;
        cursor = cursor.checked_add(1)?;
        value = value.checked_add(usize::from(byte & 0x7f).checked_shl(shift)?)?;
        if byte & 0x80 == 0 {
            return Some((value, cursor));
        }
        shift = shift.checked_add(7)?;
        if shift > 63 {
            return None;
        }
    }
}

/// A signed LEB128, for the `i32.const` in a segment's offset expression.
fn sleb128(wasm: &[u8], at: usize) -> Option<(i64, usize)> {
    let mut value: i64 = 0;
    let mut shift: u32 = 0;
    let mut cursor = at;
    loop {
        let byte = *wasm.get(cursor)?;
        cursor = cursor.checked_add(1)?;
        value |= i64::from(byte & 0x7f).checked_shl(shift)?;
        shift = shift.checked_add(7)?;
        if byte & 0x80 == 0 {
            if shift < 64 && byte & 0x40 != 0 {
                value |= -1i64 << shift;
            }
            return Some((value, cursor));
        }
        if shift > 63 {
            return None;
        }
    }
}

/// The furthest byte the data section's *active* segments write to.
///
/// `None` when nothing in the section can be evaluated — a passive-only
/// section. The two `None`s are different answers and the caller treats them
/// differently: the outer one means the walk failed and the bounds check did
/// not happen, so the module is refused; the inner one means the walk
/// succeeded and there was no active write to measure — a passive-only
/// section copies nothing at instantiation — so there is nothing to refuse.
/// What a walk of the data section found.
///
/// Three answers, not two, and collapsing any pair of them has been a bug in
/// this file already: reading "nothing to measure" as "the check did not run"
/// refused a runnable module, and reading "the check did not run" as "nothing
/// to measure" admitted a segment past the end of memory.
enum DataSectionEnd {
    /// The walk failed — a malformed section, or an opcode a later proposal
    /// added that this does not know. The bounds check did not happen.
    Unreadable,
    /// The walk succeeded and found no active write to measure: every segment
    /// is passive, so nothing is copied at instantiation.
    NothingActive,
    /// The walk succeeded, and an active segment's offset could not be
    /// evaluated — an expression past the evaluator's stack, or one reading a
    /// global this walk has not tracked. The segment *is* copied in at
    /// instantiation; this simply cannot say where, which is the one thing the
    /// bounds check needs to know.
    ActiveUnevaluable,
    /// The furthest byte an active segment writes.
    Furthest(u64),
}

impl DataSectionEnd {
    /// What this contributes to the module's `data_end`.
    ///
    /// An unreadable section contributes `u64::MAX`, so an offset that cannot
    /// be read is treated as one that cannot fit — silently contributing
    /// nothing is how a segment past the end of memory got admitted.
    const fn contribution(&self) -> u64 {
        match *self {
            Self::Unreadable | Self::ActiveUnevaluable => u64::MAX,
            Self::NothingActive => 0,
            Self::Furthest(end) => end,
        }
    }
}

fn data_section_end(wasm: &[u8], start: usize, section_end: usize) -> DataSectionEnd {
    walk_data_section(wasm, start, section_end).unwrap_or(DataSectionEnd::Unreadable)
}

/// Walk the section, or `None` if it cannot be walked to the end.
///
/// The `?`s below are all the same answer — the walk did not finish, so the
/// bounds check did not happen — and [`data_section_end`] turns that into
/// [`DataSectionEnd::Unreadable`]. Kept separate so `?` can say it once rather
/// than every early return spelling out the enum.
fn walk_data_section(wasm: &[u8], start: usize, section_end: usize) -> Option<DataSectionEnd> {
    let (count, mut at) = leb128(wasm, start)?;
    let mut furthest: Option<u64> = None;
    // An active segment whose offset this cannot evaluate is not the same as no
    // active segment at all, and reading it as one was a bounds check that
    // silently did not run: the bytes are copied in regardless of whether this
    // could work out where.
    let mut active_unevaluable = false;
    for _ in 0..count {
        let (flags, next) = leb128(wasm, at)?;
        at = next;
        // Flag 1 is a passive segment: nothing is copied at instantiation,
        // so it cannot be out of bounds.
        let active = flags != 1;
        if flags == 2 {
            let (_memory_index, next) = leb128(wasm, at)?;
            at = next;
        }
        let mut offset: Option<u64> = None;
        if active {
            let (value, next) = const_i32(wasm, at, section_end)?;
            offset = value;
            at = next;
        }
        let (len, next) = leb128(wasm, at)?;
        at = next.checked_add(len)?;
        if at > section_end {
            return None;
        }
        match (active, offset) {
            (true, Some(offset)) => {
                let segment_end = offset.checked_add(len as u64)?;
                furthest = Some(furthest.map_or(segment_end, |f: u64| f.max(segment_end)));
            }
            (true, None) => active_unevaluable = true,
            (false, _) => {}
        }
    }
    if active_unevaluable {
        return Some(DataSectionEnd::ActiveUnevaluable);
    }
    Some(furthest.map_or(DataSectionEnd::NothingActive, DataSectionEnd::Furthest))
}

/// Section ids for the element and data sections.
const ELEMENT_SECTION: u8 = 9;
const DATA_SECTION: u8 = 11;
/// The table section, whose entries carry the initial sizes the limiter
/// will be asked to admit.
const TABLE_SECTION: u8 = 4;
/// `vec(memtype)` — every linear memory the module declares for itself.
const MEMORY_SECTION: u8 = 5;
/// The global section, whose entries each become per-instance storage.
const GLOBAL_SECTION: u8 = 6;
/// The import section: entries the compiler builds a representation for.
const IMPORT_SECTION: u8 = 2;
/// The function section: one type index per function the module defines.
const FUNCTION_SECTION: u8 = 3;
/// The start section: a function the engine runs at instantiation.
const START_SECTION: u8 = 8;
/// The code section, whose *size* is the instruction volume the compiler
/// walks — a thing no entry count reveals.
const CODE_SECTION: u8 = 10;
/// The custom section is the one whose payload is not a counted vector.
const CUSTOM_SECTION: u8 = 0;

/// The gates that prove an artifact can actually be instantiated.
///
/// Distinct from the ceilings in `refuse_unbounded_shape`, which bound what
/// loading may *cost*: these say the module can be built at all. Each one
/// stands for a defect where the artifact loaded clean, inspected clean, and
/// then failed every single request it was ever given.
const fn refuse_unrunnable_shape(
    shape: &ModuleShape,
    initial_bytes: u64,
) -> Result<(), SandboxLoadError> {
    // An active segment is copied in during instantiation, which is per
    // request, so one that does not fit the memory the module starts with
    // fails every instantiation the artifact is ever given. Said once here
    // rather than 502 for the life of the plugin.
    if shape.has_start {
        return Err(SandboxLoadError::StartSectionForbidden);
    }
    if shape.data_end > initial_bytes {
        return Err(SandboxLoadError::SegmentOutOfBounds {
            what: "linear memory",
            end: shape.data_end,
            capacity: initial_bytes,
        });
    }

    // And the same for a segment written into a table rather than into
    // memory: fixing one without the other would leave half the defect.
    if let Some((end, capacity)) = shape.element_overflow {
        return Err(SandboxLoadError::SegmentOutOfBounds {
            what: "table elements",
            end,
            capacity,
        });
    }
    Ok(())
}

/// Read a table section's declared count and the elements its tables start with.
///
/// `vec(tabletype)`, and a `tabletype` is a reftype byte then `limits`: a flag,
/// the minimum, and a maximum when the flag says so. Only the minimum matters
/// here — it is what the instance allocates before the guest runs.
///
/// Returns the declared count and the summed minimums, and writes the first
/// `MAX_TABLES` minimums into `minimums`.
fn table_section_shape(
    wasm: &[u8],
    after_size: usize,
    end: usize,
    already_counted: usize,
    minimums: &mut [u64; MAX_TABLES],
    seen: &mut usize,
) -> Option<(usize, u64)> {
    let (count, mut at) = leb128(wasm, after_size)?;
    // The same argument as the segment walk in the caller, and the same shape
    // its own comment describes one step further down: bounding the
    // *allocation* per entry left the *iteration* per entry unbounded, and an
    // artifact buys that at three bytes an entry. `MAX_TABLES` refuses on the
    // count alone, so past it there is nothing left for a walk to establish.
    let walked = if already_counted.saturating_add(count) <= MAX_TABLES {
        count
    } else {
        0
    };
    let mut elements = 0u64;
    for _ in 0..walked {
        at = at.checked_add(1)?; // reftype
        let flag = *wasm.get(at)?;
        at = at.checked_add(1)?;
        let (minimum, next) = leb128(wasm, at)?;
        at = next;
        elements = elements.saturating_add(minimum as u64);
        // Only the first `MAX_TABLES` can ever be admitted, so only those are
        // worth keeping. Pushing every declaration into a growing vector put an
        // unbounded per-entry allocation inside the very walk whose whole
        // purpose is to avoid one: a 64 MiB artifact of empty table
        // declarations would have expanded here, in the code meant to refuse it
        // before anything expanded.
        if let Some(slot) = minimums.get_mut(*seen) {
            *slot = minimum as u64;
            *seen = seen.saturating_add(1);
        }
        if flag == 0x01 {
            let (_, after_max) = leb128(wasm, at)?;
            at = after_max;
        }
        if at > end {
            return None;
        }
    }
    Some((count, elements))
}

fn module_shape(wasm: &[u8]) -> Option<ModuleShape> {
    let mut cursor = 8usize; // magic + version
    let mut sections = 0usize;
    let mut memory_count = 0usize;
    let mut segments = 0usize;
    let mut bytes = 0usize;
    let mut declared_entries = 0usize;
    let mut table_elements = 0u64;
    let mut table_count = 0usize;
    let mut global_count = 0usize;
    let mut global_bytes = 0usize;
    let mut code_bytes = 0usize;
    let mut has_start = false;
    let mut function_count = 0usize;
    let mut import_count = 0usize;
    let mut data_end = 0u64;
    let mut table_minimums = [0u64; MAX_TABLES];
    let mut table_count_seen = 0usize;
    let mut element_overflow: Option<(u64, u64)> = None;
    while cursor < wasm.len() {
        let id = *wasm.get(cursor)?;
        let (size, after_size) = leb128(wasm, cursor.checked_add(1)?)?;
        let end = after_size.checked_add(size)?;
        if end > wasm.len() {
            return None;
        }
        sections = sections.saturating_add(1);
        if sections > MAX_SECTIONS {
            // Stopping here rather than at the end is the whole point: past the
            // ceiling the module is refused whatever the remaining headers say,
            // so reading them is work an artifact chose for this process.
            break;
        }
        if id != CUSTOM_SECTION {
            let (count, _) = leb128(wasm, after_size)?;
            declared_entries = declared_entries.saturating_add(count);
        }
        if id == ELEMENT_SECTION || id == DATA_SECTION {
            let (count, _) = leb128(wasm, after_size)?;
            segments = segments.saturating_add(count);
            bytes = bytes.saturating_add(size);
        }
        // Past the ceiling the module is refused on this count alone, whatever the
        // per-segment walks below would find, so the walking is pure cost — and the
        // cost is the attack: a near-64 MiB module of two-byte passive segments is tens
        // of millions of iterations spent reaching the refusal whose purpose is to
        // bound that work.
        //
        // Skipping is safe because `refuse_unbounded_shape` rejects on `segments` by
        // itself: the refusal is unconditional and the walk's findings cannot matter.
        // It rejects on `init_bytes` by itself too, which is the other half — a single
        // element segment holding tens of millions of function indices keeps `segments`
        // at one and clears the count ceiling, so the count alone let the walk run over
        // every item on the way to a refusal the byte ceiling had already decided. Both
        // counters gate the walk because either one alone refuses the module.
        let within_segment_ceiling =
            segments <= MAX_INIT_SEGMENTS && bytes <= MAX_INIT_SECTION_BYTES;
        if id == ELEMENT_SECTION && within_segment_ceiling {
            // The table section precedes this one in a well-formed module, so
            // the minimums are known by the time the segments are read.
            if let Some(element) = element_section_shape(
                wasm,
                after_size,
                end,
                table_minimums.get(..table_count_seen).unwrap_or_default(),
            ) {
                element_overflow = element.overflow;
                declared_entries = declared_entries.saturating_add(element.items);
            }
        }
        if id == DATA_SECTION && within_segment_ceiling {
            // Active segments carry a constant offset and a length, and both
            // are needed to know whether the copy fits the memory the module
            // starts with. A segment whose offset is not a plain `i32.const`
            // (a `global.get`, say) is left alone: the shim exports no globals
            // for one to read, so such a module fails to link for its own
            // reasons rather than being mis-refused here.
            data_end = data_end.max(data_section_end(wasm, after_size, end).contribution());
        }
        // The sections whose leading count (or size) is the whole answer. The
        // rest need their entries walked and are handled above.
        let leading_count = || leb128(wasm, after_size).map(|(count, _)| count);
        match id {
            IMPORT_SECTION => import_count = import_count.saturating_add(leading_count()?),
            FUNCTION_SECTION => function_count = function_count.saturating_add(leading_count()?),
            GLOBAL_SECTION => {
                global_count = global_count.saturating_add(leading_count()?);
                // The initializers are an instruction stream, not data —
                // extended-const lets one global's expression run to
                // arbitrary length — so their bytes count toward the
                // instruction-volume ceiling the same way the code
                // section's do. Counted from the header: no walk needed.
                global_bytes = global_bytes.saturating_add(size);
            }
            MEMORY_SECTION => memory_count = memory_count.saturating_add(leading_count()?),
            CODE_SECTION => code_bytes = code_bytes.saturating_add(size),
            START_SECTION => has_start = true,
            _ => {}
        }
        if id == TABLE_SECTION {
            let (count, elements) = table_section_shape(
                wasm,
                after_size,
                end,
                table_count,
                &mut table_minimums,
                &mut table_count_seen,
            )?;
            table_count = table_count.saturating_add(count);
            table_elements = table_elements.saturating_add(elements);
        }
        cursor = end;
    }
    Some(ModuleShape {
        sections,
        memory_count,
        segments,
        init_bytes: bytes,
        declared_entries,
        import_count,
        function_count,
        has_start,
        element_overflow,
        data_end,
        code_bytes,
        global_count,
        global_bytes,
        table_count,
        table_elements,
    })
}

/// Refuse a module whose declared shape would cost more to *compile* than the
/// file's own size suggests.
///
/// `Module::new` is the first thing that touches an unaudited artifact's bytes,
/// and it builds an in-memory representation of every type, function, export
/// and global before any ceiling here has run. A legal 64 MiB file of tiny
/// declarations expands many times over in that representation, so the file
/// bound is not a bound on what compiling it costs. The section headers carry
/// the counts, so the shape is knowable *first* — one LEB128 per section, no
/// per-entry work — which is what makes refusing it cheap enough to do before
/// wasmi ever sees the bytes.
fn refuse_unbounded_shape(wasm: &[u8]) -> Result<ModuleShape, SandboxLoadError> {
    // Before the walk, because the walk is the cheap part. `check_module`
    // applies this to a module the container reader unpacked, but
    // `from_module` and `imports_of` are public and take the bytes directly,
    // so on that path nothing had imposed it. The counts below do not cover
    // the gap: one import whose module or field name is enormous is one
    // import, under every count ceiling here, and `Module::new` must
    // materialise that name before the import allowlist can refuse it.
    if wasm.len() > super::MAX_MODULE_BYTES {
        return Err(SandboxLoadError::ModuleTooLarge {
            found: wasm.len(),
            max: super::MAX_MODULE_BYTES,
        });
    }
    let Some(shape) = module_shape(wasm) else {
        return Err(SandboxLoadError::Wasm(
            "the module's section stream could not be walked".to_owned(),
        ));
    };
    // First, because it is the one ceiling the walk stops early for: past it
    // the shape is only partly read, so every count below is a floor rather
    // than a total, and refusing on one of those would name the wrong reason.
    if shape.sections > MAX_SECTIONS {
        return Err(SandboxLoadError::InstantiationTooExpensive {
            what: "sections",
            found: shape.sections,
            max: MAX_SECTIONS,
        });
    }
    // Before `Module::new`, with the rest of them. These two used to be
    // checked in `from_module` *after* compiling — so a module declaring half
    // a million empty segments, under the aggregate entry ceiling and thus
    // never refused for that, had a representation built for every one of them
    // before the ceiling that exists to prevent exactly that work ran. Moving
    // the per-segment walk earlier last round bounded the walking and left the
    // compiling; this is the other half.
    if shape.segments > MAX_INIT_SEGMENTS {
        return Err(SandboxLoadError::InstantiationTooExpensive {
            what: "data and element segments",
            found: shape.segments,
            max: MAX_INIT_SEGMENTS,
        });
    }
    if shape.init_bytes > MAX_INIT_SECTION_BYTES {
        return Err(SandboxLoadError::InstantiationTooExpensive {
            what: "bytes of data and element sections",
            found: shape.init_bytes,
            max: MAX_INIT_SECTION_BYTES,
        });
    }
    if shape.code_bytes > MAX_CODE_BYTES {
        return Err(SandboxLoadError::InstantiationTooExpensive {
            what: "code section bytes",
            found: shape.code_bytes,
            max: MAX_CODE_BYTES,
        });
    }
    // The global section's initializers are an instruction stream too —
    // extended-const lets one global's expression run to arbitrary length —
    // so their bytes share the code section's instruction-volume ceiling.
    // The entry count never saw this: one global sits under `MAX_GLOBALS`
    // however long its initializer is, and `Module::new` would build a
    // representation of every one of those instructions. The sum keeps the
    // two numbers separately recorded on `ModuleShape`, so the refusal can
    // name the sections that pushed the module over rather than
    // misattributing it to the code section alone.
    //
    // Audit of the other instruction-carrying sections, stated explicitly
    // rather than assumed: element and data section offset and item
    // expressions already sit inside `init_bytes`, which has its own
    // `MAX_INIT_SECTION_BYTES` ceiling above. The global section was the
    // only one the scanner counted by entries alone.
    let instruction_bytes = shape.code_bytes.saturating_add(shape.global_bytes);
    if instruction_bytes > MAX_CODE_BYTES {
        return Err(SandboxLoadError::InstantiationTooExpensive {
            what: "code and global section bytes",
            found: instruction_bytes,
            max: MAX_CODE_BYTES,
        });
    }
    if shape.import_count > MAX_IMPORTS {
        return Err(SandboxLoadError::InstantiationTooExpensive {
            what: "imports",
            found: shape.import_count,
            max: MAX_IMPORTS,
        });
    }
    if shape.function_count > MAX_FUNCTIONS {
        return Err(SandboxLoadError::InstantiationTooExpensive {
            what: "functions",
            found: shape.function_count,
            max: MAX_FUNCTIONS,
        });
    }
    if shape.global_count > MAX_GLOBALS {
        return Err(SandboxLoadError::InstantiationTooExpensive {
            what: "globals",
            found: shape.global_count,
            max: MAX_GLOBALS,
        });
    }
    // The per-instance stores the limiter guards. These say the module can be built at
    // all, so they read as runnability rules, but they are also cost ceilings, and that
    // is what decides where they live. A module declaring hundreds of thousands of empty
    // memories or tables sits under `MAX_DECLARED_ENTRIES` and is refused by these
    // anyway, so compiling it first buys a representation of every declaration on the
    // way to a verdict that never depended on one. Checked after that compile, they were
    // the right answer at the wrong time. All three move together: `table_elements` is
    // the same argument as the other two — tables already over the ceiling at rest are
    // refused whatever `Module::new` would say — and leaving it behind would be the
    // half-fix this file warns about elsewhere.
    if shape.memory_count > MAX_MEMORIES {
        return Err(SandboxLoadError::InstantiationTooExpensive {
            what: "linear memories",
            found: shape.memory_count,
            max: MAX_MEMORIES,
        });
    }
    if shape.table_count > MAX_TABLES {
        return Err(SandboxLoadError::InstantiationTooExpensive {
            what: "tables",
            found: shape.table_count,
            max: MAX_TABLES,
        });
    }
    if shape.table_elements > u64::from(MAX_TABLE_ELEMENTS) {
        return Err(SandboxLoadError::InstantiationTooExpensive {
            what: "initial table elements",
            found: usize::try_from(shape.table_elements).unwrap_or(usize::MAX),
            max: MAX_TABLE_ELEMENTS as usize,
        });
    }
    if shape.declared_entries > MAX_DECLARED_ENTRIES {
        return Err(SandboxLoadError::InstantiationTooExpensive {
            what: "declared section entries",
            found: shape.declared_entries,
            max: MAX_DECLARED_ENTRIES,
        });
    }
    Ok(shape)
}

/// Imports the shim will not satisfy — by name **or** by type — as denials.
///
/// Checking the type here rather than letting `Linker::instantiate` discover it
/// is what keeps `autumn plugin package` honest: a module importing an
/// allowlisted name with the wrong signature would otherwise pass packaging and
/// inspection, then fail on every request as a gateway error nobody can explain
/// from the outside.
fn forbidden_imports(module: &Module) -> Vec<CapabilityDenial> {
    module
        .imports()
        .filter_map(|import| {
            let operation = import_operation(import.module(), import.name());
            if import.module() != WASI {
                return Some((operation, "the sandbox defines no such host module"));
            }
            let Some(declared) = import.ty().func() else {
                return Some((
                    operation,
                    "the sandbox provides host functions only, not memories, tables or globals",
                ));
            };
            let Some((params, results)) = shim_signature(import.name()) else {
                return Some((operation, "the sandbox defines no such host function"));
            };
            match signature_type(params, results) {
                Some(expected) if expected == *declared => None,
                _ => Some((
                    operation,
                    "the sandbox defines this host function with a different signature, so it \
                     could never link",
                )),
            }
        })
        .map(|(operation, why)| CapabilityDenial {
            capability: DeniedCapability::UnknownImport,
            operation,
            detail: format!("{why}, so the plugin is refused before it runs"),
        })
        .take(MAX_DENIALS)
        .collect()
}

/// A guest blew its output budget. Carried as a host error so the trap it
/// causes can be told apart from any other trap.
#[derive(Debug)]
struct OutputBudgetExhausted;

/// The guest answered, so there is nothing left for it to do. Carried as a host
/// error to unwind the interpreter at the frame rather than letting a guest
/// hold a permit and a blocking worker for its whole budget after the exchange
/// is over.
#[derive(Debug)]
struct AnswerComplete;

impl fmt::Display for AnswerComplete {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("the plugin answered")
    }
}

impl wasmi::core::HostError for AnswerComplete {}

impl fmt::Display for OutputBudgetExhausted {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("the plugin exceeded its response ceiling")
    }
}

impl wasmi::core::HostError for OutputBudgetExhausted {}

// ── Host state ───────────────────────────────────────────────────────────

/// Which dialogue a store is running.
///
/// The two differ only in which host frame goes in and which guest frame is a
/// legal answer, which is exactly why they are one enum rather than two code
/// paths: everything else — the shim, the fuel, the capability channel, the
/// ledger — is shared, and a second path would be a second place for a bound to
/// be missing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Exchange {
    /// A `request` frame in, a `response` frame out.
    Request,
    /// A `render` frame in, a `fragment` frame out.
    Render,
}

/// The terminal frame a guest produced.
#[derive(Debug, Clone)]
enum GuestAnswer {
    /// The answer to a request.
    Response(SandboxResponse),
    /// The answer to a render slot.
    Fragment(Vec<super::capability::FragmentNode>),
}

/// The guest's memory ceiling, and the evidence that it was applied.
#[derive(Debug)]
struct MemoryLimiter {
    max: usize,
    peak: usize,
    /// Counted apart from `table_refusals`, because the two are refused by
    /// *different ceilings* and an operator reading the ledger is trying to
    /// learn which one the guest hit. One shared counter reported every table
    /// refusal as `memory.grow` over the manifest's byte ceiling — evidence
    /// that is not merely vague but wrong, naming a limit that was never
    /// applied.
    memory_refusals: usize,
    table_refusals: usize,
    /// Elements held across every table of this instance, so the ceiling is on
    /// the instance rather than on each table separately.
    table_elements: u32,
}

impl wasmi::ResourceLimiter for MemoryLimiter {
    fn memory_growing(
        &mut self,
        _current: usize,
        desired: usize,
        _maximum: Option<usize>,
    ) -> Result<bool, wasmi::errors::MemoryError> {
        if desired > self.max {
            self.memory_refusals = self.memory_refusals.saturating_add(1);
            // `Ok(false)` makes the guest's `memory.grow` return -1, which is a
            // legal outcome a well-written allocator handles. Returning `Err`
            // would trap instead — a harsher answer that tells a hostile guest
            // less and an honest one nothing useful.
            return Ok(false);
        }
        self.peak = self.peak.max(desired);
        Ok(true)
    }

    fn table_growing(
        &mut self,
        current: u32,
        desired: u32,
        _maximum: Option<u32>,
    ) -> Result<bool, wasmi::errors::TableError> {
        // Across the instance, not per table: four tables each under a per-table
        // ceiling would still be four times that ceiling of host storage, which
        // is exactly the accounting hole this closes.
        let total = self
            .table_elements
            .saturating_sub(current)
            .saturating_add(desired);
        if total > MAX_TABLE_ELEMENTS {
            self.table_refusals = self.table_refusals.saturating_add(1);
            return Ok(false);
        }
        self.table_elements = total;
        Ok(true)
    }

    fn instances(&self) -> usize {
        1
    }

    fn tables(&self) -> usize {
        MAX_TABLES
    }

    fn memories(&self) -> usize {
        1
    }
}

struct HostState {
    /// The plugin's name, so a denial line names who was refused. Carried here
    /// rather than logged by the caller so the refusal is logged exactly once,
    /// at the point it happens, whoever is driving the host.
    plugin: String,
    /// Bytes of the request frame the guest has not read yet.
    stdin: VecDeque<u8>,
    /// The partial stdout line being accumulated.
    stdout_line: Vec<u8>,
    /// Everything the guest wrote to stderr, bounded.
    stderr: Vec<u8>,
    /// The first terminal frame the guest produced.
    answer: Option<Result<GuestAnswer, SandboxFailure>>,
    /// Which dialogue this store is running: a request, or a render slot.
    ///
    /// Carried in the state rather than inferred from the frame, because it
    /// decides which *answer* is legal. A guest that answers a render with an
    /// HTTP response is not producing a page fragment, and without this the
    /// host would have to decide what it meant.
    exchange: Exchange,
    /// Capabilities, grants, quotas and the ledger for this request.
    runtime: crate::plugin_sandbox::capability::CapabilityRuntime,
    /// Fuel owed for capability work done while the guest was inside a
    /// `fd_write`, where the `Caller` needed to charge it is not in scope.
    pending_charge: u64,
    /// Calls parsed out of a completed stdout line and **not yet dispatched**.
    ///
    /// Queued rather than serviced where they are parsed, so the shim can take
    /// each call's fixed fuel charge *before* it reaches a backend. Charging
    /// afterwards let a budget that could pay for the `fd_write` copy but not
    /// for the call itself perform a KV write, a job enqueue or an outbound
    /// POST and *then* end the request as `FuelExhausted` — an effect that
    /// happened, on a request whose caller was told it did not, which a retry
    /// then does again.
    ///
    /// Bounded by the chunk that produced it: one `fd_write` copies at most
    /// `HOST_IO_CHUNK_BYTES`, and every queued call was parsed out of those
    /// bytes.
    pending_calls: VecDeque<super::capability::CapabilityCall>,
    /// Bytes of capability replies **currently resident** in `stdin`.
    ///
    /// Counted apart from `stdin.len()`, which also holds the unread tail of
    /// the *request* frame. A manifest may declare a 64 MiB body ceiling, so a
    /// guest that makes its first call before reading its request would sit
    /// over any reply ceiling measured against the whole queue — every
    /// capability call refused, for a reason that has nothing to do with
    /// replies. The request frame is budgeted separately, at
    /// `4 × max_request_body_bytes` in `request_footprint_bytes`; this counts
    /// only what the capability channel added, and only while it is still
    /// there: `take_stdin` gives it back as the guest reads.
    queued_replies: usize,
    /// Whether a call that commits has reached its backend.
    committed: bool,
    /// Everything the guest reached for and did not get.
    denials: Vec<CapabilityDenial>,
    /// Request-seeded PRNG state, so `random_get` is deterministic without
    /// being a published constant.
    random_state: u64,
    limiter: MemoryLimiter,
    limits: ResourceLimits,
}

impl HostState {
    /// The starting point the request is mixed into. Arbitrary but fixed.
    const RANDOM_SEED: u64 = 0x2545_F491_4F6C_DD1D;

    /// Derive this request's PRNG seed from the request itself.
    ///
    /// A single fixed seed would make `random_get` a *constant* across every
    /// request to every deployment of an artifact — anyone holding the same
    /// bytes could predict every value a guest ever derived from it. Mixing the
    /// request in keeps the property that actually matters (the same request
    /// twice produces the same bytes, so an author can reproduce a bug from the
    /// request alone) without publishing the stream.
    ///
    /// This is **not** cryptographic entropy, and the sandbox offers none: a
    /// guest holds no capability that would make a secret useful to it.
    fn seed_from(frame: &[u8]) -> u64 {
        let mut seed = Self::RANDOM_SEED;
        for byte in frame {
            seed = seed.rotate_left(7) ^ u64::from(*byte);
            seed = seed.wrapping_mul(0x0000_0100_0000_01B3);
        }
        seed
    }

    fn new(
        plugin: String,
        limits: ResourceLimits,
        frame: &[u8],
        exchange: Exchange,
        runtime: crate::plugin_sandbox::capability::CapabilityRuntime,
    ) -> Self {
        Self {
            plugin,
            stdin: VecDeque::new(),
            stdout_line: Vec::new(),
            stderr: Vec::new(),
            answer: None,
            exchange,
            runtime,
            pending_charge: 0,
            pending_calls: VecDeque::new(),
            queued_replies: 0,
            committed: false,
            denials: Vec::new(),
            random_state: Self::seed_from(frame),
            limiter: MemoryLimiter {
                max: limits.memory_bytes,
                peak: 0,
                memory_refusals: 0,
                table_refusals: 0,
                table_elements: 0,
            },
            limits,
        }
    }

    /// Record one refusal, deduplicated by `(capability, operation)`.
    ///
    /// Deduplication is what keeps a guest that calls `path_open` in a loop
    /// from turning the ledger into its own memory-exhaustion channel, while
    /// still recording the fact that it tried.
    fn deny(&mut self, capability: DeniedCapability, operation: &str, detail: &str) {
        let already = self
            .denials
            .iter()
            .any(|denial| denial.capability == capability && denial.operation == operation);
        if already || self.denials.len() >= MAX_DENIALS {
            return;
        }
        let denial = CapabilityDenial {
            capability,
            operation: operation.to_owned(),
            detail: detail.to_owned(),
        };
        tracing::warn!(
            plugin = self.plugin,
            capability = capability.as_str(),
            operation,
            detail,
            "sandboxed plugin was denied a capability it reached for"
        );
        self.denials.push(denial);
    }

    /// Handle one complete line the guest wrote to stdout.
    ///
    /// Most frames end the exchange. A `call` frame does not: it is serviced
    /// and answered in the guest's stdin, and the guest carries on. That is the
    /// whole of the capability channel — see
    /// [`GuestFrame::Call`](super::wire::GuestFrame::Call).
    fn on_guest_line(&mut self, line: &str) {
        if self.answer.is_some() {
            // Already answered. Anything after is a guest that does not respect
            // the protocol; ignoring it is what stops a second frame from
            // overwriting a good first one.
            return;
        }
        self.answer = Some(match from_guest_line(line) {
            Ok(GuestFrame::Call(call)) => {
                // Queued, not serviced: the fixed charge is the shim's to take
                // first. See `pending_calls`.
                self.pending_calls.push_back(call);
                return;
            }
            Ok(GuestFrame::Response(response)) => match self.exchange {
                Exchange::Request => Ok(GuestAnswer::Response(response)),
                Exchange::Render => Err(SandboxFailure::MalformedFrame(
                    "a render slot is answered with a `fragment` frame, not a `response`"
                        .to_owned(),
                )),
            },
            Ok(GuestFrame::Fragment { nodes }) => match self.exchange {
                Exchange::Render => Ok(GuestAnswer::Fragment(nodes)),
                Exchange::Request => Err(SandboxFailure::MalformedFrame(
                    "a request is answered with a `response` frame, not a `fragment`".to_owned(),
                )),
            },
            Ok(GuestFrame::Error { detail }) => {
                Err(SandboxFailure::GuestError(guest_text(&detail)))
            }
            Err(err) => Err(SandboxFailure::MalformedFrame(guest_text(&err.to_string()))),
        });
    }

    /// Answer one capability call by appending its result to the guest's stdin.
    ///
    /// Never fails the request over the *content* of a call: everything a guest
    /// can get wrong comes back as a denial it can read. The two exits that do
    /// end the request are the host's own encoder failing, and a guest that has
    /// stopped reading its replies — see [`MAX_QUEUED_REPLY_BYTES`].
    fn service(&mut self, call: &super::capability::CapabilityCall, fuel_left: u64) {
        // The room the reply must fit, decided *before* the call runs. A reply
        // cannot be measured until its call has committed, and a request that
        // fails over a committed write is retried by the caller. So a call is
        // dispatched only when the worst-case reply fits the unread-reply queue
        // and the fuel left covers pricing it plus a fixed finishing allowance
        // for the guest. A call that commits also keeps the fuel to read that
        // reply (#2523). A call that does not fit is answered with a denial the
        // guest can read, and nothing runs.
        let queue_room = MAX_QUEUED_REPLY_BYTES.saturating_sub(self.queued_replies);
        // A quarter of the budget at most, so a small budget still serves calls.
        let allowance = FINISH_ALLOWANCE_FUEL.min(self.limits.fuel / 4);
        // After a write has run, any call can still fail the request, so every
        // call keeps the read fuel. The guest must read its unread replies too.
        let keep_read = self.committed || call.commits();
        let unread = u64::try_from(self.queued_replies).unwrap_or(u64::MAX);
        let fuel_covers = |reserve: usize| {
            let reserve = u64::try_from(reserve).unwrap_or(u64::MAX);
            let read = if keep_read {
                reserve
                    .saturating_add(unread)
                    .saturating_mul(GUEST_READ_FUEL_PER_BYTE)
            } else {
                0
            };
            fuel_left
                >= allowance
                    .saturating_add(read)
                    .saturating_add(reserve.div_ceil(BYTES_PER_FUEL))
        };
        let result = self.runtime.dispatch_checked(call, queue_room, fuel_covers);
        if call.commits() && reached_backend(&result) {
            self.committed = true;
        }
        let line = match to_line(&HostFrame::CallResult(result)) {
            Ok(line) => line,
            Err(err) => {
                // The host could not encode its own answer. Reported as a
                // plugin-prefix failure rather than propagating, exactly as
                // `run` treats the same failure on the request frame.
                self.answer = Some(Err(SandboxFailure::Instantiation(guest_text(
                    &err.to_string(),
                ))));
                return;
            }
        };
        if self.queued_replies.saturating_add(line.len()) > MAX_QUEUED_REPLY_BYTES {
            self.answer = Some(Err(SandboxFailure::MalformedFrame(format!(
                "the guest has left over {MAX_QUEUED_REPLY_BYTES} bytes of capability replies \
                 unread; it must read each answer before making the next call"
            ))));
            return;
        }
        // Only the per-byte part. The fixed part — which prices the dispatch: a
        // lock, a lookup, a frame built — is taken by the shim *before* this
        // runs, so a budget that cannot cover it never reaches a backend. What
        // is left is the reply the host has just materialised, priced at the
        // same rate every other host-side copy pays; it cannot be charged
        // earlier because it cannot be measured before the call is answered.
        self.pending_charge = self
            .pending_charge
            .saturating_add(u64::try_from(line.len()).unwrap_or(u64::MAX) / BYTES_PER_FUEL);
        self.queued_replies = self.queued_replies.saturating_add(line.len());
        self.stdin.extend(line.as_bytes());
    }

    /// Dispatch the next queued call, if any.
    ///
    /// Returns `false` when the queue is empty. The caller charges
    /// [`CAPABILITY_CALL_FUEL`] before each `true` step, which is the whole
    /// point of the queue: see [`pending_calls`](Self::pending_calls).
    fn service_next(&mut self, fuel_left: u64) -> bool {
        let Some(call) = self.pending_calls.pop_front() else {
            return false;
        };
        self.service(&call, fuel_left);
        true
    }

    /// Whether a parsed call is waiting for its fixed charge.
    fn has_pending_call(&self) -> bool {
        !self.pending_calls.is_empty()
    }

    /// Take the fuel owed for capability work, leaving nothing owed.
    const fn take_pending_charge(&mut self) -> u64 {
        std::mem::replace(&mut self.pending_charge, 0)
    }

    /// Buffer stdout bytes, consuming each completed NDJSON line.
    ///
    /// Returns `false` — the guest's write must fail — once the pending line
    /// outgrows what a legal response could possibly be.
    #[must_use]
    fn write_stdout(&mut self, bytes: &[u8]) -> bool {
        // Base64 inflates a body by 4/3, and the frame carries headers and JSON
        // punctuation around it, so the pending-line budget is the declared
        // response ceiling doubled plus slack. A frame that cannot fit under
        // this could never pass `check_size` anyway.
        let budget = self
            .limits
            .max_response_bytes
            .saturating_mul(2)
            .saturating_add(4096);
        for byte in bytes {
            if *byte == b'\n' {
                let line = std::mem::take(&mut self.stdout_line);
                // Strictly, not lossily. `from_utf8_lossy` turns each invalid
                // byte into a three-byte replacement character while the
                // original is still alive, so a guest that filled its whole
                // stdout budget with invalid bytes would make the host hold
                // four times that budget — memory no manifest accounted for.
                // A frame is JSON, so it is UTF-8 or it is not a frame.
                match String::from_utf8(line) {
                    Ok(line) => self.on_guest_line(&line),
                    Err(_) => {
                        self.answer = Some(Err(SandboxFailure::MalformedFrame(
                            "the frame is not valid UTF-8".to_owned(),
                        )));
                    }
                }
            } else {
                if self.stdout_line.len() >= budget {
                    return false;
                }
                // Grow geometrically, but never past the budget. Left to
                // itself `Vec::push` doubles, taking a buffer whose length
                // stops at `budget` to a capacity of the next power of two
                // above it — for the default ceiling, 16 MiB of allocation
                // behind an 8 MiB bound. `request_footprint_bytes` reserves
                // `2 × max_response_bytes` for this line and validates the
                // concurrency product against that reservation, so the slack
                // `Vec` takes for its own amortisation is host memory nothing
                // accounted for, at every concurrent request at once. Clamping
                // the reservation keeps the doubling, and the amortised push
                // with it, right up to the point where the next one would
                // overrun the bound. The 64-byte floor is below the smallest
                // budget this can compute (`saturating_add(4096)`), so it
                // covers only the first few pushes.
                if self.stdout_line.len() == self.stdout_line.capacity() {
                    let want = self
                        .stdout_line
                        .capacity()
                        .saturating_mul(2)
                        .clamp(64, budget);
                    self.stdout_line
                        .reserve_exact(want.saturating_sub(self.stdout_line.len()));
                }
                self.stdout_line.push(*byte);
            }
        }
        true
    }

    /// Buffer stderr bytes, silently dropping everything past the budget — a
    /// guest dying loudly should not be punished for being chatty.
    fn write_stderr(&mut self, bytes: &[u8]) {
        let room = STDERR_BUDGET_BYTES.saturating_sub(self.stderr.len());
        if let Some(kept) = bytes.get(..bytes.len().min(room)) {
            self.stderr.extend_from_slice(kept);
        }
    }

    /// Whether every further stderr byte would be discarded.
    const fn stderr_is_full(&self) -> bool {
        self.stderr.len() >= STDERR_BUDGET_BYTES
    }

    fn stderr_excerpt(&self) -> String {
        // Bounded and neutralised: truncation stops a flood, but a forged record fits
        // comfortably inside 512 characters.
        //
        // Decoded a chunk at a time rather than through `String::from_utf8_lossy`, for
        // the same reason the stdout frame is decoded strictly one function up. Lossy
        // decoding writes a three-byte replacement character per invalid subpart, so a
        // guest that fills its 64 KiB stderr budget with invalid bytes materialises
        // 192 KiB beside the still-live buffer, all to keep 512 characters of it. The
        // manifest footprint budgets the buffer, not that expansion, so it was 128 KiB
        // per concurrent request outside the ceiling. Streaming keeps the peak at the
        // excerpt itself.
        let mut chars = lossy_chars(&self.stderr).skip_while(|ch| ch.is_whitespace());
        let mut kept: String = chars.by_ref().take(STDERR_EXCERPT).collect();
        let cut = chars.next().is_some();
        if !cut {
            // The window reached the end of the buffer, so trailing whitespace
            // in it is the buffer's own and `trim` would have taken it. When
            // more bytes follow, it is interior whitespace and `trim` would
            // not have — truncating after the trim is what the two cases
            // distinguish.
            while kept.ends_with(char::is_whitespace) {
                kept.pop();
            }
        }
        // `guest_text` marks its own truncation, but only on meeting a 513th
        // character — and this hands it 512 at most, so the marker could never
        // fire here and a cut excerpt read as though the guest had stopped
        // there. The suffix is usually the interesting part of a failure, so
        // saying it was cut matters more than the characters the marker costs.
        // Appended after escaping: inside `kept` it would be escaped as guest
        // text, and would count against the bound it is reporting.
        let mut excerpt = guest_text(&kept);
        if cut {
            excerpt.push_str(TRUNCATION_MARKER);
        }
        excerpt
    }

    /// `SplitMix64`: tiny, deterministic, and good enough for a shim whose
    /// entire job is to be reproducible.
    const fn next_random_byte(&mut self) -> u8 {
        self.random_state = self.random_state.wrapping_add(0x9E37_79B9_7F4A_7C15);
        let mut z = self.random_state;
        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
        #[allow(
            clippy::cast_possible_truncation,
            reason = "taking the low byte of the mixed state is the point"
        )]
        {
            (z ^ (z >> 31)) as u8
        }
    }

    /// Pop up to `len` bytes of the pending request frame.
    /// Hand the guest up to `len` bytes of its request frame.
    ///
    /// Bounded per call at `HOST_IO_CHUNK_BYTES`, the same scratch ceiling
    /// `fd_write` and `random_get` hold themselves to and the one
    /// [`FIXED_HOST_BUFFER_BYTES`] budgets. The length is the guest's to choose
    /// — it is an iovec — and the copy comes out of a queue that keeps its
    /// whole allocation as it drains, so one iovec spanning the frame put a
    /// second copy of it beside the first. A frame is the request's metadata
    /// and a base64 body with JSON escaping over both, which makes that copy
    /// several times the raw request and none of it was in the footprint
    /// `max_concurrency` is validated against.
    ///
    /// Returning less than was asked for is what this call already promises:
    /// the caller breaks on a short chunk and reports the count, and the queue
    /// running dry short-reads today, so a guest that does not loop is already
    /// broken.
    fn take_stdin(&mut self, len: usize) -> Vec<u8> {
        let len = len.min(HOST_IO_CHUNK_BYTES);
        // The queue is the request frame followed by whatever capability
        // replies have been appended, drained front to back — so bytes come out
        // of the request frame until it is exhausted and only then out of the
        // replies. Computing the boundary before the drain is what lets the
        // reply budget be given back exactly as it is consumed.
        let head = self.stdin.len().saturating_sub(self.queued_replies);
        let mut out = Vec::with_capacity(len.min(self.stdin.len()));
        while out.len() < len {
            match self.stdin.pop_front() {
                Some(byte) => out.push(byte),
                None => break,
            }
        }
        let from_replies = out.len().saturating_sub(head);
        self.queued_replies = self.queued_replies.saturating_sub(from_replies);
        out
    }
}

// ── The WASI shim ────────────────────────────────────────────────────────

type Shim = Linker<HostState>;

fn memory_of(caller: &Caller<'_, HostState>) -> Option<wasmi::Memory> {
    caller
        .get_export("memory")
        .and_then(wasmi::Extern::into_memory)
}

fn read_u32(caller: &Caller<'_, HostState>, memory: wasmi::Memory, at: usize) -> Option<u32> {
    let mut buffer = [0u8; 4];
    memory.read(caller, at, &mut buffer).ok()?;
    Some(u32::from_le_bytes(buffer))
}

fn write_u32(
    caller: &mut Caller<'_, HostState>,
    memory: wasmi::Memory,
    at: usize,
    value: u32,
) -> Option<()> {
    memory.write(caller, at, &value.to_le_bytes()).ok()
}

/// Read one `iovec` at `index` of the array starting at `base`.
fn iovec(
    caller: &Caller<'_, HostState>,
    memory: wasmi::Memory,
    base: i32,
    index: i32,
) -> Option<(usize, usize)> {
    let base = usize::try_from(base).ok()?;
    let offset = usize::try_from(index).ok()?.checked_mul(IOVEC_SIZE)?;
    let at = base.checked_add(offset)?;
    let pointer = read_u32(caller, memory, at)?;
    let length = read_u32(caller, memory, at.checked_add(4)?)?;
    Some((
        usize::try_from(pointer).ok()?,
        usize::try_from(length).ok()?,
    ))
}

/// The WASI functions the shim implements itself, rather than refusing.
///
/// Name, parameter signature, and result signature — `i` for `i32`, `l` for
/// `i64`, empty for none. The signatures are here so a module can be
/// **type**-checked at load and not merely name-checked: an import whose type
/// disagrees with the shim links nowhere, and finding that out per request (as
/// a 502 the operator cannot explain) instead of at `autumn plugin package` is
/// exactly the failure this lane exists to move earlier.
const SERVED_IMPORTS: &[(&str, &str, &str)] = &[
    ("args_get", "ii", "i"),
    ("args_sizes_get", "ii", "i"),
    ("clock_res_get", "ii", "i"),
    ("clock_time_get", "ili", "i"),
    ("environ_get", "ii", "i"),
    ("environ_sizes_get", "ii", "i"),
    ("fd_close", "i", "i"),
    ("fd_fdstat_get", "ii", "i"),
    ("fd_read", "iiii", "i"),
    ("fd_seek", "ilii", "i"),
    ("fd_tell", "ii", "i"),
    ("fd_write", "iiii", "i"),
    ("proc_exit", "i", ""),
    ("random_get", "ii", "i"),
    ("sched_yield", "", "i"),
];

/// The WASI functions the shim answers with a refusal: name, the capability
/// class it belongs to, the detail an operator reads, and its signature.
///
/// The signature is `i` for `i32` and `l` for `i64`, in WASI order, and every
/// one of these returns an `errno`. `wasmi` matches host functions by
/// signature, so a wrong descriptor here would make an honest guest fail to
/// instantiate rather than fail to escape — which is why
/// `every_refusal_stub_matches_the_wasi_signature_it_stands_in_for` builds a
/// module importing all of them and proves they link.
const DENIED_IMPORTS: &[(&str, DeniedCapability, &str, &str)] = &[
    // There is no filesystem.
    ("fd_advise", DeniedCapability::Filesystem, FS_DETAIL, "illi"),
    (
        "fd_allocate",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "ill",
    ),
    ("fd_datasync", DeniedCapability::Filesystem, FS_DETAIL, "i"),
    (
        "fd_fdstat_set_flags",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "ii",
    ),
    (
        "fd_fdstat_set_rights",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "ill",
    ),
    (
        "fd_filestat_get",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "ii",
    ),
    (
        "fd_filestat_set_size",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "il",
    ),
    (
        "fd_filestat_set_times",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "illi",
    ),
    ("fd_pread", DeniedCapability::Filesystem, FS_DETAIL, "iiili"),
    (
        "fd_prestat_dir_name",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "iii",
    ),
    (
        "fd_prestat_get",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "ii",
    ),
    (
        "fd_pwrite",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "iiili",
    ),
    (
        "fd_readdir",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "iiili",
    ),
    ("fd_renumber", DeniedCapability::Filesystem, FS_DETAIL, "ii"),
    ("fd_sync", DeniedCapability::Filesystem, FS_DETAIL, "i"),
    (
        "path_create_directory",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "iii",
    ),
    (
        "path_filestat_get",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "iiiii",
    ),
    (
        "path_filestat_set_times",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "iiiilli",
    ),
    (
        "path_link",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "iiiiiii",
    ),
    (
        "path_open",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "iiiiillii",
    ),
    (
        "path_readlink",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "iiiiii",
    ),
    (
        "path_remove_directory",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "iii",
    ),
    (
        "path_rename",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "iiiiii",
    ),
    (
        "path_symlink",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "iiiii",
    ),
    (
        "path_unlink_file",
        DeniedCapability::Filesystem,
        FS_DETAIL,
        "iii",
    ),
    // There is no network.
    ("sock_accept", DeniedCapability::Network, NET_DETAIL, "iii"),
    ("sock_recv", DeniedCapability::Network, NET_DETAIL, "iiiiii"),
    ("sock_send", DeniedCapability::Network, NET_DETAIL, "iiiii"),
    ("sock_shutdown", DeniedCapability::Network, NET_DETAIL, "ii"),
    // The host process is not the guest's to steer.
    (
        "poll_oneoff",
        DeniedCapability::ProcessControl,
        "a sandboxed plugin may not block the host on external events",
        "iiii",
    ),
    (
        "proc_raise",
        DeniedCapability::ProcessControl,
        "a sandboxed plugin may not signal the host process",
        "i",
    ),
];

const FS_DETAIL: &str = "a sandboxed plugin has no filesystem";
const NET_DETAIL: &str = "a sandboxed plugin has no outbound network";

/// The signature the shim defines for a WASI function of this name, if any.
///
/// The load-time gate and the shim read the same two tables, so an import that
/// links at runtime is exactly one the gate admits — they cannot drift apart.
fn shim_signature(name: &str) -> Option<(&'static str, &'static str)> {
    if let Some((_, params, results)) = SERVED_IMPORTS.iter().find(|(known, ..)| *known == name) {
        return Some((params, results));
    }
    DENIED_IMPORTS
        .iter()
        .find(|(known, ..)| *known == name)
        .map(|(_, _, _, params)| (*params, "i"))
}

/// Whether the shim defines a WASI function of this name.
///
/// Test-only: the load gate needs the *signature*, not just the name, so it
/// calls [`shim_signature`] directly. This stays as the shape the
/// `the_load_gate_admits_exactly_what_the_shim_defines` invariant is written
/// against.
#[cfg(test)]
fn is_shim_function(name: &str) -> bool {
    shim_signature(name).is_some()
}

/// Build a [`wasmi::FuncType`] from a signature descriptor pair.
fn signature_type(params: &str, results: &str) -> Option<wasmi::FuncType> {
    fn types(descriptor: &str) -> Option<Vec<wasmi::core::ValType>> {
        descriptor
            .chars()
            .map(|ch| match ch {
                'i' => Some(wasmi::core::ValType::I32),
                'l' => Some(wasmi::core::ValType::I64),
                _ => None,
            })
            .collect()
    }
    Some(wasmi::FuncType::new(types(params)?, types(results)?))
}

/// What one instantiation costs in fuel: the bytes copied, plus a unit per
/// segment for the bounds check and copy set-up each one needs regardless of
/// its length, plus a unit per import.
///
/// Imports are counted for the same reason segments are: resolving one is
/// per-instance work the guest does not execute but every request pays for, so
/// leaving it unpriced is a way to buy host CPU with no fuel. `MAX_IMPORTS`
/// bounds the count; this makes the admitted ones cost something.
fn instantiation_fuel(
    segments: usize,
    init_bytes: usize,
    imports: usize,
    globals: usize,
    initial_memory_bytes: u64,
    table_elements: u64,
) -> u64 {
    let bytes = u64::try_from(init_bytes).unwrap_or(u64::MAX);
    let segments = u64::try_from(segments).unwrap_or(u64::MAX);
    let imports = u64::try_from(imports).unwrap_or(u64::MAX);
    let globals = u64::try_from(globals).unwrap_or(u64::MAX);
    // The instance's linear memory, at the same rate as every other host-side byte. A
    // module can declare its initial size and no data segments at all, so the
    // init-section terms above price none of it — yet the host allocates and zero-fills
    // the whole thing on every request, before the guest runs an instruction. Near the
    // manifest's ceiling that is hundreds of megabytes of memset a client can ask for
    // repeatedly, for one fuel unit: the same "buy host CPU with no fuel" the copying
    // charge exists to stop. The limiter bounds how much memory; only this bounds how
    // often it can be paid for.
    let memory = initial_memory_bytes
        .checked_div(BYTES_PER_FUEL)
        .unwrap_or(u64::MAX);
    // The table's initial entries, for exactly the reason the memory term
    // above exists — and the sibling that term did not cover. A module can
    // declare a table's minimum with no element segments at all, so `segments`
    // and `init_bytes` price none of it, and wasmi still allocates and
    // initialises every slot on every instantiation before the guest runs.
    // Charged per entry rather than per byte, like `segments`, `imports` and
    // `globals` beside it: what the host pays here is a slot initialised, not a
    // block copied.
    bytes
        .checked_div(BYTES_PER_FUEL)
        .unwrap_or(u64::MAX)
        .saturating_add(memory)
        .saturating_add(table_elements)
        .saturating_add(segments)
        .saturating_add(imports)
        .saturating_add(globals)
        .saturating_add(1)
}

/// Whether `result` comes from a call that reached its backend.
///
/// A denial that comes before dispatch did not. A backend error may have: an
/// outbound request can fail after the upstream got it.
const fn reached_backend(result: &super::capability::CallResult) -> bool {
    !matches!(
        result.denial(),
        Some(
            super::capability::DenialReason::CapabilityNotGranted
                | super::capability::DenialReason::NotInGrant
                | super::capability::DenialReason::QuotaExceeded
                | super::capability::DenialReason::Malformed
                | super::capability::DenialReason::Unavailable
        )
    )
}

/// Charge the guest's fuel budget for `bytes` of host-side work.
///
/// Returns the `OutOfFuel` trap when the budget cannot cover it, so a guest
/// that tries to buy unbounded copying ends exactly as a guest that spins does:
/// [`SandboxFailure::FuelExhausted`], and a 504 on its own prefix.
/// Charge fuel for host work priced per byte *copied*.
///
/// [`BYTES_PER_FUEL`] is a bulk-copy rate: a memcpy moves many bytes for what
/// one instruction costs, so 64 of them to a unit is honest. It is the wrong
/// rate for work that computes each byte — see [`charge_units`].
fn charge_bytes(caller: &mut Caller<'_, HostState>, bytes: usize) -> Result<(), wasmi::Error> {
    let units = u64::try_from(bytes)
        .unwrap_or(u64::MAX)
        .checked_div(BYTES_PER_FUEL)
        .unwrap_or(u64::MAX)
        .saturating_add(1);
    charge_units(caller, units)
}

/// Charge fuel directly, for host work a byte count does not describe.
fn charge_units(caller: &mut Caller<'_, HostState>, units: u64) -> Result<(), wasmi::Error> {
    let left = caller.get_fuel()?;
    let remaining = left
        .checked_sub(units)
        .ok_or_else(|| wasmi::Error::from(wasmi::core::TrapCode::OutOfFuel))?;
    caller.set_fuel(remaining)
}

/// Charge `units`, taking the budget to zero rather than trapping when it does
/// not cover them.
///
/// For the one charge that necessarily *follows* a committed side effect: a
/// reply can only be measured once the call has been answered, and by then a KV
/// write, a job enqueue or an outbound POST has happened. Trapping there ends
/// the request over work already done — and a retry does that work again, which
/// for a POST is the difference between one order and two.
///
/// Taking the budget to zero instead is bounded and terminal in the same
/// breath: the overshoot is one reply's worth, the next dispatch cannot start
/// because [`CAPABILITY_CALL_FUEL`] is charged before it with [`charge_units`],
/// which does trap, and the guest's own instructions run out on the next one.
/// The request still ends here — it ends after the effect is accounted for
/// rather than after it is disowned.
fn charge_units_saturating(
    caller: &mut Caller<'_, HostState>,
    units: u64,
) -> Result<(), wasmi::Error> {
    let left = caller.get_fuel()?;
    caller.set_fuel(left.saturating_sub(units))
}

/// Register the guest-visible WASI surface.
///
/// One registration per import, all in one place, because this list **is** the
/// sandbox. Read it top to bottom and you have read every capability a
/// sandboxed plugin holds.
#[allow(
    clippy::too_many_lines,
    reason = "splitting this up would hide the fact that this list IS the sandbox"
)]
fn define_wasi_shim(linker: &mut Shim) -> Result<(), SandboxLoadError> {
    fn engine_error(err: impl fmt::Display) -> SandboxLoadError {
        SandboxLoadError::Engine(err.to_string())
    }

    // ── the dialogue ─────────────────────────────────────────────────

    linker
        .func_wrap(
            WASI,
            "fd_read",
            |mut caller: Caller<'_, HostState>, fd: i32, iovs: i32, iovs_len: i32, nread: i32| {
                if fd != 0 {
                    // The guest was given one descriptor. Anything else is a
                    // reach for a file it was never handed.
                    caller.data_mut().deny(
                        DeniedCapability::Filesystem,
                        "fd_read",
                        "a sandboxed plugin has no descriptors beyond the request dialogue",
                    );
                    return Ok(errno::BADF);
                }
                let Some(memory) = memory_of(&caller) else {
                    return Ok(errno::INVAL);
                };
                if iovs_len > MAX_IOVECS {
                    return Ok(errno::INVAL);
                }

                let mut total: u32 = 0;
                for index in 0..iovs_len {
                    let Some((pointer, length)) = iovec(&caller, memory, iovs, index) else {
                        return Ok(errno::INVAL);
                    };
                    // Bounds-check BEFORE consuming: `take_stdin` pops the bytes,
                    // and a write that then fails would have destroyed part of
                    // the request frame with no way for the guest to recover it.
                    let in_bounds = pointer
                        .checked_add(length)
                        .is_some_and(|end| end <= memory.data_size(&caller));
                    if !in_bounds {
                        return Ok(errno::INVAL);
                    }
                    // Charged for what is actually copied, not for what was
                    // asked: `take_stdin` bounds the copy at
                    // `HOST_IO_CHUNK_BYTES` and by what is left, so pricing the
                    // whole iovec would bill the guest for bytes it did not get.
                    // The queue's remaining length belongs in the minimum for the
                    // same reason the chunk ceiling does — a guest reading the
                    // tail of its frame through a large buffer would otherwise pay
                    // a full chunk for a few bytes, and a tight but sufficient
                    // budget could fail on it.
                    let take = HOST_IO_CHUNK_BYTES
                        .min(length)
                        .min(caller.data().stdin.len());
                    charge_bytes(&mut caller, take)?;
                    let chunk = caller.data_mut().take_stdin(take);
                    if memory.write(&mut caller, pointer, &chunk).is_err() {
                        return Ok(errno::INVAL);
                    }
                    let Ok(read) = u32::try_from(chunk.len()) else {
                        return Ok(errno::INVAL);
                    };
                    let Some(sum) = total.checked_add(read) else {
                        return Ok(errno::INVAL);
                    };
                    total = sum;
                    if chunk.len() < length {
                        break;
                    }
                }

                let Ok(at) = usize::try_from(nread) else {
                    return Ok(errno::INVAL);
                };
                if write_u32(&mut caller, memory, at, total).is_none() {
                    return Ok(errno::INVAL);
                }
                Ok(errno::SUCCESS)
            },
        )
        .map_err(engine_error)?;

    linker
        .func_wrap(
            WASI,
            "fd_write",
            |mut caller: Caller<'_, HostState>,
             fd: i32,
             iovs: i32,
             iovs_len: i32,
             nwritten: i32|
             -> Result<i32, wasmi::Error> {
                if fd != 1 && fd != 2 {
                    caller.data_mut().deny(
                        DeniedCapability::Filesystem,
                        "fd_write",
                        "a sandboxed plugin may only write its response frame and diagnostics",
                    );
                    return Ok(errno::BADF);
                }
                let Some(memory) = memory_of(&caller) else {
                    return Ok(errno::INVAL);
                };
                if iovs_len > MAX_IOVECS {
                    return Ok(errno::INVAL);
                }

                let mut total: u32 = 0;
                for index in 0..iovs_len {
                    // Per descriptor inspected, not per byte copied. Reading an
                    // iovec out of guest memory and bounds-checking it is host
                    // work whatever the length says, and the only other charge in
                    // this function lives inside `while offset < length`, which a
                    // zero-length iovec skips and which breaks once stderr is past
                    // its budget. Sixty-four free descriptor walks per imported
                    // call, against a budget that limits only how many calls, is
                    // host CPU on a blocking worker no ceiling sees.
                    //
                    // `charge_units` rather than `charge_bytes`, for the reason
                    // `random_get` uses it: this is per-item work, not a bulk move.
                    // `fd_read` needs no such line — its `charge_bytes` sits
                    // unconditionally in the loop body and floors at one unit, so a
                    // drained queue already costs a descriptor's worth of fuel.
                    charge_units(&mut caller, 1)?;
                    let Some((pointer, length)) = iovec(&caller, memory, iovs, index) else {
                        return Ok(errno::INVAL);
                    };
                    // Bounds-check BEFORE any copy: `length` is guest-chosen,
                    // and a `u32::MAX` iovec must fail rather than start a copy
                    // the host then has to abandon.
                    let in_bounds = pointer
                        .checked_add(length)
                        .is_some_and(|end| end <= memory.data_size(&caller));
                    if !in_bounds {
                        return Ok(errno::INVAL);
                    }
                    let Ok(written) = u32::try_from(length) else {
                        return Ok(errno::INVAL);
                    };
                    let Some(sum) = total.checked_add(written) else {
                        return Ok(errno::INVAL);
                    };
                    total = sum;

                    // Copy through a bounded scratch buffer: an in-bounds iovec
                    // can span the guest's whole memory, and the host must never
                    // mirror it in one allocation.
                    let mut offset = 0usize;
                    while offset < length {
                        // Stderr past its budget is discarded, so copying it is
                        // pure host work with no output. Stop rather than
                        // faithfully copying bytes into the bin.
                        if fd == 2 && caller.data().stderr_is_full() {
                            break;
                        }
                        let take = HOST_IO_CHUNK_BYTES.min(length.saturating_sub(offset));
                        charge_bytes(&mut caller, take)?;
                        if fd == 1 {
                            // The line parser inspects each stdout byte, so
                            // add the per-byte rate to the copy rate. The host
                            // may charge for bytes it never parses. This is safe.
                            charge_units(&mut caller, u64::try_from(take).unwrap_or(u64::MAX))?;
                        }
                        let mut scratch = vec![0u8; take];
                        let at = pointer.saturating_add(offset);
                        if memory.read(&caller, at, &mut scratch).is_err() {
                            return Ok(errno::INVAL);
                        }
                        if fd == 1 {
                            let accepted = caller.data_mut().write_stdout(&scratch);
                            // Fixed charge, dispatch, byte charge — in that
                            // order, once per call the chunk completed. The
                            // fixed charge is taken *before* the call reaches a
                            // backend, so a budget too small to pay for it
                            // cannot leave a KV write, a job enqueue or an
                            // outbound POST behind on a request that then ends
                            // as `FuelExhausted`. A trap here leaves the rest of
                            // the queue undispatched, which is the same
                            // property one level up.
                            //
                            // The loop stops on a terminal answer as well as on
                            // an empty queue. One chunk may carry several call
                            // frames, and servicing an early one can end the
                            // request — a reply the guest never read pushing the
                            // queue over `MAX_QUEUED_REPLY_BYTES`, or the host
                            // failing to encode its own answer. Draining the
                            // rest afterwards would perform a job enqueue, a DB
                            // write or an outbound POST on a request that is
                            // already going to fail, which is the property the
                            // charge-before-dispatch order exists to establish.
                            //
                            // And only when the write was accepted. A chunk can
                            // carry a complete call frame followed by a line that
                            // overruns the stdout budget: `write_stdout` parses
                            // and queues the first, then refuses at the second and
                            // answers `false`. Servicing the queue anyway would
                            // commit that call's side effect on a request the
                            // `!accepted` branch below is about to end as
                            // `OutputBudget` — the guest is told the write failed
                            // and may retry it, so the enqueue or the POST happens
                            // twice. It is the same property the
                            // charge-before-dispatch order establishes for fuel,
                            // reached through the output ceiling instead.
                            if accepted {
                                while caller.data().has_pending_call()
                                    && caller.data().answer.is_none()
                                {
                                    charge_units(&mut caller, CAPABILITY_CALL_FUEL)?;
                                    let fuel_left = caller.get_fuel()?;
                                    let _ = caller.data_mut().service_next(fuel_left);
                                    // Saturating, because this charge follows a
                                    // call that has already run: see
                                    // `charge_units_saturating`. The pre-charge
                                    // above is the trapping one, and it is what
                                    // stops the next call.
                                    let owed = caller.data_mut().take_pending_charge();
                                    charge_units_saturating(&mut caller, owed)?;
                                }
                            }
                            // Charged whether the write was accepted or not, and
                            // drained before the branch below, so no exit from
                            // this arm can leave fuel owed.
                            let owed = caller.data_mut().take_pending_charge();
                            charge_units(&mut caller, owed)?;
                            if !accepted {
                                // The response ceiling is a hard stop, not an
                                // errno the guest can ignore and retry: trap so
                                // the request ends here.
                                return Err(wasmi::Error::host(OutputBudgetExhausted));
                            }
                            if caller.data().answer.is_some() {
                                // The exchange is over. A guest that keeps
                                // running would hold a permit and a blocking
                                // worker for its whole budget and then serve the
                                // answer it already had.
                                return Err(wasmi::Error::host(AnswerComplete));
                            }
                        } else {
                            caller.data_mut().write_stderr(&scratch);
                        }
                        offset = offset.saturating_add(take);
                    }
                }

                let Ok(at) = usize::try_from(nwritten) else {
                    return Ok(errno::INVAL);
                };
                if write_u32(&mut caller, memory, at, total).is_none() {
                    return Ok(errno::INVAL);
                }
                Ok(errno::SUCCESS)
            },
        )
        .map_err(engine_error)?;

    // ── inert, because a guest's runtime expects them to exist ────────

    linker
        .func_wrap(WASI, "fd_close", |_: Caller<'_, HostState>, fd: i32| {
            if (0..=2).contains(&fd) {
                errno::SUCCESS
            } else {
                errno::BADF
            }
        })
        .map_err(engine_error)?;
    linker
        .func_wrap(
            WASI,
            "fd_seek",
            |mut caller: Caller<'_, HostState>, fd: i32, _offset: i64, _whence: i32, _out: i32| {
                // Unknown descriptor: refuse and record, like `fd_read`.
                if !(0..=2).contains(&fd) {
                    caller.data_mut().deny(
                        DeniedCapability::Filesystem,
                        "fd_seek",
                        "a sandboxed plugin has no descriptors beyond the request dialogue",
                    );
                    return errno::BADF;
                }
                // stdio is a pipe. Saying so is more useful than saying no.
                errno::SPIPE
            },
        )
        .map_err(engine_error)?;
    linker
        .func_wrap(
            WASI,
            "fd_tell",
            |_: Caller<'_, HostState>, _fd: i32, _out: i32| errno::SPIPE,
        )
        .map_err(engine_error)?;
    linker
        .func_wrap(
            WASI,
            "fd_fdstat_get",
            |mut caller: Caller<'_, HostState>, fd: i32, out: i32| {
                if !(0..=2).contains(&fd) {
                    caller.data_mut().deny(
                        DeniedCapability::Filesystem,
                        "fd_fdstat_get",
                        "a sandboxed plugin has no descriptors beyond the request dialogue",
                    );
                    return errno::BADF;
                }
                let Some(memory) = memory_of(&caller) else {
                    return errno::INVAL;
                };
                let Ok(at) = usize::try_from(out) else {
                    return errno::INVAL;
                };
                // filetype 2 = character device, no rights, no flags.
                let mut stat = [0u8; FDSTAT_SIZE];
                stat[0] = 2;
                if memory.write(&mut caller, at, &stat).is_err() {
                    return errno::INVAL;
                }
                errno::SUCCESS
            },
        )
        .map_err(engine_error)?;
    linker
        .func_wrap(WASI, "sched_yield", |_: Caller<'_, HostState>| {
            errno::SUCCESS
        })
        .map_err(engine_error)?;

    // ── time and entropy: fixed, not ambient ─────────────────────────

    linker
        .func_wrap(
            WASI,
            "clock_time_get",
            |mut caller: Caller<'_, HostState>, _id: i32, _precision: i64, out: i32| {
                let Some(memory) = memory_of(&caller) else {
                    return errno::INVAL;
                };
                let Ok(at) = usize::try_from(out) else {
                    return errno::INVAL;
                };
                // A fixed instant. The host's wall clock is not a capability a
                // plugin was granted, and a plugin that is a function of its
                // request is one an author can reason about.
                if memory.write(&mut caller, at, &0u64.to_le_bytes()).is_err() {
                    return errno::INVAL;
                }
                errno::SUCCESS
            },
        )
        .map_err(engine_error)?;
    linker
        .func_wrap(
            WASI,
            "clock_res_get",
            |mut caller: Caller<'_, HostState>, _id: i32, out: i32| {
                let Some(memory) = memory_of(&caller) else {
                    return errno::INVAL;
                };
                let Ok(at) = usize::try_from(out) else {
                    return errno::INVAL;
                };
                if memory.write(&mut caller, at, &1u64.to_le_bytes()).is_err() {
                    return errno::INVAL;
                }
                errno::SUCCESS
            },
        )
        .map_err(engine_error)?;
    linker
        .func_wrap(
            WASI,
            "random_get",
            |mut caller: Caller<'_, HostState>, buf: i32, len: i32| -> Result<i32, wasmi::Error> {
                let Some(memory) = memory_of(&caller) else {
                    return Ok(errno::INVAL);
                };
                let (Ok(at), Ok(len)) = (usize::try_from(buf), usize::try_from(len)) else {
                    return Ok(errno::INVAL);
                };
                let in_bounds = at
                    .checked_add(len)
                    .is_some_and(|end| end <= memory.data_size(&caller));
                if !in_bounds {
                    return Ok(errno::INVAL);
                }
                let mut written = 0usize;
                while written < len {
                    let take = HOST_IO_CHUNK_BYTES.min(len.saturating_sub(written));
                    // Priced per byte, not at the bulk-copy rate. Every byte
                    // here is a whole `SplitMix64` step — an add, two
                    // multiplies and four shift-XOR pairs — where `fd_write`'s
                    // byte is a memcpy. Charging 64 of these to one unit let a
                    // guest buy the mixer's work at a copy's price and hold a
                    // blocking worker far longer than its declared ceiling
                    // says it may.
                    charge_units(&mut caller, u64::try_from(take).unwrap_or(u64::MAX))?;
                    let mut scratch = vec![0u8; take];
                    for slot in &mut scratch {
                        *slot = caller.data_mut().next_random_byte();
                    }
                    if memory
                        .write(&mut caller, at.saturating_add(written), &scratch)
                        .is_err()
                    {
                        return Ok(errno::INVAL);
                    }
                    written = written.saturating_add(take);
                }
                Ok(errno::SUCCESS)
            },
        )
        .map_err(engine_error)?;

    // ── the process is not the guest's to steer ──────────────────────

    linker
        .func_wrap(
            WASI,
            "proc_exit",
            |_: Caller<'_, HostState>, code: i32| -> Result<(), wasmi::Error> {
                // Ends the *guest*. The host process is not the guest's to end.
                Err(wasmi::Error::i32_exit(code))
            },
        )
        .map_err(engine_error)?;

    // ── the environment is empty, and asking is recorded ─────────────

    linker
        .func_wrap(
            WASI,
            "environ_sizes_get",
            |mut caller: Caller<'_, HostState>, count: i32, size: i32| {
                caller.data_mut().deny(
                    DeniedCapability::Environment,
                    "environ_sizes_get",
                    "a sandboxed plugin sees an empty environment",
                );
                write_two_zeroes(&mut caller, count, size)
            },
        )
        .map_err(engine_error)?;
    linker
        .func_wrap(
            WASI,
            "environ_get",
            |mut caller: Caller<'_, HostState>, _ptrs: i32, _buf: i32| {
                caller.data_mut().deny(
                    DeniedCapability::Environment,
                    "environ_get",
                    "a sandboxed plugin sees an empty environment",
                );
                // Nothing to write: the environment is empty, so success is the
                // truthful answer and needs no bytes.
                errno::SUCCESS
            },
        )
        .map_err(engine_error)?;
    linker
        .func_wrap(
            WASI,
            "args_sizes_get",
            |mut caller: Caller<'_, HostState>, count: i32, size: i32| {
                caller.data_mut().deny(
                    DeniedCapability::Environment,
                    "args_sizes_get",
                    "a sandboxed plugin sees no process arguments",
                );
                write_two_zeroes(&mut caller, count, size)
            },
        )
        .map_err(engine_error)?;
    linker
        .func_wrap(
            WASI,
            "args_get",
            |mut caller: Caller<'_, HostState>, _ptrs: i32, _buf: i32| {
                caller.data_mut().deny(
                    DeniedCapability::Environment,
                    "args_get",
                    "a sandboxed plugin sees no process arguments",
                );
                errno::SUCCESS
            },
        )
        .map_err(engine_error)?;

    // ── everything else is a refusal ─────────────────────────────────

    for (name, capability, detail, signature) in DENIED_IMPORTS {
        deny(linker, name, *capability, detail, signature)?;
    }

    Ok(())
}

/// Write two zero `u32`s — the "empty list" answer `*_sizes_get` needs.
fn write_two_zeroes(caller: &mut Caller<'_, HostState>, first: i32, second: i32) -> i32 {
    let Some(memory) = memory_of(caller) else {
        return errno::INVAL;
    };
    let (Ok(first), Ok(second)) = (usize::try_from(first), usize::try_from(second)) else {
        return errno::INVAL;
    };
    if write_u32(caller, memory, first, 0).is_none()
        || write_u32(caller, memory, second, 0).is_none()
    {
        return errno::INVAL;
    }
    errno::SUCCESS
}

/// Register one refusal stub.
///
/// `wasmi` matches host functions by signature, so a stub must have exactly the
/// shape of the WASI function it stands in for — hence the descriptor rather
/// than a hand-written closure per function. The bodies are identical by
/// design: there is nothing to implement, only a refusal to record.
fn deny(
    linker: &mut Shim,
    name: &'static str,
    capability: DeniedCapability,
    detail: &'static str,
    signature: &str,
) -> Result<(), SandboxLoadError> {
    let mut params = Vec::with_capacity(signature.len());
    for ch in signature.chars() {
        params.push(match ch {
            'i' => wasmi::core::ValType::I32,
            'l' => wasmi::core::ValType::I64,
            other => {
                return Err(SandboxLoadError::Engine(format!(
                    "unknown signature character `{other}` for {name}"
                )));
            }
        });
    }
    let ty = wasmi::FuncType::new(params, [wasmi::core::ValType::I32]);
    linker
        .func_new(
            WASI,
            name,
            ty,
            move |mut caller: Caller<'_, HostState>, _args: &[wasmi::Val], results| {
                caller.data_mut().deny(capability, name, detail);
                if let Some(slot) = results.first_mut() {
                    *slot = wasmi::Val::I32(errno::NOTCAPABLE);
                }
                Ok(())
            },
        )
        .map_err(|err| SandboxLoadError::Engine(err.to_string()))?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plugin_sandbox::manifest::{ResourceLimits, SandboxCapability, SandboxManifest};
    use crate::plugin_sandbox::test_guests as guests;

    fn manifest_with(limits: ResourceLimits) -> SandboxManifest {
        let mut manifest = SandboxManifest::parse(&format!(
            r#"
name = "autumn-plugin-hello"
version = "0.1.0"
wire_version = 1
prefix = "/hello"
capabilities = ["http-request"]
sha256 = "{digest}"

[[routes]]
method = "GET"
path = "/hello/greet"
"#,
            digest = "a".repeat(64)
        ))
        .expect("valid manifest");
        manifest.limits = limits;
        manifest
    }

    /// A bare `HostState` for the shim unit tests: an ordinary request
    /// exchange, and a capability runtime with no grants and no backends, which
    /// is what a first-slice plugin has.
    fn bare_state(limits: ResourceLimits, frame: &[u8]) -> HostState {
        HostState::new(
            "hello".to_owned(),
            limits,
            frame,
            Exchange::Request,
            crate::plugin_sandbox::capability::CapabilityRuntime::new(
                &manifest_with(limits),
                crate::plugin_sandbox::CapabilityServices::none(),
            ),
        )
    }

    fn try_host(wat: &str) -> Result<SandboxHost, SandboxLoadError> {
        try_host_with(wat, ResourceLimits::default())
    }

    fn try_host_with(wat: &str, limits: ResourceLimits) -> Result<SandboxHost, SandboxLoadError> {
        let wasm = wat::parse_str(wat).expect("the fixture is valid WAT");
        SandboxHost::from_module(manifest_with(limits), &wasm)
    }

    fn host(wat: &str) -> SandboxHost {
        try_host(wat).expect("the fixture loads")
    }

    fn request(method: &str, path: &str) -> SandboxRequest {
        SandboxRequest {
            method: method.to_owned(),
            // The declared pattern and the concrete path agree here: the
            // fixtures dispatch on the frame's *content*, so a route that
            // never varied would make every test look like a match.
            route: path.to_owned(),
            path: path.to_owned(),
            query: String::new(),
            path_params: vec![],
            headers: vec![("accept".to_owned(), "text/plain".to_owned())],
            body: vec![],
        }
    }

    fn get(path: &str) -> SandboxRequest {
        request("GET", path)
    }

    fn denied(outcome: &SandboxOutcome, capability: DeniedCapability) -> Vec<String> {
        outcome
            .denials
            .iter()
            .filter(|denial| denial.capability == capability)
            .map(|denial| denial.operation.clone())
            .collect()
    }

    // ── the happy path ───────────────────────────────────────────────

    #[test]
    fn a_well_behaved_guest_answers_the_request() {
        let outcome = host(guests::HELLO).run(&get("/hello/greet"));
        let response = outcome.result.expect("answers");
        assert_eq!(response.status, 200);
        assert_eq!(response.body, b"hello from the sandbox");
        assert!(outcome.denials.is_empty(), "{:?}", outcome.denials);
        assert!(outcome.fuel_used > 0);
    }

    #[test]
    fn the_guest_sees_the_request_it_was_sent() {
        let host = host(guests::HELLO);
        assert_eq!(
            host.run(&get("/hello/other"))
                .result
                .expect("answers")
                .status,
            404
        );
        assert_eq!(
            host.run(&request("POST", "/hello/greet"))
                .result
                .expect("answers")
                .status,
            405
        );
    }

    #[test]
    fn each_request_gets_a_fresh_instance() {
        // Nothing a guest does can survive into the next request, which is what
        // makes one request's misbehaviour unable to poison the next.
        let host = host(guests::HELLO);
        let first = host.run(&get("/hello/greet"));
        let second = host.run(&get("/hello/greet"));
        assert_eq!(
            first.result.expect("answers"),
            second.result.expect("answers")
        );
        assert_eq!(first.fuel_used, second.fuel_used);
    }

    // ── resource bounds ──────────────────────────────────────────────

    #[test]
    fn a_guest_that_never_stops_is_stopped() {
        let limits = ResourceLimits {
            fuel: 5_000_000,
            ..ResourceLimits::default()
        };
        let outcome = try_host_with(guests::CPU_SPIN, limits)
            .expect("loads")
            .run(&get("/hello/greet"));
        let failure = outcome.result.expect_err("must not answer");
        assert!(
            matches!(failure, SandboxFailure::FuelExhausted { .. }),
            "{failure}"
        );
        assert!(failure.status().is_server_error(), "{failure}");
    }

    #[test]
    fn a_guest_that_allocates_without_bound_is_capped() {
        let limits = ResourceLimits {
            fuel: 20_000_000,
            memory_bytes: 1024 * 1024,
            ..ResourceLimits::default()
        };
        let outcome = try_host_with(guests::MEMORY_BOMB, limits)
            .expect("loads")
            .run(&get("/hello/greet"));
        assert!(outcome.result.is_err(), "a memory bomb must not answer");
        assert!(
            outcome.peak_memory_bytes <= 1024 * 1024,
            "peak {} exceeded the ceiling",
            outcome.peak_memory_bytes
        );
        assert!(
            !denied(&outcome, DeniedCapability::Memory).is_empty(),
            "the refused growth must be observable: {:?}",
            outcome.denials
        );
    }

    #[test]
    fn a_guest_that_floods_stdout_without_a_newline_is_cut_off() {
        let limits = ResourceLimits {
            max_response_bytes: 4096,
            fuel: 50_000_000,
            ..ResourceLimits::default()
        };
        let outcome = try_host_with(guests::OUTPUT_FLOOD, limits)
            .expect("loads")
            .run(&get("/hello/greet"));
        let failure = outcome.result.expect_err("must not answer");
        assert!(
            matches!(failure, SandboxFailure::OutputBudget { .. }),
            "{failure}"
        );
    }

    // ── fault isolation ──────────────────────────────────────────────

    #[test]
    fn host_side_copying_is_charged_against_the_guest_s_fuel() {
        // wasmi meters the guest's instructions, not what the host does on its
        // behalf. Without a charge, a guest buys gigabytes of memcpy for single
        // digits of fuel — a spin inside the host that the CPU ceiling never
        // sees. This guest asks the host to copy 1 MiB in ~50 instructions.
        const COPIED: u64 = 1024 * 1024;
        let bulk = host(guests::STDOUT_BULK).run(&get("/hello/greet"));
        assert!(
            bulk.fuel_used >= COPIED / 64,
            "1 MiB of host-side copying cost only {} fuel units",
            bulk.fuel_used
        );
        // …and the loop itself is nothing, so the charge is the copy.
        let honest = host(guests::HELLO).run(&get("/hello/greet"));
        assert!(
            honest.fuel_used < COPIED / 64,
            "the baseline is not a baseline: {} units",
            honest.fuel_used
        );
    }

    #[test]
    fn walking_an_iovec_vector_is_charged_even_when_it_moves_no_bytes() {
        // `fd_write`'s only byte charge lives inside `while offset < length`, which a
        // zero-length descriptor skips outright. Reading that descriptor out of guest
        // memory and bounds-checking it is host work all the same, and a guest may
        // present `MAX_IOVECS` of them per imported call: a budget that prices only the
        // calls buys sixty-four times the host CPU it charged for, on a blocking worker
        // no ceiling sees. The control is the same module with one descriptor instead
        // of sixty-four — identical guest instructions, so the whole gap between them is
        // host work priced per descriptor. Only a per-descriptor charge can satisfy this.
        const CALLS: u32 = 8192;
        const WIDE: u32 = MAX_IOVECS as u32;

        let wide = host(&guests::empty_iovecs(WIDE, CALLS)).run(&get("/hello/greet"));
        let narrow = host(&guests::empty_iovecs(1, CALLS)).run(&get("/hello/greet"));
        assert!(wide.result.is_ok(), "{:?}", wide.result);
        assert!(narrow.result.is_ok(), "{:?}", narrow.result);

        let extra = wide.fuel_used.saturating_sub(narrow.fuel_used);
        // The exact figure is `CALLS * (WIDE - 1)`; halved here so the assertion
        // is about the charge existing and scaling, not about wasmi's per
        // instruction accounting staying byte-identical between two modules.
        let expected = u64::from(CALLS) * u64::from(WIDE - 1) / 2;
        assert!(
            extra >= expected,
            "sixty-four empty descriptors per call cost {extra} more fuel than one, \
             short of the {expected} that walking them is worth"
        );
    }

    #[test]
    fn parsing_a_stdout_line_is_charged_per_byte_not_at_the_copy_rate() {
        // The parser inspects every byte of a stdout line, so whitespace padding
        // costs the host one step per byte. The copy charge alone is one unit per
        // 64 bytes. The two modules differ in one `i32.const` (the pad length), so
        // the whole `fuel_used` gap is host work. Copy only: about 1,025 units.
        // Copy plus parse: about 66,561. The bound tells them apart.
        // It does not fix either rate.
        const PAD: u32 = 65_536;

        let padded = host(&guests::padded_frame(PAD)).run(&get("/hello/greet"));
        let plain = host(&guests::padded_frame(0)).run(&get("/hello/greet"));
        // The padded frame was accepted, so the gap is not an early-exit artifact.
        assert!(padded.result.is_ok(), "{:?}", padded.result);
        assert!(plain.result.is_ok(), "{:?}", plain.result);

        let extra = padded.fuel_used.saturating_sub(plain.fuel_used);
        assert!(
            extra > u64::from(PAD) / 2,
            "{PAD} bytes of padding cost {extra} more fuel than none, \
             short of the per-byte price of parsing them"
        );
    }

    #[test]
    fn instantiating_the_module_is_priced_against_the_budget() {
        // wasmi meters guest instructions, not instantiation: every request
        // copies the module's data and element segments before `_start` runs.
        // The ceiling on that is at load (below); this is the price, so the work
        // that IS admitted still comes out of the declared budget.
        let charged = host(guests::HELLO).instantiation_fuel();
        assert!(charged > 1, "the fixture carries data segments");

        // A budget that cannot even cover instantiation is refused at *load*
        // now: the artifact could never answer a request, so it never mounts.
        let err = try_host_with(
            guests::HELLO,
            ResourceLimits {
                fuel: charged / 2,
                ..ResourceLimits::default()
            },
        )
        .expect_err("a budget below the fixed charge must not produce a host");
        assert!(
            matches!(err, SandboxLoadError::FuelBelowFixedCharges { .. }),
            "{err:?}"
        );

        // The per-request refusal still matters, and is still reached: the load
        // floor compares against instantiation alone, but the frame encoding is
        // subtracted *first*, so a budget that clears the floor can still be
        // spent before `_start`. That is the case no load-time check can catch,
        // and it must still refuse before instantiating rather than after.
        let outcome = try_host_with(
            guests::HELLO,
            ResourceLimits {
                fuel: charged + 1,
                ..ResourceLimits::default()
            },
        )
        .expect("a budget above the fixed charge loads")
        .run(&get("/hello/greet"));
        assert!(
            matches!(outcome.result, Err(SandboxFailure::FuelExhausted { .. })),
            "{:?}",
            outcome.result
        );

        // …and an honest request pays for it out of the same budget.
        let outcome = host(guests::HELLO).run(&get("/hello/greet"));
        assert!(outcome.result.is_ok());
        assert!(
            outcome.fuel_used >= charged,
            "instantiation cost {} of a {charged}-unit module",
            outcome.fuel_used
        );
    }

    #[test]
    fn a_frame_that_is_not_utf8_is_refused_rather_than_expanded() {
        // `from_utf8_lossy` turns each invalid byte into a three-byte
        // replacement while the original is still alive, so a guest filling its
        // whole stdout budget with invalid bytes would make the host hold four
        // times that budget — memory no manifest accounted for.
        let outcome = host(guests::INVALID_UTF8).run(&get("/hello/greet"));
        let failure = outcome.result.expect_err("must not answer");
        assert!(
            matches!(failure, SandboxFailure::MalformedFrame(ref detail) if detail.contains("UTF-8")),
            "{failure}"
        );
    }

    #[test]
    fn a_module_without_the_memory_the_shim_needs_is_refused_at_load() {
        // Every host function reads and writes through an export named
        // `memory`. Without one they all answer EINVAL, so the plugin loads and
        // then fails every request — which packaging exists to prevent.
        let wat = r#"(module (func (export "_start") (nop)))"#;
        assert!(matches!(
            try_host(wat),
            Err(SandboxLoadError::MissingMemory)
        ));
    }

    #[test]
    fn a_module_whose_initial_memory_exceeds_the_ceiling_is_refused_at_load() {
        // 32 pages = 2 MiB of *initial* memory against a 1 MiB ceiling: the
        // limiter would refuse it at instantiation, per request, as a gateway
        // error — when it can be said once, here.
        let wat = r#"(module (memory (export "memory") 32) (func (export "_start") (nop)))"#;
        let limits = ResourceLimits {
            memory_bytes: 1024 * 1024,
            ..ResourceLimits::default()
        };
        let err = try_host_with(wat, limits).expect_err("must be refused");
        assert!(
            matches!(err, SandboxLoadError::MemoryTooLarge { found, .. } if found == 2 * 1024 * 1024),
            "{err}"
        );
    }

    #[test]
    fn table_growth_past_the_ceiling_is_refused_while_the_guest_runs() {
        // A module already over the ceiling at rest is now refused at load,
        // summed across its tables. The limiter is still what holds the line
        // here, and this is the case it alone can: a guest that starts *under*
        // the ceiling and reaches for more with `table.grow` while running,
        // which no load-time check can see.
        let wat = format!(
            r#"(module
                 (memory (export "memory") 1)
                 (table 1 funcref)
                 (func (export "_start")
                   (drop (table.grow 0 (ref.null func) (i32.const {MAX_TABLE_ELEMENTS})))))"#
        );
        let outcome = host(&wat).run(&get("/hello/greet"));
        assert!(outcome.result.is_err(), "{:?}", outcome.result);
        // Refused, and recorded: an operator has to be able to see that the
        // plugin reached past its ceiling rather than merely that it 5xx'd.
        let operations = denied(&outcome, DeniedCapability::Memory);
        assert!(
            !operations.is_empty(),
            "the refusal was not recorded: {:?}",
            outcome.denials
        );
        // …and recorded as the ceiling it actually hit. Both hooks used to
        // share one counter, so this arrived as `memory.grow` over the
        // manifest's *byte* ceiling — a limit that was never applied. Vague
        // evidence would be a nuisance; wrong evidence sends an operator to
        // raise the wrong number in the manifest, which cannot help.
        assert!(
            operations.iter().any(|op| op == "table.grow"),
            "a table refusal was not reported as one: {operations:?}"
        );
        assert!(
            !operations.iter().any(|op| op == "memory.grow"),
            "a table refusal was reported against the byte ceiling: {operations:?}"
        );
        let detail = outcome
            .denials
            .iter()
            .find(|denial| denial.operation == "table.grow")
            .map(|denial| denial.detail.clone())
            .expect("the table denial is present");
        assert!(
            detail.contains(&MAX_TABLE_ELEMENTS.to_string()),
            "the detail does not name the ceiling that applied: {detail}"
        );
    }

    #[test]
    fn a_module_that_is_expensive_to_instantiate_is_refused_at_load() {
        // Segment *count* is the sharp edge: each one costs a bounds check and a
        // copy set-up regardless of its length, so a module of many empty
        // segments is small on disk and expensive on every single request. A
        // per-request charge cannot bound work that has already been admitted,
        // so the ceiling is at load.
        use std::fmt::Write as _;

        let mut wat = String::from("(module\n  (memory (export \"memory\") 1)\n");
        for offset in 0..=MAX_INIT_SEGMENTS {
            let _ = writeln!(wat, "  (data (i32.const {offset}) \"x\")");
        }
        wat.push_str("  (func (export \"_start\") (nop))\n)");

        let err = try_host(&wat).expect_err("must be refused");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive { max, .. } if max == MAX_INIT_SEGMENTS
            ),
            "{err}"
        );
        assert!(err.to_string().contains("re-instantiates"), "{err}");
    }

    #[test]
    fn a_guest_that_floods_stderr_runs_out_of_fuel_rather_than_time() {
        let limits = ResourceLimits {
            fuel: 2_000_000,
            ..ResourceLimits::default()
        };
        let outcome = try_host_with(guests::STDERR_FLOOD, limits)
            .expect("loads")
            .run(&get("/hello/greet"));
        let failure = outcome.result.expect_err("must not answer");
        assert!(
            matches!(failure, SandboxFailure::FuelExhausted { .. }),
            "{failure}"
        );
    }

    #[test]
    fn a_guest_that_answers_and_then_spins_does_not_hold_its_whole_budget() {
        // The exchange is over at the frame. A guest that keeps running would
        // otherwise hold a permit and a blocking worker for its whole budget
        // and then serve the answer it already had.
        let limits = ResourceLimits {
            fuel: 500_000_000,
            ..ResourceLimits::default()
        };
        let outcome = try_host_with(guests::ANSWER_THEN_SPIN, limits)
            .expect("loads")
            .run(&get("/hello/greet"));
        assert_eq!(outcome.result.as_ref().expect("answers").status, 200);
        assert!(
            outcome.fuel_used < 1_000_000,
            "the answer cost {} fuel; the guest was allowed to keep spinning",
            outcome.fuel_used
        );
    }

    #[test]
    fn a_frame_without_its_newline_says_what_the_author_did() {
        let outcome = host(guests::PARTIAL_FRAME).run(&get("/hello/greet"));
        let failure = outcome.result.expect_err("must not answer");
        assert!(matches!(failure, SandboxFailure::PartialFrame), "{failure}");
        assert!(failure.to_string().contains("println!"), "{failure}");
    }

    #[test]
    fn a_guest_may_not_forge_the_host_s_own_response_headers() {
        let outcome = host(guests::FORGE_ATTRIBUTION).run(&get("/hello/greet"));
        let denied = denied(&outcome, DeniedCapability::ResponseHeader);
        assert!(
            denied.contains(&"x-autumn-sandboxed".to_owned()),
            "{denied:?}"
        );
        assert!(
            denied.contains(&"x-content-type-options".to_owned()),
            "{denied:?}"
        );
        let response = outcome.result.expect("answers");
        assert!(
            response
                .headers
                .iter()
                .all(|(name, _)| name.starts_with("content-"))
        );
    }

    #[test]
    fn a_document_content_type_is_refused_rather_than_served_from_the_host_s_origin() {
        for essence in [
            "text/html",
            "application/javascript",
            "image/svg+xml",
            "text/css",
        ] {
            let response = SandboxResponse {
                status: 200,
                headers: vec![("content-type".to_owned(), essence.to_owned())],
                body: b"<script>".to_vec(),
            };
            assert_eq!(
                response.refused_content_type().as_deref(),
                Some(essence),
                "{essence} must be refused"
            );
        }
        for essence in ["text/plain; charset=utf-8", "application/json", "image/png"] {
            let response = SandboxResponse {
                status: 200,
                headers: vec![("Content-Type".to_owned(), essence.to_owned())],
                body: vec![],
            };
            assert_eq!(
                response.refused_content_type(),
                None,
                "{essence} must be served"
            );
        }
    }

    #[test]
    fn entropy_is_deterministic_per_request_without_being_a_published_constant() {
        // The guest folds an entropy byte into its status, so this only holds
        // if the host's stream is a function of the request.
        let host = host(guests::ENTROPY);
        let first = host.run(&get("/hello/greet")).result.expect("answers");
        let again = host.run(&get("/hello/greet")).result.expect("answers");
        assert_eq!(first.status, again.status, "the same request must replay");

        let other = host.run(&get("/hello/other")).result.expect("answers");
        assert!(
            (200..=207).contains(&other.status),
            "unexpected status {}",
            other.status
        );
        // Not asserted equal *or* unequal: one byte mod 8 collides one time in
        // eight. What matters is that the seed is not a global constant, which
        // the seed function's own test below pins.
    }

    #[test]
    fn the_entropy_seed_is_a_function_of_the_request() {
        assert_ne!(
            HostState::seed_from(b"one request"),
            HostState::seed_from(b"another request")
        );
        assert_eq!(
            HostState::seed_from(b"one request"),
            HostState::seed_from(b"one request")
        );
    }

    #[test]
    fn a_trap_is_an_error_value_not_a_dead_process() {
        let outcome = host(guests::TRAP).run(&get("/hello/greet"));
        let failure = outcome.result.expect_err("must not answer");
        assert!(matches!(failure, SandboxFailure::Trap(_)), "{failure}");
    }

    #[test]
    fn proc_exit_does_not_exit_the_host() {
        let outcome = host(guests::EXIT).run(&get("/hello/greet"));
        let failure = outcome.result.expect_err("must not answer");
        assert!(matches!(failure, SandboxFailure::Exited(3)), "{failure}");
    }

    #[test]
    fn a_guest_that_never_answers_is_a_failure_not_a_hang() {
        let outcome = host(guests::SILENT).run(&get("/hello/greet"));
        assert!(
            matches!(outcome.result, Err(SandboxFailure::NoAnswer)),
            "{:?}",
            outcome.result
        );
    }

    #[test]
    fn a_module_without_a_start_is_refused_at_load() {
        let err = try_host(guests::NO_START).expect_err("must be refused");
        assert!(matches!(err, SandboxLoadError::MissingStart), "{err}");
    }

    // ── deny-by-default ──────────────────────────────────────────────

    #[test]
    fn a_file_read_is_denied_and_logged() {
        let outcome = host(guests::READ_FILE).run(&get("/hello/greet"));
        assert_eq!(
            denied(&outcome, DeniedCapability::Filesystem),
            vec!["path_open".to_owned()]
        );
        assert_eq!(outcome.result.expect("still answers").status, 200);
    }

    /// A subscriber that records the `capability` / `operation` fields of every
    /// event, so "observable in logs" can be asserted rather than assumed.
    #[derive(Default)]
    struct DenialLog(std::sync::Arc<std::sync::Mutex<Vec<String>>>);

    impl tracing::Subscriber for DenialLog {
        fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
            true
        }
        fn max_level_hint(&self) -> Option<tracing::level_filters::LevelFilter> {
            Some(tracing::level_filters::LevelFilter::TRACE)
        }
        fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
            tracing::span::Id::from_u64(1)
        }
        fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
        fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
        fn event(&self, event: &tracing::Event<'_>) {
            struct Fields<'a>(&'a mut Vec<String>);
            impl tracing::field::Visit for Fields<'_> {
                fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn fmt::Debug) {
                    self.0.push(format!("{}={value:?}", field.name()));
                }
                fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
                    self.0.push(format!("{}={value}", field.name()));
                }
            }
            let mut fields = Vec::new();
            event.record(&mut Fields(&mut fields));
            if let Ok(mut recorded) = self.0.lock() {
                recorded.push(format!(
                    "{} [{}]",
                    event.metadata().level(),
                    fields.join(" ")
                ));
            }
        }
        fn enter(&self, _: &tracing::span::Id) {}
        fn exit(&self, _: &tracing::span::Id) {}
    }

    use rusty_fork::rusty_fork_test;

    rusty_fork_test! {
        #[test]
        fn a_denial_reaches_the_log_and_not_only_the_ledger() {
            // The ledger is what tests read; the log is what an operator reads. If the
            // two could drift, "each denial observable in logs" would be a claim about
            // a field nobody sees. Forked, because `tracing`'s callsite-interest cache
            // and max-level hint are process-global: a sibling test that installs a
            // global subscriber can filter this event out before any thread-local
            // subscriber is consulted, which would make an in-process version of this
            // test pass or fail on test ordering.
            let recorded = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
            tracing::subscriber::with_default(
                DenialLog(std::sync::Arc::clone(&recorded)),
                || {
                    let _ = host(guests::READ_FILE).run(&get("/hello/greet"));
                },
            );
            let lines = recorded.lock().expect("not poisoned").clone();
            let denial = lines
                .iter()
                .find(|line| line.contains("operation=path_open"))
                .unwrap_or_else(|| panic!("no denial line in {lines:#?}"));
            assert!(denial.starts_with("WARN"), "{denial}");
            assert!(denial.contains("capability=filesystem"), "{denial}");
            assert!(denial.contains("plugin=autumn-plugin-hello"), "{denial}");
            assert!(denial.contains("no filesystem"), "{denial}");
        }
    }

    #[test]
    fn there_are_no_preopened_directories_to_discover() {
        let outcome = host(guests::DISCOVER_PREOPENS).run(&get("/hello/greet"));
        assert_eq!(
            denied(&outcome, DeniedCapability::Filesystem),
            vec!["fd_prestat_get".to_owned()]
        );
    }

    #[test]
    fn a_stray_descriptor_read_is_denied() {
        let outcome = host(guests::READ_STRAY_FD).run(&get("/hello/greet"));
        assert_eq!(
            denied(&outcome, DeniedCapability::Filesystem),
            vec!["fd_read".to_owned()]
        );
    }

    /// A guest that seeks `fd`, traps unless the answer is `errno`, then
    /// writes a fixed 200 response.
    fn seek_guest(fd: i32, errno: i32) -> String {
        format!(
            r#"(module
  (import "wasi_snapshot_preview1" "fd_seek" (func $seek (param i32 i64 i32 i32) (result i32)))
  (import "wasi_snapshot_preview1" "fd_write" (func $write (param i32 i32 i32 i32) (result i32)))
  (memory (export "memory") 1 1)
  (data (i32.const 128) "{{\"op\":\"response\",\"status\":200,\"headers\":[[\"content-type\",\"text/plain\"]],\"body_b64\":\"b2s=\"}}\0a")
  (func (export "_start")
    (if (i32.ne (call $seek (i32.const {fd}) (i64.const 0) (i32.const 0) (i32.const 0)) (i32.const {errno}))
      (then unreachable))
    (i32.store (i32.const 0) (i32.const 128))
    (i32.store (i32.const 4) (i32.const 91))
    (drop (call $write (i32.const 1) (i32.const 0) (i32.const 1) (i32.const 8)))))"#
        )
    }

    #[test]
    fn seeking_an_unknown_descriptor_is_denied_and_recorded() {
        let outcome = host(&seek_guest(99, 8)).run(&get("/hello/greet"));
        assert_eq!(outcome.result.as_ref().expect("answers").status, 200);
        assert_eq!(
            denied(&outcome, DeniedCapability::Filesystem),
            vec!["fd_seek".to_owned()]
        );
    }

    #[test]
    fn seeking_a_negative_descriptor_is_denied_too() {
        let outcome = host(&seek_guest(-1, 8)).run(&get("/hello/greet"));
        assert_eq!(outcome.result.as_ref().expect("answers").status, 200);
        assert_eq!(
            denied(&outcome, DeniedCapability::Filesystem),
            vec!["fd_seek".to_owned()]
        );
    }

    #[test]
    fn seeking_stdio_is_a_pipe_and_not_a_denial() {
        let outcome = host(&seek_guest(1, 70)).run(&get("/hello/greet"));
        assert_eq!(outcome.result.as_ref().expect("answers").status, 200);
        assert!(outcome.denials.is_empty(), "{:?}", outcome.denials);
    }

    #[test]
    fn outbound_network_is_denied() {
        let outcome = host(guests::NETWORK).run(&get("/hello/greet"));
        assert_eq!(
            denied(&outcome, DeniedCapability::Network),
            vec!["sock_send".to_owned()]
        );
    }

    #[test]
    fn the_environment_is_empty_and_the_attempt_is_logged() {
        let outcome = host(guests::ENVIRONMENT).run(&get("/hello/greet"));
        let ops = denied(&outcome, DeniedCapability::Environment);
        assert_eq!(outcome.result.expect("still answers").status, 200);
        assert!(ops.contains(&"environ_sizes_get".to_owned()), "{ops:?}");
        assert!(ops.contains(&"environ_get".to_owned()), "{ops:?}");
    }

    #[test]
    fn process_arguments_are_empty_and_the_attempt_is_logged() {
        let outcome = host(guests::ARGUMENTS).run(&get("/hello/greet"));
        assert_eq!(
            denied(&outcome, DeniedCapability::Environment),
            vec!["args_sizes_get".to_owned()]
        );
    }

    #[test]
    fn blocking_the_host_on_a_poll_is_denied() {
        let outcome = host(guests::POLL).run(&get("/hello/greet"));
        assert_eq!(
            denied(&outcome, DeniedCapability::ProcessControl),
            vec!["poll_oneoff".to_owned()]
        );
    }

    #[test]
    fn entropy_is_answered_deterministically_rather_than_denied() {
        let host = host(guests::ENTROPY);
        let first = host.run(&get("/hello/greet"));
        let second = host.run(&get("/hello/greet"));
        assert!(first.denials.is_empty(), "{:?}", first.denials);
        assert_eq!(
            first.result.expect("answers"),
            second.result.expect("answers")
        );
    }

    #[test]
    fn a_database_seam_the_host_never_defined_is_refused_at_load() {
        let err = try_host(guests::DATABASE).expect_err("must be refused");
        let SandboxLoadError::ForbiddenImports(denials) = err else {
            panic!("expected a forbidden-import refusal, got {err}");
        };
        assert_eq!(denials.len(), 1);
        assert_eq!(denials[0].capability, DeniedCapability::UnknownImport);
        assert!(denials[0].operation.contains("autumn_db"), "{denials:?}");
    }

    #[test]
    fn a_host_escape_from_an_invented_namespace_is_refused_at_load() {
        let err = try_host(guests::HOST_COMMAND).expect_err("must be refused");
        assert!(
            matches!(err, SandboxLoadError::ForbiddenImports(_)),
            "{err}"
        );
    }

    #[test]
    fn a_wasi_function_this_shim_does_not_implement_is_refused_at_load() {
        let err = try_host(guests::UNDEFINED_WASI).expect_err("must be refused");
        let SandboxLoadError::ForbiddenImports(denials) = err else {
            panic!("expected a forbidden-import refusal, got {err}");
        };
        assert!(denials[0].operation.contains("sock_connect"), "{denials:?}");
    }

    // ── the response is not a trusted channel either ─────────────────

    #[test]
    fn a_forged_session_cookie_is_stripped_and_logged() {
        let outcome = host(guests::FORGE_COOKIE).run(&get("/hello/greet"));
        assert_eq!(
            denied(&outcome, DeniedCapability::ResponseHeader),
            vec!["set-cookie".to_owned()]
        );
        let response = outcome.result.expect("answers");
        assert!(
            !response
                .headers
                .iter()
                .any(|(name, _)| name.eq_ignore_ascii_case("set-cookie")),
            "{:?}",
            response.headers
        );
    }

    #[test]
    fn a_plugin_cannot_borrow_the_reverse_proxy_s_filesystem() {
        let outcome = host(guests::PROXY_REDIRECT).run(&get("/hello/greet"));
        let denied = denied(&outcome, DeniedCapability::ResponseHeader);
        assert!(
            denied.contains(&"x-accel-redirect".to_owned()),
            "{denied:?}"
        );
        assert!(denied.contains(&"x-sendfile".to_owned()), "{denied:?}");
        let response = outcome.result.expect("answers without them");
        assert!(
            response
                .headers
                .iter()
                .all(|(name, _)| name == "content-type"),
            "{:?}",
            response.headers
        );
    }

    #[test]
    fn a_response_splitting_header_never_reaches_a_response() {
        // Two locks on this door: the header allowlist drops the name before
        // anything looks at its value, and `SandboxResponse::validate` refuses a
        // value carrying CRLF for a name that *is* allowed (asserted directly in
        // `wire`). Here the first lock holds, so the guest is served — minus the
        // header, with the attempt on the record.
        let outcome = host(guests::SPLIT_RESPONSE).run(&get("/hello/greet"));
        assert_eq!(
            denied(&outcome, DeniedCapability::ResponseHeader),
            vec!["x-evil".to_owned()]
        );
        let response = outcome.result.expect("answers without the header");
        assert!(
            response
                .headers
                .iter()
                .all(|(name, _)| name == "content-type"),
            "{:?}",
            response.headers
        );
    }

    #[test]
    fn an_impossible_status_is_refused() {
        let outcome = host(guests::IMPOSSIBLE_STATUS).run(&get("/hello/greet"));
        assert!(
            matches!(outcome.result, Err(SandboxFailure::ResponseRefused(_))),
            "{:?}",
            outcome.result
        );
    }

    #[test]
    fn a_guest_error_detail_can_neither_flood_nor_forge_a_log_line() {
        // A guest's `detail` is attacker-controlled text on its way to a log
        // the operator trusts. Two separate hazards: its *length* (a line can
        // be as large as the stdout budget, and a plugin that fails in a loop
        // writes one per request) and its *content* (a newline starts a record
        // the operator did not write; an ANSI escape repaints one they did).
        let outcome = host(guests::FORGE_LOG).run(&get("/hello/greet"));
        let Err(failure) = outcome.result else {
            panic!("the guest reported a failure");
        };
        let rendered = failure.to_string();
        assert!(
            rendered.len() < 4096,
            "a 2 KiB detail reached the log intact: {} bytes",
            rendered.len()
        );
        assert!(
            !rendered.contains('\n') && !rendered.contains('\r'),
            "the detail can start a log record of its own: {rendered:?}"
        );
        assert!(
            !rendered.contains('\u{1b}'),
            "the detail can repaint the operator's terminal: {rendered:?}"
        );
        assert!(
            rendered.contains("forged"),
            "the detail is still legible enough to debug with: {rendered:?}"
        );
    }

    #[test]
    fn a_denied_response_header_name_is_bounded_before_it_is_logged() {
        // The sibling of the content-type cap, on the header *name* rather
        // than its value. A denied name is often denied precisely because it
        // is not a valid header name, so it can carry newlines and escapes as
        // well as megabytes — and `deny` both stores it and logs it.
        let name = "x-".to_owned() + &"y".repeat(20_000);
        let frame = format!(
            r#"{{"op":"response","status":200,"headers":[["content-type","text/plain"],["{name}","v"]],"body_b64":""}}"#
        );
        let len = frame.len() + 1;
        let wat = format!(
            r#"(module
  (import "wasi_snapshot_preview1" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32)))
  (memory (export "memory") 2)
  (data (i32.const 1024) "{escaped}\0a")
  (func (export "_start")
    (i32.store (i32.const 0) (i32.const 1024))
    (i32.store (i32.const 4) (i32.const {len}))
    (drop (call $fd_write (i32.const 1) (i32.const 0) (i32.const 1) (i32.const 8)))))"#,
            escaped = frame.replace('"', "\\\""),
        );

        let outcome = host(&wat).run(&get("/hello/greet"));
        let logged = outcome
            .denials
            .iter()
            .find(|denial| denial.capability == DeniedCapability::ResponseHeader)
            .expect("the stripped header is recorded as a denial");
        assert!(
            logged.operation.len() < 1_024,
            "the denial carries the guest's whole header name: {} bytes",
            logged.operation.len()
        );
        assert!(
            logged.operation.contains("truncated"),
            "{:?}",
            logged.operation
        );
    }

    #[test]
    fn a_refused_content_type_is_bounded_before_it_is_logged() {
        // `refused_content_type` takes everything before the first `;`, so a
        // guest that writes no parameter hands back its entire header value —
        // capped only by the stdout ceiling, which is megabytes. That string
        // reached both the denial detail and the `ResponseRefused` text, and
        // both are logged, so a guest could flood an operator's log with a
        // header rather than with output.
        let essence = "x".repeat(20_000);
        let frame = format!(
            r#"{{"op":"response","status":200,"headers":[["content-type","{essence}"]],"body_b64":""}}"#
        );
        // The frame is ASCII, so its byte length is its char length; + 1 for
        // the newline that ends it. The WAT literal needs its quotes escaped,
        // which changes the *source* length but not the decoded bytes.
        let len = frame.len() + 1;
        let wat = format!(
            r#"(module
  (import "wasi_snapshot_preview1" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32)))
  (memory (export "memory") 2)
  (data (i32.const 1024) "{escaped}\0a")
  (func (export "_start")
    (i32.store (i32.const 0) (i32.const 1024))
    (i32.store (i32.const 4) (i32.const {len}))
    (drop (call $fd_write (i32.const 1) (i32.const 0) (i32.const 1) (i32.const 8)))))"#,
            escaped = frame.replace('"', "\\\""),
        );

        let outcome = host(&wat).run(&get("/hello/greet"));
        let Err(SandboxFailure::ResponseRefused(detail)) = outcome.result else {
            panic!(
                "an unsupported content type must be refused: {:?}",
                outcome.result
            );
        };
        assert!(
            detail.len() < 1_024,
            "the failure text carries the guest's whole header: {} bytes",
            detail.len()
        );
        assert!(detail.contains("truncated"), "{detail}");

        let logged = outcome
            .denials
            .iter()
            .find(|denial| denial.capability == DeniedCapability::ResponseHeader)
            .expect("the refusal is recorded as a denial");
        assert!(
            logged.detail.len() < 1_024,
            "the denial detail carries the guest's whole header: {} bytes",
            logged.detail.len()
        );
    }

    #[test]
    fn an_element_offset_this_cannot_evaluate_is_refused_like_a_data_offset() {
        // The data walk learned to refuse an active segment whose offset it
        // cannot evaluate; the element walk beside it still skipped one. Same
        // fail-open, same shape, in the sibling — an active element segment is
        // written into its table at instantiation whether or not this can work
        // out where, so skipping the check because the offset is unknown is the
        // check silently not running.
        let mut operands = String::new();
        let mut adds = String::new();
        for _ in 0..24 {
            operands.push_str("i32.const 0 ");
            adds.push_str("i32.add ");
        }
        let wat = format!(
            r#"(module
  (table 1 funcref)
  (memory (export "memory") 1)
  (func $f (export "_start") (nop))
  (elem (offset i32.const 65536 {operands} {adds}) $f)
)"#
        );
        let wasm = wat::parse_str(&wat).expect("the fixture is valid WAT");

        let mut config = wasmi::Config::default();
        config.consume_fuel(true);
        wasmi::Module::new(&wasmi::Engine::new(&config), &wasm[..])
            .expect("wasmi compiles a deep extended-const offset; the finding depends on it");

        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("an active element segment with an unevaluable offset must be refused");
        assert!(
            matches!(
                err,
                SandboxLoadError::SegmentOutOfBounds {
                    what: "table elements",
                    ..
                }
            ),
            "{err:?}",
        );

        // A passive element segment writes nothing at instantiation, so an
        // offset it has no need of cannot make it refusable.
        let passive = wat::parse_str(
            r#"(module
  (table 1 funcref)
  (memory (export "memory") 1)
  (func $f (export "_start") (nop))
  (elem funcref (ref.func $f))
)"#,
        )
        .expect("the fixture is valid WAT");
        SandboxHost::from_module(manifest_with(ResourceLimits::default()), &passive)
            .expect("a passive element segment must still load");
    }

    #[test]
    fn deciding_a_header_does_not_cross_costs_nothing_to_decide() {
        // The value clone was the obvious half. The name is the same trap one step
        // smaller: looking a header up in the allowlist by lower-casing it first
        // allocates a copy of a string the caller chose the length of, only to conclude
        // it is not wanted. And a dropped header is no longer charged against the
        // metadata ceiling — rightly, it never crosses — so nothing bounds how large
        // that name may be. The predicate now compares in place. Asserted by behaviour
        // rather than by allocation here, since `tests/sandbox_header_alloc_gate.rs`
        // does the measuring: a name that cannot be an allowlisted header must be
        // rejected without the length ever mattering.
        let enormous = "x".repeat(4 * 1024 * 1024);
        assert!(!super::super::wire::request_header_allowed(&enormous));

        // Case-insensitive, because HTTP header names are — which is what lets
        // the caller skip the lower-casing rather than merely defer it.
        assert!(super::super::wire::request_header_allowed("Accept"));
        assert!(super::super::wire::request_header_allowed("ACCEPT"));
        assert!(super::super::wire::request_header_allowed("accept"));
        assert!(!super::super::wire::request_header_allowed("Cookie"));

        // And the canonical form is still what reaches the guest, so accepting
        // a mixed-case name does not mean forwarding one.
        let canonical = super::super::wire::canonicalize_headers(&[(
            "AcCePt".to_owned(),
            "text/plain".to_owned(),
        )]);
        assert_eq!(
            canonical,
            vec![("accept".to_owned(), "text/plain".to_owned())],
        );
    }

    #[test]
    fn encoding_fuel_prices_the_sizing_pass_of_the_line() {
        // `to_line` serialises twice: once to count, once to write. The count
        // still encodes and escapes everything, so it is host work the guest's
        // fuel must pay for. Three raw walks and five expanded ones (encode and
        // escape-scan in each pass, plus the seed scan) make 9 2/3 of the body.
        let mut request = get("/hello/greet");
        request.body = vec![b'x'; 60_000];
        let charged_bytes = encoding_fuel(&request).saturating_mul(BYTES_PER_FUEL);
        assert!(
            charged_bytes >= 60_000 * 29 / 3,
            "the charge ({charged_bytes}) leaves the sizing pass free"
        );
    }

    #[test]
    fn encoding_fuel_prices_the_line_that_is_written_not_the_bytes_handed_in() {
        // A flat multiplier over the raw input under-charged, because most of the walks
        // are over the expanded form: base64 grows the body by 4/3 and every pass after
        // the encode is over that, while `serde_json` writes a control character as six
        // bytes and `seed_from` then reads the whole finished line. A request could buy
        // host work the ceiling never saw. Measured against what the serialiser actually
        // writes, so the factors cannot drift from the encoding they claim to cover.
        let granted = [SandboxCapability::HttpRequest];

        let mut request = get("/hello/greet");
        request.body = vec![b'x'; 60_000];
        let line = crate::plugin_sandbox::wire::to_line(
            &crate::plugin_sandbox::wire::HostFrame::request(&request, &granted),
        )
        .expect("serialises")
        .len();

        // The charge has to cover writing that line and reading it back at
        // least once — the seed scan — on top of the copies before it.
        let charged_bytes = encoding_fuel(&request).saturating_mul(BYTES_PER_FUEL);
        assert!(
            charged_bytes >= (line as u64).saturating_mul(2),
            "the charge ({charged_bytes}) is under writing and re-reading a \
             {line}-byte line",
        );

        // The metadata side expands further than the body does, so it must be
        // charged at a higher rate rather than at one flat factor for both.
        let mut escaped = get("/hello/greet");
        escaped.query = "\u{0}".repeat(10_000);
        let mut plain = get("/hello/greet");
        plain.query = "a".repeat(10_000);
        assert!(
            encoding_fuel(&escaped) == encoding_fuel(&plain),
            "the charge is computed from raw sizes, so it must not vary with \
             content — it is an upper bound taken before the line exists",
        );
        let escaped_line = crate::plugin_sandbox::wire::to_line(
            &crate::plugin_sandbox::wire::HostFrame::request(&escaped, &granted),
        )
        .expect("serialises")
        .len();
        let escaped_charge = encoding_fuel(&escaped).saturating_mul(BYTES_PER_FUEL);
        assert!(
            escaped_charge >= (escaped_line as u64).saturating_mul(2),
            "the charge ({escaped_charge}) is under writing and re-reading a \
             JSON-escaped {escaped_line}-byte line",
        );
    }

    #[test]
    fn direct_run_does_not_charge_for_headers_the_frame_will_drop() {
        // `HostFrame::request` filters headers through the allowlist, so a
        // `Cookie` or `Authorization` never reaches the guest. Counting those
        // bytes against the metadata ceiling refused a request that would have
        // cost nothing — and made `SandboxHost::run`, which is public, stricter
        // than the adapter that is merely its politest caller.
        let host = host(guests::HELLO);

        let mut credential_heavy = get("/hello/greet");
        credential_heavy.headers = vec![
            ("cookie".to_owned(), "s=".repeat(MAX_REQUEST_METADATA_BYTES)),
            (
                "authorization".to_owned(),
                "t=".repeat(MAX_REQUEST_METADATA_BYTES),
            ),
        ];
        assert!(
            request_metadata_bytes(&credential_heavy) < MAX_REQUEST_METADATA_BYTES,
            "headers the frame drops are still being charged for",
        );
        assert!(
            host.run(&credential_heavy).result.is_ok(),
            "a request whose only bulk is dropped headers must still be served",
        );

        // And the ceiling still holds for headers that *do* cross, or it would
        // have stopped bounding anything.
        let mut allowed_heavy = get("/hello/greet");
        allowed_heavy.headers = vec![(
            "accept".to_owned(),
            "text/plain, ".repeat(MAX_REQUEST_METADATA_BYTES),
        )];
        let err = host
            .run(&allowed_heavy)
            .result
            .expect_err("oversized allowlisted metadata must still be refused");
        assert!(
            matches!(err, SandboxFailure::RequestMetadataBudget { .. }),
            "{err:?}",
        );
    }

    #[test]
    fn a_module_of_nothing_but_custom_sections_is_refused_without_reading_them_all() {
        // Every other shape ceiling is read from a section's leading count.
        // A custom section has no count — a name and opaque bytes — so it was
        // excluded from `declared_entries` and contributed to nothing, while
        // costing three bytes to encode. The refusal that is supposed to be
        // cheap became the expensive part.
        let mut wasm = Vec::from(b"\0asm\x01\0\0\0".as_slice());
        // Empty custom section: id 0, size 1, a zero-length name.
        for _ in 0..=MAX_SECTIONS {
            wasm.extend_from_slice(&[CUSTOM_SECTION, 0x01, 0x00]);
        }
        let shape = module_shape(&wasm).expect("the header walk must not fail on legal sections");

        // The walk stopped at the ceiling rather than reading every header.
        assert_eq!(
            shape.sections,
            MAX_SECTIONS + 1,
            "the walk read past the ceiling instead of stopping at it",
        );

        let err = refuse_unbounded_shape(&wasm)
            .expect_err("a module past the section ceiling must be refused");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive {
                    what: "sections",
                    ..
                }
            ),
            "{err:?}",
        );

        // And an ordinary module, which carries a handful of sections, is not
        // caught by this — or the ceiling would refuse every real plugin.
        let hello = wat::parse_str(guests::HELLO).expect("the fixture is valid WAT");
        let shape = module_shape(&hello).expect("a real module walks");
        assert!(
            shape.sections <= MAX_SECTIONS,
            "a real module carries {} sections, at or over the ceiling",
            shape.sections,
        );
        refuse_unbounded_shape(&hello).expect("a real module must still load");
    }

    #[test]
    fn a_module_declaring_a_second_memory_is_refused_at_load_not_once_per_request() {
        // wasmi enables the multi-memory proposal by default, so `Module::new`
        // compiles this happily and only the `MemoryLimiter` objects — and it
        // objects at instantiation, which is per request. The artifact would
        // pass `autumn plugin inspect` and then answer every request with a
        // gateway error, which is the shape this file already refuses
        // elsewhere: a passing verdict on an artifact that can only ever 504 is
        // worse than no verdict, because an operator installs on it.
        let wat = r#"(module
  (memory (export "memory") 1)
  (memory 1)
  (func (export "_start") (nop))
)"#;
        let wasm = wat::parse_str(wat).expect("the fixture is valid WAT");

        // First, that the engine really does accept it — a fix for a module the
        // compiler already rejects would be guarding nothing.
        let mut config = wasmi::Config::default();
        config.consume_fuel(true);
        let engine = wasmi::Engine::new(&config);
        wasmi::Module::new(&engine, &wasm[..])
            .expect("wasmi enables multi-memory by default; if this fails the ceiling is moot");

        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("a second memory must be refused at load");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive {
                    what: "linear memories",
                    ..
                }
            ),
            "{err:?}",
        );

        // And refused *before* `Module::new`, not after it. The pre-compilation
        // gate is a separate function precisely so that a shape guaranteed to
        // be rejected does not first get a representation built for every
        // declaration in it — so the ceiling has to live there rather than
        // merely be reached eventually. Asserted by calling that gate directly:
        // it is what runs ahead of the compiler.
        let err = refuse_unbounded_shape(&wasm)
            .expect_err("the pre-compilation gate must refuse it, not a later one");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive {
                    what: "linear memories",
                    ..
                }
            ),
            "{err:?}",
        );

        // One memory is the normal case and still loads.
        let single = wat::parse_str(
            r#"(module (memory (export "memory") 1) (func (export "_start") (nop)))"#,
        )
        .expect("the fixture is valid WAT");
        SandboxHost::from_module(manifest_with(ResourceLimits::default()), &single)
            .expect("a single-memory module must still load");
    }

    #[test]
    fn a_long_import_name_is_not_copied_whole_in_order_to_refuse_it() {
        // `MAX_IMPORTS` bounds how many names a module may declare; nothing on this
        // side bounded how long one may be. wasmparser caps a single name at 100 KB, so
        // this is not module-sized — but `MAX_DENIALS` is 64, and the denial copied the
        // whole name, `Display` cloned it again, and the join built a third copy. That
        // is megabytes of host memory to refuse one artifact, repeatable, in the process
        // of trying to reject it. Observable in what comes out: a bounded operation
        // cannot be longer than the bound, however long the name was.
        let huge = "z".repeat(99_000);
        let wat = format!(
            r#"(module
  (import "not_wasi" "{huge}" (func))
  (memory (export "memory") 1)
  (func (export "_start") (nop))
)"#
        );
        let wasm = wat::parse_str(&wat).expect("the fixture is valid WAT");

        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("an import the sandbox does not provide must be refused");
        let SandboxLoadError::ForbiddenImports(denials) = &err else {
            panic!("{err:?}");
        };
        assert_eq!(denials.len(), 1);
        assert!(
            denials[0].operation.len() <= DENIAL_RECORD_BYTES,
            "the denial carries {} bytes of a {}-byte name — it was copied whole \
             in order to reject it",
            denials[0].operation.len(),
            huge.len(),
        );
        assert!(
            denials[0].operation.starts_with("not_wasi::"),
            "the operation must still say what was imported: {}",
            &denials[0].operation[..denials[0].operation.len().min(64)],
        );

        // And rendering the error does not rebuild it either. `Display` is what
        // `autumn plugin package`/`inspect` call before excerpting, so a copy
        // made here lands in the process trying to refuse the artifact.
        let rendered = err.to_string();
        assert!(
            rendered.len() <= DENIAL_RECORD_BYTES.saturating_mul(2),
            "rendering the refusal produced {} bytes from a {}-byte name",
            rendered.len(),
            huge.len(),
        );
    }

    #[test]
    fn a_table_the_instance_fills_is_charged_like_the_memory_it_fills() {
        // The memory term exists because a module can declare an initial size
        // with no data segments, so the init-section terms price none of it
        // while the host still zero-fills it every instantiation. A table's
        // minimum is the same shape and was not charged: `segments` and
        // `init_bytes` see nothing, and wasmi still allocates and initialises
        // every slot before the guest runs.
        let bare = instantiation_fuel(0, 0, 0, 0, 0, 0);
        let with_table = instantiation_fuel(0, 0, 0, 0, 0, u64::from(MAX_TABLE_ELEMENTS));
        assert!(
            with_table > bare,
            "a full table cost the same as no table at all ({with_table} vs {bare})",
        );
        assert_eq!(
            with_table - bare,
            u64::from(MAX_TABLE_ELEMENTS),
            "the charge should be one unit per slot the instance initialises",
        );

        // End to end: a module whose only weight is its table must be refused
        // when its fuel cannot cover filling it. Zero-page memory and no
        // segments, so every other fixed term is at its floor.
        let wat = format!(
            r#"(module
  (memory (export "memory") 0)
  (table {MAX_TABLE_ELEMENTS} funcref)
  (func (export "_start") (nop))
)"#
        );
        let wasm = wat::parse_str(&wat).expect("the fixture is valid WAT");
        let limits = ResourceLimits {
            fuel: u64::from(MAX_TABLE_ELEMENTS) / 2,
            ..ResourceLimits::default()
        };
        let err = SandboxHost::from_module(manifest_with(limits), &wasm)
            .expect_err("fuel below the cost of filling the table must be refused");
        assert!(
            matches!(err, SandboxLoadError::FuelBelowFixedCharges { .. }),
            "{err:?}",
        );

        // And the same module loads once its budget covers the table, so the
        // charge bounds rather than forbids.
        SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect("a table within a normal fuel budget must still load");
    }

    #[test]
    fn the_review_list_bounds_an_import_name_where_it_builds_it() {
        // The sibling of the denial-path fix, and the site it did not reach.
        // `reported_imports` bounded how *many* names it formatted and not how
        // long each one was, so 256 entries could each be as long as an
        // artifact cared to make them. The review surface does excerpt them —
        // afterwards, which is one copy too late to be the bound.
        let huge = "z".repeat(99_000);
        let wat = format!(
            r#"(module
  (import "not_wasi" "{huge}" (func))
  (memory (export "memory") 1)
  (func (export "_start") (nop))
)"#
        );
        let wasm = wat::parse_str(&wat).expect("the fixture is valid WAT");

        let imports = SandboxHost::imports_of(&wasm).expect("the module's shape is readable");
        assert_eq!(imports.len(), 1);
        assert!(
            imports[0].len() <= DENIAL_RECORD_BYTES,
            "the review list carries {} bytes of a {}-byte name",
            imports[0].len(),
            huge.len(),
        );
        assert!(
            imports[0].starts_with("not_wasi::"),
            "the entry must still say what is imported: {}",
            &imports[0][..imports[0].len().min(64)],
        );
    }

    #[test]
    fn one_oversized_element_section_is_not_walked_before_it_is_refused() {
        // The count ceiling and the byte ceiling each refuse a module on their own, so
        // the walk should be skipped when either is exceeded. Only the count gated it,
        // and a single segment keeps the count at one, so the walk ran over the section
        // on the way to a refusal the byte ceiling had already decided. Observable
        // through what the walk reports: the segment here overflows its table, so a walk
        // that runs finds `Some(..)` and a walk that is skipped leaves `None`. The
        // module is refused either way, which is why the verdict cannot be what this
        // test looks at.
        let mut wasm = Vec::from(b"\0asm\x01\0\0\0".as_slice());
        // One table, funcref, minimum 1 — so five elements written at offset 0
        // is an overflow the walk would report.
        wasm.extend_from_slice(&[TABLE_SECTION, 0x04, 0x01, 0x70, 0x00, 0x01]);

        let body_len = MAX_INIT_SECTION_BYTES + 1;
        wasm.push(ELEMENT_SECTION);
        let mut size = body_len;
        while size >= 0x80 {
            let low = u8::try_from(size & 0x7f).expect("masked to seven bits");
            wasm.push(low | 0x80);
            size >>= 7;
        }
        wasm.push(u8::try_from(size).expect("the loop leaves under 0x80"));
        let before_body = wasm.len();
        // count = 1; then an active segment: table 0, offset `i32.const 0`,
        // five function indices. The rest of the section is padding the walk
        // never reads — it is there only to carry the section over the byte
        // ceiling.
        wasm.extend_from_slice(&[0x01, 0x00, 0x41, 0x00, 0x0b, 0x05, 0, 0, 0, 0, 0]);
        wasm.resize(before_body + body_len, 0);

        let shape = module_shape(&wasm).expect("the header walk must not fail");
        assert_eq!(
            shape.segments, 1,
            "the count ceiling is not what refuses it"
        );
        assert!(
            shape.init_bytes > MAX_INIT_SECTION_BYTES,
            "the fixture should be over the byte ceiling",
        );
        assert!(
            shape.element_overflow.is_none(),
            "the segment walk ran on a section the byte ceiling already refuses: {:?}",
            shape.element_overflow,
        );

        let err =
            refuse_unbounded_shape(&wasm).expect_err("an oversized init section must be refused");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive {
                    what: "bytes of data and element sections",
                    ..
                }
            ),
            "{err:?}",
        );
    }

    #[test]
    fn one_segment_cannot_declare_more_entries_than_the_ceiling_allows() {
        // `declared_entries` sums each section's leading count, one LEB128 per section,
        // which is what makes reading the shape cheap. The element section is the one
        // place that undercounts: its leading count is the number of segments, and a
        // segment carries its own count of items. So one passive segment holding
        // millions of function indices added exactly one to the ceiling that exists to
        // bound declarations before anything allocates per declaration.
        //
        // Nothing else caught it. `MAX_TABLE_ELEMENTS` bounds what a table starts with,
        // and a passive segment is never written to a table; `MAX_INIT_SEGMENTS` counts
        // segments, and there is one; and the byte ceiling admits a 16 MiB section,
        // which is millions of one-byte indices. The walk then read every one of them,
        // and `Module::new` expanded the whole initializer list after it.
        fn uleb(mut value: usize, out: &mut Vec<u8>) {
            while value >= 0x80 {
                let low = u8::try_from(value & 0x7f).expect("masked to seven bits");
                out.push(low | 0x80);
                value >>= 7;
            }
            out.push(u8::try_from(value).expect("the loop leaves under 0x80"));
        }

        // One passive segment (flags 1, elemkind 0x00) declaring one item more
        // than the ceiling admits, each a one-byte `funcidx 0`.
        let items = MAX_DECLARED_ENTRIES + 1;
        let mut body = vec![0x01, 0x01, 0x00];
        uleb(items, &mut body);
        body.resize(body.len() + items, 0x00);

        let mut wasm = Vec::from(b"\0asm\x01\0\0\0".as_slice());
        wasm.extend_from_slice(&[0x01, 0x04, 0x01, 0x60, 0x00, 0x00]); // type () -> ()
        wasm.extend_from_slice(&[0x03, 0x02, 0x01, 0x00]); // one function
        wasm.extend_from_slice(&[TABLE_SECTION, 0x04, 0x01, 0x70, 0x00, 0x01]);
        wasm.push(ELEMENT_SECTION);
        uleb(body.len(), &mut wasm);
        wasm.extend_from_slice(&body);

        // The fixture has to clear every *other* ceiling, or it would be
        // refused for a reason that has nothing to do with the nested count.
        let shape = module_shape(&wasm).expect("the header walk must not fail");
        assert!(
            shape.segments <= MAX_INIT_SEGMENTS,
            "the segment count is not what refuses this fixture",
        );
        assert!(
            shape.init_bytes <= MAX_INIT_SECTION_BYTES,
            "the byte ceiling is not what refuses this fixture: {}",
            shape.init_bytes,
        );
        assert!(
            shape.table_elements <= u64::from(MAX_TABLE_ELEMENTS),
            "the table ceiling is not what refuses this fixture",
        );
        assert!(
            shape.declared_entries > MAX_DECLARED_ENTRIES,
            "the segment's own items never reached the ceiling: {}",
            shape.declared_entries,
        );

        let err = refuse_unbounded_shape(&wasm)
            .expect_err("a segment over the entry ceiling must be refused");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive {
                    what: "declared section entries",
                    ..
                }
            ),
            "{err:?}",
        );

        // And the count is read *before* the items are, which is what keeps the
        // refusal from costing what it refuses. Here the section claims far
        // more items than it carries: a walk that reads them runs off the end
        // of the section and reports nothing, leaving the module to be refused
        // for some later reason — or not at all. One that stops at the ceiling
        // still refuses it, from the count alone.
        let mut truncated = Vec::from(b"\0asm\x01\0\0\0".as_slice());
        truncated.extend_from_slice(&[TABLE_SECTION, 0x04, 0x01, 0x70, 0x00, 0x01]);
        let mut claim = vec![0x01, 0x01, 0x00];
        uleb(MAX_DECLARED_ENTRIES * 16, &mut claim);
        claim.extend_from_slice(&[0x00, 0x00, 0x00]);
        truncated.push(ELEMENT_SECTION);
        uleb(claim.len(), &mut truncated);
        truncated.extend_from_slice(&claim);

        let err = refuse_unbounded_shape(&truncated)
            .expect_err("a section claiming more entries than it carries must be refused");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive {
                    what: "declared section entries",
                    ..
                }
            ),
            "the count was not consulted before the items were walked: {err:?}",
        );
    }

    #[test]
    fn the_engine_refuses_a_heap_type_this_walk_would_have_to_guess_at() {
        // `skip_const_expr` reads `ref.null`'s heap type as a signed LEB rather than a
        // byte. Today that is the same one byte for every heap type the engine accepts
        // — this test is what says so, and what would notice if it stopped being true.
        // A non-minimal encoding of `funcref` (0xf0 0x7f decodes to -16, the same value
        // as 0x70) is the case a byte-wide read would desynchronise on. wasmi refuses it
        // outright, so no such module reaches instantiation: the walk cannot be led out
        // of step by it, and the load-time bounds check cannot be skipped through it.
        let mut module = Vec::from(b"\0asm\x01\0\0\0".as_slice());
        module.extend_from_slice(&[0x01, 0x04, 0x01, 0x60, 0x00, 0x00]); // type () -> ()
        module.extend_from_slice(&[0x03, 0x02, 0x01, 0x00]); // one function
        module.extend_from_slice(&[0x04, 0x04, 0x01, 0x70, 0x00, 0x01]); // table funcref, min 1
        module.extend_from_slice(&[0x05, 0x03, 0x01, 0x00, 0x01]); // memory, min 1
        module.extend_from_slice(&[0x07, 0x13, 0x02, 0x06]);
        module.extend_from_slice(b"memory");
        module.extend_from_slice(&[0x02, 0x00, 0x06]);
        module.extend_from_slice(b"_start");
        module.extend_from_slice(&[0x00, 0x00]);
        let code = [0x0a, 0x05, 0x01, 0x03, 0x00, 0x01, 0x0b];

        let mut config = wasmi::Config::default();
        config.consume_fuel(true);
        let engine = wasmi::Engine::new(&config);

        // The minimal form compiles, which is what makes the comparison mean
        // something: the fixture is well formed apart from the heap type.
        let mut minimal = module.clone();
        minimal.extend_from_slice(&[
            0x09, 0x09, 0x01, 0x04, 0x41, 0x00, 0x0b, 0x01, 0xd0, 0x70, 0x0b,
        ]);
        minimal.extend_from_slice(&code);
        wasmi::Module::new(&engine, &minimal[..]).expect("the minimal heap type compiles");

        // The non-minimal form does not.
        let mut non_minimal = module;
        non_minimal.extend_from_slice(&[
            0x09, 0x0a, 0x01, 0x04, 0x41, 0x00, 0x0b, 0x01, 0xd0, 0xf0, 0x7f, 0x0b,
        ]);
        non_minimal.extend_from_slice(&code);
        let err = wasmi::Module::new(&engine, &non_minimal[..])
            .expect_err("a non-minimal heap type must not compile");
        assert!(
            err.to_string().contains("heap type"),
            "expected the engine to name the heap type: {err}",
        );
    }

    #[test]
    fn a_swarm_of_empty_tables_is_refused_before_anything_is_compiled() {
        // The sibling of the memory case, and the reason all three ceilings
        // moved together. A module can declare far more tables than
        // `MAX_TABLES` while staying under `MAX_DECLARED_ENTRIES`, so nothing
        // else refuses it — and while the table ceiling did refuse it, it
        // refused after `Module::new` had already built a representation of
        // every declaration. The right answer at the wrong time.
        let mut wat = String::from("(module\n  (memory (export \"memory\") 1)\n");
        for _ in 0..=MAX_TABLES {
            wat.push_str("  (table 0 funcref)\n");
        }
        wat.push_str("  (func (export \"_start\") (nop))\n)");
        let wasm = wat::parse_str(&wat).expect("the fixture is valid WAT");

        // Under the aggregate ceiling, so `MAX_DECLARED_ENTRIES` is not what
        // catches this — otherwise the test would pass for the wrong reason.
        let shape = module_shape(&wasm).expect("the header walk must not fail");
        assert!(
            shape.declared_entries <= MAX_DECLARED_ENTRIES,
            "the fixture is caught by the aggregate ceiling, not the table one",
        );

        let err = refuse_unbounded_shape(&wasm)
            .expect_err("the pre-compilation gate must refuse too many tables");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive { what: "tables", .. }
            ),
            "{err:?}",
        );

        // And the third of the three: tables that are already over the element
        // ceiling at rest, also refused before compiling.
        let heavy = wat::parse_str(format!(
            "(module (memory (export \"memory\") 1) (table {} funcref) \
             (func (export \"_start\") (nop)))",
            u64::from(MAX_TABLE_ELEMENTS) + 1,
        ))
        .expect("the fixture is valid WAT");
        let err = refuse_unbounded_shape(&heavy)
            .expect_err("the pre-compilation gate must refuse oversized tables");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive {
                    what: "initial table elements",
                    ..
                }
            ),
            "{err:?}",
        );
    }

    #[test]
    fn the_metadata_walk_stops_at_the_ceiling_instead_of_finishing_the_list() {
        // Charging every entry made an oversized list fail. It did not bound the work of
        // discovering that it fails — the fold visited every pair first, before the
        // permit was taken and before the guest spent any fuel — so an unbounded list
        // still bought an unbounded scan per concurrent caller. Fixing the verdict is
        // not fixing the cost. Observable because a stopped walk returns a floor: run to
        // the end and the answer is the whole sum, stop at the ceiling and it is barely
        // past it. Same instrument as the section walk.
        let over = MAX_REQUEST_METADATA_BYTES / DROPPED_PAIR_BYTES * 16;
        let mut swarm = get("/hello/greet");
        swarm.headers = std::iter::repeat_with(|| ("cookie".to_owned(), String::new()))
            .take(over)
            .collect();

        let counted = request_metadata_bytes(&swarm);
        let whole_list = over.saturating_mul(DROPPED_PAIR_BYTES);
        assert!(
            counted <= MAX_REQUEST_METADATA_BYTES + DROPPED_PAIR_BYTES,
            "the walk counted {counted} bytes, past the ceiling plus the entry \
             that crossed it — it finished the list instead of stopping",
        );
        assert!(
            counted < whole_list / 2,
            "the walk counted {counted} of a {whole_list}-byte list, so it did \
             not stop early",
        );

        // Stopping early must not stop it refusing.
        let host = host(guests::HELLO);
        let err = host
            .run(&swarm)
            .result
            .expect_err("a list past the ceiling must still be refused");
        assert!(
            matches!(err, SandboxFailure::RequestMetadataBudget { .. }),
            "{err:?}",
        );

        // And a request under the ceiling is still counted in full, or the
        // charge the ceiling is made of would be wrong for every real request.
        let mut ordinary = get("/hello/greet");
        ordinary.headers = vec![("accept".to_owned(), "text/plain".to_owned())];
        assert_eq!(
            request_metadata_bytes(&ordinary),
            ordinary.method.len()
                + ordinary.path.len()
                + ordinary.query.len()
                + ordinary.route.len()
                + metadata_pair_bytes("accept", "text/plain"),
        );
    }

    #[test]
    fn a_header_the_frame_drops_still_costs_its_place_in_the_list() {
        // Not charging a dropped header's *contents* is right — they never
        // cross. Not charging it at all left the count unbounded, which is a
        // different resource: the list is walked once for the ceiling, once to
        // price the encoding, and once to filter it out, all before a permit is
        // taken and before the guest spends any fuel. So a million empty
        // `Cookie` pairs passed a byte ceiling for free and bought three
        // unbounded scans per request, per concurrent caller.
        let host = host(guests::HELLO);

        // Still admitted: bulk in a dropped header is bulk that costs the guest
        // nothing, and refusing it would make withholding a credential into a
        // reason to fail the request.
        let mut one_huge_cookie = get("/hello/greet");
        one_huge_cookie.headers =
            vec![("cookie".to_owned(), "s=".repeat(MAX_REQUEST_METADATA_BYTES))];
        assert!(
            host.run(&one_huge_cookie).result.is_ok(),
            "one large dropped header must still be served",
        );

        // Refused: the same total, spread across entries instead of into one
        // value. Nothing here reaches the guest either, but the host walks
        // every one of them to establish that.
        let many_empty_cookies: Vec<(String, String)> =
            std::iter::repeat_with(|| ("cookie".to_owned(), String::new()))
                .take(MAX_REQUEST_METADATA_BYTES / DROPPED_PAIR_BYTES + 1)
                .collect();
        let mut swarm = get("/hello/greet");
        swarm.headers = many_empty_cookies;
        let err = host
            .run(&swarm)
            .result
            .expect_err("an unbounded list of dropped headers must be refused");
        assert!(
            matches!(err, SandboxFailure::RequestMetadataBudget { .. }),
            "{err:?}",
        );
    }

    #[test]
    fn an_active_offset_this_cannot_evaluate_is_refused_rather_than_skipped() {
        // The extended-const fix closed the door where the walk failed. This is the
        // other door: the walk succeeds and an active segment's offset cannot be
        // evaluated. The old code reported that as "no active write to measure",
        // indistinguishable from a passive-only section, so the segment was copied in
        // at instantiation with nothing having checked where it lands. The expression
        // below is flat rather than folded: every operand is pushed before any add
        // runs, so it is the stack that is exceeded, not the parser. wasmi compiles it
        // happily.
        let mut operands = String::new();
        for _ in 0..24 {
            operands.push_str("i32.const 0 ");
        }
        let mut adds = String::new();
        for _ in 0..24 {
            adds.push_str("i32.add ");
        }
        let wat = format!(
            r#"(module
  (memory (export "memory") 1)
  (data (offset i32.const 65536 {operands} {adds}) "xx")
  (func (export "_start") (nop))
)"#
        );
        let wasm = wat::parse_str(&wat).expect("the fixture is valid WAT");

        let mut config = wasmi::Config::default();
        config.consume_fuel(true);
        wasmi::Module::new(&wasmi::Engine::new(&config), &wasm[..])
            .expect("wasmi compiles a deep extended-const offset; the finding depends on it");

        let shape = module_shape(&wasm).expect("the section still walks cleanly");
        assert_eq!(
            shape.data_end,
            u64::MAX,
            "an offset that cannot be evaluated must be treated as one that cannot fit",
        );
        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("an active segment with an unevaluable offset must be refused");
        assert!(
            matches!(err, SandboxLoadError::SegmentOutOfBounds { .. }),
            "{err:?}",
        );

        // And the refusal is about *active* segments, not about the evaluator
        // giving up: the same unevaluable expression on a passive segment is
        // copied by nothing at instantiation, so it still loads.
        let passive = wat::parse_str(
            r#"(module
  (memory (export "memory") 1)
  (data "passive, and its offset is not a question")
  (func (export "_start") (nop))
)"#,
        )
        .expect("the fixture is valid WAT");
        SandboxHost::from_module(manifest_with(ResourceLimits::default()), &passive)
            .expect("a passive segment must still load");
    }

    #[test]
    fn a_passive_only_data_section_is_not_a_walk_that_failed() {
        // `data_section_end` has two ways of saying nothing: the walk failed, or the
        // walk succeeded and there was no active write to measure. The fail-closed
        // fallback added for extended-const offsets read both as the first and refused
        // a perfectly runnable module — a passive segment is copied only by an explicit
        // `memory.init`, never at instantiation, so it cannot be out of bounds there.
        // The three outcomes are pinned together here because the bug was exactly their
        // collapse into two.
        let passive_only = wat::parse_str(
            r#"(module
  (memory (export "memory") 1)
  (data "passive bytes")
  (func (export "_start") (nop))
)"#,
        )
        .expect("the fixture is valid WAT");
        let shape = module_shape(&passive_only).expect("the section walks cleanly");
        assert_eq!(
            shape.data_end, 0,
            "a passive segment measures nothing, so it must contribute nothing",
        );
        SandboxHost::from_module(manifest_with(ResourceLimits::default()), &passive_only)
            .expect("a passive-only module must still load");

        // An active segment beside it is still measured, so "nothing to
        // measure" cannot become "measure nothing".
        let mixed = wat::parse_str(
            r#"(module
  (memory (export "memory") 1)
  (data "passive bytes")
  (data (offset (i32.const 16)) "active")
  (func (export "_start") (nop))
)"#,
        )
        .expect("the fixture is valid WAT");
        let shape = module_shape(&mixed).expect("the section walks cleanly");
        assert_eq!(
            shape.data_end, 22,
            "the active segment's end must survive the passive one beside it",
        );

        // And an active segment past the memory is still refused, so the
        // assertions above cannot be satisfied by simply never refusing.
        let out_of_bounds = wat::parse_str(
            r#"(module
  (memory (export "memory") 1)
  (data "passive bytes")
  (data (offset (i32.const 65535)) "spills")
  (func (export "_start") (nop))
)"#,
        )
        .expect("the fixture is valid WAT");
        let err =
            SandboxHost::from_module(manifest_with(ResourceLimits::default()), &out_of_bounds)
                .expect_err("an active segment past the end of memory must be refused");
        assert!(
            matches!(err, SandboxLoadError::SegmentOutOfBounds { .. }),
            "{err:?}",
        );
    }

    #[test]
    fn an_extended_const_segment_offset_is_evaluated_rather_than_waved_through() {
        // wasmi enables the extended-const proposal by default, so an active
        // data offset need not be a bare `i32.const`. Against a reader that
        // knew only the bare form this was not merely unevaluable: the walk did
        // not know `i32.add` either, so it desynced, the whole data section
        // returned nothing, and `data_end` stayed at zero. The bounds check did
        // not run — and packaging and `plugin inspect` then approved an
        // artifact whose every request would fail at instantiation, which is
        // precisely what checking at load is for.
        let out_of_bounds = wat::parse_str(
            r#"(module
  (memory (export "memory") 1)
  (data (offset (i32.add (i32.const 65535) (i32.const 2))) "xx")
  (func (export "_start") (nop))
)"#,
        )
        .expect("the fixture is valid WAT");

        // The engine accepts it, which is what makes the gap reachable: if
        // wasmi refused the module this walk's silence would cost nothing.
        let mut config = wasmi::Config::default();
        config.consume_fuel(true);
        wasmi::Module::new(&wasmi::Engine::new(&config), &out_of_bounds[..])
            .expect("wasmi compiles an extended-const offset; the finding depends on it");

        let err =
            SandboxHost::from_module(manifest_with(ResourceLimits::default()), &out_of_bounds)
                .expect_err("a segment past the end of memory must be refused at load");
        // Refused for the true reason, with the offset the arithmetic actually
        // produces — 65535 + 2, plus the two bytes copied there.
        assert!(
            matches!(
                err,
                SandboxLoadError::SegmentOutOfBounds { end, capacity, .. }
                    if end == 65539 && capacity == WASM_PAGE_BYTES
            ),
            "{err:?}",
        );

        // And the arithmetic is *evaluated*, not merely refused for being
        // unfamiliar: the same shape landing inside the memory still loads.
        // Refusing every extended-const module would pass the assertion above
        // and fail this one.
        let in_bounds = wat::parse_str(
            r#"(module
  (memory (export "memory") 1)
  (data (offset (i32.add (i32.const 16) (i32.const 8))) "xx")
  (func (export "_start") (nop))
)"#,
        )
        .expect("the fixture is valid WAT");
        SandboxHost::from_module(manifest_with(ResourceLimits::default()), &in_bounds)
            .expect("an extended-const offset inside the memory must still load");
    }

    #[test]
    fn a_bidi_override_cannot_reorder_the_record_it_appears_in() {
        // `is_control` covers the C0/C1 codes and stops there, so the Unicode
        // formatting characters went into the log verbatim. They do an ESC's job by
        // other means: U+202E reverses everything after it, so a guest can write a
        // detail that reads as a different record than the one the host wrote —
        // including reading as though the denial were an allow. The operator reads that
        // line to decide what happened. The consent screen already refuses these in a
        // route path; a detail is evidence rather than a mount, so here they are
        // escaped instead, and the attempt survives legibly as an attempt.
        let forged = guest_text("denied \u{202E}dewolla\u{202D} by policy");
        assert!(
            !forged.contains('\u{202E}') && !forged.contains('\u{202D}'),
            "a bidi override reached the log verbatim: {forged:?}",
        );
        assert!(
            forged.contains("\\u{202e}"),
            "the attempt must survive as an escape, not be silently dropped: {forged:?}",
        );
        assert!(
            forged.contains("denied") && forged.contains("by policy"),
            "the host's own words must survive: {forged:?}",
        );

        // The whole family, not just the one character: isolates and the
        // zero-width joiners hide a boundary rather than reversing a run, and
        // the log is just as unreadable either way.
        for ch in [
            '\u{061C}', '\u{200B}', '\u{200E}', '\u{200F}', '\u{2060}', '\u{2066}', '\u{2069}',
            '\u{FEFF}',
        ] {
            let out = guest_text(&format!("before{ch}after"));
            assert!(
                !out.contains(ch),
                "U+{:04X} reached the log verbatim: {out:?}",
                ch as u32,
            );
        }

        // And ordinary non-ASCII is still kept — an author debugging a plugin
        // that reports errors in their own language has to be able to read them.
        let readable = guest_text("le module n'a pas démarré — 起動しませんでした");
        assert!(
            readable.contains("démarré") && readable.contains("起動しませんでした"),
            "real text was escaped along with the formatting characters: {readable:?}",
        );
    }

    #[test]
    fn a_unicode_line_break_cannot_forge_a_second_log_record() {
        // The line breaks that are not control characters. U+2028 and U+2029 are
        // general category Zl and Zp, so `is_control` — which answers for Cc —
        // says no, and they are neither format nor default-ignorable, so the
        // reordering predicate says no as well. A log consumer that splits on
        // Unicode line breaks still renders them as a newline, which hands the
        // guest the forged record that escaping C0 exists to deny.
        for ch in ['\u{2028}', '\u{2029}'] {
            assert!(
                !ch.is_control(),
                "U+{:04X} is a control character after all; this test guards the wrong gap",
                ch as u32,
            );
            let split = guest_text(&format!("denied{ch}allowed by policy"));
            assert!(
                !split.contains(ch),
                "U+{:04X} reached the log verbatim: {split:?}",
                ch as u32,
            );
            assert!(
                split.contains(&format!("\\u{{{:x}}}", ch as u32)),
                "the attempt must survive as an escape, not be dropped: {split:?}",
            );
        }
    }

    #[test]
    fn generating_a_random_byte_costs_more_than_copying_one() {
        // `BYTES_PER_FUEL` is a bulk-copy rate: a memcpy moves 64 bytes for about what
        // one instruction costs, so charging them to a unit is honest. `random_get` does
        // not copy — every byte is a whole SplitMix64 step, an add, two multiplies, and
        // four shift-XOR pairs. Billing that at the copy rate sold the mixer's work at a
        // memcpy's price while the guest held a blocking worker for it. Measured through
        // the fuel the host actually charges, because that is the thing that was wrong:
        // an earlier version of this test compared two constants it computed itself,
        // passed against its own revert, and never ran `random_get` at all.
        fn drawing(bytes: u32) -> u64 {
            let wat = format!(
                r#"(module
  (import "wasi_snapshot_preview1" "random_get" (func $random_get (param i32 i32) (result i32)))
  (memory (export "memory") 2)
  (func (export "_start")
    (drop (call $random_get (i32.const 4096) (i32.const {bytes}))))
)"#
            );
            // The guest never answers, which is fine: the outcome carries the
            // fuel spent either way, and the answer is not what is being
            // measured.
            host(&wat).run(&request("GET", "/hello/greet")).fuel_used
        }

        let none = drawing(0);
        let many = drawing(65536);
        let charged = many.saturating_sub(none);

        // At the copy rate 64 KiB is about 1,024 units; per byte it is 65,536.
        // Halfway between separates them without pinning either rate.
        assert!(
            charged > 32768,
            "drawing 64 KiB of entropy cost {charged} fuel — the bulk-copy rate \
             would charge about 1,024, so the mixer's work is being sold at a \
             memcpy's price",
        );
    }

    #[test]
    fn the_pending_frame_never_allocates_past_the_budget_it_is_bounded_by() {
        // The pending-line ceiling bounds the buffer's *length*. Its
        // *capacity* is what the host actually holds, and `Vec`'s doubling puts
        // that at the next power of two above the ceiling — nearly twice the
        // `2 × max_response_bytes` `request_footprint_bytes` reserves for this
        // line, at every concurrent request at once. A bound the allocation can
        // exceed is not the bound the concurrency product was validated
        // against.
        let limits = ResourceLimits {
            // Small enough to fill in a test, and deliberately not a power of
            // two: an unclamped `Vec` lands on 65,536 for this budget, which a
            // ceiling of exactly 65,536 would have let pass.
            max_response_bytes: 20_000,
            ..ResourceLimits::default()
        };
        let budget = limits.max_response_bytes * 2 + 4096;
        let mut state = bare_state(limits, b"");

        // One byte at a time, because that is the growth pattern that doubles:
        // a guest writing its frame through a byte-at-a-time formatter is
        // ordinary, and `write_stdout` sees the bytes either way.
        for _ in 0..budget {
            assert!(state.write_stdout(b"x"), "the budget refused a legal frame");
        }
        assert_eq!(state.stdout_line.len(), budget, "the buffer did not fill");
        assert!(
            state.stdout_line.capacity() <= budget,
            "a {budget}-byte ceiling holds {} bytes of allocation",
            state.stdout_line.capacity(),
        );

        // …and the ceiling still stops the next byte, so bounding the
        // allocation did not cost the refusal it exists for.
        assert!(
            !state.write_stdout(b"x"),
            "a frame past the ceiling was accepted",
        );
    }

    #[test]
    fn one_read_cannot_copy_the_whole_frame_out_of_the_queue() {
        // `fd_write` and `random_get` both bound their scratch to `HOST_IO_CHUNK_BYTES`,
        // and `FIXED_HOST_BUFFER_BYTES` budgets exactly one such buffer. The read path
        // did not: the iovec length is the guest's to choose, so one iovec spanning the
        // whole frame made a second copy of it, live beside the queue it was copied out
        // of, which keeps its allocation as it drains. A frame is metadata plus a base64
        // body with JSON escaping over both, so that copy is several times the raw
        // request, and none of it was in the footprint the concurrency product is
        // validated against. Returning less than was asked for is what the call already
        // promises: the queue running dry short-reads today, so a guest that does not
        // loop is already broken.
        let mut state = bare_state(ResourceLimits::default(), b"");
        state.stdin = VecDeque::from(vec![b'x'; HOST_IO_CHUNK_BYTES * 4]);

        let chunk = state.take_stdin(HOST_IO_CHUNK_BYTES * 4);
        assert_eq!(
            chunk.len(),
            HOST_IO_CHUNK_BYTES,
            "one read copied more than the scratch the footprint budgets",
        );

        // And the rest is still there to be read, one bounded chunk at a time,
        // so bounding the copy did not lose the frame.
        let mut drained = chunk.len();
        while !state.stdin.is_empty() {
            let next = state.take_stdin(HOST_IO_CHUNK_BYTES * 4);
            assert!(
                !next.is_empty(),
                "the queue stopped yielding with bytes left"
            );
            drained += next.len();
        }
        assert_eq!(
            drained,
            HOST_IO_CHUNK_BYTES * 4,
            "the frame did not survive being read in chunks",
        );

        // A read smaller than the bound is unaffected — the cap is a ceiling,
        // not a quantum.
        let mut small = bare_state(ResourceLimits::default(), b"");
        small.stdin = VecDeque::from(b"{\"op\":\"request\"}".to_vec());
        assert_eq!(small.take_stdin(4).len(), 4, "a short read must stay short");
    }

    #[test]
    fn a_cut_stderr_excerpt_says_that_it_was_cut() {
        // `guest_text` appends " … (truncated)" when it meets a 513th
        // character, and `stderr_excerpt` hands it at most 512 — so on this
        // path the marker could never fire, and a flood that lost its most
        // recent output read as though the guest had simply stopped there. The
        // suffix is usually the interesting part of a failure.
        let mut state = bare_state(ResourceLimits::default(), b"");
        state.write_stderr("a".repeat(STDERR_EXCERPT * 2).as_bytes());
        let excerpt = state.stderr_excerpt();
        assert!(
            excerpt.ends_with(" … (truncated)"),
            "a cut excerpt must say so: {:?}",
            excerpt.get(excerpt.len().saturating_sub(40)..),
        );

        // And an excerpt that fits says nothing of the kind — the marker has to
        // mean something.
        let mut short = bare_state(ResourceLimits::default(), b"");
        short.write_stderr(b"panicked at the disco");
        let whole = short.stderr_excerpt();
        assert_eq!(
            whole, "panicked at the disco",
            "an excerpt that fits is untouched"
        );
    }

    #[test]
    fn the_streamed_lossy_decode_says_what_from_utf8_lossy_says() {
        // The excerpt is now decoded lazily so a 64 KiB stderr of invalid bytes
        // never becomes a 192 KiB replacement string. That is only an
        // improvement if it decodes to the same characters, and the sharp edge
        // is *grouping*: `from_utf8_lossy` emits one U+FFFD per maximal invalid
        // subpart, not per byte, so a truncated three-byte sequence is one
        // replacement and two stray continuation bytes are two.
        for case in [
            b"".as_slice(),
            b"plain ascii",
            b"\xff",
            b"\xff\xff\xff",
            // A truncated 3-byte sequence: one maximal subpart.
            b"\xe2\x82",
            // The same, followed by a valid character.
            b"\xe2\x82x",
            // Stray continuation bytes: one subpart each.
            b"\x80\x80",
            // Valid multi-byte text either side of a bad byte.
            "é日本".as_bytes(),
            b"caf\xe9 latte",
            // An overlong encoding, which is invalid however it looks.
            b"\xc0\xaf",
        ] {
            let streamed: String = lossy_chars(case).collect();
            assert_eq!(
                streamed,
                String::from_utf8_lossy(case),
                "streamed decode diverged on {case:?}",
            );
        }
    }

    #[test]
    fn a_stderr_of_invalid_bytes_is_still_bounded_at_the_excerpt() {
        // The flood the streaming exists for: a full budget of bytes that are
        // each their own invalid subpart, so the lossy form is three times the
        // buffer. What is kept is still one excerpt.
        let mut state = bare_state(ResourceLimits::default(), b"");
        state.write_stderr(&vec![0xff; STDERR_BUDGET_BYTES * 2]);
        assert_eq!(
            state.stderr.len(),
            STDERR_BUDGET_BYTES,
            "the buffer itself must still be capped",
        );
        let excerpt = state.stderr_excerpt();
        assert!(
            excerpt.chars().count() <= DETAIL_EXCERPT + " … (truncated)".len(),
            "the excerpt outgrew its bound: {} characters",
            excerpt.chars().count(),
        );
        // Kept verbatim rather than escaped, and deliberately so: U+FFFD is
        // neither a control nor default-ignorable nor display-reordering — it
        // is a visible glyph that says "there was a byte here that was not
        // text", which is exactly what the operator should see.
        assert!(
            excerpt.contains(char::REPLACEMENT_CHARACTER),
            "the replacement characters did not survive: {excerpt:?}",
        );
    }

    #[test]
    fn stderr_is_escaped_as_well_as_bounded() {
        // Same hazard, same answer: stderr was truncated but not neutralised,
        // so a guest could forge a record inside its 512-character excerpt.
        let mut state = bare_state(ResourceLimits::default(), b"");
        state.write_stderr(b"panicked\n2026-01-01  INFO forged\x1b[2K");
        let excerpt = state.stderr_excerpt();
        assert!(
            !excerpt.contains('\n') && !excerpt.contains('\u{1b}'),
            "{excerpt:?}"
        );
        assert!(excerpt.contains("panicked"), "{excerpt:?}");
    }

    #[test]
    fn a_manifest_mutated_after_validation_is_refused_rather_than_trusted() {
        // `SandboxManifest`'s fields are public and `from_module` is public, so
        // "the manifest was validated when it was parsed" is an invariant a
        // caller can step around without meaning to. The values that matter
        // here are the ones that panic something downstream rather than merely
        // misbehaving: a concurrency past the semaphore's ceiling, and a route
        // path axum refuses to build.
        let wasm = wat::parse_str(guests::HELLO).expect("the fixture is valid WAT");

        let mut manifest = manifest_with(ResourceLimits::default());
        manifest.limits.max_concurrency = usize::MAX;
        let err = SandboxHost::from_module(manifest, &wasm)
            .expect_err("an invalid manifest must not produce a host");
        assert!(matches!(err, SandboxLoadError::InvalidManifest(_)), "{err}");

        let mut manifest = manifest_with(ResourceLimits::default());
        manifest.routes[0].path = "/{".to_owned();
        let err = SandboxHost::from_module(manifest, &wasm)
            .expect_err("an unbuildable route must not produce a host");
        assert!(matches!(err, SandboxLoadError::InvalidManifest(_)), "{err}");
    }

    #[test]
    fn encoding_the_request_frame_is_priced_before_it_is_performed() {
        // The body is cloned into the frame and base64-expanded into the NDJSON
        // line before a single guest instruction runs. With a large body
        // ceiling and a small fuel budget that is megabytes of host CPU outside
        // the declared ceiling, repeatable for as long as a client keeps
        // sending.
        let host = host(guests::HELLO);
        let mut request = get("/hello/greet");
        request.body = vec![b'x'; 200_000];

        // Just above the load-time floor, so the host exists — and far below
        // what encoding this body costs, which is the point.
        let starved = try_host_with(
            guests::HELLO,
            ResourceLimits {
                fuel: host.instantiation_fuel() + 1,
                ..ResourceLimits::default()
            },
        )
        .expect("the fixture loads");
        let outcome = starved.run(&request);
        assert!(
            matches!(outcome.result, Err(SandboxFailure::FuelExhausted { .. })),
            "{:?}",
            outcome.result
        );

        // And an honest request pays for it rather than getting it free.
        let outcome = host.run(&request);
        assert!(
            outcome.fuel_used >= 200_000 / BYTES_PER_FUEL,
            "the encoding was not charged: {} units",
            outcome.fuel_used
        );
    }

    #[test]
    fn a_direct_caller_cannot_start_more_instances_than_the_manifest_allows() {
        // `SandboxedPlugin::serve` has a semaphore of its own, so HTTP traffic
        // is bounded. `run` is public, though, and an embedder calling it
        // directly used to bypass admission entirely — while the manifest
        // validator accepts limits on the premise that
        // `request_footprint_bytes() × max_concurrency` bounds the plugin.
        let host = try_host_with(
            guests::HELLO,
            ResourceLimits {
                max_concurrency: 1,
                ..ResourceLimits::default()
            },
        )
        .expect("the fixture loads");

        // Hold the only permit, exactly as an in-flight request would, rather
        // than racing a real one: the property is the admission, not the race.
        let held = host
            .permits
            .try_acquire()
            .expect("the first permit is free");
        assert_eq!(
            host.run(&get("/hello/greet")).result,
            Err(SandboxFailure::AtCapacity { max: 1 }),
            "a second concurrent run was admitted past max_concurrency = 1"
        );

        // And the permit comes back: the ceiling is on requests executing at
        // once, not a budget the plugin spends down.
        drop(held);
        assert!(
            host.run(&get("/hello/greet")).result.is_ok(),
            "the permit was not returned when the run finished"
        );
    }

    #[test]
    fn a_fuel_budget_that_cannot_reach_start_is_refused_at_load() {
        // `fuel = 1` passes the manifest's own range check, and every request
        // then spends the instantiation charge before `_start` — so every route
        // the manifest declares answers 504, always. `inspect` reporting that
        // artifact as loadable is worse than reporting nothing, because an
        // operator installs on the strength of the verdict.
        let err = try_host_with(
            guests::HELLO,
            ResourceLimits {
                fuel: 1,
                ..ResourceLimits::default()
            },
        )
        .expect_err("a budget below the fixed charges must not produce a host");
        let SandboxLoadError::FuelBelowFixedCharges {
            fuel,
            instantiation,
        } = err
        else {
            panic!("expected the fuel refusal, got {err:?}");
        };
        assert_eq!(fuel, 1);
        assert!(
            instantiation >= 1,
            "the charge must be real to refuse against"
        );

        // And a budget that clears the charge still loads: this is a floor, not
        // a demand for the default.
        assert!(
            try_host_with(
                guests::HELLO,
                ResourceLimits {
                    fuel: instantiation + 1,
                    ..ResourceLimits::default()
                },
            )
            .is_ok(),
            "a budget just above the fixed charge is legal"
        );
    }

    #[test]
    fn the_import_list_a_review_surface_shows_is_bounded() {
        // Each name is excerpted where it is rendered, but the *count* is a
        // separate amplification: a legal module can carry far more imports
        // than a person will read, and formatting each into its own `String`
        // turns the artifact into memory in the process refusing it.
        let imports = (0..MAX_REPORTED_IMPORTS + 50)
            .map(|n| format!(r#"  (import "env" "f{n}" (func))"#))
            .collect::<Vec<_>>()
            .join("\n");
        let wat = format!("(module\n{imports}\n  (func (export \"_start\") (nop)))");
        let wasm = wat::parse_str(&wat).expect("the fixture is valid WAT");

        let listed = SandboxHost::imports_of(&wasm).expect("a module's imports can be read");
        assert!(
            listed.len() <= MAX_REPORTED_IMPORTS + 1,
            "the list is unbounded: {} entries",
            listed.len()
        );
        // The operator must not read a truncated list as the whole of it.
        let last = listed.last().expect("a non-empty list");
        assert!(last.contains("truncated") && last.contains("50"), "{last}");
    }

    #[test]
    fn a_module_declaring_more_imports_than_the_ceiling_is_refused_at_load() {
        // The reporting cap bounds the *review surface*; it does nothing for the
        // runtime path, where every import is resolved and retained per
        // instance — per request. A module repeating one allowlisted import
        // makes every request pay for those resolutions, and neither the fuel
        // charge nor `request_footprint_bytes` knew about them.
        let imports = (0..=MAX_IMPORTS)
            .map(|_| {
                format!(
                    r#"  (import "{WASI}" "fd_write" (func (param i32 i32 i32 i32) (result i32)))"#
                )
            })
            .collect::<Vec<_>>()
            .join("\n");
        let wat = format!(
            "(module\n{imports}\n  (memory (export \"memory\") 1)\n  (func (export \"_start\") (nop)))"
        );
        let wasm = wat::parse_str(&wat).expect("the fixture is valid WAT");

        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("a module past the import ceiling must not load");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive {
                    what: "imports",
                    ..
                }
            ),
            "{err:?}"
        );
        // Every import here is allowlisted, so nothing but the *count* refuses
        // it: the ceiling is structural, not a second spelling of the
        // capability gate.
    }

    #[test]
    fn the_import_ceiling_does_not_weaken_the_forbidden_import_gate() {
        // A module hiding one forbidden import behind a crowd is still refused;
        // the count check running first changes why, never whether.
        let mut lines = (0..=MAX_IMPORTS)
            .map(|_| {
                format!(
                    r#"  (import "{WASI}" "fd_write" (func (param i32 i32 i32 i32) (result i32)))"#
                )
            })
            .collect::<Vec<_>>();
        lines.push(r#"  (import "env" "escape" (func))"#.to_owned());
        let wat = format!(
            "(module\n{}\n  (memory (export \"memory\") 1)\n  (func (export \"_start\") (nop)))",
            lines.join("\n")
        );
        let wasm = wat::parse_str(&wat).expect("the fixture is valid WAT");
        assert!(
            SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm).is_err(),
            "a module carrying a forbidden import must never load"
        );
    }

    #[test]
    fn resolving_imports_is_priced_into_the_instantiation_charge() {
        // Per-instance work the guest never executes but every request pays
        // for. Unpriced, it is host CPU bought for free — the same defect the
        // host-side copying charge exists to close.
        let bare = wat::parse_str(
            "(module (memory (export \"memory\") 1) (func (export \"_start\") (nop)))",
        )
        .expect("the fixture is valid WAT");
        let imports = (0..32)
            .map(|_| {
                format!(
                    r#"  (import "{WASI}" "fd_write" (func (param i32 i32 i32 i32) (result i32)))"#
                )
            })
            .collect::<Vec<_>>()
            .join("\n");
        let with_imports = wat::parse_str(format!(
            "(module\n{imports}\n  (memory (export \"memory\") 1)\n  (func (export \"_start\") (nop)))"
        ))
        .expect("the fixture is valid WAT");

        let cheap = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &bare)
            .expect("loads")
            .instantiation_fuel();
        let dear =
            SandboxHost::from_module(manifest_with(ResourceLimits::default()), &with_imports)
                .expect("loads")
                .instantiation_fuel();
        assert_eq!(
            dear,
            cheap + 32,
            "each admitted import must cost a unit: {cheap} then {dear}"
        );
    }

    #[test]
    fn a_module_pays_instantiation_fuel_for_the_memory_it_starts_with() {
        // A module can declare a large initial linear memory and no data segments at
        // all, so every init-section term prices none of it — and the host still
        // allocates and zero-fills the whole thing on each request, before the guest
        // runs an instruction. That is host work proportional to a guest-declared
        // quantity, exactly what the copying charge exists to make cost something. The
        // limiter already bounds how much memory; it cannot bound how often a client
        // asks for it to be zeroed.
        let limits = ResourceLimits {
            memory_bytes: 64 * 1024 * 1024,
            ..ResourceLimits::default()
        };
        let one_page = wat::parse_str(
            r#"(module (memory (export "memory") 1) (func (export "_start") (nop)))"#,
        )
        .expect("the fixture is valid WAT");
        // 512 pages = 32 MiB, under the ceiling above and carrying no segments.
        let many_pages = wat::parse_str(
            r#"(module (memory (export "memory") 512) (func (export "_start") (nop)))"#,
        )
        .expect("the fixture is valid WAT");

        let small = SandboxHost::from_module(manifest_with(limits), &one_page)
            .expect("loads")
            .instantiation_fuel();
        let large = SandboxHost::from_module(manifest_with(limits), &many_pages)
            .expect("loads")
            .instantiation_fuel();

        // 511 extra pages of memory to zero, at the same rate as every other
        // host-side byte.
        let extra = (511 * WASM_PAGE_BYTES) / BYTES_PER_FUEL;
        assert_eq!(
            large,
            small + extra,
            "initial memory is not charged: {small} then {large}"
        );
        assert!(
            extra > 0,
            "the fixture must differ by something the charge can see"
        );
    }

    #[test]
    fn a_metadata_list_of_empty_pairs_is_charged_for_its_structure() {
        // Summing only the contents leaves a million empty pairs weighing
        // nothing: past a byte ceiling for free, then cloned into the frame and
        // expanded into real JSON syntax anyway. The same shape as a response
        // frame full of `["",""]`, and it has to be priced on this side too.
        let host = host(guests::HELLO);
        let mut request = get("/hello/greet");
        request.path_params = vec![(String::new(), String::new()); 100_000];

        let err = host
            .run(&request)
            .result
            .expect_err("a list of empty pairs must not be free");
        assert!(
            matches!(err, SandboxFailure::RequestMetadataBudget { .. }),
            "{err:?}"
        );
    }

    #[test]
    fn a_module_whose_tables_start_over_the_ceiling_is_refused_at_load() {
        // The limiter enforces the table ceiling at instantiation, which is per
        // request — so a module already over it at rest loaded cleanly and then
        // failed every request. Same defect as a fuel budget below the fixed
        // charges: a passing verdict on an artifact that can never answer.
        let over = MAX_TABLE_ELEMENTS + 1;
        let wasm = wat::parse_str(format!(
            "(module (table {over} funcref) (memory (export \"memory\") 1) (func (export \"_start\") (nop)))"
        ))
        .expect("the fixture is valid WAT");

        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("a module over the table ceiling must not load");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive {
                    what: "initial table elements",
                    ..
                }
            ),
            "{err:?}"
        );
    }

    #[test]
    fn an_element_expression_whose_operand_is_the_end_opcode_still_bounds_the_segment() {
        // `ref.func 11` encodes its immediate as 0x0b, the same byte that ends a
        // constant expression. A walk that scans for the terminator instead of
        // decoding stops on that operand, reads every later byte at the wrong
        // offset, bails, and silently drops the bounds check — so a segment past
        // the end of its table sails through. Twelve functions, so index 11
        // exists and the expression form is used.
        use std::fmt::Write as _;

        let mut wat =
            String::from("(module\n  (memory (export \"memory\") 1)\n  (table 1 funcref)\n");
        for i in 0..12 {
            let _ = writeln!(wat, "  (func $f{i} (nop))");
        }
        // Past the end of a one-element table, with a `ref.func 11` item.
        wat.push_str("  (elem (i32.const 1) funcref (ref.func $f11))\n");
        wat.push_str("  (func (export \"_start\") (nop))\n)");
        let wasm = wat::parse_str(&wat).expect("the fixture is valid WAT");

        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("the operand must not be mistaken for the terminator");
        assert!(
            matches!(err, SandboxLoadError::SegmentOutOfBounds { .. }),
            "{err:?}"
        );
    }

    #[test]
    fn an_element_segment_past_the_end_of_its_table_is_refused_at_load() {
        // The exact sibling of the data-segment case: an active element segment
        // is written into its table during instantiation, so one that does not
        // fit compiles clean and fails every request. Fixing segments into
        // memory without fixing segments into tables would have left half the
        // defect in place.
        let wat = r#"(module
             (memory (export "memory") 1)
             (table 1 funcref)
             (func $f (nop))
             (elem (i32.const 1) $f)
             (func (export "_start") (nop)))"#;
        let wasm = wat::parse_str(wat).expect("the fixture is valid WAT");

        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("a segment past the end of its table must not load");
        assert!(
            matches!(err, SandboxLoadError::SegmentOutOfBounds { .. }),
            "{err:?}"
        );
    }

    #[test]
    fn a_module_carrying_a_start_section_is_refused() {
        // The engine runs a `start` function at instantiation, before any
        // request. If it traps the plugin can never answer, and the only way to
        // find out at load would be to execute an unaudited artifact's code
        // while inspecting it. A sandboxed plugin answers through the exported
        // `_start` the shim calls, so the section has no legitimate use here.
        let wat = r#"(module
             (memory (export "memory") 1)
             (func $init (nop))
             (start $init)
             (func (export "_start") (nop)))"#;
        let wasm = wat::parse_str(wat).expect("the fixture is valid WAT");

        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("a start section must not load");
        assert!(
            matches!(err, SandboxLoadError::StartSectionForbidden),
            "{err:?}"
        );
    }

    #[test]
    fn a_negative_segment_offset_is_refused_rather_than_ignored() {
        // A wasm offset is unsigned: `i32.const -1` means 4294967295, which is
        // out of bounds for anything this sandbox admits. Reading it as a
        // *signed* value and dropping it when the conversion failed meant the
        // one offset guaranteed to be invalid was the one the walk called
        // unevaluable — a fail-open in the check meant to catch exactly this.
        let wat = r#"(module
             (memory (export "memory") 1)
             (data (i32.const -1) "x")
             (func (export "_start") (nop)))"#;
        let wasm = wat::parse_str(wat).expect("the fixture is valid WAT");

        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("a negative offset must not load");
        assert!(
            matches!(err, SandboxLoadError::SegmentOutOfBounds { .. }),
            "{err:?}"
        );
    }

    #[test]
    fn a_data_segment_past_the_end_of_memory_is_refused_at_load() {
        // An active segment is copied in during instantiation, which is per
        // request. One that does not fit the module's own initial memory
        // compiles clean and then fails every instantiation, so the artifact
        // inspects green and 502s forever — the same shape as a fuel budget
        // below the fixed charges.
        let wat = r#"(module
             (memory (export "memory") 1)
             (data (i32.const 65536) "x")
             (func (export "_start") (nop)))"#;
        let wasm = wat::parse_str(wat).expect("the fixture is valid WAT");

        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("a segment past the end of memory must not load");
        assert!(
            matches!(err, SandboxLoadError::SegmentOutOfBounds { .. }),
            "{err:?}"
        );
    }

    #[test]
    fn the_segment_ceiling_is_enforced_by_the_pre_compilation_gate() {
        // Not merely "the module is refused" — where it is refused is the point.
        // `from_module` calls `refuse_unbounded_shape` before `Module::new` precisely
        // because compiling is what builds a representation of every declaration, so a
        // ceiling checked after it is checked too late. These two ceilings were checked
        // after it, under a comment saying they must not be. A module can sit over
        // `MAX_INIT_SEGMENTS` (4,096) and still be far under `MAX_DECLARED_ENTRIES`
        // (1,000,000), so nothing else refused it first and wasmi expanded every segment
        // before the answer came back. Asserting through `refuse_unbounded_shape`
        // directly is what makes this about ordering: the gate that runs first has to be
        // the one that says no.
        use std::fmt::Write as _;

        let mut wat = String::from("(module\n  (memory (export \"memory\") 1)\n");
        for offset in 0..=MAX_INIT_SEGMENTS {
            let _ = writeln!(wat, "  (data (i32.const {offset}) \"x\")");
        }
        wat.push_str("  (func (export \"_start\") (nop))\n)");
        let wasm = wat::parse_str(&wat).expect("the fixture is valid WAT");

        let err = refuse_unbounded_shape(&wasm)
            .expect_err("the pre-compilation gate must refuse the segment count");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive {
                    what: "data and element segments",
                    ..
                }
            ),
            "{err:?}"
        );
        // And the fixture really is under the aggregate ceiling, so it is this
        // check refusing it and not the entry one standing in.
        let shape = module_shape(&wasm).expect("the fixture walks");
        assert!(
            shape.declared_entries <= MAX_DECLARED_ENTRIES,
            "the fixture would have been refused for its entry count anyway"
        );
    }

    #[test]
    fn a_module_past_the_segment_ceiling_is_refused_without_walking_its_segments() {
        // The count check runs before the per-segment walks now, because the walk was
        // work an artifact could buy at two bytes a segment purely to reach the refusal
        // that exists to bound it. The risk in skipping a walk is that the walk was also
        // doing a bounds check — the fail-open shape this file has been bitten by twice.
        // So the case that matters is a module over the ceiling that also carries a
        // segment past the end of its memory: it must still be refused. The sibling
        // tests above cover the other side, that a module under the ceiling is still
        // walked and still caught.
        use std::fmt::Write as _;

        let mut wat = String::from("(module\n  (memory (export \"memory\") 1)\n");
        // Past the end of the single page this module declares.
        let _ = writeln!(wat, "  (data (i32.const 65536) \"x\")");
        for offset in 0..=MAX_INIT_SEGMENTS {
            let _ = writeln!(wat, "  (data (i32.const {offset}) \"x\")");
        }
        wat.push_str("  (func (export \"_start\") (nop))\n)");
        let wasm = wat::parse_str(&wat).expect("the fixture is valid WAT");

        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("a module past the segment ceiling must not load");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive {
                    what: "data and element segments",
                    ..
                }
            ),
            "{err:?}"
        );
    }

    #[test]
    fn a_module_declaring_more_tables_than_the_ceiling_is_refused_on_the_count() {
        // The same ordering, on the table walk — which the review named only
        // for elements and data, but which this loop shares. Its own comment
        // already said a 64 MiB artifact of empty table declarations must not
        // expand here; bounding the per-entry *allocation* left the per-entry
        // *iteration* unbounded, at three bytes an entry.
        use std::fmt::Write as _;

        let mut wat = String::from("(module\n  (memory (export \"memory\") 1)\n");
        for _ in 0..=MAX_TABLES {
            let _ = writeln!(wat, "  (table 1 funcref)");
        }
        wat.push_str("  (func (export \"_start\") (nop))\n)");
        let wasm = wat::parse_str(&wat).expect("the fixture is valid WAT");

        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("a module past the table ceiling must not load");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive { what: "tables", .. }
            ),
            "{err:?}"
        );
    }

    #[test]
    fn a_module_whose_code_section_is_too_large_is_refused_before_compilation() {
        // One function declares one entry however long its body is, so the
        // declaration ceilings never saw this: a single body filling the file
        // allowance still hands the compiler tens of megabytes to translate.
        // The section header carries the size, so the refusal costs one LEB128
        // and never touches the instruction stream.
        let mut wasm = wat::parse_str(
            "(module (memory (export \"memory\") 1) (func (export \"_start\") (nop)))",
        )
        .expect("the fixture is valid WAT");

        // Rewrite the code section's declared size to just over the ceiling
        // rather than building a module that large: the check reads the header,
        // and a fixture of real instructions would cost the test minutes.
        let over = u32::try_from(MAX_CODE_BYTES + 1).expect("fits");
        let mut header = vec![10u8]; // the code section id
        let mut size = over;
        loop {
            let mut byte = (size & 0x7f) as u8;
            size >>= 7;
            if size != 0 {
                byte |= 0x80;
            }
            header.push(byte);
            if size == 0 {
                break;
            }
        }
        // The bytes have to actually be there: a header claiming a length the
        // file does not carry is refused as malformed, which is a correct
        // refusal but a different one from the ceiling under test.
        header.extend(std::iter::repeat_n(0u8, over as usize));
        wasm.extend_from_slice(&header);

        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("an oversized code section must not reach the compiler");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive {
                    what: "code section bytes",
                    ..
                }
            ),
            "{err:?}"
        );
    }

    #[test]
    fn a_module_whose_global_section_is_too_large_is_refused_before_compilation() {
        // The global section's initializers are an instruction stream —
        // extended-const lets one global's expression run to arbitrary
        // length — but the scanner only recorded the entry count, so a
        // single global with a ceiling-scale initializer sat under every
        // check while handing the compiler that much code to translate.
        // The section header carries the size, so the refusal costs one
        // LEB128 and never touches the instruction stream: the fixture
        // rewrites the global section's declared size rather than building
        // a module that large, the way the code-section test above does.
        let mut wasm = wat::parse_str(
            "(module (memory (export \"memory\") 1) (func (export \"_start\") (nop)))",
        )
        .expect("the fixture is valid WAT");

        // One global, claiming just over the instruction-volume ceiling.
        let over = u32::try_from(MAX_CODE_BYTES + 1).expect("fits");
        let mut header = vec![6u8]; // the global section id
        let mut size = over;
        loop {
            let mut byte = (size & 0x7f) as u8;
            size >>= 7;
            if size != 0 {
                byte |= 0x80;
            }
            header.push(byte);
            if size == 0 {
                break;
            }
        }
        // A count of one, then padding: the bytes have to actually be there,
        // or the header is refused as malformed — a correct refusal, but a
        // different one from the ceiling under test.
        header.push(1u8);
        header.extend(std::iter::repeat_n(0u8, over as usize - 1));
        wasm.extend_from_slice(&header);

        // First the gate itself: this is about ordering, and the gate that
        // runs before `Module::new` has to be the one that says no.
        let err = refuse_unbounded_shape(&wasm)
            .expect_err("an oversized global section must not reach the compiler");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive {
                    what: "code and global section bytes",
                    ..
                }
            ),
            "{err:?}"
        );

        // Then both public doors onto the same bytes.
        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("an oversized global section must not load");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive {
                    what: "code and global section bytes",
                    ..
                }
            ),
            "{err:?}"
        );
        let err =
            SandboxHost::imports_of(&wasm).expect_err("imports_of must apply the same ceiling");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive {
                    what: "code and global section bytes",
                    ..
                }
            ),
            "expected the ceiling on imports_of, got: {err:?}"
        );
    }

    #[test]
    fn a_global_section_at_exactly_the_instruction_ceiling_still_passes_the_gate() {
        // The ceiling is a strict greater-than, so exactly at it must pass.
        // Asserted through the gate directly: `from_module` would then hand
        // the padding to `Module::new`, which refuses the malformed bytes
        // for its own reasons — a correct refusal, but a different one from
        // the ceiling under test.
        let mut wasm = wat::parse_str(
            "(module (memory (export \"memory\") 1) (func (export \"_start\") (nop)))",
        )
        .expect("the fixture is valid WAT");

        // The fixture's own code section counts toward the same ceiling, so
        // the global section fills exactly what it leaves.
        let code_bytes = refuse_unbounded_shape(&wasm)
            .expect("the fixture passes the gate")
            .code_bytes;
        let global_len = MAX_CODE_BYTES - code_bytes;
        let at = u32::try_from(global_len).expect("fits");
        let mut header = vec![6u8]; // the global section id
        let mut size = at;
        loop {
            let mut byte = (size & 0x7f) as u8;
            size >>= 7;
            if size != 0 {
                byte |= 0x80;
            }
            header.push(byte);
            if size == 0 {
                break;
            }
        }
        header.push(1u8);
        header.extend(std::iter::repeat_n(0u8, at as usize - 1));
        wasm.extend_from_slice(&header);

        let shape = refuse_unbounded_shape(&wasm)
            .expect("a global section at exactly the ceiling must pass the gate");
        assert_eq!(
            shape.global_bytes, global_len,
            "the gate must see the section's full size"
        );
        assert_eq!(
            shape.code_bytes.saturating_add(shape.global_bytes),
            MAX_CODE_BYTES,
            "the combined instruction volume sits exactly on the ceiling"
        );
    }

    #[test]
    fn a_module_past_the_byte_ceiling_is_refused_on_the_direct_path_too() {
        // `check_module` applies MAX_MODULE_BYTES to a module the container
        // reader unpacked, but `from_module` and `imports_of` are public and
        // take the bytes directly, so on that path nothing had imposed it. The
        // count ceilings do not close the gap — a module can sit under every
        // one of them and still be enormous, and `Module::new` touches the
        // bytes before any of this build's import checks can refuse them.
        //
        // Padded with a well-formed custom section rather than junk, so the
        // module stays parseable and it is provably the byte ceiling doing the
        // refusing rather than the wasm decoder.
        let base = wat::parse_str(
            "(module (memory (export \"memory\") 1) (func (export \"_start\") (nop)))",
        )
        .expect("the fixture is valid WAT");

        let padding = super::super::MAX_MODULE_BYTES + 1 - base.len();
        let mut section = vec![0x00u8]; // custom section id
        let mut payload = vec![0x04u8]; // name length
        payload.extend_from_slice(b"pad\0");
        payload.resize(payload.len() + padding, 0);
        let mut len = payload.len();
        loop {
            // LEB128 of the payload length.
            let mut byte = u8::try_from(len & 0x7f).expect("masked to 7 bits");
            len >>= 7;
            if len != 0 {
                byte |= 0x80;
            }
            section.push(byte);
            if len == 0 {
                break;
            }
        }
        section.extend_from_slice(&payload);

        let mut wasm = base;
        wasm.extend_from_slice(&section);
        assert!(
            wasm.len() > super::super::MAX_MODULE_BYTES,
            "the fixture must exceed the ceiling: {} bytes",
            wasm.len(),
        );

        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("a module past the byte ceiling must not load");
        assert!(
            matches!(err, SandboxLoadError::ModuleTooLarge { .. }),
            "expected the byte ceiling to refuse it, got: {err}",
        );

        // The review surface is the other public door onto the same bytes, and
        // is exactly where an unaudited artifact would be pointed first.
        let err =
            SandboxHost::imports_of(&wasm).expect_err("imports_of must apply the same ceiling");
        assert!(
            matches!(err, SandboxLoadError::ModuleTooLarge { .. }),
            "expected the byte ceiling on imports_of, got: {err}",
        );
    }

    #[test]
    fn a_module_defining_more_functions_than_the_ceiling_is_refused_at_load() {
        // Neither general ceiling bounds these: a flood of tiny functions sits
        // under both the aggregate declared-entry cap and the code-section byte
        // cap, because each is a couple of bytes of body and one byte of type
        // index — while every instance still allocates an entry per function.
        // The section header carries the count, so the refusal reads one LEB128.
        use std::fmt::Write as _;

        let mut wat = String::from("(module\n  (memory (export \"memory\") 1)\n");
        for i in 0..=MAX_FUNCTIONS {
            let _ = writeln!(wat, "  (func $f{i} (nop))");
        }
        wat.push_str("  (func (export \"_start\") (nop))\n)");
        let wasm = wat::parse_str(&wat).expect("the fixture is valid WAT");

        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("a module past the function ceiling must not load");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive {
                    what: "functions",
                    ..
                }
            ),
            "{err:?}"
        );
    }

    #[test]
    fn a_module_declaring_more_globals_than_the_ceiling_is_refused_at_load() {
        // Every instance allocates and initialises its own copy of each global,
        // and an instance is per request. The aggregate declared-entry ceiling
        // is far too generous to bound them: a module can sit well under a
        // million total entries and still carry hundreds of thousands of
        // globals, which no fuel charge priced and no footprint counted.
        use std::fmt::Write as _;

        let mut wat = String::from("(module\n  (memory (export \"memory\") 1)\n");
        for _ in 0..=MAX_GLOBALS {
            let _ = writeln!(wat, "  (global i32 (i32.const 0))");
        }
        wat.push_str("  (func (export \"_start\") (nop))\n)");
        let wasm = wat::parse_str(&wat).expect("the fixture is valid WAT");

        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("a module past the globals ceiling must not load");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive {
                    what: "globals",
                    ..
                }
            ),
            "{err:?}"
        );
    }

    #[test]
    fn globals_are_priced_into_the_instantiation_charge() {
        // Per-instance work the guest never executes but every request pays
        // for — the same reason segments and imports are charged.
        use std::fmt::Write as _;

        let bare = wat::parse_str(
            "(module (memory (export \"memory\") 1) (func (export \"_start\") (nop)))",
        )
        .expect("the fixture is valid WAT");
        let mut wat = String::from("(module\n  (memory (export \"memory\") 1)\n");
        for _ in 0..64 {
            let _ = writeln!(wat, "  (global i32 (i32.const 0))");
        }
        wat.push_str("  (func (export \"_start\") (nop))\n)");
        let with_globals = wat::parse_str(&wat).expect("the fixture is valid WAT");

        let cheap = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &bare)
            .expect("loads")
            .instantiation_fuel();
        let dear =
            SandboxHost::from_module(manifest_with(ResourceLimits::default()), &with_globals)
                .expect("loads")
                .instantiation_fuel();
        assert_eq!(
            dear,
            cheap + 64,
            "each admitted global must cost a unit: {cheap} then {dear}"
        );
    }

    #[test]
    fn a_flood_of_table_declarations_is_refused_without_collecting_them() {
        // The walk collects each table's initial size so element segments can be
        // bounded against the right table. Collecting them into a growing vector
        // put an unbounded per-entry allocation inside the code whose entire job
        // is to refuse before anything allocates per entry — so a module of
        // empty table declarations expanded the process trying to reject it.
        // Only the first `MAX_TABLES` can ever be admitted, so only those are
        // kept, and the refusal names the count.
        use std::fmt::Write as _;

        let mut wat = String::from("(module\n  (memory (export \"memory\") 1)\n");
        for _ in 0..50_000 {
            let _ = writeln!(wat, "  (table 0 funcref)");
        }
        wat.push_str("  (func (export \"_start\") (nop))\n)");
        let wasm = wat::parse_str(&wat).expect("the fixture is valid WAT");

        // Refused — by wasmi's own hundred-table limit here, since `module_shape`
        // runs before `Module::new` and hands off to it. That the walk no longer
        // grows a vector per declaration on the way is what this change is for,
        // and it is not observable from a test: the allocation was never visible
        // in the result, only in the memory used to produce it.
        assert!(
            SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm).is_err(),
            "a flood of table declarations must not load"
        );
    }

    #[test]
    fn a_module_with_more_tables_than_the_store_will_build_is_refused_at_load() {
        // Sizes and count are separate ceilings, and the element sum says
        // nothing about the second: five *empty* tables cost no elements at all
        // and still exceed what the limiter will build, so the artifact loaded,
        // inspected clean, and failed every request at instantiation.
        use std::fmt::Write as _;

        let mut wat = String::from("(module\n  (memory (export \"memory\") 1)\n");
        for _ in 0..=MAX_TABLES {
            let _ = writeln!(wat, "  (table 0 funcref)");
        }
        wat.push_str("  (func (export \"_start\") (nop))\n)");
        let wasm = wat::parse_str(&wat).expect("the fixture is valid WAT");

        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("a module past the table-count ceiling must not load");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive { what: "tables", .. }
            ),
            "{err:?}"
        );
    }

    #[test]
    fn tables_within_the_ceiling_still_load() {
        // The ceiling is a ceiling, not a ban: a module with real tables must
        // still mount, and the sum is across the module rather than per table.
        let half = MAX_TABLE_ELEMENTS / 4;
        let wasm = wat::parse_str(format!(
            "(module (table {half} funcref) (table {half} funcref) (memory (export \"memory\") 1) (func (export \"_start\") (nop)))"
        ))
        .expect("the fixture is valid WAT");
        assert!(
            SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm).is_ok(),
            "tables under the ceiling must load"
        );
    }

    #[test]
    fn a_module_declaring_more_entries_than_the_ceiling_never_reaches_the_compiler() {
        // `Module::new` builds a representation of every declaration before any
        // later ceiling runs, so the file's size is not a bound on what
        // compiling it costs. The section headers carry the counts, so the
        // shape is knowable first.
        //
        // A header claiming far more entries than the section holds is refused
        // either way — by this ceiling if the claim is large, by wasmi if the
        // bytes do not back it. Both are a refusal before anything allocates
        // per entry.
        let mut wasm = wat::parse_str("(module (func (export \"_start\") (nop)))")
            .expect("the fixture is valid WAT");
        // Rewrite the type section's declared count to something no 64 MiB file
        // could honestly carry.
        let forged = {
            let mut bytes = vec![0x01u8, 0x05]; // type section, 5 bytes
            bytes.extend_from_slice(&[0xFF, 0xFF, 0xFF, 0xFF, 0x07]); // count: ~2^31
            bytes
        };
        wasm.splice(8..8, forged);

        let err = SandboxHost::from_module(manifest_with(ResourceLimits::default()), &wasm)
            .expect_err("a module past the declared-entry ceiling must not load");
        assert!(
            matches!(
                err,
                SandboxLoadError::InstantiationTooExpensive {
                    what: "declared section entries",
                    ..
                }
            ),
            "{err:?}"
        );

        // And the review surface refuses it too: `inspect` runs this on
        // artifacts nobody has audited, so it must not be the way one exhausts
        // the process reviewing it.
        assert!(
            SandboxHost::imports_of(&wasm).is_err(),
            "the import listing compiled a module the loader would not"
        );
    }

    #[test]
    fn the_metadata_footprint_covers_what_json_escaping_expands_it_to() {
        // The footprint charged metadata at `4 ×`: the caller's strings, the
        // frame's clone of them, and the serialised line priced at the raw byte
        // count. But JSON is an *escaping* encoding — `serde_json` writes a
        // control character as `\u0000`, six bytes for one — and every byte of
        // a metadata field can be one. An HTTP request cannot carry them, but
        // `SandboxHost::run` is public and an embedder builds the request by
        // hand, so the bound has to hold for the API rather than for the
        // adapter that is merely its politest caller.
        //
        // Measured, not asserted from arithmetic: the constant has to track
        // what the serialiser actually writes, so if that ever changes this
        // fails rather than quietly understating the product again.
        let granted = [SandboxCapability::HttpRequest];
        let filler = "\u{0}".repeat(4096);

        let mut request = get("/hello/greet");
        request.query = filler.clone();
        let with = crate::plugin_sandbox::wire::to_line(
            &crate::plugin_sandbox::wire::HostFrame::request(&request, &granted),
        )
        .expect("serialises")
        .len();

        request.query = String::new();
        let without = crate::plugin_sandbox::wire::to_line(
            &crate::plugin_sandbox::wire::HostFrame::request(&request, &granted),
        )
        .expect("serialises")
        .len();

        // What one raw metadata byte becomes in the line.
        let expansion = with.saturating_sub(without) / filler.len();
        assert!(
            expansion > 4,
            "the fixture does not exceed the old factor, so it proves nothing: {expansion}"
        );
        assert!(
            expansion <= 6,
            "escaping expands further than the footprint charges: {expansion}"
        );

        // …so the term must cover the caller's copy, the frame's clone, and the
        // expanded line — all three live while the line is built.
        //
        // Isolated by subtraction rather than compared against the whole
        // footprint: at the default limits the other terms come to ~58 MiB, so
        // `footprint >= 2 MiB` would hold at *any* metadata factor and prove
        // nothing. Zeroing the three manifest-driven terms leaves only the
        // fixed ones, which are subtracted here by name.
        let bare = ResourceLimits {
            memory_bytes: 0,
            max_request_body_bytes: 0,
            max_response_bytes: 0,
            ..ResourceLimits::default()
        };
        let fixed = u128::from(MAX_TABLE_ELEMENTS) * 16
            + MAX_GLOBALS as u128 * 16
            + MAX_FUNCTIONS as u128 * 32
            + FIXED_HOST_BUFFER_BYTES as u128;
        let charged_for_metadata = bare.request_footprint_bytes().saturating_sub(fixed);
        assert_eq!(
            charged_for_metadata,
            MAX_REQUEST_METADATA_BYTES as u128 * (2 + expansion as u128),
            "the metadata term does not match what the serialiser was measured to write"
        );
    }

    #[test]
    fn request_metadata_over_the_ceiling_is_refused_before_the_frame_is_built() {
        // The body ceiling was the manifest's and only ever covered the body.
        // Everything else on a `SandboxRequest` — query, headers, path params —
        // is cloned into the frame and serialised into the NDJSON line just the
        // same, and `request_footprint_bytes` budgets for none of it. The
        // encoding charge prices those bytes, but a manifest may declare fuel
        // enough to buy more than a terabyte of them, so pricing is not a bound.
        let host = host(guests::HELLO);
        let mut request = get("/hello/greet");
        request.query = "x=".repeat(MAX_REQUEST_METADATA_BYTES);

        let outcome = host.run(&request);
        let err = outcome
            .result
            .expect_err("oversized metadata must be refused");
        assert!(
            matches!(err, SandboxFailure::RequestMetadataBudget { .. }),
            "{err:?}"
        );
        // The caller's request was refused, not the plugin's answer: 413, the
        // same door the body ceiling answers through.
        assert_eq!(err.status(), http::StatusCode::PAYLOAD_TOO_LARGE);
        assert_eq!(
            outcome.fuel_used, 0,
            "nothing was built, so nothing was spent"
        );
    }

    #[test]
    fn the_metadata_ceiling_leaves_an_ordinary_request_alone() {
        // A ceiling that a real request could reach would be a bug of its own:
        // every HTTP server in front of this caps a URI and a header block far
        // below it.
        let host = host(guests::HELLO);
        let mut request = get("/hello/greet");
        request.query = "x=1&".repeat(64);
        request
            .headers
            .push(("x-trace".to_owned(), "a".repeat(1024)));
        assert!(
            host.run(&request).result.is_ok(),
            "an ordinary request must not be caught by the metadata ceiling"
        );
    }

    #[test]
    fn a_body_over_the_ceiling_is_refused_by_run_itself() {
        // The Axum adapter applies the ceiling while reading, so nothing
        // oversized reaches `run` on that path. But `run` is public: an
        // embedder builds the `SandboxRequest` itself, and a manifest with
        // generous fuel would otherwise buy an arbitrarily large host-side
        // copy — cloned into the frame and base64-expanded — of a body the
        // manifest said it would never accept.
        let host = try_host_with(
            guests::HELLO,
            ResourceLimits {
                max_request_body_bytes: 1_024,
                // Deliberately generous — the largest a manifest may declare.
                // The encoding price must not be what saves us here, or the
                // ceiling is decorative on this path.
                fuel: 100_000_000_000,
                ..ResourceLimits::default()
            },
        )
        .expect("the fixture loads");

        let mut request = get("/hello/greet");
        request.body = vec![b'x'; 1_025];
        let outcome = host.run(&request);
        assert_eq!(
            outcome.result,
            Err(SandboxFailure::RequestBudget {
                max: 1_024,
                len: 1_025,
            }),
            "a body over the ceiling must be refused, not encoded"
        );
        // Refused before the request was priced or walked at all.
        assert_eq!(outcome.fuel_used, 0);
        assert_eq!(outcome.peak_memory_bytes, 0);
        // The same answer the adapter gives for the same condition.
        assert_eq!(
            outcome.result.unwrap_err().status(),
            http::StatusCode::PAYLOAD_TOO_LARGE
        );

        // And a body exactly at the ceiling is still served: the check is a
        // ceiling, not an off-by-one that costs the last byte.
        request.body = vec![b'x'; 1_024];
        let outcome = host.run(&request);
        assert!(outcome.result.is_ok(), "{:?}", outcome.result);
    }

    #[test]
    fn a_malformed_frame_is_refused() {
        let outcome = host(guests::MALFORMED_FRAME).run(&get("/hello/greet"));
        assert!(
            matches!(outcome.result, Err(SandboxFailure::MalformedFrame(_))),
            "{:?}",
            outcome.result
        );
    }

    #[test]
    fn an_op_the_wire_does_not_define_is_refused() {
        let outcome = host(guests::UNKNOWN_OP).run(&get("/hello/greet"));
        assert!(
            matches!(outcome.result, Err(SandboxFailure::MalformedFrame(_))),
            "{:?}",
            outcome.result
        );
    }

    #[test]
    fn the_first_answer_is_the_answer() {
        let outcome = host(guests::DOUBLE_ANSWER).run(&get("/hello/greet"));
        assert_eq!(
            outcome.result.expect("answers").body,
            b"hello from the sandbox"
        );
    }

    #[test]
    fn every_refusal_stub_matches_the_wasi_signature_it_stands_in_for() {
        // A wrong signature would not weaken the sandbox — it would stop an
        // honest guest from linking at all. This builds a module importing
        // every refusal with the shape the table declares and proves it
        // instantiates and runs.
        use std::fmt::Write as _;

        let mut wat = String::from("(module\n");
        for (name, _, _, signature) in DENIED_IMPORTS {
            let params: Vec<&str> = signature
                .chars()
                .map(|ch| if ch == 'l' { "i64" } else { "i32" })
                .collect();
            let _ = writeln!(
                wat,
                "  (import \"wasi_snapshot_preview1\" \"{name}\" (func (param {params}) (result i32)))",
                params = params.join(" ")
            );
        }
        wat.push_str("  (memory (export \"memory\") 1)\n  (func (export \"_start\") (nop))\n)");
        let outcome = host(&wat).run(&get("/hello/greet"));
        assert!(
            matches!(outcome.result, Err(SandboxFailure::NoAnswer)),
            "every stub must link: {:?}",
            outcome.result
        );
    }

    #[test]
    fn an_import_with_the_wrong_signature_is_refused_at_load() {
        // Name-checking alone lets a module through packaging and inspection
        // and then fails it on every request, as a gateway error nobody can
        // explain from outside.
        let wat = r#"(module
             (import "wasi_snapshot_preview1" "fd_write"
               (func (param i32 i32) (result i32)))
             (memory (export "memory") 1)
             (func (export "_start") (nop)))"#;
        let err = try_host(wat).expect_err("must be refused");
        let SandboxLoadError::ForbiddenImports(denials) = err else {
            panic!("expected a forbidden-import refusal, got {err}");
        };
        assert!(denials[0].operation.contains("fd_write"), "{denials:?}");
        assert!(denials[0].detail.contains("signature"), "{denials:?}");
    }

    #[test]
    fn a_non_function_import_is_refused_at_load() {
        let wat = r#"(module
             (import "wasi_snapshot_preview1" "fd_write" (memory 1))
             (memory (export "memory") 1)
             (func (export "_start") (nop)))"#;
        assert!(matches!(
            try_host(wat),
            Err(SandboxLoadError::ForbiddenImports(_))
        ));
    }

    #[test]
    fn a_start_that_takes_arguments_is_not_a_start() {
        // The host looks `_start` up as `() -> ()`, so anything else loads and
        // then fails on every request.
        let wat = r#"(module
             (memory (export "memory") 1)
             (func (export "_start") (param i32) (nop)))"#;
        assert!(matches!(try_host(wat), Err(SandboxLoadError::MissingStart)));

        let wat = r#"(module
             (memory (export "memory") 1)
             (func (export "_start") (result i32) (i32.const 0)))"#;
        assert!(matches!(try_host(wat), Err(SandboxLoadError::MissingStart)));
    }

    #[test]
    fn the_load_gate_admits_exactly_what_the_shim_defines() {
        for (name, ..) in SERVED_IMPORTS {
            assert!(is_shim_function(name), "{name} is served but not admitted");
        }
        for (name, ..) in DENIED_IMPORTS {
            assert!(is_shim_function(name), "{name} is refused but not admitted");
        }
        for name in ["sock_connect", "path_open_v2", "fd_write2"] {
            assert!(!is_shim_function(name), "{name} must not be admitted");
        }
    }

    #[test]
    fn the_import_list_is_readable_for_review() {
        let imports = host(guests::HELLO).imports();
        assert!(
            imports.contains(&"wasi_snapshot_preview1::fd_read".to_owned()),
            "{imports:?}"
        );
    }

    // ── Reply room is reserved before a call commits (issue #2523) ───

    fn outbound_state(
        queued: usize,
    ) -> (
        HostState,
        std::sync::Arc<crate::plugin_sandbox::RecordingHttp>,
    ) {
        let limits = ResourceLimits::default();
        let manifest = crate::plugin_sandbox::manifest::SandboxManifest::parse(&format!(
            r#"
name = "hello"
version = "0.1.0"
wire_version = 1
prefix = "/hello"
capabilities = ["http-request", "http-outbound", "kv"]
sha256 = "{digest}"

[[routes]]
method = "GET"
path = "/hello/greet"

[grants]
hosts = ["api.example.com"]
"#,
            digest = "a".repeat(64)
        ))
        .expect("valid manifest");
        let http = crate::plugin_sandbox::RecordingHttp::new();
        let services = crate::plugin_sandbox::CapabilityServices {
            http: Some(std::sync::Arc::clone(&http)
                as std::sync::Arc<dyn crate::plugin_sandbox::OutboundHttp>),
            kv: Some(crate::plugin_sandbox::MemoryKvStore::new()
                as std::sync::Arc<dyn crate::plugin_sandbox::KvStore>),
            ..crate::plugin_sandbox::CapabilityServices::none()
        };
        let mut state = HostState::new(
            "hello".to_owned(),
            limits,
            b"",
            Exchange::Request,
            crate::plugin_sandbox::capability::CapabilityRuntime::new(&manifest, services),
        );
        state.queued_replies = queued;
        (state, http)
    }

    fn post() -> crate::plugin_sandbox::CapabilityCall {
        crate::plugin_sandbox::CapabilityCall::HttpFetch {
            id: 1,
            method: "POST".to_owned(),
            url: "https://api.example.com/orders".to_owned(),
            headers: Vec::new(),
            body: String::new(),
        }
    }

    #[test]
    fn a_call_is_not_committed_when_its_reply_could_not_be_queued() {
        // One MiB queue, nearly full of unread replies: a POST could commit and
        // then fail the request on its own reply.
        let (mut state, http) = outbound_state(MAX_QUEUED_REPLY_BYTES - 1024);
        state.service(&post(), u64::MAX);
        assert!(http.seen().is_empty(), "the POST left the host");
        assert!(state.answer.is_none(), "the request must go on");
        let queued =
            String::from_utf8_lossy(&state.stdin.iter().copied().collect::<Vec<_>>()).into_owned();
        assert!(queued.contains("quota-exceeded"), "{queued}");
    }

    #[test]
    fn a_call_is_not_committed_when_the_fuel_could_not_pay_for_its_reply() {
        let (mut state, http) = outbound_state(0);
        state.service(&post(), 1_000);
        assert!(http.seen().is_empty(), "the POST left the host");
        assert!(state.answer.is_none(), "the request must go on");
    }

    #[test]
    fn a_call_with_room_and_fuel_is_dispatched() {
        let (mut state, http) = outbound_state(0);
        state.service(&post(), u64::MAX);
        assert_eq!(http.seen().len(), 1);
    }
    /// Fuel to price `call`'s worst-case reply and write the answer.
    fn priced(call: &crate::plugin_sandbox::CapabilityCall) -> u64 {
        let allowance = FINISH_ALLOWANCE_FUEL.min(ResourceLimits::default().fuel / 4);
        allowance + (call.reply_reserve() as u64).div_ceil(BYTES_PER_FUEL)
    }

    fn get_call() -> crate::plugin_sandbox::CapabilityCall {
        crate::plugin_sandbox::CapabilityCall::HttpFetch {
            id: 1,
            method: "GET".to_owned(),
            url: "https://api.example.com/".to_owned(),
            headers: Vec::new(),
            body: String::new(),
        }
    }

    #[test]
    fn the_fuel_edge_for_a_write_includes_the_guest_s_read() {
        // #2523 finding 7. Fuel to price the reply is not fuel to read it. A
        // POST that commits and then runs out of fuel in the guest fails, and a
        // retry sends it again.
        let need = priced(&post()) + post().reply_reserve() as u64 * GUEST_READ_FUEL_PER_BYTE;
        let (mut state, http) = outbound_state(0);
        state.service(&post(), priced(&post()));
        assert!(http.seen().is_empty(), "the guest could not read the reply");
        let (mut state, http) = outbound_state(0);
        state.service(&post(), need - 1);
        assert!(http.seen().is_empty(), "one unit short must not dispatch");
        let (mut state, http) = outbound_state(0);
        state.service(&post(), need);
        assert_eq!(http.seen().len(), 1);
    }

    #[test]
    fn the_fuel_edge_for_a_read_is_its_price() {
        // A read that fails commits nothing, so it keeps no fuel to be read.
        let (mut state, http) = outbound_state(0);
        state.service(&get_call(), priced(&get_call()) - 1);
        assert!(http.seen().is_empty(), "one unit short must not dispatch");
        let (mut state, http) = outbound_state(0);
        state.service(&get_call(), priced(&get_call()));
        assert_eq!(http.seen().len(), 1);
    }

    /// What the host queued for the guest, as text.
    fn queued_text(state: &HostState) -> String {
        String::from_utf8_lossy(&state.stdin.iter().copied().collect::<Vec<_>>()).into_owned()
    }

    /// Fuel to price `call`, write the answer, and read `unread` bytes plus the
    /// reply.
    fn with_read(call: &crate::plugin_sandbox::CapabilityCall, unread: usize) -> u64 {
        priced(call) + (call.reply_reserve() + unread) as u64 * GUEST_READ_FUEL_PER_BYTE
    }

    #[test]
    fn a_fuel_refusal_and_a_queue_refusal_say_different_things() {
        let (mut state, http) = outbound_state(0);
        state.service(&post(), priced(&post()));
        assert!(http.seen().is_empty());
        assert!(state.answer.is_none(), "the request must go on");
        let text = queued_text(&state);
        assert!(text.contains("quota-exceeded"), "{text}");
        assert!(text.contains("increase `fuel`"), "{text}");
        assert!(!text.contains("pending replies"), "{text}");

        let (mut state, _) = outbound_state(MAX_QUEUED_REPLY_BYTES - 1024);
        state.service(&post(), u64::MAX);
        let text = queued_text(&state);
        assert!(text.contains("pending replies"), "{text}");
        assert!(!text.contains("fuel"), "{text}");
    }

    #[test]
    fn a_write_keeps_fuel_to_read_the_replies_not_yet_read() {
        let unread = 10_000;
        let (mut state, http) = outbound_state(unread);
        state.service(&post(), with_read(&post(), unread) - 1);
        assert!(http.seen().is_empty(), "one unit short must not dispatch");
        let (mut state, http) = outbound_state(unread);
        state.service(&post(), with_read(&post(), unread));
        assert_eq!(http.seen().len(), 1);
    }

    #[test]
    fn a_read_after_a_write_keeps_fuel_to_read_its_reply() {
        // The write has run. A read that then fails the request makes a retry
        // do the write again.
        let (mut state, http) = outbound_state(0);
        state.service(&post(), u64::MAX);
        assert_eq!(http.seen().len(), 1);
        state.service(
            &get_call(),
            with_read(&get_call(), state.queued_replies) - 1,
        );
        assert_eq!(http.seen().len(), 1, "one unit short must not dispatch");
        state.service(&get_call(), with_read(&get_call(), state.queued_replies));
        assert_eq!(http.seen().len(), 2);
    }

    #[test]
    fn a_write_refused_before_it_runs_does_not_make_reads_keep_fuel() {
        let (mut state, http) = outbound_state(0);
        state.service(&post(), priced(&post()));
        assert!(http.seen().is_empty());
        state.service(&get_call(), priced(&get_call()));
        assert_eq!(http.seen().len(), 1);
    }

    #[test]
    fn the_fuel_edge_for_a_kv_write_is_about_0_6_million() {
        let set = crate::plugin_sandbox::CapabilityCall::KvSet {
            id: 1,
            key: "cart".to_owned(),
            value: crate::plugin_sandbox::PluginValue::Text("one".to_owned()),
        };
        // The guide quotes this number.
        assert_eq!(with_read(&set, 0), 624_352);
        let (mut state, _) = outbound_state(0);
        state.service(&set, with_read(&set, 0) - 1);
        assert!(queued_text(&state).contains("increase `fuel`"));
        let (mut state, _) = outbound_state(0);
        state.service(&set, with_read(&set, 0));
        let text = queued_text(&state);
        assert!(text.contains(r#""status":"ok""#), "{text}");
    }

    #[test]
    fn a_get_is_denied_not_failed_when_the_fuel_cannot_price_its_reply() {
        let read = || crate::plugin_sandbox::CapabilityCall::HttpFetch {
            id: 1,
            method: "GET".to_owned(),
            url: "https://api.example.com/".to_owned(),
            headers: Vec::new(),
            body: String::new(),
        };
        let queued = |state: &HostState| {
            String::from_utf8_lossy(&state.stdin.iter().copied().collect::<Vec<_>>()).into_owned()
        };
        let (mut state, _) = outbound_state(0);
        state.service(&read(), 10);
        assert!(state.answer.is_none(), "the request must go on");
        assert!(
            queued(&state).contains("quota-exceeded"),
            "{}",
            queued(&state)
        );
        let (mut state, _) = outbound_state(0);
        state.service(&read(), 1_000_000);
        assert!(
            !queued(&state).contains("quota-exceeded"),
            "{}",
            queued(&state)
        );
    }
}