rapid-structure-rs 1.0.0

Rust document-structure engine for PaddleOCR-family ONNX models: text detection/recognition (PP-OCRv6), table structure (SLANet-plus) and formula recognition (PP-FormulaNet) on Windows x64 via ONNX Runtime.
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
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
//! 端到端测试:**真实绑定的端口** + 原始 TCP 客户端(§12 的"协议/安全/队列"三行)。
//!
//! # 为什么用原始 TCP 而不是 HTTP 客户端
//!
//! 要验证的东西里有相当一部分是"客户端**故意**不规矩"时服务端的行为:错误的 `Host`
//! (防 DNS rebinding)、缺失/`null`/不匹配的 `Origin`、声明了但永不发送的
//! `Content-Length`(413 必须**在读 body 之前**给出)、错误的 `Content-Type`。
//! 这些用常规客户端库很难精确构造,而直接写字节既精确又不新增依赖。
//!
//! # 引擎为什么可以被脚本化
//!
//! 队列、准入、任务生命周期这些行为与"真实模型识别得对不对"无关,但真实引擎每张图要
//! 几百毫秒到数秒、还要 30 MB 模型在场。因此 [`ScriptedBackend`] 通过
//! `ServeContext::engine_factory`(见 `engine.rs` 的模块文档)替换引擎:
//! 生产路径永远是 `real_engine_factory`,脚本化只出现在本测试模块里。
//!
//! 模型目录由**本地 manifest** 构造(三个几十字节的假文件 + 真实 SHA-256),
//! 因此"模型齐备 → 引擎预加载 Ready"这条路径在测试里也走的是**真实**的
//! `ModelSource` / `ModelSet` / 单一来源规则,而不是被 stub 掉。
//!
//! # 公平性怎么驱动(§12 的双向要求)
//!
//! 引擎只有一个 worker,因此"另一个队列被灌满时本队列多久被服务"必须靠**慢速后端**观察:
//! `delay=25ms` 的脚本化后端 + `limit=0` 的滑动窗口。两个方向都跑:
//! 公式洪水下的普通任务、普通洪水下的公式任务,上界取调度器的
//! `wait_bound`(`capacity × 对方配额`)再乘上单任务耗时并留足余量。
//! 公式队列在 M1 生产路径上不可达(§10.8),因此这里用 `--formula-detector` 打开它(见
//! `TestOptions::with_formula_routing`),并用 `?queue=formula` 选择队列——这就是"测试专用
//! 慢速路径"的全部内容。

use std::io::{Cursor, Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use super::download::{DownloadJob, DownloadSink, DownloaderFactory, ModelDownloader};
use super::engine::{BackendProvider, EngineFactory, OcrBackend};
use super::evaluate::EvalRoot;
use super::flowlog::FlowSink;
use super::http::{BoundServer, ServeHandle};
use super::limits::RawServeLimits;
use super::model_plan::ModelPlan;
use super::queue::QueueClass;
use super::run::render_page;
use super::security::{LocalOrigin, ServeToken, generate_nonce};
use super::server::{FreeSpaceFactory, ServeContext, ServeShared};
use super::state::ServeStartup;
use rapid_structure_rs::{
    CoordinateSpace, DetectionOutcome, DownloadError, EngineConfig, EngineInfo, FileIdentity,
    FormulaOutcome, FormulaPolicy, GenericProviderPreference, ImageInfo, ImageSize, LangDet,
    LangRec, ModelFileSpec, ModelType, OcrOutput, OcrRegion, OcrRequest, OcrTimings, OcrVersion,
    OcrWord, Polygon, ProviderInfo, ProviderResolutionInfo, RapidOcrError, RecognitionOutcome,
    RegionKind, RegionSource, ResolvedProvider, StageReports, TableCellMatch, TableCellOutcome,
    TableDegradation, TableOutcome, TablePolicy, TableStructureConfidence, TableTextPolicy,
    WordOutputMode, sha256_file,
};
use serde_json::{Value, json};

// ---------------------------------------------------------------- 测试基础设施

/// 脚本化后端的参数。
#[derive(Clone)]
struct Scripted {
    delay: Duration,
    regions: usize,
    text_bytes: usize,
    fail: bool,
    calls: Arc<AtomicUsize>,
    running: Arc<AtomicBool>,
    /// 本后端的 `selected_ep` 标签(M3 的 provider 切换靠它证明"换了哪个会话")。
    ep: String,
    /// 每次识别是谁服务的(按顺序),用来断言"队列里的任务用了新引擎"。
    served: Arc<Mutex<Vec<String>>>,
    /// 每次识别收到的(请求体, `FormulaPolicy`)(M4:公式队列真的把公式管线接上了)。
    ///
    /// 与 `tables` 同一手法(复审 P2-3):请求体与策略成对记录,断言用请求体把策略关联
    /// 回具体请求 —— 多 worker 下 `recognize` 的进入顺序不等于提交顺序,按下标取偶发错位。
    formulas: Arc<Mutex<Vec<(String, FormulaPolicy)>>>,
    /// 每次识别收到的(请求体, `TablePolicy`)(E16.2:`?table=1` 真的把表格阶段接上了)。
    ///
    /// 两者在**同一次加锁**内成对记录:多 worker 下 `recognize` 的进入顺序不等于提交顺序,
    /// 只按顺序取下标会偶发错位,因此断言改为用请求体把策略关联回具体请求。
    tables: Arc<Mutex<Vec<(String, TablePolicy)>>>,
    /// 可选的闸门:识别在返回**之前**阻塞,直到测试放行(M4 的单飞测试用它把
    /// "评估正在跑"变成确定性事实,而不是靠 sleep 猜时序)。
    gate: Option<Arc<Gate>>,
    /// 输出里附加的**公式**区域数(M5 的契约用例:`/result` 的 `formula.latex`
    /// 只有真的有一条公式区域时才被这条端到端路径覆盖)。
    formula_regions: usize,
    /// 输出里附加的**表格**区域数(E16.2/E16.3 的契约用例:`/result` 的 `table.html`
    /// 只有真的有一条表格区域时才被这条端到端路径覆盖)。
    table_regions: usize,
    /// 每次识别收到的(请求体, `WordOutputMode`)(Step 1:`?words=` 真的到达了引擎)。
    ///
    /// 与 `formulas`/`tables` 同一手法:按请求体关联,不按下标。本后端的输出**也**由这一档
    /// 合成(见 [`scripted_output_modes`]),因此“引擎看到了哪一档”与“载荷里有哪种框”
    /// 是同一件事的两面,不能各说一套。
    word_modes: Arc<Mutex<Vec<(String, WordOutputMode)>>>,
}

impl Scripted {
    fn fast() -> Self {
        Self {
            delay: Duration::from_millis(0),
            regions: 3,
            text_bytes: 0,
            fail: false,
            calls: Arc::new(AtomicUsize::new(0)),
            running: Arc::new(AtomicBool::new(false)),
            ep: "cpu".to_string(),
            served: Arc::new(Mutex::new(Vec::new())),
            formulas: Arc::new(Mutex::new(Vec::new())),
            tables: Arc::new(Mutex::new(Vec::new())),
            gate: None,
            formula_regions: 0,
            table_regions: 0,
            word_modes: Arc::new(Mutex::new(Vec::new())),
        }
    }

    /// 输出里附带 `count` 条公式区域(M5 的契约用例)。
    fn with_formula_regions(mut self, count: usize) -> Self {
        self.formula_regions = count;
        self
    }

    /// 输出里附带 `count` 条表格区域(E16.2/E16.3 的契约用例)。
    fn with_table_regions(mut self, count: usize) -> Self {
        self.table_regions = count;
        self
    }

    fn slow(delay: Duration) -> Self {
        Self {
            delay,
            ..Self::fast()
        }
    }

    /// 识别进入闸门(到达即通知测试,然后阻塞到放行)。
    fn with_gate(mut self, gate: Arc<Gate>) -> Self {
        self.gate = Some(gate);
        self
    }

    /// 每次识别收到的(请求体, 公式策略),按后端进入顺序;M4。
    fn formulas(&self) -> Vec<(String, FormulaPolicy)> {
        self.formulas
            .lock()
            .expect("the scripted recorder is not poisoned")
            .clone()
    }

    /// 指定请求体收到的公式策略;一次都没记录时直接 panic(漏跑也是回归)。
    fn formula_policy(&self, body: &str) -> FormulaPolicy {
        self.formulas()
            .iter()
            .find(|(recorded, _)| recorded == body)
            .unwrap_or_else(|| panic!("no formula policy recorded for request body {body:?}"))
            .1
            .clone()
    }

    /// 每次识别收到的(请求体, 表格策略),按后端进入顺序;E16.2。
    fn tables(&self) -> Vec<(String, TablePolicy)> {
        self.tables
            .lock()
            .expect("the scripted recorder is not poisoned")
            .clone()
    }

    /// 指定请求体收到的表格策略;一次都没记录时直接 panic(漏跑也是回归)。
    fn table_policy(&self, body: &str) -> TablePolicy {
        self.tables()
            .iter()
            .find(|(recorded, _)| recorded == body)
            .unwrap_or_else(|| panic!("no table policy recorded for request body {body:?}"))
            .1
            .clone()
    }

    /// 每次识别收到的(请求体, 逐词/逐字档位),按后端进入顺序;Step 1。
    fn word_modes(&self) -> Vec<(String, WordOutputMode)> {
        self.word_modes
            .lock()
            .expect("the scripted recorder is not poisoned")
            .clone()
    }

    /// 指定请求体收到的档位;一次都没记录时直接 panic(参数被丢掉也是回归)。
    fn word_mode(&self, body: &str) -> WordOutputMode {
        self.word_modes()
            .iter()
            .find(|(recorded, _)| recorded == body)
            .unwrap_or_else(|| panic!("no word mode recorded for request body {body:?}"))
            .1
    }

    fn factory(self) -> EngineFactory {
        Arc::new(
            move |_config: &EngineConfig| -> Result<Box<dyn OcrBackend>, RapidOcrError> {
                Ok(Box::new(ScriptedBackend {
                    state: self.clone(),
                }))
            },
        )
    }
}

struct ScriptedBackend {
    state: Scripted,
}

impl OcrBackend for ScriptedBackend {
    fn recognize(&mut self, request: OcrRequest) -> Result<OcrOutput, RapidOcrError> {
        self.state.calls.fetch_add(1, Ordering::SeqCst);
        // 请求体是各次提交之间唯一互不相同的标识,用它把策略关联回具体请求。
        let body = match &request.input {
            rapid_structure_rs::ImageInput::Encoded(bytes) => {
                String::from_utf8_lossy(bytes).to_string()
            }
            other => format!("<non-encoded input: {other:?}>"),
        };
        self.state
            .formulas
            .lock()
            .expect("the scripted recorder is not poisoned")
            .push((body.clone(), request.formula.clone()));
        self.state
            .word_modes
            .lock()
            .expect("the scripted recorder is not poisoned")
            .push((body.clone(), request.recognition.words));
        self.state
            .tables
            .lock()
            .expect("the scripted recorder is not poisoned")
            .push((body, request.table.clone()));
        self.state
            .served
            .lock()
            .expect("the scripted recorder is not poisoned")
            .push(self.state.ep.clone());
        if let Some(gate) = &self.state.gate {
            gate.wait();
        }
        self.state.running.store(true, Ordering::SeqCst);
        if !self.state.delay.is_zero() {
            std::thread::sleep(self.state.delay);
        }
        self.state.running.store(false, Ordering::SeqCst);
        if self.state.fail {
            return Err(RapidOcrError::InvalidImage(
                "scripted failure: the image cannot be decoded".to_string(),
            ));
        }
        Ok(scripted_output_modes(
            self.state.regions,
            self.state.text_bytes,
            self.state.formula_regions,
            self.state.table_regions,
            request.recognition.words,
        ))
    }

    fn provider(&self) -> BackendProvider {
        BackendProvider {
            selected_ep: self.state.ep.clone(),
            fallback_to_cpu: false,
        }
    }
}

/// 一份结构完整、可被 `to_output_json` 序列化的输出。
///
/// `pub(crate)`:`results.rs` 的单元测试也用它构造成功载荷(同一份样例,避免两处各写一套)。
pub(crate) fn scripted_output(regions: usize, text_bytes: usize) -> OcrOutput {
    scripted_output_with(regions, text_bytes, 0, 0)
}

/// 一份可用的表格区域结果(E16.2/E16.3 的契约用例)。
///
/// `html` 里**故意**带一个注入型单元格文本:网页侧的 `sanitizeTableHtml` 与
/// 服务端侧的 `TableTextPolicy::Escape` 都必须让它变成惰性文本。夹具本身不净化,
/// 因为"模型产物可能带标签"正是这条链路的真实输入。
fn scripted_table_outcome() -> TableOutcome {
    TableOutcome {
        html: "<html><body><table><tr><td>a</td><td><script>alert(1)</script></td></tr></table></body></html>"
            .to_string(),
        table_html:
            "<table><tr><td>a</td><td><script>alert(1)</script></td></tr></table>".to_string(),
        markdown: "| a | <script>alert(1)</script> |\n| --- | --- |\n".to_string(),
        rows: 1,
        cols: 2,
        confidence: TableStructureConfidence::Low,
        degradations: vec![TableDegradation::GridHoles { holes: 1 }],
        holes: 1,
        cells: vec![
            TableCellOutcome {
                row: 0,
                col: 0,
                rowspan: 1,
                colspan: 1,
                text: "a".to_string(),
                score: Some(0.9),
                match_kind: TableCellMatch::Single,
                polygon: Some(Polygon {
                    points: [[1.0, 1.0], [5.0, 1.0], [5.0, 3.0], [1.0, 3.0]],
                }),
            },
            TableCellOutcome {
                row: 0,
                col: 1,
                rowspan: 1,
                colspan: 1,
                text: "<script>alert(1)</script>".to_string(),
                score: None,
                match_kind: TableCellMatch::BlankBox,
                polygon: None,
            },
        ],
        source_line_indices: vec![0],
        model_id: "scripted-table".to_string(),
    }
}

/// 同上,另外附带 `formula_regions` 条 [`RegionKind::Formula`] 区域(M5 的契约用例)。
///
/// 公式区域**不带** `recognition`(`src/api.rs` 的语义:公式模型没有可与 CTC 平行解释的
/// 逐字置信度),页面因此只要求它有 `formula.latex`——这正是契约里最容易写错的一处。
pub(crate) fn scripted_output_with(
    regions: usize,
    text_bytes: usize,
    formula_regions: usize,
    table_regions: usize,
) -> OcrOutput {
    scripted_output_modes(
        regions,
        text_bytes,
        formula_regions,
        table_regions,
        WordOutputMode::Off,
    )
}

/// 脚本化文本区域的行框:`(x0, y0, x1, y1)`。
///
/// [`scripted_output_modes`] 用它构造区域 polygon,[`scripted_words`] 把 word 框铺在**同一行带**
/// 里。两处共用一组常量,“word 框被自己的行框包住”才是可断言的形式(而不是两处各自写死)。
const SCRIPT_ROW: (f32, f32, f32, f32) = (1.0, 1.0, 10.0, 5.0);

/// 按档位合成 `recognition.words`(Step 1 的端到端契约用例)。
///
/// 这里的几何是**脚本化**的:把 [`SCRIPT_ROW`] 那条行带按项数等宽切片。这条链路要钉的是
/// “serve 把 word 的文本、粒度标签与坐标原样带到线上:不重缩放、不丢项、不改顺序”,
/// **不是**“模型给的字符框够准”——后者属于字符定位基准(IoU / 左右边界误差),
/// 不能用人造几何来冒充。
///
/// - `Off` → `None`:线上不允许用空数组冒充“档位已开启”。
/// - `Words` → 按空白切分的 token。
/// - `Chars` → 逐个 `char`,不丢任何字符,因此拼接必然等于 `text`。
fn scripted_words(text: &str, mode: WordOutputMode) -> Option<Vec<OcrWord>> {
    let items: Vec<&str> = match mode {
        WordOutputMode::Off => return None,
        WordOutputMode::Words => text.split_whitespace().collect(),
        WordOutputMode::Chars => text
            .char_indices()
            .map(|(start, ch)| &text[start..start + ch.len_utf8()])
            .collect(),
    };
    let (x0, y0, x1, y1) = SCRIPT_ROW;
    let kind = mode.kind_for();
    let band = (x1 - x0) / items.len().max(1) as f32;
    Some(
        items
            .iter()
            .enumerate()
            .map(|(index, item)| {
                let left = x0 + band * index as f32;
                let right = left + band;
                OcrWord {
                    text: (*item).to_string(),
                    score: 0.9,
                    polygon: Polygon {
                        points: [[left, y0], [right, y0], [right, y1], [left, y1]],
                    },
                    kind,
                }
            })
            .collect(),
    )
}

/// 同上,再按 `mode` 决定文本区域的 `recognition.words` 给不给、给哪种粒度(Step 1)。
///
/// 公式与表格区域**不跟随**档位:它们根本没有 `recognition`(见上面的注释),
/// 逐词/逐字框在语义上只属于 CTC 文本区域。
pub(crate) fn scripted_output_modes(
    regions: usize,
    text_bytes: usize,
    formula_regions: usize,
    table_regions: usize,
    mode: WordOutputMode,
) -> OcrOutput {
    let provider = ProviderResolutionInfo {
        requested: GenericProviderPreference::Cpu,
        selected_ep: ResolvedProvider::Cpu,
        fallback_to_cpu: false,
    };
    let built = (0..regions)
        .map(|index| {
            let text = if text_bytes == 0 {
                format!("region-{index}")
            } else {
                "x".repeat(text_bytes)
            };
            // word 框要落在自己的行框里,所以两处共用 [`SCRIPT_ROW`]。
            let (x0, y0, x1, y1) = SCRIPT_ROW;
            let words = scripted_words(&text, mode);
            OcrRegion::text(
                RegionSource::Detected {
                    detector_index: index,
                },
                Some(Polygon {
                    points: [[x0, y0], [x1, y0], [x1, y1], [x0, y1]],
                }),
                Some(DetectionOutcome { score: 0.9 }),
                None,
                Some(RecognitionOutcome {
                    text,
                    score: 0.9,
                    words,
                }),
            )
        })
        .chain((0..formula_regions).map(|index| OcrRegion {
            source: RegionSource::Detected {
                detector_index: regions + index,
            },
            kind: RegionKind::Formula,
            polygon: Some(Polygon {
                points: [[2.0, 2.0], [20.0, 2.0], [20.0, 9.0], [2.0, 9.0]],
            }),
            detection: Some(DetectionOutcome { score: 0.88 }),
            classification: None,
            // 公式区域刻意**不带** `recognition`:这正是契约里"公式区域没有 CTC 文本"的语义。
            recognition: None,
            formula: Some(FormulaOutcome {
                latex: format!("E = mc^{{{index}}}"),
                eos_index: Some(3),
                truncated: false,
                model_id: "scripted-formula".to_string(),
                token_ids: None,
            }),
            // 表格区域刻意**不带** `recognition`(同公式:表格区域的文本来自单元格回填,
            // 不是 CTC 逐字置信度)。
            table: None,
        }))
        .chain((0..table_regions).map(|index| {
            OcrRegion::table(
                RegionSource::Detected {
                    detector_index: regions + formula_regions + index,
                },
                Some(Polygon {
                    points: [[1.0, 1.0], [30.0, 1.0], [30.0, 12.0], [1.0, 12.0]],
                }),
                Some(DetectionOutcome { score: 0.85 }),
                scripted_table_outcome(),
            )
        }))
        .collect();
    OcrOutput {
        schema_version: 1,
        image: ImageInfo {
            original_size: ImageSize {
                width: 100,
                height: 50,
            },
            processed_size: ImageSize {
                width: 100,
                height: 50,
            },
            coordinate_space: CoordinateSpace::Image,
        },
        stages: StageReports::default(),
        regions: built,
        timings: OcrTimings {
            total_ms: 1.0,
            ..OcrTimings::default()
        },
        engine: EngineInfo {
            model_id: "scripted".to_string(),
            provider: ProviderInfo {
                detector: provider,
                classifier: None,
                recognizer: provider,
            },
        },
    }
}

/// 测试运行时的组装参数。
struct TestOptions {
    limits: RawServeLimits,
    allow_download: bool,
    allow_download_hosts: Vec<String>,
    /// `--allow-provider-fallback`(§7.5):运行期切换 provider 会用同一个值。
    allow_provider_fallback: bool,
    /// `--formula-detector`(M4)的 **CLI 路径**。
    ///
    /// 路由与"该哈希谁"都由 `ModelPlan::resolve` 从这一条路径唯一解析(单一的运行计划),
    /// 测试因此不再自己拼一份 `FormulaDetectorSpec`——那正是"报告一份、加载另一份"的形状。
    formula_detector: Option<PathBuf>,
    /// `--table-model`(E16.2)的 **CLI 路径**,与 `formula_detector` 同一条规则:
    /// 路由与"该哈希谁"都由 `ModelPlan::resolve` 从这一条路径唯一解析。
    table_model: Option<PathBuf>,
    /// `--eval-root` 沙箱(评审 P2-3):默认指向测试模型目录(评估夹具就写在那里)。
    eval_root: Option<EvalRoot>,
    engine_factory: EngineFactory,
    downloader: DownloaderFactory,
    free_space: FreeSpaceFactory,
    model_dir: PathBuf,
    engine_config: EngineConfig,
    /// A2 的确定性钩子:**模型冷验证返回之后、响应写出之前**调用一次(原始 HTTP 层用)。
    ///
    /// 单飞("第二个并发调用得到 503 `busy`")必须被确定性地观察到,而不是靠 sleep 猜时序:
    /// 有了它,测试可以在"第一个调用已经写完校验结论、但还没有回响应"的**精确窗口**里
    /// 发第二个请求。
    post_verify: Option<Box<dyn Fn() + Send + Sync>>,
    /// 流动日志出口(M5):默认 `FlowSink::Off`(与生产的默认一致)。
    ///
    /// 需要断言的用例用 [`TestOptions::with_flow_capture`] 换成内存捕获——**同一个**出口
    /// 类型、**同一份**格式化实现,因此测试断言的就是生产会打印的那些行。
    flow: FlowSink,
}

impl TestOptions {
    fn new(model_dir: PathBuf, scripted: Scripted) -> Self {
        let eval_root = EvalRoot::new(&model_dir).ok();
        Self {
            limits: RawServeLimits::default(),
            allow_download: false,
            allow_download_hosts: Vec::new(),
            allow_provider_fallback: false,
            formula_detector: None,
            table_model: None,
            eval_root,
            engine_factory: scripted.factory(),
            downloader: ScriptedDownload::default().factory(),
            free_space: Arc::new(|_dir: &Path| Ok(1 << 40)),
            model_dir,
            engine_config: test_engine_config(),
            post_verify: None,
            flow: FlowSink::Off,
        }
    }

    /// 把流动日志收进内存(M5):返回 `(options, lines)`,`lines` 是逐行可见的记录。
    fn with_flow_capture(mut self) -> (Self, Arc<Mutex<Vec<String>>>) {
        let FlowSink::Capture(lines) = FlowSink::capture() else {
            unreachable!("FlowSink::capture always yields a Capture sink");
        };
        self.flow = FlowSink::Capture(Arc::clone(&lines));
        (self, lines)
    }

    /// 打开公式路由(M4):给出 `--formula-detector` 的路径,公式队列因此可达。
    ///
    /// `detector` 只需是一个路径:脚本化后端不加载它(真实启动期的存在性校验在 `run.rs`),
    /// 但 `FormulaPolicy.detector_path` 必须真的有值——否则接上的就是"只处理显式区域"的
    /// 退化形状,公式任务会静默地一个区域都产不出来。
    ///
    /// **文件必须真的在磁盘上,而且必须"像 ONNX"**:评审 P1-2 之后,公式队列的准入按检测
    /// 模型的状态判定;集合之外的文件没有声明摘要,因此按文档化规则(存在 + 可读 + 像 ONNX)
    /// 判定,而 `run.rs` 在启动期就拒绝"配置了检测模型但文件不在"。夹具因此写一份
    /// protobuf 序言(`0x08 0x07`)开头的占位内容。
    ///
    /// **无条件重写**:夹具目录在 `target/` 下、跨进程保留,`unique()` 每次从 0 开始——
    /// 只写"文件不在时"的话,上一次运行留下的同名文件(旧内容)会决定本次测试的结论。
    fn with_formula_routing(mut self, detector: &Path) -> Self {
        std::fs::write(detector, plausible_onnx_bytes("detector fixture"))
            .expect("write the detector fixture");
        self.formula_detector = Some(detector.to_path_buf());
        self
    }

    /// 打开表格路由(E16.2):给出 `--table-model` 的路径,`?table=1` 因此可达。
    ///
    /// 与 [`TestOptions::with_formula_routing`] 完全同形,包括"文件必须真的在磁盘上、
    /// 而且必须像 ONNX"这一条:集合之外的结构模型没有声明摘要,准入因此按文档化规则
    /// (存在 + 可读 + 像 ONNX)判定,而 `run.rs` 在启动期就拒绝"配置了结构模型但文件不在"。
    fn with_table_routing(mut self, model: &Path) -> Self {
        std::fs::write(model, plausible_onnx_bytes("table structure fixture"))
            .expect("write the table structure fixture");
        self.table_model = Some(model.to_path_buf());
        self
    }

    /// 关闭评估沙箱(评审 P2-3:不给 `--eval-root` 时端点必须拒绝)。
    fn without_eval_root(mut self) -> Self {
        self.eval_root = None;
        self
    }

    /// 覆盖队列容量/配额(§8.3 的公平性测试用)。
    fn with_limits(mut self, limits: RawServeLimits) -> Self {
        self.limits = limits;
        self
    }
}

/// 与 `models/configs/test-config-small.yaml` 一致的文本管线选择(PP-OCRv6 small / multi+ch)。
///
/// 用它而不是 `EngineConfig::default()`:`/api/models` 的集合由这个选择决定,而
/// 默认表的 v4 条目没有 `size_bytes`(M0a 记录),会让"每个文件都报告体积"的断言
/// 变成在测另一件事。
fn test_engine_config() -> EngineConfig {
    let mut config = EngineConfig::default();
    config.det.ocr_version = OcrVersion::PPocrV6;
    config.det.model_type = ModelType::Small;
    config.det.lang = LangDet::Multi;
    config.rec.model.ocr_version = OcrVersion::PPocrV6;
    config.rec.model.model_type = ModelType::Small;
    config.rec.model.lang = LangRec::Ch;
    config
}

/// 一个真实运行的服务实例(Drop 时关闭)。
struct TestServer {
    handle: Option<ServeHandle>,
    addr: SocketAddr,
    token: String,
    host: String,
    origin: String,
}

impl TestServer {
    fn start(options: TestOptions) -> Self {
        let bound = BoundServer::bind(0).expect("an ephemeral port must bind");
        let addr = bound.local_addr();
        let local = LocalOrigin::from_bound(addr).expect("loopback");
        let token = ServeToken::generate().expect("the OS CSPRNG must be available");
        let nonce = generate_nonce().expect("the OS CSPRNG must be available");
        let page = render_page(&token, &nonce).expect("the page must inject cleanly");
        let startup = ServeStartup::validate(
            options.limits,
            options.engine_config,
            None,
            None,
            options.allow_provider_fallback,
        )
        .expect("the test limits must be valid");
        let model_plan = ModelPlan::resolve(
            &options.model_dir,
            &startup.plan.engine,
            options.formula_detector.as_deref(),
            options.table_model.as_deref(),
        )
        .expect("model plan");
        let snapshot = model_plan.snapshot();
        let post_verify = options.post_verify;
        let context = ServeContext {
            limits: startup.limits,
            plan: startup.plan,
            model_plan,
            snapshot,
            token,
            local,
            page,
            nonce,
            allow_download: options.allow_download,
            allow_download_hosts: options.allow_download_hosts,
            // §7.5:`ServeStartup::validate` 用的是同一个开关,运行期切换 provider 也用它。
            allow_provider_fallback: options.allow_provider_fallback,
            eval_root: options.eval_root,
            flow: options.flow,
            engine_factory: options.engine_factory,
            downloader: options.downloader,
            free_space: options.free_space,
            post_verify,
        };
        let handle = ServeHandle::start(bound, context).expect("the runtime must start");
        let token = handle.shared().token().as_str().to_string();
        Self {
            handle: Some(handle),
            addr,
            token,
            host: format!("127.0.0.1:{}", addr.port()),
            origin: format!("http://127.0.0.1:{}", addr.port()),
        }
    }

    fn shared(&self) -> Arc<ServeShared> {
        Arc::clone(self.handle.as_ref().expect("running").shared())
    }

    /// 捕获到的流动日志行(`FlowSink::Off` 时为空;`with_flow_capture` 才有内容)。
    fn flow_lines(&self) -> Vec<String> {
        self.shared().flow().lines()
    }

    /// 一次 GET(默认带 token 与 Host)。
    fn get(&self, path: &str) -> RawResponse {
        self.request(
            "GET",
            path,
            &[
                ("Host", self.host.as_str()),
                ("X-RapidStructure-Token", self.token.as_str()),
            ],
            None,
        )
    }

    /// 一次 POST,带 token + Host + Origin(除非显式覆盖)。
    fn post(&self, path: &str, headers: &[(&str, &str)], body: &[u8]) -> RawResponse {
        let mut all = vec![
            ("Host", self.host.as_str()),
            ("X-RapidStructure-Token", self.token.as_str()),
            ("Origin", self.origin.as_str()),
        ];
        all.extend_from_slice(headers);
        self.request("POST", path, &all, Some(body))
    }

    /// 一次原始请求(`headers` 里可以重复/覆盖默认头;`body` 为 `None` 时不发送 body,
    /// 但 `Content-Length` 由调用方在 headers 里显式给出)。
    ///
    /// 每个请求都带 `Connection: close`:响应因此一定以关闭连接结束,测试客户端不必
    /// 依赖 `Content-Length`(`tiny_http` 对 >32 KiB 的已知长度响应用 chunked,
    /// 内联页面正是这种)。
    fn request(
        &self,
        method: &str,
        path: &str,
        headers: &[(&str, &str)],
        body: Option<&[u8]>,
    ) -> RawResponse {
        raw_request(self.addr, method, path, headers, body)
    }

    fn submit_ocr(&self, body: &[u8]) -> RawResponse {
        self.post(
            "/api/ocr",
            &[("Content-Type", "application/octet-stream")],
            body,
        )
    }

    /// `POST /api/models/download`:请求体**只有** `set_id`(§7.2 禁止 URL)。
    fn download(&self, set_id: &str) -> RawResponse {
        self.post(
            "/api/models/download",
            &[("Content-Type", "application/json")],
            format!("{{\"set_id\":\"{set_id}\"}}").as_bytes(),
        )
    }

    /// 轮询任务直到终态(或超时)。
    fn wait_terminal(&self, id: &str, timeout: Duration) -> Value {
        let deadline = Instant::now() + timeout;
        loop {
            let response = self.get(&format!("/api/jobs/{id}"));
            assert_eq!(response.status, 200, "job view: {}", response.text());
            let value = response.json();
            let state = value["state"].as_str().unwrap_or_default().to_string();
            if matches!(state.as_str(), "succeeded" | "failed" | "cancelled") {
                return value;
            }
            assert!(
                Instant::now() < deadline,
                "job {id} did not finish within {timeout:?}: {value}"
            );
            std::thread::sleep(Duration::from_millis(5));
        }
    }
}

impl Drop for TestServer {
    fn drop(&mut self) {
        // `ServeHandle` 的 `Drop` 负责 unblock + join;这里只是让它确定地发生。
        self.handle.take();
    }
}

/// 极简 HTTP 响应。
struct RawResponse {
    status: u16,
    headers: Vec<(String, String)>,
    body: Vec<u8>,
}

impl RawResponse {
    fn header(&self, name: &str) -> Option<&str> {
        self.headers
            .iter()
            .find(|(field, _)| field.eq_ignore_ascii_case(name))
            .map(|(_, value)| value.as_str())
    }

    fn json(&self) -> Value {
        serde_json::from_slice(&self.body)
            .unwrap_or_else(|error| panic!("body is not JSON ({error}): {}", self.text()))
    }

    fn text(&self) -> String {
        String::from_utf8_lossy(&self.body).into_owned()
    }

    fn code(&self) -> String {
        self.json()["code"].as_str().unwrap_or_default().to_string()
    }
}

/// 一次原始请求的自由函数形式(**并发**测试用:另一个线程只需要有 `addr` 就能发请求,
/// 而不必借用 `TestServer`。M3 的 provider 切换请求会一直阻塞到切换序列结束,
/// 因此它必须在后台线程里发出)。
///
/// 每个请求都带 `Connection: close`:响应因此一定以关闭连接结束,测试客户端不必
/// 依赖 `Content-Length`(`tiny_http` 对 >32 KiB 的已知长度响应用 chunked,
/// 内联页面正是这种)。
fn raw_request(
    addr: SocketAddr,
    method: &str,
    path: &str,
    headers: &[(&str, &str)],
    body: Option<&[u8]>,
) -> RawResponse {
    let mut raw = format!("{method} {path} HTTP/1.1\r\nConnection: close\r\n");
    for (name, value) in headers {
        raw.push_str(&format!("{name}: {value}\r\n"));
    }
    match body {
        Some(body) => {
            raw.push_str(&format!("Content-Length: {}\r\n", body.len()));
            raw.push_str("\r\n");
            let mut bytes = raw.into_bytes();
            bytes.extend_from_slice(body);
            send(addr, &bytes)
        }
        None => {
            raw.push_str("\r\n");
            send(addr, raw.as_bytes())
        }
    }
}

/// 直接把请求字节写进 socket,读到连接关闭,再按响应的定界方式取出 body。
fn send(addr: SocketAddr, raw: &[u8]) -> RawResponse {
    let mut stream = TcpStream::connect(addr).expect("connect");
    stream
        .set_read_timeout(Some(Duration::from_secs(20)))
        .expect("read timeout");
    stream.write_all(raw).expect("write request");
    stream.flush().expect("flush");

    let mut buffer = Vec::new();
    let mut chunk = [0_u8; 8192];
    loop {
        match stream.read(&mut chunk) {
            Ok(0) => break,
            Ok(read) => buffer.extend_from_slice(&chunk[..read]),
            Err(error) => panic!("reading the response failed: {error}"),
        }
    }
    parse_response(&buffer)
}

/// 把一份完整的原始响应字节解析成 [`RawResponse`]。
///
/// 抽成自由函数的理由:A2 的单飞用例必须在**同一个连接**上"先写头、再写体",
/// 因此它自己读字节,然后复用这里的定界逻辑(不能有两套解析)。
fn parse_response(buffer: &[u8]) -> RawResponse {
    let head_end = find(buffer, b"\r\n\r\n").expect("the response must contain a header block") + 4;
    let head = String::from_utf8_lossy(&buffer[..head_end - 4]).into_owned();
    let mut lines = head.split("\r\n");
    let status_line = lines.next().unwrap_or_default();
    let status = status_line
        .split_whitespace()
        .nth(1)
        .and_then(|code| code.parse().ok())
        .unwrap_or_else(|| panic!("cannot parse the status line: {status_line:?}"));
    let headers: Vec<(String, String)> = lines
        .filter_map(|line| line.split_once(':'))
        .map(|(name, value)| (name.trim().to_string(), value.trim().to_string()))
        .collect();
    let raw_body = buffer.get(head_end..).unwrap_or_default();

    let header = |name: &str| -> Option<String> {
        headers
            .iter()
            .find(|(field, _)| field.eq_ignore_ascii_case(name))
            .map(|(_, value)| value.clone())
    };
    let body = match header("Transfer-Encoding") {
        Some(value) if value.to_ascii_lowercase().contains("chunked") => decode_chunked(raw_body),
        _ => match header("Content-Length").and_then(|value| value.parse::<usize>().ok()) {
            Some(length) => raw_body.get(..length).unwrap_or(raw_body).to_vec(),
            None => raw_body.to_vec(),
        },
    };
    RawResponse {
        status,
        headers,
        body,
    }
}

/// 解 chunked 响应体(`tiny_http` 对 >32 KiB 的已知长度响应会用 chunked)。
fn decode_chunked(body: &[u8]) -> Vec<u8> {
    let mut out = Vec::new();
    let mut rest = body;
    while let Some(position) = find(rest, b"\r\n") {
        let size_line = String::from_utf8_lossy(&rest[..position]).into_owned();
        let size_text = size_line.split(';').next().unwrap_or_default().trim();
        let Ok(size) = usize::from_str_radix(size_text, 16) else {
            break;
        };
        rest = &rest[position + 2..];
        if size == 0 {
            break;
        }
        let Some(chunk) = rest.get(..size) else {
            out.extend_from_slice(rest);
            break;
        };
        out.extend_from_slice(chunk);
        rest = rest.get(size + 2..).unwrap_or_default();
    }
    out
}

fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack
        .windows(needle.len())
        .position(|window| window == needle)
}

// ------------------------------------------------ M2 的下载接缝(无网络)

/// 测试模型文件的内容:**由文件名唯一决定**。
///
/// 模型目录的 manifest 用它的真实 SHA-256 声明哈希,脚本化下载器写出同样的字节,
/// 因此"下载完成后 `/api/models` 真的变成 `complete`"走的是库的真实哈希校验,
/// 而不是把状态标记成"完成"。
fn model_file_bytes(name: &str) -> Vec<u8> {
    format!("M2 scripted model file {name}").into_bytes()
}

/// 一份"看起来像 ONNX"的内容:protobuf 序言 = 字段 1(`ir_version`)= 7。
///
/// 集合之外的 `--formula-detector` **没有声明摘要**,因此按文档化规则判定
/// (存在 + 可读 + 像 ONNX);夹具必须过这一关,否则"公式队列可用"的用例会在准入处
/// 拿到 409 而不是 202。声明了摘要的文件看哈希,内容与本函数无关。
fn plausible_onnx_bytes(tag: &str) -> Vec<u8> {
    let mut bytes = vec![0x08, 0x07];
    bytes.extend_from_slice(tag.as_bytes());
    bytes
}

/// 一个用本地 manifest 描述的模型目录:
/// `det.onnx` / `rec.onnx` / `dict.txt`(文本管线)+ `fx.onnx`(`formula_recognizer`)。
///
/// M4 起**每个**清单来源都必须声明公式 role:`serve` 的模型清单请求
/// `ModelRequest::text_and_formula`(页面要能报告公式集合的体积并让用户按集合下载),
/// 因此缺 role 是一个可定位的启动期错误(§5.3),不是静默降级。
///
/// `present` 里的文件真的写到磁盘上(内容 = [`model_file_bytes`]),其余缺失;
/// `declared_size` 为 `Some` 时每个文件的 `size_bytes` 都写成它(用于构造
/// "声明体积超过预算/磁盘空间"的场景,而文件本身仍然很小)。
fn manifest_model_dir(name: &str, present: &[&str], declared_size: Option<u64>) -> PathBuf {
    let dir = m2_root().join(format!("manifest-{name}-{}", unique()));
    std::fs::create_dir_all(&dir).expect("create the model dir");
    let files = model_fixture_files();
    let mut manifest = String::from(
        "{\"schema_version\":1,\"id\":\"test-set\",\"family\":\"PP-OCR\",\"version\":\"v-test\",\
         \"languages\":[\"en\"],\"files\":[",
    );
    for (index, (file, role)) in files.iter().enumerate() {
        let bytes = model_file_bytes(file);
        let path = dir.join(file);
        std::fs::write(&path, &bytes).expect("write the model file");
        let sha = sha256_file(&path).expect("hash the model file");
        if index > 0 {
            manifest.push(',');
        }
        let size = declared_size.unwrap_or(bytes.len() as u64);
        manifest.push_str(&format!(
            "{{\"name\":\"{file}\",\"role\":\"{role}\",\"sha256\":\"{sha}\",\"size_bytes\":{size},\
             \"source_url\":\"https://www.modelscope.cn/models/{file}\"}}"
        ));
    }
    manifest.push_str("]}");
    std::fs::write(dir.join("manifest.json"), manifest).expect("write the manifest");
    for (file, _) in files {
        if !present.contains(&file) {
            std::fs::remove_file(dir.join(file)).expect("remove the absent file");
        }
    }
    dir
}

/// 测试清单描述的四个文件(M4 起包含公式识别模型)。
///
/// 文本三个 + 公式一个:这样**同一个集合**里就有两条管线的 role,
/// "按 role 分组判定就绪"这条规则在本地清单来源下也被真实地走到了。
fn model_fixture_files() -> [(&'static str, &'static str); 4] {
    [
        ("det.onnx", "detector"),
        ("rec.onnx", "recognizer"),
        ("dict.txt", "dictionary"),
        ("fx.onnx", "formula_recognizer"),
    ]
}

/// 测试清单里的文本管线文件(`present` 参数里最常用的那一组)。
fn text_fixture_files() -> [&'static str; 3] {
    ["det.onnx", "rec.onnx", "dict.txt"]
}

/// 与 [`manifest_model_dir`] 相同,但公式识别模型**已经在场**。
///
/// M2 的下载用例考察的是**文本集合**的进度、预算、磁盘核算与取消;公式文件(566 MB,
/// 在真实场景里是一个独立的下载动作)不该参与这些数字。M4 起每个清单都必须声明
/// `formula_recognizer` role(否则启动期就报缺 role),因此这里把它放成 `present`:
/// 它不出现在"待下载"集合里,M2 的数字仍然逐字成立。
fn manifest_model_dir_text_only(
    name: &str,
    present: &[&str],
    declared_size: Option<u64>,
) -> PathBuf {
    let mut files: Vec<&str> = present.to_vec();
    files.push("fx.onnx");
    manifest_model_dir(name, &files, declared_size)
}

/// M2 fixture 的根目录(与 M1 的 `target/m1-serve-tests` 分开,避免互相干扰)。
fn m2_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target/m2-serve-tests")
}

/// 一个"到点即停"的闸门:脚本化下载器在某个文件开始后阻塞,直到测试放行。
///
/// 有了它,"运行中的进度"与"运行中取消"就是**确定性**的断言,而不是靠 sleep 猜时序。
/// 两条 channel 的容量都是 0:`send` 会一直阻塞到对端 `recv`。
struct Gate {
    reached: std::sync::mpsc::SyncSender<()>,
    reached_rx: Mutex<std::sync::mpsc::Receiver<()>>,
    release: std::sync::mpsc::SyncSender<()>,
    release_rx: Mutex<std::sync::mpsc::Receiver<()>>,
}

impl Gate {
    fn new() -> Arc<Self> {
        let (reached, reached_rx) = std::sync::mpsc::sync_channel(0);
        let (release, release_rx) = std::sync::mpsc::sync_channel(0);
        Arc::new(Self {
            reached,
            reached_rx: Mutex::new(reached_rx),
            release,
            release_rx: Mutex::new(release_rx),
        })
    }

    /// 下载器侧:通知测试"到达"并阻塞到放行。
    fn wait(&self) {
        let _ = self.reached.send(());
        let release = self.release_rx.lock().expect("the gate is not poisoned");
        let _ = release.recv();
    }

    /// 测试侧:等到下载器到达闸门。
    fn arrive(&self) {
        let reached = self.reached_rx.lock().expect("the gate is not poisoned");
        let _ = reached.recv();
    }

    /// 测试侧:放行一次。
    fn release(&self) {
        let _ = self.release.send(());
    }
}

/// 脚本化下载器里"一个待下载文件"的动作(不足时复用最后一个;空计划 = 全部写入)。
#[derive(Debug, Clone)]
enum Step {
    /// 把 [`model_file_bytes`] 写到模型目录(因此哈希校验真的会通过)。
    Write,
    /// 报告哈希不匹配(文件**不**落盘,模拟库侧删除临时文件后的结论)。
    HashMismatch,
    /// 报告传输失败。
    Network,
    /// 报告在文件边界取消。
    Cancelled,
}

/// 脚本化下载器的共享状态(工厂每次调用都克隆它,因此多次任务共享记录)。
#[derive(Clone)]
struct ScriptedDownload {
    plan: Vec<Step>,
    /// 每次任务收到的**显式** host 允许列表(证明它是参数而不是被改掉的常量)。
    seen_hosts: Arc<Mutex<Vec<Vec<String>>>>,
    /// 真正写完的文件(按顺序),用于断言"取消后停在哪"。
    written: Arc<Mutex<Vec<String>>>,
    /// 每个文件开始后阻塞一次(可选)。
    gate: Option<Arc<Gate>>,
}

impl Default for ScriptedDownload {
    fn default() -> Self {
        Self {
            plan: Vec::new(),
            seen_hosts: Arc::new(Mutex::new(Vec::new())),
            written: Arc::new(Mutex::new(Vec::new())),
            gate: None,
        }
    }
}

impl ScriptedDownload {
    fn with_plan(plan: Vec<Step>) -> Self {
        Self {
            plan,
            ..Self::default()
        }
    }

    fn with_gate(gate: Arc<Gate>) -> Self {
        Self {
            gate: Some(gate),
            ..Self::default()
        }
    }

    fn step(&self, index: usize) -> Step {
        if self.plan.is_empty() {
            return Step::Write;
        }
        self.plan
            .get(index)
            .cloned()
            .unwrap_or_else(|| self.plan.last().cloned().expect("a non-empty plan"))
    }

    fn factory(self) -> DownloaderFactory {
        Arc::new(move || {
            Box::new(ScriptedDownloader {
                state: self.clone(),
            })
        })
    }

    fn hosts_per_call(&self) -> Vec<Vec<String>> {
        self.seen_hosts.lock().expect("not poisoned").clone()
    }

    fn written(&self) -> Vec<String> {
        self.written.lock().expect("not poisoned").clone()
    }
}

/// 把 [`ScriptedDownload`] 的计划演成一个 [`ModelDownloader`]。
///
/// 它**只**替代"网络 + 落盘"这一段:待下载文件如何选出(`state_in` 的真实实现)、
/// 进度回调、取消检查点、任务状态机、`/api/models` 的哈希校验全部是生产代码。
struct ScriptedDownloader {
    state: ScriptedDownload,
}

impl ModelDownloader for ScriptedDownloader {
    fn download(
        &mut self,
        job: &DownloadJob<'_>,
        sink: &mut dyn DownloadSink,
    ) -> Result<Vec<PathBuf>, RapidOcrError> {
        self.state
            .seen_hosts
            .lock()
            .expect("not poisoned")
            .push(job.allowed_hosts.clone());
        let pending: Vec<ModelFileSpec> = job
            .set
            .files
            .iter()
            .filter(|file| !file.state_in(job.root).is_present())
            .cloned()
            .collect();
        let total = pending.len();
        let mut paths = Vec::with_capacity(total);
        for (offset, file) in pending.iter().enumerate() {
            let index = offset + 1;
            // 生产代码里的**唯一**取消检查点(由 `JobSink` 查询任务存储)。
            if !sink.file_started(file, index, total, file.size_bytes) {
                return Err(DownloadError::Cancelled.into());
            }
            if let Some(gate) = &self.state.gate {
                gate.wait();
            }
            match self.state.step(offset) {
                Step::Write => {
                    let bytes = model_file_bytes(&file.name);
                    std::fs::write(job.root.join(&file.name), &bytes)
                        .expect("the scripted download must be able to write the model file");
                    // 分两块上报:进度是"当前文件的累计值"(与库的分块读取一致)。
                    sink.bytes_written(bytes.len() as u64 / 2);
                    sink.bytes_written(bytes.len() as u64);
                    sink.file_finished(file, index, bytes.len() as u64);
                    self.state
                        .written
                        .lock()
                        .expect("not poisoned")
                        .push(file.name.clone());
                    paths.push(job.root.join(&file.name));
                }
                Step::HashMismatch => {
                    sink.bytes_written(1);
                    return Err(DownloadError::HashMismatch {
                        expected: file.sha256.clone(),
                        actual: "00".repeat(32),
                    }
                    .into());
                }
                Step::Network => {
                    return Err(DownloadError::Network {
                        detail: "scripted transport failure".to_string(),
                    }
                    .into());
                }
                Step::Cancelled => return Err(DownloadError::Cancelled.into()),
            }
        }
        Ok(paths)
    }
}

/// 空的模型目录(默认表来源,全部文件缺失)。
fn empty_model_dir(name: &str) -> PathBuf {
    let dir = test_root().join(format!("empty-{name}-{}", unique()));
    std::fs::create_dir_all(&dir).expect("create the empty model dir");
    dir
}

/// 齐备的模型目录:本地 `manifest.json` + 四个内容为 `name` 的文件(SHA-256 真实计算)。
///
/// 四个 = 文本三个 + `fx.onnx`(`formula_recognizer`):M4 起"齐备"是**两条管线**都齐备,
/// 否则 `/api/models` 的 `formula.complete` 会是假、页面上的公式开关会被正确地禁用。
fn complete_model_dir(name: &str) -> PathBuf {
    let dir = test_root().join(format!("complete-{name}-{}", unique()));
    std::fs::create_dir_all(&dir).expect("create the model dir");
    let files = model_fixture_files();
    let mut manifest = String::from(
        "{\"schema_version\":1,\"id\":\"test-set\",\"family\":\"PP-OCR\",\"version\":\"v-test\",\
         \"files\":[",
    );
    for (index, (file, role)) in files.iter().enumerate() {
        let path = dir.join(file);
        std::fs::write(&path, format!("test model file {file}")).expect("write the model file");
        let sha = sha256_file(&path).expect("hash the model file");
        if index > 0 {
            manifest.push(',');
        }
        manifest.push_str(&format!(
            "{{\"name\":\"{file}\",\"role\":\"{role}\",\"sha256\":\"{sha}\",\"size_bytes\":18}}"
        ));
    }
    manifest.push_str("]}");
    std::fs::write(dir.join("manifest.json"), manifest).expect("write the manifest");
    dir
}

fn test_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target/m1-serve-tests")
}

/// 与 [`complete_model_dir`] 相同,但**清单声明了表格结构模型**(`role = table_structure`)。
///
/// 单独一个夹具而不是往 [`model_fixture_files`] 里加一个文件:那张清单的四个文件被
/// M1/M2/M4 的许多断言按名字与数量钉住,往里加一个会让那些数字全部漂移。
/// E16 要证明的命题是"**集合声明的**摘要真的流到了 `TablePolicy.expected_model_sha256`",
/// 因此这个夹具必须让清单真的声明它——否则断言两侧同为 `None`,什么也没证明。
fn complete_model_dir_with_table(name: &str) -> PathBuf {
    let dir = test_root().join(format!("complete-table-{name}-{}", unique()));
    std::fs::create_dir_all(&dir).expect("create the model dir");
    let mut files: Vec<(&'static str, &'static str)> = model_fixture_files().to_vec();
    files.push(("slanet-plus.onnx", "table_structure"));
    let mut manifest = String::from(
        "{\"schema_version\":1,\"id\":\"test-set\",\"family\":\"PP-OCR\",\"version\":\"v-test\",\
         \"files\":[",
    );
    for (index, (file, role)) in files.iter().enumerate() {
        let path = dir.join(file);
        std::fs::write(&path, format!("test model file {file}")).expect("write the model file");
        let sha = sha256_file(&path).expect("hash the model file");
        if index > 0 {
            manifest.push(',');
        }
        manifest.push_str(&format!(
            "{{\"name\":\"{file}\",\"role\":\"{role}\",\"sha256\":\"{sha}\",\"size_bytes\":18}}"
        ));
    }
    manifest.push_str("]}");
    std::fs::write(dir.join("manifest.json"), manifest).expect("write the manifest");
    dir
}

fn unique() -> u64 {
    use std::sync::atomic::AtomicU64;
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    COUNTER.fetch_add(1, Ordering::SeqCst)
}

/// 串行化"会动**进程级**校验缓存"的用例:`POST /api/models/reverify` 会
/// `clear_verification_cache()`,`force_verify_file` 会写入条目——两者都会影响
/// 别的用例对 `verification.cold_this_call` 的**精确**断言("第二次轮询必须是 0")。
///
/// 这与库内 `model_verify::tests` 的 `serial()` 是同一个理由:缓存是进程级的,而
/// `cargo test` 并行跑用例。因此凡是"清缓存"或"断言这一次算了几个"的用例都持有它;
/// 没有它,"精确计数"就只能是概率事件(`docs/06` 记录过同类偶发失败)。
fn cache_serial() -> std::sync::MutexGuard<'static, ()> {
    static SERIAL: Mutex<()> = Mutex::new(());
    SERIAL.lock().unwrap_or_else(|error| error.into_inner())
}

fn limits(text: usize, formula: usize) -> RawServeLimits {
    RawServeLimits {
        max_queue_text: text,
        max_queue_formula: formula,
        ..RawServeLimits::default()
    }
}

/// 等待某个条件(用于把测试的时序断言写成"有上界"而不是"恰好")。
fn wait_until(timeout: Duration, mut condition: impl FnMut() -> bool) -> bool {
    let deadline = Instant::now() + timeout;
    while Instant::now() < deadline {
        if condition() {
            return true;
        }
        std::thread::sleep(Duration::from_millis(5));
    }
    false
}

// ---------------------------------------------------------------- 页面与安全

#[test]
fn the_page_carries_the_nonce_csp_and_the_frozen_security_headers() {
    let server = TestServer::start(TestOptions::new(empty_model_dir("page"), Scripted::fast()));
    // 浏览器请求 `GET /` 时**不会**带令牌(§7.2:令牌只对 /api/* 必需)——
    // 这正是页面把令牌注入 `window.__RROCR__` 的原因。
    let response = server.request("GET", "/", &[("Host", server.host.as_str())], None);

    assert_eq!(response.status, 200, "{}", response.text());
    assert_eq!(
        response.header("Content-Type"),
        Some("text/html; charset=utf-8")
    );
    assert_eq!(response.header("X-Content-Type-Options"), Some("nosniff"));
    assert_eq!(response.header("Referrer-Policy"), Some("no-referrer"));
    assert_eq!(response.header("Cache-Control"), Some("no-store"));
    assert!(
        response.header("Access-Control-Allow-Origin").is_none(),
        "CORS headers must never be sent"
    );

    let csp = response
        .header("Content-Security-Policy")
        .expect("CSP header");
    assert!(!csp.contains("unsafe-inline"), "{csp}");
    assert!(csp.contains("script-src 'nonce-"), "{csp}");
    assert!(csp.contains("style-src 'nonce-"), "{csp}");
    // nonce 与页面里的每一个 nonce 属性逐字节相同。
    let nonce = csp
        .split("script-src 'nonce-")
        .nth(1)
        .and_then(|rest| rest.split('\'').next())
        .expect("a nonce in the CSP");
    assert_eq!(nonce, server.shared().nonce());
    let page = response.text();
    assert!(
        !page.contains("__CSP_NONCE__"),
        "no placeholder may survive"
    );
    assert!(!page.contains("__SRV_TOKEN__"));
    assert_eq!(page.matches(&format!("nonce=\"{nonce}\"")).count(), 3);
    assert_eq!(page.matches(&server.token).count(), 3);
}

#[test]
fn the_token_is_required_on_every_api_route() {
    let server = TestServer::start(TestOptions::new(empty_model_dir("token"), Scripted::fast()));
    // 没有令牌时 `GET /` 仍然可用(它是令牌的下发者),而每个 /api/* 都是 401。
    assert_eq!(
        server
            .request("GET", "/", &[("Host", server.host.as_str())], None)
            .status,
        200
    );
    for path in ["/api/status", "/api/models", "/api/jobs/job-0"] {
        let response = server.request("GET", path, &[("Host", server.host.as_str())], None);
        assert_eq!(response.status, 401, "{path}: {}", response.text());
        assert_eq!(response.code(), "unauthorized", "{path}");
        // 错误体形状固定为三键。
        let body = response.json();
        assert!(body.get("code").is_some() && body.get("message").is_some());
        assert!(body.get("detail").is_some(), "detail must exist: {body}");
    }
    // 错误的 token 同样是 401(不是 403 / 404)。
    let response = server.request(
        "GET",
        "/api/status",
        &[
            ("Host", server.host.as_str()),
            ("X-RapidStructure-Token", "not-the-token"),
        ],
        None,
    );
    assert_eq!(response.status, 401);
}

/// `GET /static/*`:公式渲染引擎的同源资源。**不带令牌**也可获取(不在 `/api/*`
/// 边界内,§7.2),响应带正确 MIME 与 `no-store`;未知路径、目录穿越形状与
/// 编码变体全部落到和其它未知路径同一个 404;POST → 405。
#[test]
fn static_formula_assets_are_served_same_origin_without_the_token() {
    let server = TestServer::start(TestOptions::new(
        empty_model_dir("static"),
        Scripted::fast(),
    ));
    for (path, mime) in [
        (
            "/static/katex/katex.min.js",
            "application/javascript; charset=utf-8",
        ),
        ("/static/katex/katex.min.css", "text/css; charset=utf-8"),
        ("/static/katex/fonts/KaTeX_Main-Regular.woff2", "font/woff2"),
        (
            "/static/mathjax/tex-svg.js",
            "application/javascript; charset=utf-8",
        ),
    ] {
        let response = server.request("GET", path, &[("Host", server.host.as_str())], None);
        assert_eq!(response.status, 200, "{path}: {}", response.text());
        assert_eq!(response.header("Content-Type"), Some(mime), "{path}");
        assert_eq!(response.header("Cache-Control"), Some("no-store"), "{path}");
        assert!(!response.body.is_empty(), "{path} must not be empty");
    }

    // 表外路径 / 穿越形状 / 编码变体 / 前缀本身:与任意未知路径同一个 404。
    for path in [
        "/static/nope.js",
        "/static/",
        "/static/../Cargo.toml",
        "/static/katex/../../Cargo.toml",
        "/static/%2e%2e%2f%2e%2e%2fCargo.toml",
    ] {
        let response = server.request("GET", path, &[("Host", server.host.as_str())], None);
        assert_eq!(response.status, 404, "{path}: {}", response.text());
        assert_eq!(response.code(), "not_found", "{path}");
    }

    let response = server.request(
        "POST",
        "/static/katex/katex.min.js",
        &[("Host", server.host.as_str())],
        None,
    );
    assert_eq!(response.status, 405);
    assert_eq!(response.header("Allow"), Some("GET"));
}

#[test]
fn the_host_header_is_validated_for_dns_rebinding() {
    let server = TestServer::start(TestOptions::new(empty_model_dir("host"), Scripted::fast()));
    let token = server.token.clone();
    for host in [
        "evil.example:8760",
        "127.0.0.1:1",
        "[::1]:8760",
        "localhost",
        "127.0.0.10:1",
    ] {
        let response = server.request(
            "GET",
            "/api/status",
            &[("Host", host), ("X-RapidStructure-Token", token.as_str())],
            None,
        );
        assert_eq!(response.status, 421, "Host: {host} → {}", response.text());
        assert_eq!(response.code(), "bad_host");
    }
    // 没有 Host 头也是 421。
    let response = server.request(
        "GET",
        "/api/status",
        &[("X-RapidStructure-Token", token.as_str())],
        None,
    );
    assert_eq!(response.status, 421);
}

#[test]
fn state_changing_requests_require_a_matching_origin() {
    let server = TestServer::start(TestOptions::new(
        empty_model_dir("origin"),
        Scripted::fast(),
    ));
    let token = server.token.clone();
    let host = server.host.clone();
    let body = b"not-an-image".as_slice();

    // 缺失 Origin。
    let response = server.request(
        "POST",
        "/api/ocr",
        &[
            ("Host", host.as_str()),
            ("X-RapidStructure-Token", token.as_str()),
            ("Content-Type", "application/octet-stream"),
        ],
        Some(body),
    );
    assert_eq!(response.status, 403, "{}", response.text());
    assert_eq!(response.code(), "bad_origin");

    // `Origin: null`(沙箱 iframe / file:// 会这么发)。
    let response = server.request(
        "POST",
        "/api/ocr",
        &[
            ("Host", host.as_str()),
            ("X-RapidStructure-Token", token.as_str()),
            ("Origin", "null"),
            ("Content-Type", "application/octet-stream"),
        ],
        Some(body),
    );
    assert_eq!(response.status, 403);

    // 另一个 origin。
    let response = server.request(
        "POST",
        "/api/ocr",
        &[
            ("Host", host.as_str()),
            ("X-RapidStructure-Token", token.as_str()),
            ("Origin", "http://127.0.0.1:1"),
            ("Content-Type", "application/octet-stream"),
        ],
        Some(body),
    );
    assert_eq!(response.status, 403);

    // 正确 origin 但队列/模型状态另有结论:403 不再是它的失败原因。
    let response = server.request(
        "POST",
        "/api/ocr",
        &[
            ("Host", host.as_str()),
            ("X-RapidStructure-Token", token.as_str()),
            ("Origin", "http://127.0.0.1:1/"),
            ("Content-Type", "application/octet-stream"),
        ],
        Some(body),
    );
    assert_eq!(response.status, 403, "a trailing slash is still a mismatch");
}

#[test]
fn read_requests_do_not_require_an_origin() {
    let server = TestServer::start(TestOptions::new(
        empty_model_dir("get-origin"),
        Scripted::fast(),
    ));
    let response = server.get("/api/status");
    assert_eq!(response.status, 200, "{}", response.text());
}

// ---------------------------------------------------------------- 准入顺序

#[test]
fn an_over_long_content_length_is_rejected_before_the_body_is_read() {
    let mut raw = limits(4, 2);
    raw.max_body_mb = 1;
    let server = TestServer::start(TestOptions {
        limits: raw,
        ..TestOptions::new(empty_model_dir("413"), Scripted::fast())
    });

    // 声明 4 MiB、**一个字节都不发**:服务端必须直接回 413。这正是"拒绝发生在读取
    // 请求体之前"的可观测证据(否则这个请求会一直等到读取超时)。
    let response = server.request(
        "POST",
        "/api/ocr",
        &[
            ("Host", server.host.as_str()),
            ("X-RapidStructure-Token", server.token.as_str()),
            ("Origin", server.origin.as_str()),
            ("Content-Type", "application/octet-stream"),
            ("Content-Length", "4194304"),
        ],
        None,
    );
    assert_eq!(response.status, 413, "{}", response.text());
    assert_eq!(response.code(), "payload_too_large");
}

#[test]
fn unknown_paths_are_404_and_wrong_methods_are_405() {
    let server = TestServer::start(TestOptions::new(empty_model_dir("route"), Scripted::fast()));

    // 不存在的东西仍然是 404(`not_found` 只用于"没有这条路由")。
    for path in [
        "/favicon.ico",
        "/api",
        "/api/jobs/job-0/annotated",
        "/api/nope",
    ] {
        let response = server.get(path);
        assert_eq!(response.status, 404, "{path}: {}", response.text());
        assert_eq!(response.code(), "not_found", "{path}");
    }

    // M3 的两个端点现在是**真实路由**:任务不存在 → 404 `job_not_found`(不是路由没匹配)。
    for path in [
        "/api/jobs/job-0/annotated.png",
        "/api/jobs/job-0/export?format=json",
    ] {
        let response = server.get(path);
        assert_eq!(response.status, 404, "{path}: {}", response.text());
        assert_eq!(response.code(), "job_not_found", "{path}");
    }

    let response = server.get("/api/ocr");
    assert_eq!(response.status, 405, "{}", response.text());
    assert_eq!(response.code(), "method_not_allowed");
    assert_eq!(response.header("Allow"), Some("POST"));

    // M2 新增的 `POST /api/engine/reload` 是真实路由:GET 它必须是 405 而不是 404。
    let response = server.get("/api/engine/reload");
    assert_eq!(response.status, 405, "{}", response.text());
    assert_eq!(response.code(), "method_not_allowed");
    assert_eq!(response.header("Allow"), Some("POST"));

    // M3 的两个端点只接受 GET。
    for path in ["/api/jobs/job-0/annotated.png", "/api/jobs/job-0/export"] {
        let response = server.post(path, &[], b"");
        assert_eq!(response.status, 405, "{path}: {}", response.text());
        assert_eq!(response.header("Allow"), Some("GET"), "{path}");
    }
}

#[test]
fn the_ocr_media_type_is_validated() {
    let server = TestServer::start(TestOptions::new(empty_model_dir("ctype"), Scripted::fast()));
    let response = server.post(
        "/api/ocr",
        &[("Content-Type", "application/x-www-form-urlencoded")],
        b"x=1",
    );
    assert_eq!(response.status, 400, "{}", response.text());
    assert_eq!(response.code(), "bad_request");
}

#[test]
fn the_max_side_query_parameter_is_validated() {
    let server = TestServer::start(TestOptions::new(
        empty_model_dir("maxside"),
        Scripted::fast(),
    ));
    for bad in ["0", "29", "abc", "99999999999999999999"] {
        let response = server.post(
            &format!("/api/ocr?max_side={bad}"),
            &[("Content-Type", "application/octet-stream")],
            b"image",
        );
        assert_eq!(response.status, 400, "max_side={bad}: {}", response.text());
    }
}

// ---------------------------------------------------------------- 协议闭环

#[test]
fn the_job_goes_from_202_to_succeeded_and_its_result_round_trips() {
    let server = TestServer::start(TestOptions::new(
        complete_model_dir("flow"),
        Scripted::fast(),
    ));
    // 模型齐备 → 引擎预加载 Ready(走的是真实的 ModelSource/ModelSet 路径)。
    let status = server.get("/api/status").json();
    assert_eq!(status["state"], "ready");
    assert_eq!(status["engine"]["state"], "ready");
    assert_eq!(status["engine"]["fallback_to_cpu"], false);
    assert_eq!(
        status["provider"]["requested"],
        rapid_structure_rs::format_provider_preference(
            rapid_structure_rs::ProviderPreference::default()
        )
    );
    assert_eq!(status["provider"]["selected_ep"], "cpu");
    assert_eq!(status["provider"]["fallback_to_cpu"], false);

    let response = server.submit_ocr(b"pretend png bytes");
    assert_eq!(response.status, 202, "{}", response.text());
    let accepted = response.json();
    assert_eq!(accepted["state"], "queued");
    assert_eq!(accepted["queue"], "text");
    assert_eq!(accepted["kind"], "ocr");
    assert!(accepted["job_id"].as_str().is_some());
    assert!(accepted["position"].as_u64().is_some());

    let id = accepted["job_id"].as_str().expect("job id").to_string();
    let view = server.wait_terminal(&id, Duration::from_secs(20));
    assert_eq!(view["state"], "succeeded", "{view}");

    let result = server.get(&format!("/api/jobs/{id}/result"));
    assert_eq!(result.status, 200, "{}", result.text());
    assert_eq!(
        result.header("Content-Type"),
        Some("application/json; charset=utf-8")
    );
    let value = result.json();
    assert_eq!(value["regions"].as_array().map(Vec::len), Some(3));
    assert_eq!(value["regions"][0]["kind"], "text");
    assert_eq!(value["regions"][0]["recognition"]["text"], "region-0");
    assert!(value["regions"][0]["polygon"]["points"].is_array());
    assert!(
        value["text"]
            .as_str()
            .is_some_and(|text| text.contains("region-1")),
        "plain text must be present: {value}"
    );
    // 冻结页面的"复制全文"读 `plain_text`(docs/05 §9.2);它与库的 `text` 同值。
    assert_eq!(value["plain_text"], value["text"]);
}

#[test]
fn a_failed_job_replays_its_original_status_and_code_on_result() {
    let server = TestServer::start(TestOptions::new(
        complete_model_dir("fail"),
        Scripted {
            fail: true,
            ..Scripted::fast()
        },
    ));
    let accepted = server.submit_ocr(b"broken").json();
    let id = accepted["job_id"].as_str().expect("job id").to_string();
    let view = server.wait_terminal(&id, Duration::from_secs(20));
    assert_eq!(view["state"], "failed");
    assert!(
        view["error"]
            .as_str()
            .is_some_and(|error| error.contains("cannot be decoded")),
        "{view}"
    );

    // `/result` 重放真实原因(422 unsupported_input),而不是把它压成 job_not_finished。
    let result = server.get(&format!("/api/jobs/{id}/result"));
    assert_eq!(result.status, 422, "{}", result.text());
    assert_eq!(result.code(), "unsupported_input");
}

#[test]
fn a_result_over_the_limit_is_a_413_result_too_large() {
    let mut raw = limits(4, 2);
    raw.max_result_mb = 1;
    let server = TestServer::start(TestOptions {
        limits: raw,
        ..TestOptions::new(
            complete_model_dir("toobig"),
            Scripted {
                regions: 1,
                text_bytes: 2 * 1024 * 1024,
                ..Scripted::fast()
            },
        )
    });
    let accepted = server.submit_ocr(b"huge result").json();
    let id = accepted["job_id"].as_str().expect("job id").to_string();
    let view = server.wait_terminal(&id, Duration::from_secs(30));
    assert_eq!(view["state"], "failed", "{view}");

    let result = server.get(&format!("/api/jobs/{id}/result"));
    assert_eq!(result.status, 413, "{}", result.text());
    assert_eq!(result.code(), "result_too_large");
}

#[test]
fn a_result_under_the_limit_is_served_intact() {
    let mut raw = limits(4, 2);
    raw.max_result_mb = 1;
    let server = TestServer::start(TestOptions {
        limits: raw,
        ..TestOptions::new(
            complete_model_dir("under"),
            Scripted {
                regions: 1,
                text_bytes: 64 * 1024,
                ..Scripted::fast()
            },
        )
    });
    let accepted = server.submit_ocr(b"small result").json();
    let id = accepted["job_id"].as_str().expect("job id").to_string();
    assert_eq!(
        server.wait_terminal(&id, Duration::from_secs(20))["state"],
        "succeeded"
    );
    let result = server.get(&format!("/api/jobs/{id}/result"));
    assert_eq!(result.status, 200);
    assert_eq!(
        result.json()["regions"][0]["recognition"]["text"],
        "x".repeat(64 * 1024)
    );
}

#[test]
fn cancelling_a_queued_job_succeeds_and_a_running_job_is_409() {
    let server = TestServer::start(TestOptions {
        limits: limits(2, 1),
        ..TestOptions::new(
            complete_model_dir("cancel"),
            Scripted::slow(Duration::from_millis(400)),
        )
    });

    // 第一个任务进入 Running。
    let first = server.submit_ocr(b"a").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    assert!(
        wait_until(Duration::from_secs(10), || {
            server.get(&format!("/api/jobs/{first}")).json()["state"] == "running"
        }),
        "the first job must reach running"
    );

    // 排队中的第二个任务可以被可靠取消(§4.3)。
    let second = server.submit_ocr(b"b").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    let cancelled = server.post(&format!("/api/jobs/{second}/cancel"), &[], b"");
    assert_eq!(cancelled.status, 200, "{}", cancelled.text());
    assert_eq!(cancelled.json()["state"], "cancelled");

    // 运行中的任务不可取消:409 not_cancellable,且状态**不变**。
    let running = server.post(&format!("/api/jobs/{first}/cancel"), &[], b"");
    assert_eq!(running.status, 409, "{}", running.text());
    assert_eq!(running.code(), "not_cancellable");
    assert_eq!(
        server.get(&format!("/api/jobs/{first}")).json()["state"],
        "running",
        "a refused cancel must not change the state"
    );

    // 终态再取消也是 409(不假装成功)。
    server.wait_terminal(&first, Duration::from_secs(20));
    let again = server.post(&format!("/api/jobs/{first}/cancel"), &[], b"");
    assert_eq!(again.status, 409);
}

#[test]
fn a_full_queue_is_503_without_reading_the_body() {
    let server = TestServer::start(TestOptions {
        limits: limits(1, 1),
        ..TestOptions::new(
            complete_model_dir("busy"),
            Scripted::slow(Duration::from_millis(400)),
        )
    });

    let first = server.submit_ocr(b"a").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    assert!(wait_until(Duration::from_secs(10), || {
        server.get(&format!("/api/jobs/{first}")).json()["state"] == "running"
    }));
    // 队列容量 1 → 第二个任务占满队列。
    let second = server.submit_ocr(b"b");
    assert_eq!(second.status, 202, "{}", second.text());
    // 第三个任务立刻 503(不等、不读 body)。
    let third = server.submit_ocr(b"c");
    assert_eq!(third.status, 503, "{}", third.text());
    assert_eq!(third.code(), "busy");

    server.wait_terminal(&first, Duration::from_secs(20));
}

/// 评审 P2-1:队列在容量上限时,**并发**到达的一批请求必须全部 503,
/// 且**没有一个**读入了请求体。
///
/// 证据与 413 的用例同一手法:声明 1 MiB 却一个字节都不发。任何一个请求只要越过了
/// 第 4 步,就会阻塞在读取 body 上(直到 30 s 的读取超时),而这些请求必须是**立刻**
/// 503——因此"全部 503"本身就证明它们都没有读 body。
#[test]
fn a_full_queue_rejects_every_concurrent_request_without_reading_a_body() {
    let server = TestServer::start(TestOptions {
        limits: limits(1, 1),
        ..TestOptions::new(
            complete_model_dir("reserve-full"),
            Scripted::slow(Duration::from_millis(600)),
        )
    });

    // 一个长任务占住 worker,队列里再放一个 → 队列满(容量 1)。
    let running = server.submit_ocr(b"a").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    assert!(wait_until(Duration::from_secs(10), || {
        server.get(&format!("/api/jobs/{running}")).json()["state"] == "running"
    }));
    let queued = server.submit_ocr(b"b");
    assert_eq!(queued.status, 202, "{}", queued.text());

    let addr = server.addr;
    let host = server.host.clone();
    let origin = server.origin.clone();
    let token = server.token.clone();
    let barrier = Arc::new(std::sync::Barrier::new(8));
    let mut threads = Vec::new();
    for _ in 0..8 {
        let (host, origin, token) = (host.clone(), origin.clone(), token.clone());
        let barrier = Arc::clone(&barrier);
        threads.push(std::thread::spawn(move || {
            barrier.wait();
            raw_request(
                addr,
                "POST",
                "/api/ocr",
                &[
                    ("Host", host.as_str()),
                    ("X-RapidStructure-Token", token.as_str()),
                    ("Origin", origin.as_str()),
                    ("Content-Type", "application/octet-stream"),
                    ("Content-Length", "1048576"),
                ],
                None,
            )
        }));
    }
    let mut refused = 0;
    for thread in threads {
        let response = thread.join().expect("the request thread must finish");
        assert_eq!(response.status, 503, "{}", response.text());
        assert_eq!(response.code(), "busy");
        refused += 1;
    }
    assert_eq!(refused, 8);

    // 被占住的那些请求**都没有**消耗容量:任务照常跑完。
    let view = server.wait_terminal(&running, Duration::from_secs(20));
    assert_eq!(view["state"], "succeeded", "{view}");
}

/// 评审 P2-1 的核心:**预留是原子的,而且不会泄漏容量**。
///
/// 为什么这条断言在 `reserve_queue_slot` 这一层而不是 HTTP 层:`accept_loop` 今天在
/// **单线程**里处理请求(准入 → 读 body → 入队都在 `handle` 的一次调用内),因此
/// HTTP 上那三个步骤本来就不可能交错。把"判定 + 占位"合成同一个临界区之后,
/// 这条保证不再依赖那个线程模型的事实——它由数据结构本身成立。
/// 并发因此在这里被真正地跑出来(8 个线程抢同一个容量 1 的队列)。
#[test]
fn the_queue_reservation_is_atomic_and_never_leaks_capacity() {
    let server = TestServer::start(TestOptions {
        limits: limits(1, 1),
        ..TestOptions::new(complete_model_dir("reserve-atomic"), Scripted::fast())
    });
    let shared = server.shared();

    let barrier = Arc::new(std::sync::Barrier::new(8));
    let mut threads = Vec::new();
    for _ in 0..8 {
        let shared = Arc::clone(&shared);
        let barrier = Arc::clone(&barrier);
        threads.push(std::thread::spawn(move || {
            barrier.wait();
            let reservation = shared.reserve_queue_slot(QueueClass::Text);
            let held = reservation.is_some();
            // 抢到的那个凭据被**故意保留**一会儿(不提交、也不提前释放),
            // 因此容量 1 的队列最多只能有一个赢家。
            std::thread::sleep(Duration::from_millis(50));
            drop(reservation);
            held
        }));
    }
    let mut winners = 0;
    for thread in threads {
        if thread.join().expect("the contender must finish") {
            winners += 1;
        }
    }
    assert_eq!(winners, 1, "exactly one contender may hold the only slot");

    // 全部释放之后,容量必须**完好无损**:下一个请求又能拿到那个槽位(没有泄漏,
    // 也没有反向的"多释放"把容量变大——后者用两次连续预留来证明)。
    let first = shared
        .reserve_queue_slot(QueueClass::Text)
        .expect("the released slot must be available again");
    assert!(
        shared.reserve_queue_slot(QueueClass::Text).is_none(),
        "capacity 1 must admit exactly one reservation"
    );
    drop(first);
    shared
        .reserve_queue_slot(QueueClass::Text)
        .expect("dropping a reservation must return the slot");
}

#[test]
fn evicted_jobs_are_410_and_after_the_ttl_they_become_404() {
    let mut raw = limits(2, 1);
    raw.max_retained = 1;
    raw.job_ttl_secs = 1;
    let server = TestServer::start(TestOptions {
        limits: raw,
        ..TestOptions::new(complete_model_dir("evict"), Scripted::fast())
    });

    let first = server.submit_ocr(b"a").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    server.wait_terminal(&first, Duration::from_secs(20));
    let second = server.submit_ocr(b"b").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    server.wait_terminal(&second, Duration::from_secs(20));

    // 保留上限 1 → 第一个任务被淘汰,但进了 tombstone → 410(不是 404)。
    let evicted = server.get(&format!("/api/jobs/{first}"));
    assert_eq!(evicted.status, 410, "{}", evicted.text());
    assert_eq!(evicted.code(), "job_evicted");
    assert_eq!(server.get(&format!("/api/jobs/{first}/result")).status, 410);

    // tombstone 自己也有 TTL:过期后同一个 id 变成 404(两条语义必须可区分)。
    assert!(
        wait_until(Duration::from_secs(15), || {
            server.get(&format!("/api/jobs/{first}")).status == 404
        }),
        "the tombstone must expire back to 404"
    );
    assert_eq!(server.get("/api/jobs/never-existed").status, 404);
}

// ---------------------------------------------------------------- 状态与模型

#[test]
fn status_reports_the_frozen_three_provider_fields_and_redacts_paths() {
    let dir = complete_model_dir("status");
    let server = TestServer::start(TestOptions::new(dir.clone(), Scripted::fast()));
    let response = server.get("/api/status");
    assert_eq!(response.status, 200);
    let value = response.json();

    for key in ["requested", "selected_ep", "fallback_to_cpu"] {
        assert!(
            value["provider"].get(key).is_some(),
            "provider.{key} must always exist: {value}"
        );
    }
    assert_eq!(value["model_dir"], "<redacted>");
    assert_eq!(value["source"], "local_manifest");
    assert_eq!(value["downloads_allowed"], false);
    assert!(value["ort"]["version"].is_string() || value["ort"]["version"].is_null());
    assert!(value["queues"]["text"]["capacity"].as_u64().unwrap_or(0) > 0);
    assert!(value["queues"]["formula"]["capacity"].as_u64().unwrap_or(0) > 0);
    assert!(value["limits"]["max_body_bytes"].as_u64().unwrap_or(0) > 0);
    assert!(
        value["memory"]["peak_working_set_bytes"]
            .as_u64()
            .unwrap_or(0)
            > 0
    );
    assert!(value["retention"]["job_ttl_ms"].as_u64().unwrap_or(0) > 0);

    // 本机绝对路径绝不出现在任何状态响应里(§7.4/§10.9)。
    let text = response.text();
    assert!(!text.contains(&dir.display().to_string()), "{text}");
    assert!(!text.contains("\\\\?\\"), "{text}");
    assert!(
        !server
            .get("/api/models")
            .text()
            .contains(&dir.display().to_string())
    );
}

#[test]
fn models_reports_every_file_state_and_matches_the_ocr_409() {
    // 空目录:默认表来源,文本三个文件全缺 + 公式模型缺失(M4)。
    let server = TestServer::start(TestOptions::new(
        empty_model_dir("models"),
        Scripted::fast(),
    ));
    let models = server.get("/api/models");
    assert_eq!(models.status, 200);
    let value = models.json();
    assert_eq!(value["source"], "default_table");
    assert_eq!(value["downloads_allowed"], false);
    let sets = value["sets"].as_array().expect("sets");
    assert_eq!(sets.len(), 2, "text set + formula set (M4): {value}");
    let files = sets[0]["files"].as_array().expect("files");
    assert_eq!(files.len(), 3);
    for file in files {
        assert_eq!(file["state"], "missing");
        assert!(file["name"].as_str().is_some());
        assert!(file["role"].as_str().is_some());
        assert!(file["size_bytes"].as_u64().is_some());
        assert!(file["sha256"].as_str().is_some());
        assert!(file["source_url"].as_str().is_some());
    }
    // 公式集合:**一个**文件、有体积与哈希(页面必须能在下载前显示 566 MB)。
    let formula_set = &sets[1];
    assert_eq!(formula_set["id"], "PP-FormulaNet_plus-M");
    let formula_files = formula_set["files"].as_array().expect("formula files");
    assert_eq!(formula_files.len(), 1);
    assert_eq!(formula_files[0]["role"], "formula_recognizer");
    assert_eq!(formula_files[0]["name"], "pp_formulanet_plus_m.onnx");
    assert_eq!(formula_files[0]["state"], "missing");
    assert_eq!(formula_files[0]["size_bytes"], 593_916_167u64);
    assert_eq!(
        formula_files[0]["sha256"],
        "6e509ec4b7cda604dc9bf80a876ae6494693deea4c7f4157a4dc0eba0ebda745"
    );
    assert_eq!(
        formula_files[0]["source_url"],
        "https://www.modelscope.cn/seeyuer/pp-formulanet-plus-m-optimized/resolve/0bb8154e3583d24613eaa74448de43ecf4ae73ec/pp_formulanet_plus_m.onnx"
    );

    // 顶层四个字段是**文本管线**作用域(引擎要加载的那些文件);
    // 公式管线在 `formula` 块里单独报告(M4 的根因修复:公式缺失不得让普通 OCR 变 409)。
    let missing: Vec<&str> = value["missing"]
        .as_array()
        .expect("missing")
        .iter()
        .filter_map(Value::as_str)
        .collect();
    assert_eq!(missing.len(), 3);
    assert_eq!(value["complete"], false);
    assert_eq!(value["blocked"], value["missing"]);
    assert_eq!(
        value["formula"]["missing"],
        serde_json::json!(["pp_formulanet_plus_m.onnx"])
    );
    assert_eq!(value["formula"]["complete"], false);
    assert_eq!(
        value["formula"]["required_roles"],
        serde_json::json!(["formula_recognizer"])
    );
    // 这个测试实例没有配置检测模型:路由关闭,且理由是可读文字(不是只有禁用态)。
    assert_eq!(value["formula"]["routing"], false);
    assert!(
        value["formula"]["disabled_reason"]
            .as_str()
            .is_some_and(|reason| reason.contains("--formula-detector")),
        "{value}"
    );

    // 引擎在空模型目录下是 BlockedModelsMissing,而**服务**是 Ready(§7.6)。
    let status = server.get("/api/status").json();
    assert_eq!(status["state"], "ready");
    assert_eq!(status["engine"]["state"], "blocked_models_missing");
    // 引擎的缺失清单同样只含文本文件(公式模型缺失不是"引擎起不来")。
    let engine_missing = status["engine"]["missing"]
        .as_array()
        .expect("engine missing");
    assert_eq!(engine_missing.len(), 3, "{status}");
    assert_eq!(status["formula"]["routing"], false);
    assert!(status["limits"]["max_eval_cases"].as_u64().unwrap_or(0) > 0);

    // OCR 409:字段与 /api/models **逐字节一致**(文本作用域)。
    let rejected = server.submit_ocr(b"image bytes");
    assert_eq!(rejected.status, 409, "{}", rejected.text());
    assert_eq!(rejected.code(), "models_missing");
    let detail = &rejected.json()["detail"];
    assert_eq!(detail["missing"], value["missing"], "{detail}");
    assert_eq!(detail["corrupt"], value["corrupt"]);
    assert_eq!(detail["source"], value["source"]);
    assert_eq!(detail["model_dir"], value["model_dir"]);

    // 公式队列:路由未启用 → 400(不静默按文本处理,M1 的语义在 M4 不变)。
    let formula = server.post(
        "/api/ocr?queue=formula",
        &[("Content-Type", "application/octet-stream")],
        b"image bytes",
    );
    assert_eq!(formula.status, 400, "{}", formula.text());
    assert_eq!(formula.code(), "bad_request");
}

#[test]
fn an_engine_that_fails_to_load_is_failed_with_a_reason_and_503() {
    let dir = complete_model_dir("enginefail");
    let server = TestServer::start(TestOptions {
        engine_factory: Arc::new(|_config: &EngineConfig| {
            Err(RapidOcrError::UnsupportedProvider(
                "scripted: the requested provider is unavailable in this build".to_string(),
            ))
        }),
        ..TestOptions::new(dir, Scripted::fast())
    });

    let status = server.get("/api/status").json();
    assert_eq!(
        status["state"], "ready",
        "the service is ready even if the engine is not"
    );
    assert_eq!(status["engine"]["state"], "failed");
    assert!(
        status["engine"]["reason"]
            .as_str()
            .is_some_and(|reason| reason.contains("provider is unavailable")),
        "{status}"
    );
    // 引擎不可用 → 503 engine_unavailable 且带 reason。
    let rejected = server.submit_ocr(b"image");
    assert_eq!(rejected.status, 503, "{}", rejected.text());
    assert_eq!(rejected.code(), "engine_unavailable");
    assert!(rejected.json()["detail"]["reason"].is_string());
}

// ---------------------------------------------------------------- 下载接缝(M2)

/// `POST /api/models/download` 的三种"必须拒绝"与"已经齐备时如实成功"。
///
/// **M2 的行为变化**(这里是有意的期望变更,不是弱化):
/// - M1 的 worker 会把任务判为失败并写明"未实现、无网络 I/O";M2 替换了处理体,
///   因此同一个请求现在要么真的下载,要么(集合已经齐备时)**成功且 0 个文件要下**;
/// - 未知 `set_id` 从 M1 的 400 `bad_request` 变成 **404 `model_set_not_found`**:
///   §4.2 的请求体只有 `set_id`,"未知集合"必须有可定位的答复(带上请求的 id 与已知集合),
///   而不是与"请求体畸形"共用 400。
#[test]
fn the_download_endpoint_refuses_disabled_unknown_and_url_bearing_requests() {
    let dir = complete_model_dir("download");
    let disabled = TestServer::start(TestOptions::new(dir.clone(), Scripted::fast()));
    let response = disabled.post(
        "/api/models/download",
        &[("Content-Type", "application/json")],
        br#"{"set_id":"test-set"}"#,
    );
    assert_eq!(response.status, 403, "{}", response.text());
    assert_eq!(response.code(), "downloads_disabled");

    // 打开 --allow-download:这是一个**真实**任务。集合已经齐备 → 0 个文件要下 → 成功。
    let enabled = TestServer::start(TestOptions {
        allow_download: true,
        ..TestOptions::new(dir, Scripted::fast())
    });
    let response = enabled.post(
        "/api/models/download",
        &[("Content-Type", "application/json")],
        br#"{"set_id":"test-set"}"#,
    );
    assert_eq!(response.status, 202, "{}", response.text());
    let accepted = response.json();
    assert_eq!(accepted["kind"], "model_download");
    assert_eq!(accepted["queue"], "download");
    assert_eq!(accepted["download"]["files_total"], 0);
    let id = accepted["job_id"].as_str().expect("job id").to_string();
    let view = enabled.wait_terminal(&id, Duration::from_secs(20));
    assert_eq!(view["state"], "succeeded", "{view}");
    assert_eq!(view["kind"], "model_download");
    assert_eq!(view["failure"], serde_json::Value::Null);

    // 未知 set_id 与带 URL 的请求体都必须被拒绝,而不是被忽略。
    let unknown = enabled.post(
        "/api/models/download",
        &[("Content-Type", "application/json")],
        br#"{"set_id":"nope"}"#,
    );
    assert_eq!(unknown.status, 404, "{}", unknown.text());
    assert_eq!(unknown.code(), "model_set_not_found");
    let with_url = enabled.post(
        "/api/models/download",
        &[("Content-Type", "application/json")],
        br#"{"set_id":"test-set","url":"https://evil.example/x.onnx"}"#,
    );
    assert_eq!(with_url.status, 400, "{}", with_url.text());
}

// ---------------------------------------------------------------- 双向公平性

/// 公式洪水下普通任务不被饿死(§8.3 方向一)。
#[test]
fn a_formula_flood_does_not_starve_text_jobs() {
    let delay = Duration::from_millis(25);
    let dir = complete_model_dir("fair-formula");
    let scripted = Scripted::slow(delay);
    let server = TestServer::start(
        TestOptions::new(dir.clone(), scripted.clone())
            .with_formula_routing(&dir.join("pix2text-mfd-1.5.onnx"))
            .with_limits(limits(4, 2)),
    );
    let shared = server.shared();
    // 上界来自 `/api/status` 的公开字段(调度参数的可观测口径),而不是内部访问器。
    let status = server.get("/api/status").json();
    let bound = status["queues"]["text"]["wait_bound"]
        .as_u64()
        .expect("wait_bound") as usize;
    assert!(bound > 0, "{status}");
    assert_eq!(shared.service_state(), super::state::ServiceState::Ready);

    let starved = run_flood(&server, "formula", QueueClass::Text, bound, delay);
    assert!(
        starved.is_none(),
        "the text job was starved under a formula flood: {starved:?}"
    );
}

/// 普通洪水下公式任务不被饿死(§8.3 方向二)。
#[test]
fn a_text_flood_does_not_starve_formula_jobs() {
    let delay = Duration::from_millis(25);
    let dir = complete_model_dir("fair-text");
    let scripted = Scripted::slow(delay);
    let server = TestServer::start(
        TestOptions::new(dir.clone(), scripted.clone())
            .with_formula_routing(&dir.join("pix2text-mfd-1.5.onnx"))
            .with_limits(limits(4, 2)),
    );
    let shared = server.shared();
    assert_eq!(shared.engine_state_name(), "ready");
    let status = server.get("/api/status").json();
    let bound = status["queues"]["formula"]["wait_bound"]
        .as_u64()
        .expect("wait_bound") as usize;
    assert!(bound > 0, "{status}");

    let starved = run_flood(&server, "text", QueueClass::Formula, bound, delay);
    assert!(
        starved.is_none(),
        "the formula job was starved under a text flood: {starved:?}"
    );
}

/// 让 `flood` 队列保持饱和,同时提交一个 `victim` 队列的任务并计时。
///
/// 返回 `Some(elapsed_ms)` 表示超过上界(被饿死),`None` 表示在界内完成。
fn run_flood(
    server: &TestServer,
    flood: &str,
    victim: QueueClass,
    bound_jobs: usize,
    delay: Duration,
) -> Option<u128> {
    let flood = flood.to_string();
    let url = format!("/api/ocr?queue={flood}");
    let stop = Arc::new(AtomicBool::new(false));
    let flooded = Arc::new(AtomicUsize::new(0));

    // 先让 worker 忙起来(否则第一次提交会立刻被服务,测不出排队时长)。
    let warmup = server.submit_ocr(b"warmup");
    assert!(warmup.status == 202, "{}", warmup.text());
    let warmup_id = warmup.json()["job_id"].as_str().expect("id").to_string();
    server.wait_terminal(&warmup_id, Duration::from_secs(20));

    let flooder = {
        let stop = Arc::clone(&stop);
        let flooded = Arc::clone(&flooded);
        let addr = server.addr;
        let host = server.host.clone();
        let origin = server.origin.clone();
        let token = server.token.clone();
        let url = url.clone();
        std::thread::spawn(move || {
            while !stop.load(Ordering::SeqCst) {
                let raw = format!(
                    "POST {url} HTTP/1.1\r\nConnection: close\r\nHost: {host}\r\nOrigin: {origin}\r\n\
                     X-RapidStructure-Token: {token}\r\nContent-Type: application/octet-stream\r\n\
                     Content-Length: 5\r\n\r\nimage"
                );
                let response = send(addr, raw.as_bytes());
                if response.status == 202 {
                    flooded.fetch_add(1, Ordering::SeqCst);
                } else {
                    // 队列满(503):让出一点时间,避免把 accept 线程打满。
                    std::thread::sleep(Duration::from_millis(2));
                }
            }
        })
    };

    // 等洪水真的把**目标队列灌满**(`used == capacity`):只有这样,"受害者仍在界内被服务"
    // 才能证明双向配额在生效,而不是因为另一队列恰好是空的。
    let saturated = wait_until(Duration::from_secs(10), || {
        let status = server.get("/api/status").json();
        let queues = &status["queues"][flood.as_str()];
        let used = queues["used"].as_u64().unwrap_or(0);
        let capacity = queues["capacity"].as_u64().unwrap_or(0);
        used >= capacity
    });
    assert!(
        saturated,
        "the flood never saturated the {flood} queue (accepted {} job(s))",
        flooded.load(Ordering::SeqCst)
    );

    let victim_path = match victim {
        QueueClass::Text => "/api/ocr?queue=text",
        QueueClass::Formula => "/api/ocr?queue=formula",
    };
    let started = Instant::now();
    let mut accepted = None;
    for _ in 0..200 {
        let response = server.post(
            victim_path,
            &[("Content-Type", "application/octet-stream")],
            b"victim",
        );
        if response.status == 202 {
            accepted = Some(response.json());
            break;
        }
        assert_eq!(response.status, 503, "{}", response.text());
        std::thread::sleep(Duration::from_millis(2));
    }
    let accepted = accepted.expect("the victim job must eventually be accepted");
    let id = accepted["job_id"].as_str().expect("id").to_string();
    let view = server.wait_terminal(&id, Duration::from_secs(30));
    let elapsed = started.elapsed();
    // 计时窗口里洪水一直在被服务(否则"没被饿死"就没有意义)。
    let flooded_during_wait = flooded.load(Ordering::SeqCst);
    stop.store(true, Ordering::SeqCst);
    let _ = flooder.join();

    assert_eq!(view["state"], "succeeded", "{view}");
    assert!(
        flooded_during_wait > 0,
        "the {flood} queue was never served while the victim waited"
    );
    // 可证明上界:`capacity × 对方配额` 个"对方"任务 + 1 个正在运行的 + 余量。
    let budget = delay * u32::try_from(bound_jobs + 3).expect("small bound");
    if elapsed > budget + Duration::from_millis(750) {
        return Some(elapsed.as_millis());
    }
    None
}

// ---------------------------------------------------------------- 路由守卫

#[test]
fn the_formula_queue_is_refused_when_formula_routing_is_off() {
    let server = TestServer::start(TestOptions::new(
        complete_model_dir("noformula"),
        Scripted::fast(),
    ));
    let response = server.post(
        "/api/ocr?queue=formula",
        &[("Content-Type", "application/octet-stream")],
        b"image",
    );
    assert_eq!(response.status, 400, "{}", response.text());
    assert_eq!(response.code(), "bad_request");
    // 普通任务照常可提交(公式关闭不影响文本)。
    assert_eq!(server.submit_ocr(b"image").status, 202);

    // M4:路由关闭的**理由**必须能通过 `/api/models`(页面据此禁用开关)与 `/api/status`
    // 读到,而不是只表现为一个禁用控件(§9.4:不只靠颜色)。
    let models = server.get("/api/models").json();
    assert_eq!(models["formula"]["routing"], false);
    let reason = models["formula"]["disabled_reason"]
        .as_str()
        .expect("a textual reason");
    assert!(reason.contains("--formula-detector"), "{reason}");
    assert_eq!(models["formula"]["detector"]["configured"], false);
    assert_eq!(models["formula"]["detector"]["file"], Value::Null);
    let status = server.get("/api/status").json();
    assert_eq!(status["formula"]["routing"], false);
    assert_eq!(
        status["formula"]["disabled_reason"],
        models["formula"]["disabled_reason"]
    );
}

// ---------------------------------------------------------------- M4:公式队列

/// 公式队列是**真实**的第二条管线:`queue=formula` 进公式队列,并在 worker 里拿到
/// 由模型集解析出的 `FormulaPolicy`(识别模型 + 集合声明的 SHA-256 + 检测模型)。
///
/// 脚本化后端不加载模型,但它在 `OcrRequest.formula` 上看到的正是生产路径组装的那一份,
/// 因此"路由真的接上了公式管线"不是靠猜测:三个字段逐个断言。
#[test]
fn the_formula_queue_runs_the_formula_pipeline_from_the_model_set() {
    let dir = complete_model_dir("m4-formula");
    let detector = dir.join("pix2text-mfd-1.5.onnx");
    let scripted = Scripted::fast();
    let server = TestServer::start(
        TestOptions::new(dir.clone(), scripted.clone()).with_formula_routing(&detector),
    );

    // 模型集报告公式集合齐备 + 路由可用(页面据此允许勾选)。
    let models = server.get("/api/models").json();
    assert_eq!(models["formula"]["complete"], true, "{models}");
    assert_eq!(models["formula"]["routing"], true);
    assert_eq!(models["formula"]["disabled_reason"], Value::Null);
    assert_eq!(models["formula"]["detector"]["configured"], true);
    assert_eq!(
        models["formula"]["detector"]["file"], "pix2text-mfd-1.5.onnx",
        "only the file name is exposed (§7.4)"
    );
    assert!(
        !models.to_string().contains(&dir.display().to_string()),
        "no absolute path may leak: {models}"
    );

    let text = server.submit_ocr(b"text image");
    assert_eq!(text.status, 202, "{}", text.text());
    assert_eq!(text.json()["queue"], "text");
    let formula = server.post(
        "/api/ocr?queue=formula",
        &[("Content-Type", "application/octet-stream")],
        b"formula image",
    );
    assert_eq!(formula.status, 202, "{}", formula.text());
    let accepted = formula.json();
    assert_eq!(accepted["queue"], "formula", "{accepted}");
    assert_eq!(accepted["kind"], "ocr");

    let text_id = text.json()["job_id"].as_str().expect("id").to_string();
    let formula_id = accepted["job_id"].as_str().expect("id").to_string();
    let text_view = server.wait_terminal(&text_id, Duration::from_secs(20));
    let formula_view = server.wait_terminal(&formula_id, Duration::from_secs(20));
    assert_eq!(text_view["state"], "succeeded", "{text_view}");
    assert_eq!(formula_view["state"], "succeeded", "{formula_view}");
    assert_eq!(formula_view["queue"], "formula");

    let policies = scripted.formulas();
    assert_eq!(policies.len(), 2, "one request per job");
    // 策略按**请求体**关联,不按下标(复审 P2-3):两条队列并行,`recognize` 的进入顺序
    // 不等于提交顺序,"文本任务先入队"不是测试可以依赖的事实。
    let text_policy = scripted.formula_policy("text image");
    assert!(
        !text_policy.enabled,
        "the text queue must not enable the formula pipeline: every recorded policy: {policies:?}"
    );
    assert_eq!(text_policy.model_path, None);
    let formula = scripted.formula_policy("formula image");
    assert!(
        formula.enabled,
        "the formula queue must enable it: every recorded policy: {policies:?}"
    );
    assert_eq!(
        formula.model_path.as_deref(),
        Some(dir.join("fx.onnx").as_path())
    );
    assert_eq!(
        formula.detector_path.as_deref(),
        Some(detector.as_path()),
        "the detector comes from the startup-resolved path"
    );
    // 识别模型的 SHA-256 来自**模型集**(权威判定在下一次真实加载时由库执行)。
    let declared = models["sets"][0]["files"]
        .as_array()
        .expect("files")
        .iter()
        .find(|file| file["role"] == "formula_recognizer")
        .and_then(|file| file["sha256"].as_str())
        .expect("the formula model's declared hash");
    assert_eq!(formula.expected_model_sha256.as_deref(), Some(declared));
    // §10.8:识别模型是被**显式**下载的集合成员,公式区域仍按请求开关逐次选择。
    assert!(
        !formula.include_token_ids,
        "token ids stay out of the default"
    );
}

/// 公式集合不齐备:`queue=formula` 是 **409**(可定位、指向要下载的文件),
/// 而普通 OCR 完全不受影响(M4 的核心不变量,走真实 HTTP)。
#[test]
fn an_incomplete_formula_set_is_409_while_text_ocr_keeps_working() {
    let dir = manifest_model_dir("m4-formula-incomplete", &text_fixture_files(), None);
    let detector = dir.join("pix2text-mfd-1.5.onnx");
    let server = TestServer::start(
        TestOptions::new(dir.clone(), Scripted::fast()).with_formula_routing(&detector),
    );

    // `/api/models`:文本齐备(顶层 complete=true),公式不齐备(formula.complete=false)。
    let models = server.get("/api/models").json();
    assert_eq!(models["complete"], true, "{models}");
    assert_eq!(models["missing"], serde_json::json!([]));
    assert_eq!(models["formula"]["complete"], false);
    assert_eq!(models["formula"]["missing"], serde_json::json!(["fx.onnx"]));
    assert_eq!(models["formula"]["routing"], true);

    // 公式请求在**读 body 之前**就被拒绝(§4.4 第 4 步之后),且 detail 是公式作用域。
    let formula = server.post(
        "/api/ocr?queue=formula",
        &[("Content-Type", "application/octet-stream")],
        b"formula image",
    );
    assert_eq!(formula.status, 409, "{}", formula.text());
    assert_eq!(formula.code(), "models_missing");
    let detail = &formula.json()["detail"];
    assert_eq!(detail["scope"], "formula");
    assert_eq!(detail["missing"], serde_json::json!(["fx.onnx"]));
    // 评审 P1-2:请求路径**不再**有"只看存在性"的第二套清单——判定与 `/api/models`
    // 同源(哈希状态)。检测模型在场且没有声明哈希时它如实报告 `present`/`sha256: null`。
    assert_eq!(detail["detector"]["state"], "present");
    assert_eq!(detail["detector"]["sha256"], Value::Null);
    assert!(
        detail.get("missing_on_disk").is_none(),
        "the existence-only field is gone: {detail}"
    );

    // 普通 OCR 照常可用(脚本化后端),并且它拿到的策略**没有**启用公式。
    let text = server.submit_ocr(b"text image");
    assert_eq!(text.status, 202, "{}", text.text());
    let id = text.json()["job_id"].as_str().expect("id").to_string();
    let view = server.wait_terminal(&id, Duration::from_secs(20));
    assert_eq!(view["state"], "succeeded", "{view}");
    assert_eq!(view["queue"], "text");
}

/// 公式角色在**运行期**被拿掉(文件删除)时:`/api/models` 与 409 都如实反映,
/// 而不是缓存启动期快照(与 M2"下载完成后立刻变 present"同一条规则)。
#[test]
fn removing_the_formula_model_turns_the_route_into_a_409() {
    let dir = complete_model_dir("m4-formula-removed");
    let detector = dir.join("pix2text-mfd-1.5.onnx");
    let server = TestServer::start(
        TestOptions::new(dir.clone(), Scripted::fast()).with_formula_routing(&detector),
    );
    assert_eq!(
        server.get("/api/models").json()["formula"]["complete"],
        true
    );
    std::fs::remove_file(dir.join("fx.onnx")).expect("remove the formula model");

    let models = server.get("/api/models").json();
    assert_eq!(models["formula"]["complete"], false);
    assert_eq!(models["formula"]["missing"], serde_json::json!(["fx.onnx"]));
    // 文本集合仍然齐备:顶层字段不受公式影响。
    assert_eq!(models["complete"], true, "{models}");
    let formula = server.post(
        "/api/ocr?queue=formula",
        &[("Content-Type", "application/octet-stream")],
        b"formula image",
    );
    assert_eq!(formula.status, 409, "{}", formula.text());
    assert_eq!(formula.json()["detail"]["scope"], "formula");
    assert_eq!(server.submit_ocr(b"text").status, 202);
}

// ---------------------------------------------------------------- E16.2:表格路由

/// `?table=1` 在表格路由关闭时是 **400**(不是静默按文本处理)。
///
/// 静默忽略会让页面以为表格在跑、结果却是一份没有表格的载荷——那正是"两个开关互相
/// 矛盾"的经典形状。路由关闭的**理由**必须能从 `/api/models` 与 `/api/status` 读到,
/// 页面据此禁用选项(§9.4:不只靠颜色)。
#[test]
fn the_table_switch_is_refused_when_table_routing_is_off() {
    let server = TestServer::start(TestOptions::new(
        complete_model_dir("notable"),
        Scripted::fast(),
    ));

    for query in ["?table=1", "?queue=text&table=1", "?queue=formula&table=1"] {
        let response = server.post(
            &format!("/api/ocr{query}"),
            &[("Content-Type", "application/octet-stream")],
            b"image",
        );
        assert_eq!(response.status, 400, "{query}: {}", response.text());
        assert_eq!(response.code(), "bad_request");
    }

    // 关闭表格路由不影响任何既有路径:不带参数、`?table=0`、公式队列都照旧。
    assert_eq!(server.submit_ocr(b"image").status, 202);
    assert_eq!(
        server
            .post(
                "/api/ocr?table=0",
                &[("Content-Type", "application/octet-stream")],
                b"image",
            )
            .status,
        202
    );

    let models = server.get("/api/models").json();
    assert_eq!(models["table"]["routing"], false);
    let reason = models["table"]["disabled_reason"]
        .as_str()
        .expect("a textual reason");
    assert!(reason.contains("--table-model"), "{reason}");
    assert!(reason.contains("ordinary OCR"), "{reason}");
    assert_eq!(models["table"]["structure"]["configured"], false);
    assert_eq!(models["table"]["structure"]["file"], Value::Null);
    assert_eq!(models["table"]["in_plan"], false);
    // 表格是**第三条**管线:文本组仍然齐备,页面据此只禁用表格选项。
    assert_eq!(models["complete"], true, "{models}");
    assert_eq!(models["pipelines"]["table"]["routing"], false);
    assert_eq!(models["pipelines"]["table"]["in_plan"], false);
    assert_eq!(models["pipelines"]["table"]["complete"], false);

    let status = server.get("/api/status").json();
    assert_eq!(status["table"]["routing"], false);
    assert_eq!(
        status["table"]["disabled_reason"],
        models["table"]["disabled_reason"]
    );
}

/// `?table=` 的取值面只有 `1` / `0` / 缺省;其它任何写法都是 400,且**不建任务**。
#[test]
fn the_table_switch_rejects_anything_but_one_and_zero() {
    let dir = complete_model_dir("e16-table-values");
    let model = dir.join("slanet-plus.onnx");
    let scripted = Scripted::fast();
    let server = TestServer::start(
        TestOptions::new(dir.clone(), scripted.clone()).with_table_routing(&model),
    );

    for raw in ["2", "true", "yes", "", "TRUE", "-1"] {
        let response = server.post(
            &format!("/api/ocr?table={raw}"),
            &[("Content-Type", "application/octet-stream")],
            b"image",
        );
        assert_eq!(response.status, 400, "`?table={raw}`: {}", response.text());
        assert_eq!(response.code(), "bad_request");
    }
    // 一个任务都没建:取值校验发生在建任务之前。
    assert_eq!(
        scripted.calls.load(Ordering::SeqCst),
        0,
        "a rejected request must not reach the backend"
    );
}

/// E16.2 的核心:`?table=1` 真的把表格阶段接上了,而且接的是**启动期解析出的那一份**
/// `TablePolicy`(路径 + **集合声明的** SHA-256 + `Escape` 文本策略)。
///
/// 脚本化后端不加载模型,但它在 `OcrRequest.table` 上看到的正是生产路径组装的那一份,
/// 因此"路由真的接上了表格管线"不是靠猜测:字段逐个断言。
///
/// 夹具用 [`complete_model_dir_with_table`]:清单**真的声明了** `table_structure` role。
/// 这一点是必要的——如果清单不声明它,`expected_model_sha256` 与"集合里声明的摘要"
/// 会同时是 `None`,断言恒真而什么也没证明。
#[test]
fn the_table_stage_runs_from_the_model_set_when_requested() {
    let dir = complete_model_dir_with_table("e16-table-on");
    let model = dir.join("slanet-plus.onnx");
    let detector = dir.join("pix2text-mfd-1.5.onnx");
    let scripted = Scripted::fast().with_table_regions(1);
    let server = TestServer::start(
        TestOptions::new(dir.clone(), scripted.clone())
            // 集合已经把结构模型声明在模型目录里,因此**不需要** `--table-model`:
            // "清单声明即启用"这条规则与公式识别模型是同一条(E16.1.3 显示的就是这条计划)。
            .with_formula_routing(&detector),
    );

    // 路由可用:`/api/models` 与 `/api/status` 都报告它,且逐文件状态可见。
    let models = server.get("/api/models").json();
    assert_eq!(models["table"]["routing"], true);
    assert_eq!(models["table"]["disabled_reason"], Value::Null);
    assert_eq!(models["table"]["complete"], true, "{models}");
    assert_eq!(models["table"]["structure"]["configured"], true);
    assert_eq!(models["table"]["structure"]["file"], "slanet-plus.onnx");
    assert_eq!(models["table"]["in_plan"], true);
    assert_eq!(
        models["table"]["required_roles"],
        json!(["table_structure"])
    );
    assert_eq!(models["pipelines"]["table"]["complete"], true);
    assert_eq!(
        models["pipelines"]["table"]["pipeline"], "table",
        "the pipeline label is the documented one"
    );
    // E16.1.3 的数据源:逐管线的**逐文件计划项**(role + 声明摘要 + 状态),
    // 页面据此回答"哪个文件的哪个角色被哪条管线使用",不需要自己拼路径。
    let plan = models["pipelines"]["table"]["plan"]
        .as_array()
        .expect("the table pipeline publishes its plan");
    assert_eq!(plan.len(), 1, "{plan:?}");
    assert_eq!(plan[0]["name"], "slanet-plus.onnx");
    assert_eq!(plan[0]["role"], "table_structure");
    assert_eq!(plan[0]["pipeline"], "table");
    assert_eq!(plan[0]["state"], "present");
    assert_eq!(plan[0]["has_declared_digest"], true);
    let text_plan = models["pipelines"]["text"]["plan"]
        .as_array()
        .expect("the text pipeline publishes its plan");
    assert_eq!(
        text_plan
            .iter()
            .map(|file| file["role"].as_str().unwrap_or("").to_string())
            .collect::<Vec<_>>(),
        ["detector", "recognizer", "dictionary"]
    );
    // 集合声明(清单里的 `family`/`version`)与磁盘状态分开显示。
    assert_eq!(models["sets"][0]["id"], "test-set");
    assert_eq!(models["sets"][0]["family"], "PP-OCR");
    assert_eq!(models["sets"][0]["version"], "v-test");
    assert_eq!(models["sets"][0]["complete"], true);
    assert!(
        !models.to_string().contains(&dir.display().to_string()),
        "no absolute path may leak: {models}"
    );

    // 四种模式各提交一次:`queue` 决定排哪条队,`table` 决定那条队是否跑表格阶段。
    let plain = server.submit_ocr(b"plain");
    assert_eq!(plain.status, 202, "{}", plain.text());
    assert_eq!(plain.json()["queue"], "text");
    let text_table = server.post(
        "/api/ocr?queue=text&table=1",
        &[("Content-Type", "application/octet-stream")],
        b"text+table",
    );
    assert_eq!(text_table.status, 202, "{}", text_table.text());
    assert_eq!(text_table.json()["queue"], "text");
    let formula_table = server.post(
        "/api/ocr?queue=formula&table=1",
        &[("Content-Type", "application/octet-stream")],
        b"formula+table",
    );
    assert_eq!(formula_table.status, 202, "{}", formula_table.text());
    assert_eq!(formula_table.json()["queue"], "formula");
    let explicit_off = server.post(
        "/api/ocr?table=0",
        &[("Content-Type", "application/octet-stream")],
        b"explicit off",
    );
    assert_eq!(explicit_off.status, 202, "{}", explicit_off.text());

    for response in [&plain, &text_table, &formula_table, &explicit_off] {
        let id = response.json()["job_id"].as_str().expect("id").to_string();
        let view = server.wait_terminal(&id, Duration::from_secs(20));
        assert_eq!(view["state"], "succeeded", "{view}");
    }

    // 策略逐条断言:**只有** `?table=1` 的那两次开启了表格阶段。
    //
    // 按请求体取策略,不按下标:后端进入顺序不等于提交顺序,下标断言曾在门禁里偶发错位。
    let policies = scripted.tables();
    assert_eq!(policies.len(), 4, "one request per job");
    assert!(
        !scripted.table_policy("plain").enabled,
        "absent means off; every recorded policy: {policies:?}"
    );
    assert!(
        !scripted.table_policy("explicit off").enabled,
        "`?table=0` is an explicit off; every recorded policy: {policies:?}"
    );
    assert_eq!(
        policies.iter().filter(|(_, policy)| policy.enabled).count(),
        2,
        "only the two `?table=1` requests may enable the stage: {policies:?}"
    );
    // 清单声明的那份摘要(断言两侧都必须真的有值——否则这条断言恒真)。
    let declared = models["sets"][0]["files"]
        .as_array()
        .expect("files")
        .iter()
        .find(|file| file["role"] == "table_structure")
        .and_then(|file| file["sha256"].as_str())
        .expect("the fixture manifest declares the table structure model")
        .to_string();
    for (body, label) in [
        ("text+table", "?table=1"),
        ("formula+table", "?queue=formula&table=1"),
    ] {
        let policy = scripted.table_policy(body);
        assert!(policy.enabled, "{label} must enable the table stage");
        assert_eq!(
            policy.model_path.as_deref(),
            Some(model.as_path()),
            "{label}: the structure model comes from the startup-resolved path"
        );
        assert_eq!(
            policy.expected_model_sha256.as_deref(),
            Some(declared.as_str()),
            "{label}: the declared hash comes from the model set"
        );
        // §7.4:面向用户的路径必须转义,绝不把模型产物当标记。
        assert_eq!(policy.text_policy, TableTextPolicy::Escape);
    }
}

/// 结构模型缺失/损坏:`?table=1` 是 **409**(可定位、指向要下载的文件),
/// 而普通 OCR 完全不受影响。
#[test]
fn an_incomplete_table_set_is_409_while_text_ocr_keeps_working() {
    let dir = manifest_model_dir("e16-table-incomplete", &text_fixture_files(), None);
    let model = dir.join("slanet-plus.onnx");
    let server = TestServer::start(
        TestOptions::new(dir.clone(), Scripted::fast()).with_table_routing(&model),
    );
    // `with_table_routing` 已经把结构模型写进磁盘(它必须存在,否则启动期就拒绝)。
    // 这里再把它删掉,模拟"启动之后模型被移走"——路由仍然是打开的。
    std::fs::remove_file(&model).expect("remove the structure model");

    let models = server.get("/api/models").json();
    assert_eq!(models["table"]["routing"], true);
    assert_eq!(models["table"]["complete"], false, "{models}");
    assert_eq!(models["table"]["missing"], json!(["slanet-plus.onnx"]));
    assert_eq!(
        models["pipelines"]["table"]["blocked"],
        json!(["slanet-plus.onnx"])
    );
    assert_eq!(models["complete"], true, "the text pipeline is unaffected");

    let refused = server.post(
        "/api/ocr?table=1",
        &[("Content-Type", "application/octet-stream")],
        b"table image",
    );
    assert_eq!(refused.status, 409, "{}", refused.text());
    assert_eq!(refused.code(), "models_missing");
    assert_eq!(refused.json()["detail"]["scope"], "table");
    assert_eq!(
        refused.json()["detail"]["missing"],
        json!(["slanet-plus.onnx"])
    );

    // 表格路由的 409 不影响其它任何模式。
    assert_eq!(server.submit_ocr(b"text").status, 202);
    assert_eq!(
        server
            .post(
                "/api/ocr?table=0",
                &[("Content-Type", "application/octet-stream")],
                b"text",
            )
            .status,
        202
    );
}

/// 表格区域的载荷真的走到了 `/api/jobs/{id}/result`,并且页面契约字段齐备。
#[test]
fn the_table_region_round_trips_through_the_result_endpoint() {
    let dir = complete_model_dir("e16-table-result");
    let model = dir.join("slanet-plus.onnx");
    let server = TestServer::start(
        TestOptions::new(dir.clone(), Scripted::fast().with_table_regions(1))
            .with_table_routing(&model),
    );

    let accepted = server.post(
        "/api/ocr?table=1",
        &[("Content-Type", "application/octet-stream")],
        b"table image",
    );
    assert_eq!(accepted.status, 202, "{}", accepted.text());
    let id = accepted.json()["job_id"].as_str().expect("id").to_string();
    let view = server.wait_terminal(&id, Duration::from_secs(20));
    assert_eq!(view["state"], "succeeded", "{view}");

    let result = server.get(&format!("/api/jobs/{id}/result")).json();
    let regions = result["regions"].as_array().expect("regions");
    assert_eq!(regions.len(), 4, "three text regions plus one table");
    let table = regions
        .iter()
        .find(|region| region["kind"] == "table")
        .expect("a table region");
    assert!(
        table["recognition"].is_null(),
        "a table region has no CTC text"
    );
    assert!(table["formula"].is_null());
    let outcome = &table["table"];
    assert_eq!(outcome["rows"], 1);
    assert_eq!(outcome["cols"], 2);
    assert_eq!(outcome["confidence"], "low");
    assert_eq!(outcome["holes"], 1);
    assert_eq!(outcome["degradations"][0]["kind"], "grid_holes");
    assert_eq!(outcome["source_line_indices"], json!([0]));
    assert_eq!(outcome["model_id"], "scripted-table");
    assert_eq!(outcome["cells"].as_array().expect("cells").len(), 2);
    // 服务端**不**净化 `table.html`(它是模型产物的忠实副本,净化是输出层的职责);
    // 网页侧必须在渲染前再过一次 `sanitizeTableHtml`(E16.3.2 / 门禁 G8)。
    assert!(
        outcome["html"].as_str().expect("html").contains("<script>"),
        "the wire format carries the model's own HTML"
    );
}

// ---------------------------------------------- Step 1:`?words=` 的输出档位

/// 三档共用的样板:带查询串提交一张图 → 等终态 → 取回 `/result` 的 JSON。
///
/// 两个作用:把“`?words=` 真的传到了引擎”折进每一条端到端断言(不再需要单独一条只测
/// 参数的用例),并且用**请求体**关联而不是按下标(复审 P2-3):worker 不止一个,
/// 后端进入顺序不等于提交顺序。
fn submit_words_query(
    server: &TestServer,
    scripted: &Scripted,
    query: &str,
    body: &str,
    expected: WordOutputMode,
) -> Value {
    let accepted = server.post(
        &format!("/api/ocr{query}"),
        &[("Content-Type", "application/octet-stream")],
        body.as_bytes(),
    );
    assert_eq!(accepted.status, 202, "{query}: {}", accepted.text());
    let id = accepted.json()["job_id"].as_str().expect("id").to_string();
    let view = server.wait_terminal(&id, Duration::from_secs(20));
    assert_eq!(view["state"], "succeeded", "{view}");
    assert_eq!(
        scripted.word_mode(body),
        expected,
        "the query must reach the engine as a mode, not be dropped on the way: {:?}",
        scripted.word_modes()
    );
    server.get(&format!("/api/jobs/{id}/result")).json()
}

/// 结果里所有**文本**区域(公式与表格区域没有 `recognition`,逐词/逐字框只属于它们)。
fn text_regions(result: &Value) -> Vec<&Value> {
    result["regions"]
        .as_array()
        .expect("regions")
        .iter()
        .filter(|region| region["kind"] == "text")
        .collect()
}

/// polygon 的轴对齐范围 `(x0, y0, x1, y1)`,附带“恰好四点、每点两分量”的结构检查。
///
/// 取的是**外接范围**,不是把四边形替换成矩形:word 的框可以带倾斜,这里只问“它有没有
/// 跑出图外、跑出自己那一行”,不声明形状本身。
fn polygon_bounds(points: &Value) -> (f64, f64, f64, f64) {
    let rows = points.as_array().expect("polygon points");
    assert_eq!(rows.len(), 4, "a polygon is exactly four points");
    let mut xs = Vec::with_capacity(4);
    let mut ys = Vec::with_capacity(4);
    for row in rows {
        let pair = row.as_array().expect("a point is (x, y)");
        assert_eq!(pair.len(), 2, "a point is (x, y)");
        xs.push(pair[0].as_f64().expect("x is a number"));
        ys.push(pair[1].as_f64().expect("y is a number"));
    }
    (
        xs.iter().copied().fold(f64::INFINITY, f64::min),
        ys.iter().copied().fold(f64::INFINITY, f64::min),
        xs.iter().copied().fold(f64::NEG_INFINITY, f64::max),
        ys.iter().copied().fold(f64::NEG_INFINITY, f64::max),
    )
}

/// 缺省与显式 `?words=off` 都**不输出** `recognition.words`。
///
/// 钉的是“连空数组都不给”:`[]` 与 `null` 在宿主侧含义不同(前者会被当成“已开启但一行
/// 也没识出来”),而缺省必须是 off,否则每个请求都无条件多付一份响应体与后处理。
#[test]
fn the_default_and_the_explicit_off_both_omit_recognition_words() {
    let dir = complete_model_dir("words-off");
    let scripted = Scripted::fast();
    let server = TestServer::start(TestOptions::new(dir, scripted.clone()));

    let omitted = submit_words_query(&server, &scripted, "", "words absent", WordOutputMode::Off);
    let explicit = submit_words_query(
        &server,
        &scripted,
        "?words=off",
        "words explicit off",
        WordOutputMode::Off,
    );

    for result in [&omitted, &explicit] {
        for region in text_regions(result) {
            let words = &region["recognition"]["words"];
            assert!(
                words.is_null(),
                "`off` must omit the array entirely, not emit an empty one: {words}"
            );
        }
    }
    // 两档在线上不可区分(同一份 `regions`):缺省不会多付一份载荷。
    assert_eq!(omitted["regions"], explicit["regions"]);
}

/// `?words=` 的未知取值是 400,而且**不建任务**(worker 一次都没被调用)。
#[test]
fn an_unknown_words_value_is_rejected_before_any_job_is_created() {
    let dir = complete_model_dir("words-unknown");
    let scripted = Scripted::fast();
    let server = TestServer::start(TestOptions::new(dir, scripted.clone()));

    // 静默降级比报错难查得多:请求方会以为字符框已经在载荷里。
    for raw in ["char", "WORDS", "1", "true", ""] {
        let response = server.post(
            &format!("/api/ocr?words={raw}"),
            &[("Content-Type", "application/octet-stream")],
            b"unknown words value",
        );
        assert_eq!(response.status, 400, "?words={raw}: {}", response.text());
    }
    assert!(
        scripted.word_modes().is_empty(),
        "a rejected query must not reach the engine: {:?}",
        scripted.word_modes()
    );
}

/// `?words=words` 输出的框全部标为 `token`,且 token 序列就是文本的空白切分。
#[test]
fn the_words_mode_emits_token_boxes() {
    let dir = complete_model_dir("words-tokens");
    let scripted = Scripted::fast();
    let server = TestServer::start(TestOptions::new(dir, scripted.clone()));

    let result = submit_words_query(
        &server,
        &scripted,
        "?words=words",
        "token mode",
        WordOutputMode::Words,
    );
    for region in text_regions(&result) {
        let text = region["recognition"]["text"].as_str().expect("text");
        let words = region["recognition"]["words"]
            .as_array()
            .expect("`words` must emit an array");
        assert!(!words.is_empty(), "no boxes for {text:?}");
        assert_eq!(
            words
                .iter()
                .map(|word| word["kind"].as_str().expect("kind"))
                .collect::<Vec<_>>(),
            vec!["token"; words.len()],
            "`words` is the token granularity"
        );
        assert_eq!(
            words
                .iter()
                .map(|word| word["text"].as_str().expect("word text"))
                .collect::<Vec<_>>(),
            text.split_whitespace().collect::<Vec<_>>(),
            "tokens must appear in reading order, verbatim"
        );
    }
}

/// `?words=chars` 输出的框全部标为 `char`,逐字拼接必须还原 `recognition.text`。
///
/// 这一条是选区层能复制的前提:宿主把字符框按顺序拼回去,得到的就是用户看到的那行字,
/// 不需要自己再切词,也不会把一个词拆成两种粒度。
#[test]
fn the_chars_mode_emits_char_boxes_that_rebuild_the_text() {
    let dir = complete_model_dir("words-chars");
    let scripted = Scripted::fast();
    let server = TestServer::start(TestOptions::new(dir, scripted.clone()));

    let result = submit_words_query(
        &server,
        &scripted,
        "?words=chars",
        "char mode",
        WordOutputMode::Chars,
    );
    for region in text_regions(&result) {
        let text = region["recognition"]["text"].as_str().expect("text");
        let words = region["recognition"]["words"]
            .as_array()
            .expect("`chars` must emit an array");
        assert_eq!(
            words.len(),
            text.chars().count(),
            "one box per char, nothing dropped"
        );
        let kinds: Vec<&str> = words
            .iter()
            .map(|word| word["kind"].as_str().expect("kind"))
            .collect();
        assert!(
            kinds.iter().all(|kind| *kind == "char"),
            "`chars` is the char granularity, got {kinds:?}"
        );
        let rejoined: String = words
            .iter()
            .map(|word| word["text"].as_str().expect("char text"))
            .collect();
        assert_eq!(rejoined, text, "char concatenation must rebuild the text");
    }
}

/// word 的 polygon 一律在**原图坐标系**里:与图像尺寸、区域框同一坐标空间。
///
/// 断的是“serve/序列化没有把识别裁剪图上的坐标原样吐给宿主”这类错:坐标一旦不在原图
/// 空间,网页的透明文本层就会整体错位。这里**不**声明框得准不准——那是字符定位基准
/// (IoU / 左右边界误差)要回答的问题。
#[test]
fn the_word_polygons_are_in_the_original_image_space() {
    let dir = complete_model_dir("words-geometry");
    let scripted = Scripted::fast();
    let server = TestServer::start(TestOptions::new(dir, scripted.clone()));

    let result = submit_words_query(
        &server,
        &scripted,
        "?words=chars",
        "char geometry",
        WordOutputMode::Chars,
    );
    // 线上拼写是 `"Image"`:`CoordinateSpace` 没有 `rename_all`,只有一个变体,而且入库的
    // `/result` 捕获夹具按这份拼写往返(`the_three_output_channels_are_frozen_…`),Step 1
    // 不动它。宿主需要的是“坐标与原图像素同一空间”这个语义,不是某个大小写。
    // (`WordKind` 本次改成 `snake_case` 是因为它从未出现在任何冻结夹具与文档里。)
    assert_eq!(result["image"]["coordinate_space"], "Image");
    let width = result["image"]["original_size"]["width"]
        .as_f64()
        .expect("width");
    let height = result["image"]["original_size"]["height"]
        .as_f64()
        .expect("height");

    for region in text_regions(&result) {
        let (row_x0, row_y0, row_x1, row_y1) = polygon_bounds(&region["polygon"]["points"]);
        let words = region["recognition"]["words"]
            .as_array()
            .expect("char boxes");
        for word in words {
            let (x0, y0, x1, y1) = polygon_bounds(&word["polygon"]["points"]);
            // 非退化:零宽/零高的框在网页上选不中,也不该出现在线上。
            assert!(x1 > x0 && y1 > y0, "degenerate word box: {word}");
            assert!(
                x0 >= 0.0 && y0 >= 0.0 && x1 <= width && y1 <= height,
                "word box {word} is outside the {width}x{height} image"
            );
            // 行包含:逐字框必须落在自己那一行里(这里允许与行框重合)。
            assert!(
                x0 >= row_x0 - 1e-4
                    && x1 <= row_x1 + 1e-4
                    && y0 >= row_y0 - 1e-4
                    && y1 <= row_y1 + 1e-4,
                "word box {word} escapes its own row box ({row_x0}, {row_y0}, {row_x1}, {row_y1})"
            );
        }
    }
}

/// 字符顺序稳定:同一张图两次提交的逐字序列逐字节相同,且中心 x 严格递增。
///
/// “稳定”两层含义都要:同一个请求重跑不能换顺序(否则缓存/对比无意义),以及
/// 数组顺序与几何顺序一致(否则宿主按 polygon 排 `span` 时会得倒一个乱序选区)。
#[test]
fn the_word_sequence_is_identical_across_two_identical_submissions() {
    let dir = complete_model_dir("words-stable");
    let scripted = Scripted::fast();
    let server = TestServer::start(TestOptions::new(dir, scripted.clone()));

    let first = submit_words_query(
        &server,
        &scripted,
        "?words=chars",
        "stable order",
        WordOutputMode::Chars,
    );
    let second = submit_words_query(
        &server,
        &scripted,
        "?words=chars",
        "stable order",
        WordOutputMode::Chars,
    );

    let boxes_of = |result: &Value| {
        serde_json::to_string(&result["regions"][0]["recognition"]["words"]).expect("serialize")
    };
    assert_eq!(
        boxes_of(&first),
        boxes_of(&second),
        "the same image must yield the same word array: text, kind, coordinates and order"
    );

    let words = second["regions"][0]["recognition"]["words"]
        .as_array()
        .expect("char boxes");
    let centers: Vec<f64> = words
        .iter()
        .map(|word| {
            let (x0, _, x1, _) = polygon_bounds(&word["polygon"]["points"]);
            (x0 + x1) / 2.0
        })
        .collect();
    for pair in centers.windows(2) {
        assert!(
            pair[1] > pair[0],
            "array order must follow left-to-right geometry, got {centers:?}"
        );
    }
}

// ---------------------------------------------- E16.2 / E16.3:页面侧的三项优化

/// 页面必须真的带上 E16.2 的模式选择器与 E16.3 的表格渲染入口。
///
/// 页面是**冻结契约**的一部分(docs/05 §9:nonce 属性 ×3、占位符与令牌计数固定),
/// 所以这里同时断言"新元素没有破坏那三条不变量":没有内联 `onclick=`/`style=`。
///
/// 为什么断言"`sanitizeTableHtml` 出现在页面里"还不够:**净化必须是唯一入口**。
/// 因此这里还断言渲染路径上不存在任何"把模型 HTML 直接塞进 `innerHTML`"的写法 ——
/// 那条路径一旦出现,白名单就成了摆设。
#[test]
fn the_page_carries_the_mode_selector_and_the_table_renderer() {
    let server = TestServer::start(TestOptions::new(
        empty_model_dir("page-e16-markup"),
        Scripted::fast(),
    ));
    let page = server.get("/").text();

    // E16.2.1:四态模式选择器取代了原来的单个 `#fxToggle` 复选框。
    for anchor in [
        "id=\"modeRow\"",
        "id=\"modeOpts\"",
        "id=\"modeCap\"",
        "role=\"radiogroup\"",
    ] {
        assert!(page.contains(anchor), "the mode selector needs {anchor}");
    }
    assert!(
        !page.contains("id=\"fxToggle\""),
        "the single formula checkbox is gone: the mode selector replaces it (E16.2.1)"
    );
    // 四个模式 id 必须都在源码里(选项由 JS 渲染,所以断言的是 MODES 表)。
    for mode in [
        "\"text\"",
        "\"formula\"",
        "\"text-table\"",
        "\"formula-table\"",
    ] {
        assert!(
            page.contains(mode),
            "the mode table must carry the {mode} mode"
        );
    }
    assert!(
        page.contains("modeAvailability") && page.contains("renderModeRow"),
        "the modes must be gated by readiness, not rendered unconditionally"
    );

    // E16.2.1 的请求表达:`?table=1` 与 `queue` 是**两个**独立的参数。
    assert!(
        page.contains(r#""/api/ocr?queue=" + queue + (mode.table ? "&table=1" : "")"#),
        "the table switch must ride on the documented query parameter"
    );

    // E16.1.5:表格队列就绪状态与公式行同形。
    assert!(
        page.contains("id=\"qReadyTable\"") && page.contains("表格队列 · "),
        "the queue panel must report the table queue as a third line"
    );

    // E16.3.1/E16.3.2:表格渲染走净化函数,且净化是白名单重建。
    assert!(
        page.contains("sanitizeTableHtml") && page.contains("DOMParser"),
        "the table renderer must parse and rebuild, not paste (E16.3.2)"
    );
    assert!(
        page.contains("TABLE_ALLOWED_TAGS") && page.contains("TABLE_ALLOWED_ATTRS"),
        "the sanitizer must be driven by an explicit whitelist"
    );
    assert!(
        page.contains(r#"wrap.innerHTML = sanitizeTableHtml("#),
        "the only way a table reaches the DOM is through the sanitizer"
    );
    // E24:表格默认**不渲染** —— 只有 HTML 原文 + 一个「渲染表格」按钮。
    assert!(
        page.contains(r#"data-table-render="1""#)
            && page.contains("渲染表格")
            && page.contains("收起表格"),
        "each table region needs its own render toggle (E24)"
    );
    assert!(
        page.contains(r#"<div class="rt-wrap" hidden></div>"#)
            && page.contains(r#"<pre class="rt-raw""#),
        "a table must start collapsed, showing its HTML source instead (E24)"
    );
    assert!(
        page.contains(r#"btn.getAttribute("data-table-html")"#)
            && page.contains(r#"data-table-html="${esc(html)}""#),
        "the render input must be the same string the source line shows (E24)"
    );
    assert!(
        page.contains(r#"const tbtn = e.target.closest("[data-table-render]")"#),
        "the toggle must be intercepted before the region-selection handler (E24)"
    );
    // 模型 HTML 绝不能被直接赋给 `innerHTML`:出现一次就绕过整个白名单。
    assert!(
        !page.contains("innerHTML = t.html")
            && !page.contains("innerHTML = table.html")
            && !page.contains("innerHTML = r.table"),
        "the model's own HTML must never be assigned to innerHTML"
    );
    // 净化不得用正则实现(docs/11 §4.3 E16.3.2 明确禁止)。
    assert!(
        !page.contains("replace(/</g") && !page.contains("replace(/<script"),
        "a regex sanitizer cannot be correct for HTML (E16.3.2)"
    );

    // 低置信必须**文字可见**,不能只靠颜色(docs/11 §4.3 E16.3.3)。
    assert!(
        page.contains("低置信(网格空洞或截断)"),
        "a low-confidence table must say so in words"
    );

    // 冻结不变量:新标记没有引入内联处理器或内联样式。
    assert!(
        !page.contains("onclick=") && !page.contains(" style=\""),
        "no inline handlers or styles under the page's nonce CSP"
    );
}

/// E22:表格模式的就绪判定必须读**服务端的表格路由块**,不能去 `sets[].files[]` 里按
/// `table_structure` 角色找文件。
///
/// 为什么这条断言存在(它是**绊线**,不是行为测试):`--table-model` 指定的结构模型按设计
/// 可以完全不在任何模型集合里(`models/serve/manifest.json` 声明的五个 role 里就没有
/// `table_structure`),于是"集合里找不到这个角色"会被误读成"模型缺失",把一个服务端明明
/// 回 `routing: true` 的模式永久置灰 —— 这就是 m12799 用户看到的那颗灰按钮。
/// 真正跑 JS 的行为测试在 `tools/check_web_model_gating.js`(Node 抽函数 + 真实 /api/models);
/// 这里只钉住"这段代码还在、且排在角色扫描之前"。
#[test]
fn the_page_gates_the_table_mode_on_the_server_route_block() {
    let server = TestServer::start(TestOptions::new(
        empty_model_dir("page-e22-table-gate"),
        Scripted::fast(),
    ));
    let page = server.get("/").text();

    let marker = "服务端未返回表格路由状态(/api/models.table)";
    let scan = "const need = QUEUE_ROLES[queue]";
    let marker_at = page.find(marker).unwrap_or_else(|| {
        panic!("the table readiness branch must exist (E22): {marker}");
    });
    let scan_at = page
        .find(scan)
        .unwrap_or_else(|| panic!("the shared role scan must still exist: {scan}"));
    assert!(
        marker_at < scan_at,
        "the table branch must run **before** the shared role scan, otherwise the role lookup \
         reports `表格结构` missing and greys the mode out (E22)"
    );
    assert!(
        page.contains("if (queue === \"table\")"),
        "the table queue needs its own readiness branch (E22)"
    );
    // 反向:角色表里**不得**再声明 table,否则同一个角色查找会回来。
    assert!(
        !page.contains("table: [\"table_structure\"]"),
        "QUEUE_ROLES must not require table_structure from a model set (E22)"
    );
    // 离线预览:演示数据也必须带表格路由块,否则演示模式里表格模式不可选(E16.3.8)。
    assert!(
        page.contains("function planRow(")
            && page.contains("required_roles: [\"table_structure\"]"),
        "the demo models need a table route block and plan rows (E22/E16.3.8)"
    );
}

/// E16.1:横幅从"只报错"改成**常驻模型清单面板**,并显示本机解析出的模型计划。
#[test]
fn the_page_carries_the_model_manifest_panel() {
    let server = TestServer::start(TestOptions::new(
        empty_model_dir("page-e16-manifest"),
        Scripted::fast(),
    ));
    let page = server.get("/").text();

    assert!(
        page.contains("function planRowsHtml") && page.contains("管线"),
        "the panel must render the resolved model plan (E16.1.3)"
    );
    assert!(
        page.contains("const pipes = m && m.pipelines") && page.contains("p.plan.forEach"),
        "the plan must come from the server's own pipelines payload, not a path built in the page"
    );
    assert!(
        page.contains("命令行指定"),
        "a model given on the command line is not in any set: the panel must say so"
    );
    assert!(
        page.contains("data-reverify=\"1\"") && page.contains("重新校验"),
        "a complete set still needs a reverify button (E16.1.1)"
    );
    assert!(
        page.contains(r#"e.target.closest("[data-reverify]")"#),
        "the reverify button must be wired through delegation, not a per-set listener"
    );
    assert!(
        page.contains("function fileStateCell") && page.contains("bf-sha-row"),
        "every file needs a three-state icon and an expandable sha256 (E16.1.2)"
    );
    assert!(
        page.contains("表格管线:"),
        "the reverify verdict must carry the table pipeline as well"
    );
    assert!(
        !page.contains("onclick=") && !page.contains(" style=\""),
        "no inline handlers or styles under the page's nonce CSP"
    );
}

/// 门禁 G8:注入型单元格文本经 `sanitizeTableHtml` 后**不产生可执行节点**。
///
/// # 为什么需要真的开一个浏览器
///
/// 净化的正确性完全取决于 **HTML 解析器怎么切分输入**(`<svg/onload=…>`、
/// `<td onclick=…>`、未闭合标签…),而这正是正则写不对、手写 DOM 也无法替代的部分。
/// 因此本用例把**服务端实际返回的页面**里那段主脚本抽出来,在一个空白文档里执行,
/// 直接调用页面自己的 `sanitizeTableHtml`,再把结果原样带回 Rust 断言。
///
/// 只有抽取脚本与暴露函数两步是测试自己做的(插一行 `globalThis.__RROCR_SANITIZE__ =`),
/// 被断言的函数体与线上逐字节相同。
///
/// 本机没有浏览器时**跳过**(与仓库里"真实模型不在仓库内就 skip"同一口径),
/// 而不是让 CI 因为缺一个可选工具而变红。
#[test]
fn the_table_sanitizer_produces_no_executable_nodes() {
    let Some(browser) = test_browser() else {
        eprintln!(
            "skipping: no headless browser found; set RAPID_STRUCTURE_TEST_BROWSER to run gate G8"
        );
        return;
    };

    let server = TestServer::start(TestOptions::new(
        empty_model_dir("page-e16-g8"),
        Scripted::fast(),
    ));
    let page = server.get("/").text();
    let script = main_inline_script(&page).expect("the page must carry its main inline script");

    // 函数声明在 IIFE 作用域里被提升,所以在 `"use strict";` 之后立刻暴露是安全的 ——
    // 也必须在**脚本开头**,因为脚本尾部的 `renderVerify()` 在空白文档里会抛。
    let exposed = script.replacen(
        "\"use strict\";",
        "\"use strict\";\n        globalThis.__RROCR_SANITIZE__ = sanitizeTableHtml;",
        1,
    );
    assert!(
        exposed.contains("__RROCR_SANITIZE__"),
        "the exposure seam must land: the main script must open with \"use strict\";"
    );

    // 每个 payload 都包在**真实的 `<table><tr>` 里**。
    //
    // 不是装饰:裸 `<td>` 会被 HTML 解析器按 "foster parenting" 规则丢掉标签、只把内容留在
    // body 里,于是 `colspan`/`rowspan` 根本到不了净化函数 —— 那条"合法跨度必须留下"的
    // 反向对照会**因为属性压根不存在而失败**(本轮实测:`sanitized[7]` 只剩 `"spanned"`)。
    // 真实输入永远是整表,测试也应当用整表。
    let payloads = [
        r#"<table><tr><td><script>alert(1)</script></td></tr></table>"#,
        r#"<table><tr><td><img src=x onerror="alert(1)"></td></tr></table>"#,
        r#"<table><tr><td><a href="javascript:alert(1)">click</a></td></tr></table>"#,
        r#"<table><tr><td onclick="alert(1)">tap</td></tr></table>"#,
        r#"<table><tr><td><iframe src="javascript:alert(1)"></iframe></td></tr></table>"#,
        r#"<table><tr><td><svg/onload=alert(1)></td></tr></table>"#,
        r#"<table><tr><td style="background:url(javascript:alert(1))">styled</td></tr></table>"#,
        r#"<table><tr><td colspan="2" rowspan="3">spanned</td></tr></table>"#,
        r#"<table><tr><td colspan="0">zero</td><td colspan="abc">nan</td><td colspan="1e9">huge</td></tr></table>"#,
        r#"<table><tr><td><b>bold</b><sub>2</sub><sup>+</sup><br>next</td></tr></table>"#,
        r#"<table><tr><td>&lt;script&gt;alert(1)&lt;/script&gt;</td></tr></table>"#,
    ];
    // `</script>` 一旦出现在 `<script>` 元素里就会**提前结束脚本**,即使它只是 JS 字符串里
    // 的一段文本。第 0 个 payload 恰恰带着 `</script>`,不转义的话驱动脚本被 HTML 解析器
    // 腰斩:`<pre>` 从不出现,而 `--dump-dom` 也再也等不到页面加载完成
    // (实测:同一份 HTML 少这个转义就 60 s 没有任何输出,加上它 400 ms 就有)。
    // `<\/` 在 JSON 里与 `/` 等价,所以字符串内容一个字节都没变。
    let payload_json = serde_json::to_string(&payloads)
        .expect("payloads serialize")
        .replace("</", "<\\/");

    let driver = format!(
        r#"<script>
        const payloads = {payload_json};
        const out = payloads.map((p) => {{
          const fn = globalThis.__RROCR_SANITIZE__;
          if (typeof fn !== "function") return "__MISSING__";
          return fn(p);
        }});
        const bytes = new TextEncoder().encode(JSON.stringify(out));
        let hex = "";
        for (const b of bytes) hex += b.toString(16).padStart(2, "0");
        const pre = document.createElement("pre");
        pre.id = "sanitizer-out";
        pre.textContent = hex;
        document.body.appendChild(pre);
        </script>"#
    );

    let html = format!(
        "<!doctype html><html><head><meta charset=\"utf-8\"></head><body>\n\
         <script>{exposed}</script>\n{driver}\n</body></html>"
    );
    let dir = std::env::temp_dir().join(format!("rrocr-g8-{}", std::process::id()));
    std::fs::create_dir_all(&dir).expect("temp dir");
    let file = dir.join("g8.html");
    std::fs::write(&file, html).expect("write harness");

    // 把孩子的 stdout/stderr 接到**文件**上,而不是管道。
    //
    // 两条理由,都是本轮实测逼出来的:① 缺 `--user-data-dir` 时 `msedge.exe` 会把这次启动
    // **交给已经在跑的那个 Edge 实例**,于是既没有 stdout 也没有退出码,测试会一直等下去
    // (整条 `cargo test` 因此挂住 28 分钟);② 管道形态下浏览器(及其若干孙子进程)的行为
    // 与重定向到文件不同,同一组参数在 `Start-Process -RedirectStandardOutput` 下 0.5 s 退出、
    // 在 `Stdio::piped()` 下 60 s 不退出。落盘既避开了这两个坑,也让失败时能留下证据。
    let stdout_path = dir.join("dom.txt");
    let stderr_path = dir.join("browser.log");
    let stdout_file = std::fs::File::create(&stdout_path).expect("stdout file");
    let stderr_file = std::fs::File::create(&stderr_path).expect("stderr file");

    let profile = dir.join("profile");
    let mut child = match std::process::Command::new(&browser)
        .args([
            "--headless=new",
            "--disable-gpu",
            "--no-first-run",
            "--no-default-browser-check",
            "--disable-extensions",
            "--disable-background-networking",
            "--allow-file-access-from-files",
            "--virtual-time-budget=4000",
            "--dump-dom",
        ])
        .arg(format!("--user-data-dir={}", profile.display()))
        .arg(&file)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::from(stdout_file))
        .stderr(std::process::Stdio::from(stderr_file))
        .spawn()
    {
        Ok(child) => child,
        Err(error) => {
            eprintln!("skipping: cannot launch {browser:?}: {error}");
            return;
        }
    };

    // 完成判定看**输出**,不看进程退出。
    //
    // 实测事实(三次独立探针一致):`msedge.exe --headless=new --dump-dom` 在 400 ms 左右
    // 就把完整 DOM 写进了 stdout,但**进程之后还要再活很久**(文件已经 186,002 B 时
    // `HasExited` 仍是 false,在 Rust 侧 60 s 都没有退出)。等退出会让一条可选工具的用例
    // 决定整条套件的时长,所以这里等输出变非空,然后主动收掉进程。
    let deadline = Instant::now() + Duration::from_secs(60);
    let mut ready = false;
    while Instant::now() < deadline {
        let written = std::fs::metadata(&stdout_path)
            .map(|meta| meta.len() > 0)
            .unwrap_or(false);
        if written {
            ready = true;
            break;
        }
        match child.try_wait() {
            // 进程退出了却什么都没写出来:不再等,走下面的失败分支。
            Ok(Some(_)) => break,
            Ok(None) => std::thread::sleep(Duration::from_millis(200)),
            Err(error) => {
                eprintln!("skipping: cannot poll {browser:?}: {error}");
                break;
            }
        }
    }
    // 无论走哪条路径都要收掉进程:它可能还会活很久(见上)。
    let _ = child.kill();
    let _ = child.wait();
    if !ready {
        let log = std::fs::read_to_string(&stderr_path).unwrap_or_default();
        let _ = std::fs::remove_dir_all(&dir);
        eprintln!(
            "skipping: {browser:?} wrote no DOM within 60s; \
             the sanitizer is not verified on this machine (browser log: {})",
            log.trim()
        );
        return;
    }

    let dom = std::fs::read_to_string(&stdout_path).unwrap_or_default();
    let browser_log = std::fs::read_to_string(&stderr_path).unwrap_or_default();
    let _ = std::fs::remove_dir_all(&dir);

    let hex = extract_pre_hex(&dom, "sanitizer-out").unwrap_or_else(|| {
        panic!(
            "the harness produced no output (browser log: {})",
            browser_log.trim()
        )
    });
    let json = decode_hex(&hex).expect("the harness output must be hex-encoded UTF-8");
    let sanitized: Vec<String> =
        serde_json::from_str(&json).expect("the harness output must be a JSON array");

    assert_eq!(
        sanitized.len(),
        payloads.len(),
        "every payload must come back"
    );
    for (input, output) in payloads.iter().zip(sanitized.iter()) {
        assert_ne!(
            output, "__MISSING__",
            "the page's sanitizer must be reachable: {input}"
        );
        let lowered = output.to_lowercase();
        for forbidden in [
            "<script",
            "<img",
            "<iframe",
            "<svg",
            "<a ",
            "onerror",
            "onclick",
            "onload",
            "javascript:",
            "style=",
        ] {
            assert!(
                !lowered.contains(forbidden),
                "gate G8: {forbidden:?} survived sanitizing {input:?} -> {output:?}"
            );
        }
    }

    // 反向对照:白名单里的东西必须**留下**,否则"什么都删掉"也能通过上面的断言。
    let spanned = &sanitized[7];
    assert!(
        spanned.contains("colspan=\"2\"") && spanned.contains("rowspan=\"3\""),
        "a legal span must survive: {spanned:?}"
    );
    let inline = &sanitized[9];
    for kept in ["<b>", "<sub>", "<sup>", "<br>"] {
        assert!(
            inline.contains(kept),
            "{kept} is on the whitelist and must survive: {inline:?}"
        );
    }
    // 越界的 `colspan` 一律丢弃(`1` 等价于没写,`0`/`abc`/`1e9` 不是合法跨度)。
    let spans = &sanitized[8];
    assert!(
        !spans.contains("colspan"),
        "out-of-range spans must be dropped, not clamped: {spans:?}"
    );
    // 转义后的标签是**文本**,必须原样留下(净化器不做二次转义)。
    assert!(
        sanitized[10].contains("&lt;script&gt;"),
        "already-escaped text must survive as text: {:?}",
        sanitized[10]
    );
}

/// 表格的渲染按钮(E24):默认只显示原文,点击才渲染,且渲染仍只走净化入口。
///
/// 驱动的是**页面自己的** `tableRegionHtml` + `toggleTableRender`。
///
/// 为什么不是"在真页面上点一下":`regionList` 的委托处理器在页面尾部才注册(空白文档里
/// `renderVerify()` 会先抛),所以这里直接调函数;而"按钮必须被委托拦在选中区域之前"
/// 由 `the_page_carries_the_mode_selector_and_the_table_renderer` 的结构断言把守。
///
/// 原文行(`.rt-raw > code`)由 `renderRegions()` 用 `getAttribute("data-table-html")` 写回,
/// 那条委托同样在页面尾部,本用例不驱动它 —— 这里断言的是更硬的属性:**`esc()` 之后
/// `getAttribute` 必须逐字节还原模型 HTML**(含引号),原文行才可能与渲染输入同源。
///
/// 本机没有浏览器时**跳过**(与 G8 的净化用例同一口径)。
#[test]
fn the_table_render_toggle_is_lazy_and_stays_sanitized() {
    let Some(browser) = test_browser() else {
        eprintln!(
            "skipping: no headless browser found; set RAPID_STRUCTURE_TEST_BROWSER to run the E24 toggle"
        );
        return;
    };

    let server = TestServer::start(TestOptions::new(
        empty_model_dir("page-e24-toggle"),
        Scripted::fast(),
    ));
    let page = server.get("/").text();
    let script = main_inline_script(&page).expect("the page must carry its main inline script");
    let exposed = script.replacen(
        "\"use strict\";",
        "\"use strict\";\n        globalThis.__RROCR_SANITIZE__ = sanitizeTableHtml;\n        \
         globalThis.__RROCR_TABLE_HTML__ = tableRegionHtml;\n        \
         globalThis.__RROCR_TOGGLE__ = toggleTableRender;",
        1,
    );
    assert!(
        exposed.contains("__RROCR_TOGGLE__") && exposed.contains("__RROCR_TABLE_HTML__"),
        "the exposure seam must land: the main script must open with \"use strict\";"
    );
    assert!(
        page.contains("function tableRegionHtml(") && page.contains("function toggleTableRender("),
        "the toggle harness drives page functions that must exist"
    );

    // E24:表格的渲染按钮。见函数文档:这里驱动页面自己的两个函数。
    let payloads = [
        r#"<table><tr><th>甲</th><th>乙</th></tr><tr><td>1</td><td colspan="2">2</td></tr></table>"#,
        r#"<table><tr><td><script>alert(1)</script></td><td><img src=x onerror="alert(1)"></td></tr></table>"#,
    ];
    let payload_json = serde_json::to_string(&payloads)
        .expect("payloads serialize")
        .replace("</", "<\\/");
    let driver = format!(
        r#"<script>
        const payloads = {payload_json};
        const make = globalThis.__RROCR_TABLE_HTML__;
        const toggle = globalThis.__RROCR_TOGGLE__;
        const out = [];
        for (const payload of payloads) {{
          const host = document.createElement("div");
          document.body.appendChild(host);
          if (typeof make !== "function" || typeof toggle !== "function") {{
            out.push({{ missing: true }});
            continue;
          }}
          host.innerHTML = make(
            {{
              kind: "table",
              table: {{
                html: payload,
                rows: 2,
                cols: 3,
                holes: 1,
                confidence: "low",
                degradations: [{{ kind: "grid_holes", holes: 1 }}],
                cells: [{{ match_kind: "single" }}, {{ match_kind: "unmatched" }}],
                sourceLineIndices: [0, 1],
              }},
            }},
            0,
            "1,2 3,4 5,6 7,8",
            "1,2 → 7,8",
          );
          const btn = host.querySelector("[data-table-render]");
          const wrap = host.querySelector(".rt-wrap");
          const raw = host.querySelector(".rt-raw");
          const fold = host.querySelector(".ri-fold");
          const row = {{}};
          row.attr = btn ? (btn.getAttribute("data-table-html") === payload ? "same" : "diff") : "__NO_BUTTON__";
          row.collapsed = wrap && wrap.hidden ? "yes" : "no";
          row.rawShown = raw && !raw.hidden ? "yes" : "no";
          row.label = btn ? btn.textContent : "";
          row.expanded = btn ? String(btn.getAttribute("aria-expanded")) : "";
          row.rendered = wrap ? wrap.innerHTML.length : -1;
          if (btn) toggle(btn);
          row.afterHidden = wrap && wrap.hidden ? "hidden" : "shown";
          row.afterHtml = wrap ? wrap.innerHTML.toLowerCase() : "";
          row.afterLabel = btn ? btn.textContent : "";
          row.afterExpanded = btn ? String(btn.getAttribute("aria-expanded")) : "";
          row.afterRaw = raw && raw.hidden ? "hidden" : "shown";
          if (btn) toggle(btn);
          row.backHidden = wrap && wrap.hidden ? "hidden" : "shown";
          row.backCleared = wrap && wrap.innerHTML === "" ? "cleared" : "kept";
          row.backLabel = btn ? btn.textContent : "";
          row.backRaw = raw && !raw.hidden ? "shown" : "hidden";
          row.span = payload.indexOf("colspan") >= 0 ? "yes" : "no";
          row.folded = fold ? "yes" : "no";
          out.push(row);
        }}
        const bytes = new TextEncoder().encode(JSON.stringify(out));
        let hex = "";
        for (const b of bytes) hex += b.toString(16).padStart(2, "0");
        const pre = document.createElement("pre");
        pre.id = "table-render-out";
        pre.textContent = hex;
        document.body.appendChild(pre);
        </script>"#
    );
    let html = format!(
        "<!doctype html><html><head><meta charset=\"utf-8\"></head><body>\n\
         <script>{exposed}</script>\n{driver}\n</body></html>"
    );
    let (dom, browser_log) = match run_headless_dom(&browser, &html, "e24-toggle") {
        Ok(result) => result,
        Err(reason) => {
            eprintln!(
                "skipping: {reason}; the table render toggle is not verified on this machine"
            );
            return;
        }
    };
    let hex = extract_pre_hex(&dom, "table-render-out").unwrap_or_else(|| {
        panic!(
            "the toggle harness produced no output (browser log: {})",
            browser_log.trim()
        )
    });
    let json = decode_hex(&hex).expect("the toggle harness output must be hex-encoded UTF-8");
    let rows: Vec<serde_json::Value> =
        serde_json::from_str(&json).expect("the toggle harness output must be a JSON array");
    assert_eq!(rows.len(), payloads.len(), "every payload must come back");
    for row in &rows {
        assert!(
            row["missing"].as_bool() != Some(true),
            "the exposed page functions must be reachable: {row}"
        );
        assert_ne!(
            row["attr"], "__NO_BUTTON__",
            "every table card needs its own render button (E24)"
        );
        assert_eq!(
            row["attr"], "same",
            "esc() + getAttribute must round-trip the model HTML byte for byte"
        );
        assert_eq!(
            row["collapsed"], "yes",
            "a table must start collapsed (E24)"
        );
        assert_eq!(row["rawShown"], "yes", "the source must be shown instead");
        assert_eq!(row["label"], "渲染表格");
        assert_eq!(row["expanded"], "false");
        assert_eq!(
            row["rendered"], 0,
            "nothing may be rendered before the click"
        );
        assert_eq!(row["afterHidden"], "shown", "the click renders the table");
        assert_eq!(row["afterLabel"], "收起表格");
        assert_eq!(row["afterExpanded"], "true");
        assert_eq!(row["afterRaw"], "hidden");
        let rendered = row["afterHtml"]
            .as_str()
            .expect("rendered html is a string");
        assert!(
            rendered.contains("<table"),
            "the rendered DOM must be a real table: {rendered}"
        );
        // 反向对照:源里有合法跨度时,跨度必须活下来(净化不能把合法内容一起删掉)。
        if row["span"] == "yes" {
            assert!(
                rendered.contains("colspan"),
                "a legal span in the source must survive sanitizing: {rendered}"
            );
        } else {
            assert_eq!(
                row["span"], "no",
                "every payload must report whether it carries a span"
            );
        }
        for forbidden in ["<script", "<img", "onerror", "onload"] {
            assert!(
                !rendered.contains(forbidden),
                "gate G8 on the lazy path: {forbidden:?} survived -> {rendered}"
            );
        }
        assert_eq!(
            row["backHidden"], "hidden",
            "the second click collapses again"
        );
        assert_eq!(
            row["backCleared"], "cleared",
            "collapsing must drop the rendered DOM (a big table must not stay resident)"
        );
        assert_eq!(row["backLabel"], "渲染表格");
        assert_eq!(row["backRaw"], "shown");
        assert_eq!(
            row["folded"], "no",
            "the table card is not a folded row; it must not gain a details element"
        );
    }
}

/// 用无头浏览器跑一段独立 HTML,返回(序列化后的 DOM,浏览器日志)。
///
/// `Err(reason)` 表示**这台机器上没跑成**(启动失败 / 60 s 内没有 DOM):调用方按"跳过"处理,
/// 与仓库里"真实模型不在仓库内就 skip"同一口径,而不是让 CI 因为缺一个可选工具变红。
///
/// 启动参数里的两条都是实测逼出来的:① 缺 `--user-data-dir` 时 `msedge.exe` 会把这次启动
/// **交给已经在跑的那个 Edge 实例**,于是既没有 stdout 也没有退出码,测试会一直等下去
/// (整条 `cargo test` 因此挂住 28 分钟);② stdout/stderr 必须接到**文件**而不是管道 ——
/// 管道形态下浏览器(及其若干孙子进程)的句柄行为不同,同一组参数重定向到文件 0.5 s 退出、
/// 用 `Stdio::piped()` 60 s 不退出。落盘既避开这两个坑,也让失败时留下证据。
fn run_headless_dom(browser: &Path, html: &str, tag: &str) -> Result<(String, String), String> {
    let dir = std::env::temp_dir().join(format!("rrocr-{tag}-{}", std::process::id()));
    std::fs::create_dir_all(&dir).map_err(|error| format!("temp dir: {error}"))?;
    let file = dir.join("harness.html");
    std::fs::write(&file, html).map_err(|error| format!("write harness: {error}"))?;
    let stdout_path = dir.join("dom.txt");
    let stderr_path = dir.join("browser.log");
    let stdout_file = std::fs::File::create(&stdout_path).map_err(|error| error.to_string())?;
    let stderr_file = std::fs::File::create(&stderr_path).map_err(|error| error.to_string())?;
    let profile = dir.join("profile");
    let mut child = match std::process::Command::new(browser)
        .args([
            "--headless=new",
            "--disable-gpu",
            "--no-first-run",
            "--no-default-browser-check",
            "--disable-extensions",
            "--disable-background-networking",
            "--allow-file-access-from-files",
            "--virtual-time-budget=4000",
            "--dump-dom",
        ])
        .arg(format!("--user-data-dir={}", profile.display()))
        .arg(&file)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::from(stdout_file))
        .stderr(std::process::Stdio::from(stderr_file))
        .spawn()
    {
        Ok(child) => child,
        Err(error) => {
            let _ = std::fs::remove_dir_all(&dir);
            return Err(format!("cannot launch {browser:?}: {error}"));
        }
    };

    // 完成判定看**输出**,不看进程退出。
    //
    // 实测事实(三次独立探针一致):`msedge.exe --headless=new --dump-dom` 在 400 ms 左右
    // 就把完整 DOM 写进了 stdout,但**进程之后还要再活很久**(文件已经 186,002 B 时
    // `HasExited` 仍是 false,在 Rust 侧 60 s 都没有退出)。等退出会让一条可选工具的用例
    // 决定整条套件的时长,所以这里等输出变非空,然后主动收掉进程。
    let deadline = Instant::now() + Duration::from_secs(60);
    let mut ready = false;
    while Instant::now() < deadline {
        let written = std::fs::metadata(&stdout_path)
            .map(|meta| meta.len() > 0)
            .unwrap_or(false);
        if written {
            ready = true;
            break;
        }
        match child.try_wait() {
            // 进程退出了却什么都没写出来:不再等,走下面的失败分支。
            Ok(Some(_)) => break,
            Ok(None) => std::thread::sleep(Duration::from_millis(200)),
            Err(error) => {
                eprintln!("warning: cannot poll {browser:?}: {error}");
                break;
            }
        }
    }
    // 无论走哪条路径都要收掉进程:它可能还会活很久(见上)。
    let _ = child.kill();
    let _ = child.wait();
    let dom = std::fs::read_to_string(&stdout_path).unwrap_or_default();
    let log = std::fs::read_to_string(&stderr_path).unwrap_or_default();
    let _ = std::fs::remove_dir_all(&dir);
    if !ready {
        return Err(format!("wrote no DOM within 60s: {}", log.trim()));
    }
    Ok((dom, log))
}

/// 找一个可用的无头浏览器:环境变量优先,其次 Edge、Chrome 的默认安装位置。
fn test_browser() -> Option<PathBuf> {
    if let Some(path) = std::env::var_os("RAPID_STRUCTURE_TEST_BROWSER") {
        let path = PathBuf::from(path);
        if path.is_file() {
            return Some(path);
        }
    }
    [
        r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
        r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
        r"C:\Program Files\Google\Chrome\Application\chrome.exe",
        r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
    ]
    .into_iter()
    .map(PathBuf::from)
    .find(|path| path.is_file())
}

/// 取出页面里**最后**一段内联 `<script nonce=...>` 的脚本体。
///
/// 不能按 `<script` 文本搜索:页面里还有注释与模板字符串中的假命中,因此按行定位
/// 最后一个带 `nonce=` 的开标签与它之后的第一个 `</script>`。
fn main_inline_script(page: &str) -> Option<String> {
    let lines: Vec<&str> = page.lines().collect();
    let open = lines
        .iter()
        .rposition(|line| line.contains("<script nonce="))?;
    let close = lines
        .iter()
        .skip(open + 1)
        .position(|line| line.trim() == "</script>")?
        + open
        + 1;
    Some(lines[open + 1..close].join("\n"))
}

/// 从序列化后的 DOM 里取出 `<pre id="...">` 的文本内容。
fn extract_pre_hex(dom: &str, id: &str) -> Option<String> {
    let needle = format!("<pre id=\"{id}\">");
    let start = dom.find(&needle)? + needle.len();
    let rest = &dom[start..];
    let end = rest.find("</pre>")?;
    Some(rest[..end].trim().to_string())
}

/// 十六进制 → UTF-8 字符串(测试自己解码,避免为了一个用例引入 base64 依赖)。
fn decode_hex(hex: &str) -> Option<String> {
    if !hex.len().is_multiple_of(2) {
        return None;
    }
    let bytes = (0..hex.len())
        .step_by(2)
        .map(|index| u8::from_str_radix(&hex[index..index + 2], 16).ok())
        .collect::<Option<Vec<u8>>>()?;
    String::from_utf8(bytes).ok()
}
// ------------------------------------------------- M1 评审:检测模型完整性 / 校验缓存

/// 一个带 `formula_detector` role 的本地清单目录(评审 P1-1 的夹具)。
///
/// 五个文件:文本三个 + 公式识别 + 公式检测。检测模型的**声明哈希**就是写盘时那一份
/// 内容的哈希,因此测试可以随后把它改写来构造"存在但内容不对"。
struct DetectorFixture {
    dir: PathBuf,
    detector: PathBuf,
    detector_sha: String,
}

fn detector_model_dir(name: &str) -> DetectorFixture {
    let dir = m2_root().join(format!("detector-{name}-{}", unique()));
    std::fs::create_dir_all(&dir).expect("create the model dir");
    let files = [
        ("det.onnx", "detector"),
        ("rec.onnx", "recognizer"),
        ("dict.txt", "dictionary"),
        ("fx.onnx", "formula_recognizer"),
        ("mfd.onnx", "formula_detector"),
    ];
    let mut manifest = String::from(
        "{\"schema_version\":1,\"id\":\"test-set\",\"family\":\"PP-OCR\",\"version\":\"v-test\",\
         \"languages\":[\"en\"],\"files\":[",
    );
    let mut detector_sha = String::new();
    for (index, (file, role)) in files.iter().enumerate() {
        let bytes = model_file_bytes(file);
        let path = dir.join(file);
        std::fs::write(&path, &bytes).expect("write the model file");
        let sha = sha256_file(&path).expect("hash the model file");
        if *file == "mfd.onnx" {
            detector_sha = sha.clone();
        }
        if index > 0 {
            manifest.push(',');
        }
        manifest.push_str(&format!(
            "{{\"name\":\"{file}\",\"role\":\"{role}\",\"sha256\":\"{sha}\",\"size_bytes\":{},\
             \"source_url\":\"https://www.modelscope.cn/models/{file}\"}}",
            bytes.len()
        ));
    }
    manifest.push_str("]}");
    std::fs::write(dir.join("manifest.json"), manifest).expect("write the manifest");
    DetectorFixture {
        detector: dir.join("mfd.onnx"),
        detector_sha,
        dir,
    }
}

/// 评审 P1-1:损坏的公式**检测**模型必须被抓住——`/api/models` 如实报 `corrupt`,
/// 并且 `queue=formula` 在**读 body 之前**就是 409 `models_corrupt`。
///
/// 旧实现的缺口(本用例的根因):检测模型的路径被单独传递、集合声明的 SHA-256 被丢掉,
/// 而请求路径只做存在性预检——于是"文件在、内容错"能一路走到 worker 里才失败。
#[test]
fn a_corrupt_formula_detector_is_reported_and_refused_before_the_body() {
    let fixture = detector_model_dir("corrupt-detector");
    std::fs::write(&fixture.detector, b"corrupted detector bytes").expect("corrupt the detector");
    // 检测模型由**集合声明**(`formula_detector` role),因此它自动进入运行计划并启用路由。
    let server = TestServer::start(TestOptions::new(fixture.dir.clone(), Scripted::fast()));

    // `/api/models`:集合里的检测模型是损坏的,且**只给文件名**(§7.4 脱敏)。
    let models = server.get("/api/models").json();
    assert_eq!(models["formula"]["complete"], false, "{models}");
    assert_eq!(
        models["formula"]["corrupt"],
        json!(["mfd.onnx"]),
        "{models}"
    );
    assert_eq!(models["formula"]["detector"]["configured"], true);
    assert_eq!(models["formula"]["detector"]["file"], "mfd.onnx");
    assert_eq!(
        models["formula"]["detector"]["state"], "corrupt",
        "{models}"
    );
    assert_eq!(
        models["formula"]["detector"]["sha256"], fixture.detector_sha,
        "the declared hash must be reported (not dropped)"
    );
    // 运行计划的公式块:识别模型在计划里、检测模型**在**计划里且是唯一的阻塞项。
    assert_eq!(models["pipelines"]["formula"]["in_plan"], true, "{models}");
    assert_eq!(
        models["pipelines"]["formula"]["corrupt"],
        json!(["mfd.onnx"]),
        "{models}"
    );
    assert_eq!(
        models["pipelines"]["formula"]["files"],
        json!(["fx.onnx", "mfd.onnx"]),
        "the run plan's formula pipeline is exactly the recognizer + the detector: {models}"
    );
    assert!(
        !models
            .to_string()
            .contains(&fixture.dir.display().to_string()),
        "no absolute path may leak: {models}"
    );

    // 请求体**没有被读**:声明 1 MiB 却一个字节都不发。若服务端在这里读 body,
    // 这个请求会一直等到读取超时(测试因此会超时失败),所以 409 本身就是证据。
    let refused = server.request(
        "POST",
        "/api/ocr?queue=formula",
        &[
            ("Host", server.host.as_str()),
            ("X-RapidStructure-Token", server.token.as_str()),
            ("Origin", server.origin.as_str()),
            ("Content-Type", "application/octet-stream"),
            ("Content-Length", "1048576"),
        ],
        None,
    );
    assert_eq!(refused.status, 409, "{}", refused.text());
    assert_eq!(refused.code(), "models_corrupt");
    let detail = &refused.json()["detail"];
    assert_eq!(detail["scope"], "formula");
    assert_eq!(detail["corrupt"], json!(["mfd.onnx"]));
    assert_eq!(detail["detector"]["state"], "corrupt");
    assert_eq!(detail["in_plan"], true);

    // 普通 OCR 完全不受影响(那是公式队列的缺口,不是引擎的)。
    let text = server.submit_ocr(b"text image");
    assert_eq!(text.status, 202, "{}", text.text());
}

/// 评审 P1-1 + 本轮:检测模型来自 `--formula-detector`(**不在任何集合里**)时同样进入
/// 运行计划、同样被校验,而且它是唯一阻塞项时 `detail.corrupt` 仍要点名它。
///
/// **本轮的行为变化(有意的期望变更)**:集合之外的文件**没有可信摘要**,因此
/// `/api/models` 与 409 的 `detector.sha256` 是 `null`——旧用例给它塞了一个"声明哈希"
/// 来走哈希分支,那正是"报告一份、加载另一份"的形状。现在的判据是文档化规则:
/// 存在 + 可读 + 像 ONNX(`0x08` + `ir_version` varint)。内容被换成不是 ONNX 的东西时
/// 状态变成 `corrupt`,公式队列因此在**读 body 之前** 409——旧用例证的那条保证仍然成立。
#[test]
fn a_cli_formula_detector_is_verified_by_the_same_rule() {
    let dir = manifest_model_dir_text_only("cli-detector", &text_fixture_files(), None);
    let detector = dir.join("pix2text-mfd-1.5.onnx");
    std::fs::write(
        &detector,
        plausible_onnx_bytes("a detector the manifest never declared"),
    )
    .expect("write detector");
    let server = TestServer::start(
        TestOptions::new(dir.clone(), Scripted::fast()).with_formula_routing(&detector),
    );

    // 内容看起来是 ONNX → 检测模型 `present`、公式队列照常 202。
    let models = server.get("/api/models").json();
    assert_eq!(models["formula"]["detector"]["state"], "present");
    assert_eq!(
        models["formula"]["detector"]["sha256"],
        Value::Null,
        "an external detector has no declared digest, and the service must not invent one: {models}"
    );
    assert_eq!(models["formula"]["routing"], true);
    // 它在**运行计划**里(这是本轮修复的根因:旧实现把它排除在 `required_files` 之外)。
    assert_eq!(
        models["pipelines"]["formula"]["files"],
        json!(["fx.onnx", "pix2text-mfd-1.5.onnx"]),
        "{models}"
    );
    let accepted = server.post(
        "/api/ocr?queue=formula",
        &[("Content-Type", "application/octet-stream")],
        b"formula image",
    );
    assert_eq!(accepted.status, 202, "{}", accepted.text());

    // 同一个路径、内容被换成"不是 ONNX" → 文档化规则(存在 + 可读 + 像 ONNX)判成 corrupt,
    // 准入在**读 body 之前** 409(不能继续用第一次的结论)。
    std::fs::write(&detector, b"corrupted after the first verification").expect("corrupt");
    let models = server.get("/api/models").json();
    assert_eq!(
        models["formula"]["detector"]["state"], "corrupt",
        "{models}"
    );
    assert_eq!(
        models["pipelines"]["formula"]["corrupt"],
        json!(["pix2text-mfd-1.5.onnx"]),
        "{models}"
    );
    let refused = server.request(
        "POST",
        "/api/ocr?queue=formula",
        &[
            ("Host", server.host.as_str()),
            ("X-RapidStructure-Token", server.token.as_str()),
            ("Origin", server.origin.as_str()),
            ("Content-Type", "application/octet-stream"),
            ("Content-Length", "1048576"),
        ],
        None,
    );
    assert_eq!(refused.status, 409, "{}", refused.text());
    assert_eq!(refused.code(), "models_corrupt");
    assert_eq!(
        refused.json()["detail"]["corrupt"],
        json!(["pix2text-mfd-1.5.onnx"]),
        "the detector is the only blocker and must be named"
    );
    assert!(
        refused.json()["detail"]["detector"]["sha256"].is_null(),
        "no declared digest → null (never a fabricated one)"
    );

    // 普通 OCR 照常可用:公式缺口不得阻塞文本管线。
    let text = server.submit_ocr(b"text image");
    assert_eq!(text.status, 202, "{}", text.text());
}

/// 评审 P1-2 + 性能一节:`/api/models` 复用**身份键控**的校验结论,而不是每次重新哈希。
///
/// `cold_this_call` 是**单次报告**里真的重算了摘要的文件数:启动快照已经验证过一次,
/// 因此稳态下必须是 0;一个文件被替换(体积/mtime 变化)时,只有它必须重新验证。
#[test]
fn models_reuses_the_verified_digest_until_the_file_identity_changes() {
    // 进程级校验缓存:本用例会清缓存或断言精确的重算次数,必须与同类用例串行。
    let _serial = cache_serial();
    let fixture = detector_model_dir("verify-cache");
    let server = TestServer::start(TestOptions::new(fixture.dir.clone(), Scripted::fast()));

    let first = server.get("/api/models").json();
    assert_eq!(
        first["verification"]["cold_this_call"], 0,
        "the startup snapshot already verified every declared file: {first}"
    );
    assert_eq!(
        first["verification"]["identity"],
        "path + size + mtime + SHA-256 of the first and last 64 KiB",
        "the identity must name all four components (B: the windows narrow the blind spot)"
    );
    assert_eq!(
        first["verification"]["partial_window_bytes"], 65536,
        "{first}"
    );
    assert!(
        first["verification"]["partial_reads"].as_u64().unwrap_or(0) >= 5,
        "every check reads the 128 KiB window: {first}"
    );
    assert!(
        first["verification"]["residual_blind_spot"]
            .as_str()
            .unwrap_or_default()
            .contains("not a security boundary"),
        "the honest statement must say what the heuristic is not: {first}"
    );
    assert!(first["verification"]["last_cold_ms"].is_number(), "{first}");
    assert!(
        first["verification"]["cold_verifications"]
            .as_u64()
            .unwrap_or(0)
            >= 5,
        "the five declared files were verified at least once: {first}"
    );
    let hits = first["verification"]["cache_hits"].as_u64().unwrap_or(0);

    let second = server.get("/api/models").json();
    assert_eq!(
        second["verification"]["cold_this_call"], 0,
        "a cache hit must not re-hash: {second}"
    );
    assert!(
        second["verification"]["cache_hits"].as_u64().unwrap_or(0) >= hits + 5,
        "five files were answered from the cache: {second}"
    );

    // 替换公式识别模型:身份变化 → **只有它**重新验证,并且结论变为 corrupt。
    std::fs::write(fixture.dir.join("fx.onnx"), b"replaced formula model").expect("replace");
    let third = server.get("/api/models").json();
    assert_eq!(
        third["verification"]["cold_this_call"], 1,
        "only the replaced file may be re-hashed: {third}"
    );
    assert_eq!(third["formula"]["complete"], false, "{third}");
    assert_eq!(third["formula"]["corrupt"], json!(["fx.onnx"]));
}

// ------------------------------------------- A1:`--reverify-models`(启动期冷验证,fail-fast)

/// A2 的页面侧:`重新校验` 按钮必须真的在页面里,并按页面既有的写法接线。
///
/// 页面是**冻结契约**的一部分(§9:三个 `nonce=` 属性逐字节相同、占位符与令牌计数固定),
/// 因此这里同时断言"新增按钮没有破坏那三条不变量":
///
/// - 没有内联 `style=` 或 `onclick=`(CSP 是 nonce,内联处理器会被拦掉;
///   页面既有的做法是 `addEventListener` + CSS 类);
/// - 按钮与结论区都在,且用 `role="status"`(`aria-live`)通报结果;
/// - 离线预览(`DEMO`)分支不发请求,如实解释"没有服务端"。
#[test]
fn the_page_carries_the_reverify_button_without_inline_handlers_or_styles() {
    let server = TestServer::start(TestOptions::new(
        empty_model_dir("page-reverify"),
        Scripted::fast(),
    ));
    let page = server.get("/").text();

    assert!(
        page.contains("id=\"verifyBtn\"") && page.contains("重新校验"),
        "the page must carry the reverify button"
    );
    assert!(
        page.contains("/api/models/reverify"),
        "the button must go through the documented endpoint"
    );
    assert!(
        page.contains(r#"$("verifyBtn").addEventListener("click", reverifyModels)"#),
        "the handler must be attached with addEventListener (no inline onclick under the nonce CSP)"
    );
    assert!(
        page.contains("id=\"verifyOut\"") && page.contains("role=\"status\""),
        "the outcome must be announced through a live region"
    );
    assert!(
        !page.contains("onclick=") && !page.contains(" style=\""),
        "no inline handlers or inline styles (docs/05 §9.5, WCAG: the page's own CSP forbids them)"
    );
    // 页面里那个唯一的空请求体入口(有 body 就是 400)。
    assert!(
        page.contains(r#"xhrSend("POST", "/api/models/reverify", "")"#),
        "the request body must be empty, exactly as the endpoint requires"
    );
    // A2 的逐管线结论必须被显示:否则"文本就绪、公式损坏"在页面上又会退化回一句笼统的
    // 结论(服务端把它分开说了,页面不能把它合并回去)。
    assert!(
        page.contains("c.pipelines") && page.contains("公式管线:"),
        "the page must render A2's per-pipeline verdict"
    );
    // 冻结的占位符计数(§9:nonce 属性 ×3、占位符出现 ×4、令牌 ×3)。
    assert_eq!(
        page.matches("__CSP_NONCE__").count(),
        0,
        "placeholders are injected"
    );
    assert_eq!(
        page.matches("__SRV_TOKEN__").count(),
        0,
        "placeholders are injected"
    );
}

// A1 的门禁本身在 `serve::run::tests`(三个用例:健康 / 损坏 / 缺失),
// **进程边界**那一条在 `tests/serve_startup.rs`。
//
// 为什么不在这个文件里跑子进程:本模块的测试二进制在 `target/<profile>/deps/` 下,
// cargo 在那里不保证注入 `CARGO_BIN_EXE_rapidstruct`,靠"猜上一级目录"可能拿到
// `cargo build` 留下的、**没有** `serve` feature 的旧可执行文件——那会让断言对象
// 与本次构建无关。集成测试里有 cargo 的保证。

// ------------------------------- A2:`POST /api/models/reverify`(清缓存 + 冷验证 + 重建引擎)

/// B × A2 的端到端证据:**同体积 + 同 mtime** 的内容替换在真实服务路径上被抓住。
///
/// 旧的 `(path, size, mtime)` 身份对这次替换会命中缓存、继续报 `present`;现在
/// `/api/models` 会把它报成 `corrupt`,并且在 `verification` 的成本账里留下两条痕迹:
/// `partial_mismatches` 增长、本次 `cold_this_call` 至少 1(**只有它**被重新哈希)。
#[test]
fn models_detects_a_same_size_same_mtime_swap_through_the_content_windows() {
    // 进程级校验缓存:本用例会清缓存或断言精确的重算次数,必须与同类用例串行。
    let _serial = cache_serial();
    let dir = complete_model_dir("verify-window-swap");
    let path = dir.join("rec.onnx");
    let server = TestServer::start(TestOptions::new(dir, Scripted::fast()));

    let first = server.get("/api/models").json();
    assert_eq!(first["complete"], true, "{first}");
    let mismatches_before = first["verification"]["partial_mismatches"]
        .as_u64()
        .expect("partial_mismatches");

    // 同体积 + 把 mtime 写回原值:stat 身份三项全部不变。
    let identity_before = FileIdentity::of(&path).expect("identity before the swap");
    let before = std::fs::metadata(&path)
        .expect("metadata")
        .modified()
        .expect("mtime");
    let original = std::fs::read(&path).expect("read the healthy model");
    std::fs::write(&path, corrupt_bytes(original.len())).expect("swap the content");
    let file = std::fs::OpenOptions::new()
        .write(true)
        .open(&path)
        .expect("open to restore the timestamp");
    file.set_modified(before).expect("write the old mtime back");
    drop(file);
    let identity_after = FileIdentity::of(&path).expect("identity after the swap");
    assert_eq!(
        identity_after.size(),
        identity_before.size(),
        "the size must be unchanged"
    );
    assert_eq!(
        identity_after.modified(),
        identity_before.modified(),
        "the mtime must be written back"
    );
    assert_ne!(
        identity_after.partial(),
        identity_before.partial(),
        "only the first/last 64 KiB windows can distinguish this swap"
    );

    let second = server.get("/api/models").json();
    assert!(
        second["verification"]["cold_this_call"]
            .as_u64()
            .expect("cold_this_call")
            >= 1,
        "the swap must force a re-hash (a stale hit would make this 0 and miss it): {second}"
    );
    assert!(
        second["verification"]["partial_mismatches"]
            .as_u64()
            .expect("partial_mismatches")
            > mismatches_before,
        "the reason must be visible in the cost ledger: {second}"
    );
    assert_eq!(second["complete"], false, "{second}");
    assert_eq!(second["corrupt"], json!(["rec.onnx"]), "{second}");

    // 端点也报同一个结论(同一条哈希证据),并且 reason 说的是"内容变了"。
    let response = server.post("/api/models/reverify", &[], b"");
    assert_eq!(response.status, 200, "{}", response.text());
    let body = response.json();
    assert_eq!(body["corrupt"], json!(["rec.onnx"]), "{body}");
    let culprit = body["files"]
        .as_array()
        .expect("files")
        .iter()
        .find(|file| file["name"] == "rec.onnx")
        .expect("the swapped file must be listed");
    assert_eq!(culprit["state"], "corrupt", "{body}");
    assert_eq!(
        culprit["cause"], "first_sight",
        "a forced verification never consults the cache, so its cause is the cold path: {body}"
    );
}

/// 与夹具**同体积**的替换内容。
///
/// 同体积是这几条用例的要点:`(path, size, mtime)` 三项全部不变,因此只有首尾 64 KiB 的
/// 局部摘要能把这次替换抓出来(旧身份下缓存会继续返回旧摘要,这正是 B 要收窄的窗口)。
fn corrupt_bytes(size: usize) -> Vec<u8> {
    let seed = b"corrupted model bytes";
    (0..size).map(|index| seed[index % seed.len()]).collect()
}

/// A2:损坏但**存在**的模型 → 端点报 `corrupt`,并把服务留在**可定位的错误态**,
/// 而不是"旧引擎继续 ready"。
///
/// 这是本端点的核心价值:只清缓存不重建引擎,页面上的按钮按下去什么都不会变——
/// 流水线的会话缓存(按文件身份失效)可能仍然服务着磁盘上已经不是这个文件的模型。
/// 因此这里断言的是**引擎状态本身**(`failed` + 点名文件 `rec.onnx`),
/// 而不是一句"端点返回了 200"。
///
/// 夹具的写法:先让引擎**真正建起来**(健康模型),再让"服务看到的那份文件"变成
/// 同体积的坏内容,最后调端点。恢复过程(写回正确字节 → ready)在
/// [`reverify_restores_ready_and_rebuilds_the_engine_after_a_healthy_revert`] 里,
/// 那条用例还断言了"会话真的被重建"。
#[test]
fn reverify_reports_a_corrupt_model_and_leaves_the_service_blocked_not_stale_ready() {
    // 进程级校验缓存:本用例会清缓存或断言精确的重算次数,必须与同类用例串行。
    let _serial = cache_serial();
    let dir = complete_model_dir("reverify-corrupt");
    // 破坏**文本管线**里的识别模型:它才是引擎要加载的那一份,因此"服务的状态"会从
    // `ready` 变成**可定位的错误态**(公式模型损坏只影响公式队列,普通 OCR 不受影响,
    // 那是 M4 的正确行为,不是本用例要考察的东西)。
    //
    // 同体积 + 把 mtime 写回原值:`(path, size, mtime)` 三项全部不变。旧身份下缓存会
    // 继续报 `present`(这正是 B 要收窄的窗口),因此这一条同时是局部摘要在真实服务
    // 路径上的证据。
    let path = dir.join("rec.onnx");
    let before = std::fs::metadata(&path)
        .expect("metadata")
        .modified()
        .expect("mtime");
    let original = std::fs::read(&path).expect("read the healthy model");
    assert!(
        original.starts_with(b"test model file"),
        "the fixture content must be the healthy one: {:?}",
        String::from_utf8_lossy(&original)
    );
    std::fs::write(&path, corrupt_bytes(original.len())).expect("corrupt the recognizer");
    let file = std::fs::OpenOptions::new()
        .write(true)
        .open(&path)
        .expect("open to restore the timestamp");
    file.set_modified(before).expect("write the old mtime back");
    drop(file);

    let built = Arc::new(AtomicUsize::new(0));
    let server = TestServer::start(TestOptions {
        engine_factory: counting_engine_factory(Arc::clone(&built)),
        ..TestOptions::new(dir.clone(), Scripted::fast())
    });
    // 启动期就如实报告:齐备性判定用的是同一份哈希证据,坏文件不会被当成好文件。
    assert_eq!(
        server.get("/api/status").json()["engine"]["state"],
        "blocked_models_missing",
        "the startup readiness check must already see the corrupt recognizer"
    );
    assert_eq!(built.load(Ordering::SeqCst), 0, "no session was created");

    let response = server.post("/api/models/reverify", &[], b"");
    assert_eq!(response.status, 200, "{}", response.text());
    let body = response.json();
    assert_eq!(
        body["computed"].as_u64(),
        Some(3),
        "every file **this run's plan** uses was re-hashed; the formula model is not planned \
         (no --formula-detector), so the 566 MB file must not be hashed: {body}"
    );
    assert_eq!(body["corrupt"], json!(["rec.onnx"]), "{body}");
    assert_eq!(
        body["pipelines"]["formula"]["in_plan"], false,
        "the formula pipeline is not part of this run: {body}"
    );
    assert_eq!(
        body["pipelines"]["text"]["outcome"], "blocked_models_missing",
        "the text engine's outcome is reported per pipeline: {body}"
    );
    assert_eq!(
        body["outcome"], "blocked_models_missing",
        "the state must be locatable, not a stale ready: {body}"
    );
    assert_eq!(body["engine"]["state"], "blocked_models_missing", "{body}");
    assert_eq!(body["engine"]["missing"], json!(["rec.onnx"]), "{body}");
    let culprit = body["files"]
        .as_array()
        .expect("files")
        .iter()
        .find(|file| file["name"] == "rec.onnx")
        .expect("the corrupt file must be listed");
    assert_eq!(culprit["state"], "corrupt", "{body}");
    assert_eq!(
        culprit["cause"], "first_sight",
        "this call's cold verification has no earlier identity to compare against: {body}"
    );
    assert_eq!(culprit["digest_computed_this_call"], true, "{body}");

    // 可定位的错误态:后续 OCR 得到 409(而不是"成功但用了旧模型")。
    let ocr = server.submit_ocr(b"image");
    assert_eq!(ocr.status, 409, "{}", ocr.text());
    assert_eq!(ocr.code(), "models_corrupt", "{}", ocr.text());
    assert_eq!(
        ocr.json()["detail"]["corrupt"],
        json!(["rec.onnx"]),
        "the 409 must name the file"
    );
    // 引擎没有被"重建成功"——模型不齐备时**不创建会话**。
    assert_eq!(
        built.load(Ordering::SeqCst),
        0,
        "a blocked model set must not create a session"
    );
}

/// A2:健康文件被还原后,同一个端点把服务恢复成 `ready`,**并且真的重建了会话**。
///
/// "重建引擎"这一步如果只是清缓存,这个断言会失败(建会话次数不会增加)——
/// 而用户看到的就是"按钮按下去模型没换"。
#[test]
fn reverify_restores_ready_and_rebuilds_the_engine_after_a_healthy_revert() {
    // 进程级校验缓存:本用例会清缓存或断言精确的重算次数,必须与同类用例串行。
    let _serial = cache_serial();
    let dir = complete_model_dir("reverify-revert");
    let kept = dir.join("kept.onnx");
    std::fs::write(&kept, std::fs::read(dir.join("rec.onnx")).expect("read")).expect("seed");
    let built = Arc::new(AtomicUsize::new(0));
    let server = TestServer::start(TestOptions {
        engine_factory: counting_engine_factory(Arc::clone(&built)),
        ..TestOptions::new(dir.clone(), Scripted::fast())
    });
    assert_eq!(server.get("/api/status").json()["engine"]["state"], "ready");
    assert_eq!(built.load(Ordering::SeqCst), 1);

    // 写坏 → 端点报 corrupt、引擎状态是可定位的错误态(`failed` + 点名文件)。
    std::fs::write(dir.join("rec.onnx"), b"corrupted same-len").expect("corrupt");
    let broken = server.post("/api/models/reverify", &[], b"").json();
    assert_eq!(broken["outcome"], "failed", "{broken}");
    assert_eq!(broken["corrupt"], json!(["rec.onnx"]), "{broken}");

    // 还原成正确的字节 → 同一个端点必须恢复 ready,并重建会话(状态机是
    // `failed → Loading → Ready`,这条边是合法的)。
    std::fs::copy(&kept, dir.join("rec.onnx")).expect("restore the model");
    let response = server.post("/api/models/reverify", &[], b"");
    assert_eq!(response.status, 200, "{}", response.text());
    let body = response.json();
    assert_eq!(body["outcome"], "ready", "{body}");
    assert_eq!(body["engine"]["state"], "ready", "{body}");
    assert!(body["load_ms"].as_u64().is_some(), "{body}");
    assert_eq!(body["content_changed"], json!([]), "{body}");
    assert_eq!(body["missing"], json!([]), "{body}");
    assert_eq!(
        built.load(Ordering::SeqCst),
        2,
        "the endpoint must rebuild the engine, not just clear a cache"
    );
    assert_eq!(server.get("/api/status").json()["engine"]["state"], "ready");

    // 恢复正常之后普通 OCR 也要能用(不是"只把状态字段改回 ready")。
    let id = server.submit_ocr(b"image").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    assert_eq!(
        server.wait_terminal(&id, Duration::from_secs(20))["state"],
        "succeeded"
    );
}

/// A2:**缓存命中之后**调用本端点,摘要必须被**重新计算**(这就是"重新校验"的定义)。
///
/// 断言的是绝对数字:这次运行的**计划**里有 3 个文件(det/rec/dict)——公式路由没有启用
/// (没有 `--formula-detector`),因此 566 MB 的 `fx.onnx` **不在计划里**、一个字节都不读。
/// 每个文件的 `cause` 都不是 `cache_hit`(冷验证不查缓存),且它确实出现在 `files[]` 里。
///
/// **本轮的行为变化(有意的期望变更)**:旧实现无条件把 `formula_recognizer` 加进这份清单,
/// 于是这里断言的是 4——一个本轮根本不会加载的 566 MB 文件。现在数字是 3,并且额外断言
/// "`fx.onnx` 不在清单里",这正是修复的根因所在(见 `docs/06` 的本轮记录)。
///
/// 注:库的校验缓存与它的累计账都是**进程级**的(同一个进程看到的同一个文件只有一种
/// 结论),而 `cargo test` 并行跑用例,因此这里只断言"缓存命中确实发生了"
/// (`cold_this_call == 0` 且 `cache_hits` 增长),不去断言某个精确的增量。
#[test]
fn reverify_recomputes_digests_that_the_cache_would_have_answered() {
    // 进程级校验缓存:本用例会清缓存或断言精确的重算次数,必须与同类用例串行。
    let _serial = cache_serial();
    let dir = complete_model_dir("reverify-cold");
    let server = TestServer::start(TestOptions::new(dir, Scripted::fast()));

    // 预热缓存:第一次 `/api/models` 可能还要为**库存**里的公式模型算一次摘要(它不在
    // 本次运行的计划里,因此启动快照没有读它——这正是本轮修复的可见效果);从那以后
    // 每一次 `/api/models` 都必须全程命中,`cold_this_call == 0`。
    let first = server.get("/api/models").json();
    let hits_before = first["verification"]["cache_hits"]
        .as_u64()
        .expect("cache_hits");
    let second = server.get("/api/models").json();
    assert_eq!(
        second["verification"]["cold_this_call"], 0,
        "a second poll must not re-hash anything: {second}"
    );
    assert!(
        second["verification"]["cache_hits"]
            .as_u64()
            .expect("cache_hits")
            > hits_before,
        "the cache really answered the files this time: {second}"
    );
    // 计划口径(本轮修复的根因回归):公式不在计划里,公式模型因此不在清单里。
    assert_eq!(second["pipelines"]["formula"]["in_plan"], false, "{second}");
    assert_eq!(
        second["pipelines"]["formula"]["files"],
        json!([]),
        "{second}"
    );

    let response = server.post("/api/models/reverify", &[], b"");
    assert_eq!(response.status, 200, "{}", response.text());
    let body = response.json();
    assert_eq!(
        body["computed"].as_u64(),
        Some(3),
        "a cache hit must not survive the forced re-verification, and only this run's plan is \
         hashed: {body}"
    );
    assert_eq!(body["verification"]["digests_computed"], 3, "{body}");
    let files = body["files"].as_array().expect("files");
    assert_eq!(files.len(), 3, "{body}");
    let names: Vec<&str> = files
        .iter()
        .map(|file| file["name"].as_str().expect("name"))
        .collect();
    assert_eq!(names, vec!["det.onnx", "rec.onnx", "dict.txt"], "{body}");
    assert!(
        !names.contains(&"fx.onnx"),
        "the 566 MB formula recognizer is not part of this run's plan: {body}"
    );
    for file in files {
        assert_ne!(
            file["cause"], "cache_hit",
            "a forced verification never reports a cache hit: {body}"
        );
        assert_eq!(file["digest_computed_this_call"], true, "{body}");
    }
    // 请求体必须为空:这是无参数动作,任何 body 都是协议级错误。
    let with_body = server.post("/api/models/reverify", &[], b"{}");
    assert_eq!(with_body.status, 400, "{}", with_body.text());
}

/// A2:并发调用只有一个真的跑(**单飞**),另一个立刻 503 `busy`;并且整个序列
/// **不在 accept 线程上**。
///
/// 确定性地构造"两个调用重叠":靠 [`ServeContext::post_verify`] 把第一次调用精确地停在
/// "校验结论已经算完、引擎还没重建"的窗口里——请求体因此也还没有发完。此时从**另一个
/// 连接**发第二次请求,它必须立刻拿到 503(不排队);而 `busy` 的响应正是在 accept 线程上
/// 产生的,这就是"它没有被这个序列占住"的证据(旧实现在 accept 线程上跑的话,
/// 第二次请求连响应都拿不到,会一直等到第一次结束)。
#[test]
fn concurrent_reverifications_are_single_flight_and_never_run_on_the_accept_thread() {
    // 进程级校验缓存:本用例会清缓存或断言精确的重算次数,必须与同类用例串行。
    let _serial = cache_serial();
    let dir = complete_model_dir("reverify-busy");
    let (tx, rx) = std::sync::mpsc::sync_channel::<()>(0);
    let server = TestServer::start(TestOptions {
        post_verify: Some(Box::new(move || {
            let _ = tx.send(());
        })),
        ..TestOptions::new(dir, Scripted::fast())
    });

    // 第一次调用:完整的请求字节(**空 body**),一次写完。
    //
    // 连接保持打开、响应尚未写出,因为这一次序列被 [`ServeContext::post_verify`] 的钩子
    // 按在"校验已算完、引擎还没重建"的窗口里——"序列仍在进行"因此是确定的事实,
    // 而不是靠时序猜出来的。
    let mut stream = TcpStream::connect(server.addr).expect("connect");
    stream
        .set_read_timeout(Some(Duration::from_secs(60)))
        .expect("read timeout");
    let head = format!(
        "POST /api/models/reverify HTTP/1.1\r\nConnection: close\r\nHost: {}\r\n\
         X-RapidStructure-Token: {}\r\nOrigin: {}\r\nContent-Length: 0\r\n\r\n",
        server.host, server.token, server.origin
    );
    stream
        .write_all(head.as_bytes())
        .expect("write the request");
    stream.flush().expect("flush");

    // 服务端已经冷验证完(钩子被调用),但还没写响应。
    rx.recv_timeout(Duration::from_secs(30))
        .expect("the first call must reach the post-verification hook");

    // 第二个连接:单飞资格已被第一次调用持有 → 立刻 503 busy,而不是排队。
    let second = Instant::now();
    let response = server.post("/api/models/reverify", &[], b"");
    let elapsed = second.elapsed();
    assert_eq!(response.status, 503, "{}", response.text());
    assert_eq!(response.code(), "busy", "{}", response.text());
    assert!(
        elapsed < Duration::from_secs(5),
        "the second call must not queue behind the first: {elapsed:?}"
    );

    // 第一次调用随后照常完成:连接关闭,响应是一个 200 + 逐文件结论。
    let mut buffer = Vec::new();
    stream
        .read_to_end(&mut buffer)
        .expect("read the first response");
    let first = parse_response(&buffer);
    assert_eq!(first.status, 200, "{}", first.text());
    let body = first.json();
    assert_eq!(
        body["computed"].as_u64(),
        Some(3),
        "the formula model is not part of this run's plan: {}",
        first.text()
    );
    assert_eq!(body["outcome"], "ready", "{}", first.text());
}

// ---------------------- 本轮:一份运行计划(公式检测模型 + 逐管线报告 + 身份断言)

/// 需求 1(HTTP 层)+ 需求 3:损坏的公式**检测**模型在 A2 的 `files[]` 里、
/// **这一次真的重算了它的摘要**,并且响应把"文本就绪"与"公式损坏"分开说清楚。
///
/// 旧实现的根因:`required_files` 只收 detector/recognizer/dictionary + 可选的 classifier +
/// `formula_recognizer`,**把 `formula_detector` 漏在外面**,因此
/// `POST /api/models/reverify` 既不列它、也不为它算摘要(一个同体积同 mtime 的中段改动可以
/// 一直留在陈旧摘要上)。现在检测模型属于运行计划,判定与冷验证都覆盖它。
#[test]
fn reverify_cold_verifies_the_formula_detector_and_reports_it_per_pipeline() {
    // 进程级校验缓存:本用例会清缓存或断言精确的重算次数,必须与同类用例串行。
    let _serial = cache_serial();
    let fixture = detector_model_dir("plan-detector");
    let original = std::fs::read(&fixture.detector).expect("read the detector");
    // 存在但内容与集合声明的摘要不符("损坏"的检测模型)。
    std::fs::write(&fixture.detector, corrupt_bytes(original.len())).expect("corrupt the detector");
    let actual = sha256_file(&fixture.detector).expect("hash the corrupted detector");
    assert_ne!(actual, fixture.detector_sha);

    let server = TestServer::start(TestOptions::new(fixture.dir.clone(), Scripted::fast()));

    let response = server.post("/api/models/reverify", &[], b"");
    assert_eq!(response.status, 200, "{}", response.text());
    let body = response.json();

    // **整份计划**(两个管线)都被冷验证:3 个文本文件 + 公式识别 + 公式检测。
    assert_eq!(
        body["computed"].as_u64(),
        Some(5),
        "the formula detector must be cold-verified too: {body}"
    );
    let files = body["files"].as_array().expect("files");
    let names: Vec<&str> = files
        .iter()
        .map(|file| file["name"].as_str().expect("name"))
        .collect();
    assert_eq!(
        names,
        vec!["det.onnx", "rec.onnx", "dict.txt", "fx.onnx", "mfd.onnx"],
        "{body}"
    );
    let detector = files
        .iter()
        .find(|file| file["name"] == "mfd.onnx")
        .expect("the detector must be listed");
    assert_eq!(detector["role"], "formula_detector");
    assert_eq!(detector["pipeline"], "formula");
    assert_eq!(detector["state"], "corrupt", "{body}");
    assert_eq!(
        detector["declared_sha256"], fixture.detector_sha,
        "the set's declared digest must be reported"
    );
    assert_eq!(
        detector["sha256"], actual,
        "this call must have re-read the file and reported the digest it computed: {body}"
    );
    assert_eq!(detector["digest_computed_this_call"], true, "{body}");
    assert_eq!(detector["has_declared_digest"], true, "{body}");

    // **逐管线**:文本就绪(引擎重建成功),公式损坏——两件事分别说,而不是一句 ready。
    assert_eq!(body["outcome"], "ready", "{body}");
    assert_eq!(body["pipelines"]["text"]["outcome"], "ready", "{body}");
    assert_eq!(body["pipelines"]["text"]["complete"], true, "{body}");
    assert_eq!(body["pipelines"]["text"]["blocked"], json!([]), "{body}");
    assert_eq!(
        body["pipelines"]["text"]["files"],
        json!(["det.onnx", "rec.onnx", "dict.txt"])
    );
    assert_eq!(body["pipelines"]["formula"]["in_plan"], true, "{body}");
    assert_eq!(body["pipelines"]["formula"]["routing"], true, "{body}");
    assert_eq!(body["pipelines"]["formula"]["complete"], false, "{body}");
    assert_eq!(
        body["pipelines"]["formula"]["corrupt"],
        json!(["mfd.onnx"]),
        "{body}"
    );
    assert_eq!(
        body["pipelines"]["formula"]["files"],
        json!(["fx.onnx", "mfd.onnx"]),
        "{body}"
    );
    assert_eq!(
        body["pipelines"]["formula"]["detector"]["sha256"], fixture.detector_sha,
        "{body}"
    );
    assert_eq!(
        body["pipelines"]["formula"]["detector"]["state"], "corrupt",
        "{body}"
    );

    // 运行期准入保持**按管线**:公式队列在读 body 之前 409(公式作用域、点名检测模型),
    // 普通 OCR 完全不受影响。
    let refused = server.request(
        "POST",
        "/api/ocr?queue=formula",
        &[
            ("Host", server.host.as_str()),
            ("X-RapidStructure-Token", server.token.as_str()),
            ("Origin", server.origin.as_str()),
            ("Content-Type", "application/octet-stream"),
            ("Content-Length", "1048576"),
        ],
        None,
    );
    assert_eq!(refused.status, 409, "{}", refused.text());
    assert_eq!(refused.code(), "models_corrupt");
    assert_eq!(refused.json()["detail"]["scope"], "formula");
    assert_eq!(
        refused.json()["detail"]["corrupt"],
        json!(["mfd.onnx"]),
        "the detector is the only formula blocker and must be named"
    );
    let text = server.submit_ocr(b"text image");
    assert_eq!(text.status, 202, "{}", text.text());
    let text_id = text.json()["job_id"].as_str().expect("id").to_string();
    assert_eq!(
        server.wait_terminal(&text_id, Duration::from_secs(20))["state"],
        "succeeded"
    );
}

/// 需求 3:文本健康、公式识别模型损坏 → A2 的响应必须**同时**说"文本 ready"与
/// "公式 corrupt",而不是一个笼统的 `ready`/`failed`。
///
/// 这也是仲裁后的启动期语义在运行期的对照:`--reverify-models` 会在这种目录上拒绝启动
/// (公式属于这次运行的整份计划),而运行期准入**只**让公式队列 409。
#[test]
fn reverify_reports_text_ready_and_formula_corrupt_explicitly() {
    // 进程级校验缓存:本用例会清缓存或断言精确的重算次数,必须与同类用例串行。
    let _serial = cache_serial();
    let fixture = detector_model_dir("plan-text-ready-formula-corrupt");
    // 只损坏公式**识别**模型(声明哈希不匹配);文本三个文件与检测模型都是好的。
    std::fs::write(fixture.dir.join("fx.onnx"), b"corrupted formula recognizer")
        .expect("corrupt the formula recognizer");
    let built = Arc::new(AtomicUsize::new(0));
    let server = TestServer::start(TestOptions {
        engine_factory: counting_engine_factory(Arc::clone(&built)),
        ..TestOptions::new(fixture.dir.clone(), Scripted::fast())
    });
    assert_eq!(
        server.get("/api/status").json()["engine"]["state"],
        "ready",
        "the text engine must load: the formula model is not part of it"
    );

    let body = server.post("/api/models/reverify", &[], b"").json();
    assert_eq!(
        body["outcome"], "ready",
        "the text engine outcome is ready (it really rebuilt): {body}"
    );
    assert_eq!(built.load(Ordering::SeqCst), 2, "startup + rebuild");
    assert_eq!(body["missing"], json!([]), "{body}");
    assert_eq!(
        body["corrupt"],
        json!([]),
        "the top-level lists stay text-scoped: {body}"
    );
    assert_eq!(body["pipelines"]["text"]["outcome"], "ready", "{body}");
    assert_eq!(body["pipelines"]["text"]["complete"], true, "{body}");
    assert_eq!(body["pipelines"]["text"]["blocked"], json!([]), "{body}");
    assert_eq!(body["pipelines"]["formula"]["in_plan"], true, "{body}");
    assert_eq!(
        body["pipelines"]["formula"]["corrupt"],
        json!(["fx.onnx"]),
        "'text ready, formula corrupt' must be explicit: {body}"
    );
    assert_eq!(body["pipelines"]["formula"]["complete"], false, "{body}");
    assert_eq!(body["pipelines"]["formula"]["missing"], json!([]), "{body}");

    // 公式队列 409(公式作用域),普通 OCR 照常成功——按管线的准入没有变。
    let refused = server.post(
        "/api/ocr?queue=formula",
        &[("Content-Type", "application/octet-stream")],
        b"formula image",
    );
    assert_eq!(refused.status, 409, "{}", refused.text());
    assert_eq!(refused.code(), "models_corrupt");
    assert_eq!(
        refused.json()["detail"]["corrupt"],
        json!(["fx.onnx"]),
        "{}",
        refused.text()
    );
    let text = server.submit_ocr(b"text image");
    assert_eq!(text.status, 202, "{}", text.text());
    let text_id = text.json()["job_id"].as_str().expect("id").to_string();
    assert_eq!(
        server.wait_terminal(&text_id, Duration::from_secs(20))["state"],
        "succeeded"
    );
}

/// 需求 4(HTTP 层):集合之外的 `--formula-detector`(**没有声明摘要**)在计划里、
/// 被 `/api/models` 与 A2 如实报告(`sha256: null`,摘要这一次真的算过),
/// 而"存在 + 可读 + 像 ONNX"这条文档化规则在运行期准入上同样生效。
#[test]
fn an_external_detector_is_reported_honestly_without_a_declared_digest() {
    // 进程级校验缓存:本用例会清缓存或断言精确的重算次数,必须与同类用例串行。
    let _serial = cache_serial();
    let dir = manifest_model_dir_text_only("plan-external-detector", &text_fixture_files(), None);
    // 模型目录**之外**的检测模型:任何集合都没有声明它。
    let outside = m2_root().join(format!("external-detector-{}.onnx", unique()));
    let name = outside
        .file_name()
        .expect("file name")
        .to_string_lossy()
        .into_owned();

    let server = TestServer::start(
        TestOptions::new(dir.clone(), Scripted::fast()).with_formula_routing(&outside),
    );
    // 夹具的字节由 `with_formula_routing` 写定,因此在服务起来之后再取它的真实摘要。
    let expected_sha = sha256_file(&outside).expect("hash the external detector");

    // `/api/models`:它在**运行计划**里(旧实现把它整个排除在外)。
    let models = server.get("/api/models").json();
    assert_eq!(models["formula"]["routing"], true, "{models}");
    assert_eq!(
        models["pipelines"]["formula"]["files"],
        json!(["fx.onnx", name.clone()]),
        "{models}"
    );
    assert_eq!(
        models["pipelines"]["formula"]["detector"]["sha256"],
        Value::Null,
        "no digest was declared, and the service must not invent one: {models}"
    );
    assert_eq!(
        models["pipelines"]["formula"]["detector"]["state"], "present",
        "exists + readable + plausible ONNX: {models}"
    );
    assert!(
        !models.to_string().contains(&dir.display().to_string()),
        "no absolute path may leak: {models}"
    );

    // A2:冷验证为它算了摘要(如实报告),但声明值是 `null`。
    let body = server.post("/api/models/reverify", &[], b"").json();
    assert_eq!(body["computed"].as_u64(), Some(5), "{body}");
    let detector = body["files"]
        .as_array()
        .expect("files")
        .iter()
        .find(|file| file["name"] == name.as_str())
        .expect("the external detector must be in the plan");
    assert_eq!(detector["declared_sha256"], Value::Null, "{body}");
    assert_eq!(detector["has_declared_digest"], false, "{body}");
    assert_eq!(
        detector["sha256"], expected_sha,
        "the digest computed by this call must be reported: {body}"
    );
    assert_eq!(detector["digest_computed_this_call"], true, "{body}");
    assert_eq!(detector["state"], "present", "{body}");

    // 公式队列可用(可读且像 ONNX),普通 OCR 也照常。
    let accepted = server.post(
        "/api/ocr?queue=formula",
        &[("Content-Type", "application/octet-stream")],
        b"formula image",
    );
    assert_eq!(accepted.status, 202, "{}", accepted.text());

    // 文档化的存在/可读/像 ONNX 规则:内容不是 ONNX → 运行期就是 409(不必等重新校验)。
    std::fs::write(&outside, b"not a model at all").expect("corrupt the detector");
    let models = server.get("/api/models").json();
    assert_eq!(
        models["pipelines"]["formula"]["detector"]["state"], "corrupt",
        "{models}"
    );
    assert_eq!(
        models["pipelines"]["formula"]["corrupt"],
        json!([name.clone()]),
        "{models}"
    );
    let refused = server.request(
        "POST",
        "/api/ocr?queue=formula",
        &[
            ("Host", server.host.as_str()),
            ("X-RapidStructure-Token", server.token.as_str()),
            ("Origin", server.origin.as_str()),
            ("Content-Type", "application/octet-stream"),
            ("Content-Length", "1048576"),
        ],
        None,
    );
    assert_eq!(refused.status, 409, "{}", refused.text());
    assert_eq!(refused.code(), "models_corrupt");
    assert_eq!(refused.json()["detail"]["corrupt"], json!([name.clone()]));
    let text = server.submit_ocr(b"text image");
    assert_eq!(text.status, 202, "{}", text.text());

    std::fs::remove_file(&outside).ok();
}

/// 需求 5(身份断言):A1、A2、`/api/models`、准入与加载路径读的是**同一份运行计划**。
///
/// 断言方式:先用**同一个** `ModelPlan::resolve` 算出期望的计划(这是唯一构造函数),
/// 然后经四个入口把它读回来比对——任何一个入口另起一套清单都会让这条用例失败。
#[test]
fn every_entry_point_reads_the_same_run_plan() {
    // 进程级校验缓存:本用例会清缓存或断言精确的重算次数,必须与同类用例串行。
    let _serial = cache_serial();
    let fixture = detector_model_dir("plan-identity");
    let plan =
        ModelPlan::resolve(&fixture.dir, &test_engine_config(), None, None).expect("model plan");
    let expected: Vec<&str> = plan
        .plan_files()
        .iter()
        .map(|file| file.name.as_str())
        .collect();
    assert_eq!(
        expected,
        vec!["det.onnx", "rec.onnx", "dict.txt", "fx.onnx", "mfd.onnx"],
        "{expected:?}"
    );
    let text_expected: Vec<&str> = plan
        .plan_files_in(super::model_plan::Pipeline::Text)
        .iter()
        .map(|file| file.name.as_str())
        .collect();
    let formula_expected: Vec<&str> = plan
        .plan_files_in(super::model_plan::Pipeline::Formula)
        .iter()
        .map(|file| file.name.as_str())
        .collect();
    assert_eq!(text_expected, vec!["det.onnx", "rec.onnx", "dict.txt"]);
    assert_eq!(formula_expected, vec!["fx.onnx", "mfd.onnx"]);

    let server = TestServer::start(TestOptions::new(fixture.dir.clone(), Scripted::fast()));

    // 1) `/api/models` 的 `pipelines` 块(两个管线,按计划顺序)。
    let models = server.get("/api/models").json();
    assert_eq!(models["pipelines"]["text"]["files"], json!(text_expected));
    assert_eq!(
        models["pipelines"]["formula"]["files"],
        json!(formula_expected)
    );

    // 2) A2 的逐文件结论与计划**同序同集**,且 `computed` 等于计划长度。
    let body = server.post("/api/models/reverify", &[], b"").json();
    let verified: Vec<&str> = body["files"]
        .as_array()
        .expect("files")
        .iter()
        .map(|file| file["name"].as_str().expect("name"))
        .collect();
    assert_eq!(verified, expected, "A2 must verify exactly this run's plan");
    assert_eq!(
        body["computed"].as_u64(),
        Some(expected.len() as u64),
        "{body}"
    );
    assert_eq!(
        body["pipelines"]["text"]["files"],
        json!(text_expected),
        "the per-pipeline report is the same plan"
    );
    assert_eq!(
        body["pipelines"]["formula"]["files"],
        json!(formula_expected)
    );

    // 3) 加载路径(运行期):`FormulaPolicy` 的两个路径与两个声明摘要都来自计划。
    let policy = server
        .shared()
        .formula_policy()
        .expect("formula is planned");
    assert_eq!(
        policy.model_path.as_deref(),
        Some(
            plan.plan_file(rapid_structure_rs::ModelRole::FormulaRecognizer)
                .expect("planned")
                .path
                .as_path()
        )
    );
    assert_eq!(
        policy.expected_model_sha256,
        plan.plan_file(rapid_structure_rs::ModelRole::FormulaRecognizer)
            .expect("planned")
            .declared_sha256
    );
    assert_eq!(
        policy.detector_path.as_deref(),
        Some(
            plan.plan_file(rapid_structure_rs::ModelRole::FormulaDetector)
                .expect("planned")
                .path
                .as_path()
        )
    );
    assert_eq!(
        policy.expected_detector_sha256,
        plan.plan_file(rapid_structure_rs::ModelRole::FormulaDetector)
            .expect("planned")
            .declared_sha256
    );

    // 4) 准入:把计划里的检测模型写坏 → 公式队列 409 点名**同一个文件**,文本队列照常;
    //    恢复 → 公式队列重新可用(判据与上面报告的是同一份状态)。
    let original = std::fs::read(&fixture.detector).expect("read the detector");
    std::fs::write(&fixture.detector, b"corrupted detector bytes").expect("corrupt");
    let refused = server.post(
        "/api/ocr?queue=formula",
        &[("Content-Type", "application/octet-stream")],
        b"formula image",
    );
    assert_eq!(refused.status, 409, "{}", refused.text());
    assert_eq!(
        refused.json()["detail"]["corrupt"],
        json!(["mfd.onnx"]),
        "admission names the same planned file the report does"
    );
    assert_eq!(server.submit_ocr(b"text image").status, 202);
    std::fs::write(&fixture.detector, &original).expect("restore");
    let accepted = server.post(
        "/api/ocr?queue=formula",
        &[("Content-Type", "application/octet-stream")],
        b"formula image",
    );
    assert_eq!(accepted.status, 202, "{}", accepted.text());
}

// ---------------------------------------------------------------- M4:评估
/// `POST /api/evaluate`:清单里每个用例跑一次真实识别路径,返回**库的**汇总
/// (`EvaluationSummary` + CLI 附加的运行时字段)。
///
/// 指标由库的 `evaluate_case` 计算,因此期望值在这里独立算一遍
/// (`cer=0` 的用例 + 一个不匹配的用例),而不是断言"有个数字"。
#[test]
fn the_evaluate_endpoint_returns_the_library_summary() {
    let dir = complete_model_dir("m4-evaluate");
    // 脚本化后端为每个区域产出 `region-<i>`,三个区域换行拼接 → 这就是"预测文本"。
    let scripted = Scripted::fast();
    let server = TestServer::start(TestOptions::new(dir.clone(), scripted));

    let manifest = eval_manifest(
        &dir,
        "eval-ok",
        &[
            ("01.png", "region-0\nregion-1\nregion-2"),
            ("02.png", "totally different"),
        ],
    );
    let response = server.post(
        "/api/evaluate",
        &[("Content-Type", "application/json")],
        format!("{{\"manifest\":{:?}}}", manifest.display().to_string()).as_bytes(),
    );
    assert_eq!(response.status, 200, "{}", response.text());
    let report = response.json();

    let expected_second = cer("totally different", "region-0\nregion-1\nregion-2");
    let expected_mean = (0.0_f32 + expected_second) / 2.0;
    assert_eq!(report["cases"].as_array().expect("cases").len(), 2);
    assert_eq!(report["cases"][0]["image"], "01.png");
    assert_eq!(report["cases"][0]["cer"], 0.0);
    assert_eq!(report["cases"][0]["exact_text"], true);
    assert_eq!(report["cases"][1]["image"], "02.png");
    assert!(
        (report["cases"][1]["cer"].as_f64().expect("cer") - f64::from(expected_second)).abs()
            < 1e-6,
        "{report}"
    );
    assert!(
        (report["mean_cer"].as_f64().expect("mean_cer") - f64::from(expected_mean)).abs() < 1e-6
    );
    assert_eq!(report["exact_match_rate"], 0.5);
    // 与 `rapidstruct evaluate` 的报告字段逐字段相同(同一份实现)。
    assert_eq!(report["iou_threshold"], 0.5);
    assert_eq!(report["manifest_file"], "manifest.json");
    assert!(report["peak_working_set_bytes"].as_u64().unwrap_or(0) > 0);
    assert!(report["memory_source"].is_string());
    assert!(report["ort_runtime"].is_object());
    assert!(report["ort_runtime_version"].is_string());
    assert!(
        !report.to_string().contains(&dir.display().to_string()),
        "no absolute path in the report: {report}"
    );
}

/// 评估的拒绝路径全部是**可定位**的 400,而不是笼统的 `bad_request`。
#[test]
fn an_invalid_evaluation_request_is_a_locating_400() {
    let dir = complete_model_dir("m4-evaluate-refused");
    let server = TestServer::start(TestOptions::new(dir.clone(), Scripted::fast()));

    let no_body = server.post(
        "/api/evaluate",
        &[("Content-Type", "application/json")],
        b"{}",
    );
    assert_eq!(no_body.status, 400, "{}", no_body.text());

    let extra_key = server.post(
        "/api/evaluate",
        &[("Content-Type", "application/json")],
        br#"{"manifest":"a.json","iou_threshold":0.9}"#,
    );
    assert_eq!(extra_key.status, 400);

    let missing = dir.join("no-such-manifest.json");
    let response = server.post(
        "/api/evaluate",
        &[("Content-Type", "application/json")],
        format!("{{\"manifest\":{:?}}}", missing.display().to_string()).as_bytes(),
    );
    assert_eq!(response.status, 400, "{}", response.text());
    assert_eq!(response.code(), "bad_request");
    let reason = response.json()["detail"]["reason"]
        .as_str()
        .expect("reason")
        .to_string();
    assert!(reason.contains("no-such-manifest.json"), "{reason}");

    // 超过 `--max-eval-cases` 的清单:同样 400,理由点名那个开关。
    let manifest = eval_manifest(
        &dir,
        "eval-too-many",
        &[("a.png", "x"), ("b.png", "x"), ("c.png", "x")],
    );
    let server = TestServer::start(TestOptions::new(dir.clone(), Scripted::fast()).with_limits(
        RawServeLimits {
            max_eval_cases: 2,
            ..RawServeLimits::default()
        },
    ));
    let response = server.post(
        "/api/evaluate",
        &[("Content-Type", "application/json")],
        format!("{{\"manifest\":{:?}}}", manifest.display().to_string()).as_bytes(),
    );
    assert_eq!(response.status, 400, "{}", response.text());
    let reason = response.json()["detail"]["reason"]
        .as_str()
        .expect("reason")
        .to_string();
    assert!(reason.contains("--max-eval-cases"), "{reason}");
}

/// 评审 P2-3:没有 `--eval-root` 时 `/api/evaluate` **整体拒绝**,
/// 而且理由点名要加哪个开关(可定位,而不是一句"评估不可用")。
#[test]
fn evaluation_is_refused_without_an_explicit_eval_root() {
    let dir = complete_model_dir("m4-evaluate-no-root");
    let server =
        TestServer::start(TestOptions::new(dir.clone(), Scripted::fast()).without_eval_root());
    // 清单本身是合法的、就在模型目录里:拒绝必须来自"没有沙箱",不是输入问题。
    let manifest = eval_manifest(&dir, "eval-no-root", &[("01.png", "x")]);
    let response = server.post(
        "/api/evaluate",
        &[("Content-Type", "application/json")],
        format!("{{\"manifest\":{:?}}}", manifest.display().to_string()).as_bytes(),
    );
    assert_eq!(response.status, 400, "{}", response.text());
    assert_eq!(response.code(), "bad_request");
    let reason = response.json()["detail"]["reason"]
        .as_str()
        .expect("reason")
        .to_string();
    assert!(reason.contains("--eval-root"), "{reason}");
    assert!(reason.contains("disabled"), "{reason}");
}

/// 评审 P2-3:清单**自己**在沙箱外 → 拒绝,并点名那个路径。
#[test]
fn an_evaluation_manifest_outside_the_eval_root_is_refused() {
    let dir = complete_model_dir("m4-evaluate-escape");
    let server = TestServer::start(TestOptions::new(dir.clone(), Scripted::fast()));

    // 清单写在沙箱之外(`m2_root()` 与模型目录是两棵不同的树)。
    let outside = m2_root().join(format!("outside-manifest-{}", unique()));
    std::fs::create_dir_all(&outside).expect("create the outside dir");
    let manifest = outside.join("manifest.json");
    std::fs::write(&manifest, br#"[{"image":"01.png","text":"x","boxes":[]}]"#).expect("write");
    std::fs::write(outside.join("01.png"), b"image bytes").expect("write the image");

    let response = server.post(
        "/api/evaluate",
        &[("Content-Type", "application/json")],
        format!("{{\"manifest\":{:?}}}", manifest.display().to_string()).as_bytes(),
    );
    assert_eq!(response.status, 400, "{}", response.text());
    let reason = response.json()["detail"]["reason"]
        .as_str()
        .expect("reason")
        .to_string();
    assert!(reason.contains("--eval-root sandbox"), "{reason}");
    assert!(
        reason.contains("manifest"),
        "the offending path must be named: {reason}"
    );
    std::fs::remove_dir_all(&outside).ok();
}

/// 评审 P2-3:清单在沙箱内,但它引用的**图片**越界(绝对路径、`..`、符号链接)
/// → 拒绝,并点名那个图片路径。三条路径都必须被抓住,而不是只看清单。
#[test]
fn an_evaluation_image_outside_the_eval_root_is_refused() {
    let dir = complete_model_dir("m4-evaluate-image-escape");
    let server = TestServer::start(TestOptions::new(dir.clone(), Scripted::fast()));

    // 沙箱之外的**真实存在**的一张图片:越界必须由"规范化后的包含关系"判定,
    // 而不是"路径不存在"这种偶然原因。
    let outside_dir = test_root().join(format!("outside-image-{}", unique()));
    std::fs::create_dir_all(&outside_dir).expect("create the outside dir");
    let outside_image = outside_dir.join("01.png");
    std::fs::write(&outside_image, b"image bytes outside the sandbox").expect("write the image");
    let outside_name = outside_dir
        .file_name()
        .expect("a directory name")
        .to_string_lossy()
        .into_owned();

    let sandbox_dir = dir.join(format!("escape-images-{}", unique()));
    std::fs::create_dir_all(&sandbox_dir).expect("create the sandbox subdir");

    // 1) 绝对路径越界。
    let absolute = sandbox_dir.join("absolute.json");
    std::fs::write(
        &absolute,
        format!(
            "[{{\"image\":{:?},\"text\":\"x\",\"boxes\":[]}}]",
            outside_image.display().to_string()
        ),
    )
    .expect("write the absolute manifest");
    let response = server.post(
        "/api/evaluate",
        &[("Content-Type", "application/json")],
        format!("{{\"manifest\":{:?}}}", absolute.display().to_string()).as_bytes(),
    );
    assert_eq!(response.status, 400, "{}", response.text());
    let reason = response.json()["detail"]["reason"]
        .as_str()
        .expect("reason")
        .to_string();
    assert!(
        reason.contains("outside the --eval-root sandbox"),
        "an escaping absolute path must be named as an escape, not as a missing file: {reason}"
    );
    assert!(reason.contains("01.png"), "{reason}");

    // 2) `..` 相对路径越界:沙箱根是 `<test_root>/complete-…`,清单在它下面的子目录里,
    //    因此 `../../<outside>/01.png` 是一条**真实存在**却在沙箱外的路径。
    let relative = sandbox_dir.join("relative.json");
    std::fs::write(
        &relative,
        format!(
            "[{{\"image\":{:?},\"text\":\"x\",\"boxes\":[]}}]",
            format!("../../{outside_name}/01.png")
        ),
    )
    .expect("write the relative manifest");
    let response = server.post(
        "/api/evaluate",
        &[("Content-Type", "application/json")],
        format!("{{\"manifest\":{:?}}}", relative.display().to_string()).as_bytes(),
    );
    assert_eq!(response.status, 400, "{}", response.text());
    let reason = response.json()["detail"]["reason"]
        .as_str()
        .expect("reason")
        .to_string();
    assert!(
        reason.contains("outside the --eval-root sandbox"),
        "a `..` escape must be refused as an escape: {reason}"
    );

    // 3) 符号链接逃逸:规范化会解析它,因此指向沙箱外的链接同样越界。
    //    Windows 上创建符号链接需要权限/开发者模式:环境不允许时如实说明这一条没有
    //    在本机跑,而绝对路径与 `..` 两条已经覆盖同一条"规范化后必须落在根内"的规则。
    let link = sandbox_dir.join("link.png");
    match std::os::windows::fs::symlink_file(&outside_image, &link) {
        Ok(()) => {
            let linked = sandbox_dir.join("symlink.json");
            std::fs::write(&linked, br#"[{"image":"link.png","text":"x","boxes":[]}]"#)
                .expect("write the symlink manifest");
            // 链接的**字面路径**在沙箱内,规范化后却指向沙箱外——这正是"只做字符串
            // 前缀判断"会漏掉的情形。
            let response = server.post(
                "/api/evaluate",
                &[("Content-Type", "application/json")],
                format!("{{\"manifest\":{:?}}}", linked.display().to_string()).as_bytes(),
            );
            assert_eq!(response.status, 400, "{}", response.text());
            assert!(
                response.json()["detail"]["reason"]
                    .as_str()
                    .unwrap_or_default()
                    .contains("outside the --eval-root sandbox"),
                "a symlink escape must be refused: {}",
                response.text()
            );
        }
        Err(error) => eprintln!(
            "serve tests: cannot create a symlink to prove the symlink-escape case ({error}); \
             the absolute and `..` cases exercise the same canonical-containment rule"
        ),
    }

    std::fs::remove_dir_all(&outside_dir).ok();
}

/// 模型缺失时评估与 OCR 一样是 409(同一条准入),而不是在建会话时崩掉。
#[test]
fn evaluation_needs_the_same_model_admission_as_ocr() {
    let dir = empty_model_dir("m4-evaluate-models");
    let server = TestServer::start(TestOptions::new(dir.clone(), Scripted::fast()));
    // 清单本身必须能读出来:否则先得到的是"清单读不出来"的 400(那是输入问题),
    // 而不是模型准入的 409。两件事各自可定位,顺序在 `evaluate::run` 里写死。
    let manifest = eval_manifest(&dir, "admission", &[("01.png", "x")]);
    let response = server.post(
        "/api/evaluate",
        &[("Content-Type", "application/json")],
        format!("{{\"manifest\":{:?}}}", manifest.display().to_string()).as_bytes(),
    );
    assert_eq!(response.status, 409, "{}", response.text());
    assert_eq!(response.code(), "models_missing");
    assert_eq!(
        response.json()["detail"]["missing"],
        server.get("/api/models").json()["missing"]
    );
}

/// 同时只允许一个评估:第二个请求得到 503 `busy`(不排队),第一个照常完成。
#[test]
fn a_second_evaluation_is_refused_while_one_is_running() {
    let dir = complete_model_dir("m4-evaluate-busy");
    let gate = Gate::new();
    let server = TestServer::start(TestOptions::new(
        dir.clone(),
        Scripted::fast().with_gate(Arc::clone(&gate)),
    ));
    let manifest = eval_manifest(
        &dir,
        "eval-busy",
        &[("01.png", "region-0\nregion-1\nregion-2")],
    );
    let body = format!("{{\"manifest\":{:?}}}", manifest.display().to_string()).into_bytes();

    let addr = server.addr;
    let host = server.host.clone();
    let origin = server.origin.clone();
    let token = server.token.clone();
    let first_body = body.clone();
    let first = std::thread::spawn(move || {
        raw_request(
            addr,
            "POST",
            "/api/evaluate",
            &[
                ("Host", host.as_str()),
                ("X-RapidStructure-Token", token.as_str()),
                ("Origin", origin.as_str()),
                ("Content-Type", "application/json"),
            ],
            Some(&first_body),
        )
    });
    // 评估线程已经进到第一张图(闸门在推理之前)。
    gate.arrive();
    let second = server.post(
        "/api/evaluate",
        &[("Content-Type", "application/json")],
        &body,
    );
    assert_eq!(second.status, 503, "{}", second.text());
    assert_eq!(second.code(), "busy");
    gate.release();
    let first = first.join().expect("the evaluation thread must finish");
    assert_eq!(first.status, 200, "{}", first.text());
    // 资格已释放:第三次请求可以正常开始(这里用一个不存在的清单证明它走到了解析阶段,
    // 而不是又被 503 挡住)。
    let third = server.post(
        "/api/evaluate",
        &[("Content-Type", "application/json")],
        br#"{"manifest":"definitely-not-here.json"}"#,
    );
    assert_eq!(third.status, 400, "{}", third.text());
}

/// 评估的逐例文本 → 期望 CER(与库同一个公式:字符级编辑距离 / 参考长度)。
fn cer(reference: &str, hypothesis: &str) -> f32 {
    rapid_structure_rs::evaluation::ocr::character_error_rate(reference, hypothesis)
}

/// 写一份 `rapidstruct evaluate --manifest` 格式的清单 + 对应的小图片文件。
///
/// 图片内容不重要(脚本化后端不解码),但**文件必须存在**:端点读不到文件时是 400。
fn eval_manifest(dir: &Path, label: &str, cases: &[(&str, &str)]) -> PathBuf {
    let root = dir.join(format!("{label}-{}", unique()));
    std::fs::create_dir_all(&root).expect("create the manifest dir");
    let mut manifest = String::from("[");
    for (index, (image, text)) in cases.iter().enumerate() {
        std::fs::write(root.join(image), format!("image bytes for {image}")).expect("write image");
        if index > 0 {
            manifest.push(',');
        }
        manifest.push_str(&format!(
            "{{\"image\":{image:?},\"text\":{text:?},\"boxes\":[]}}"
        ));
    }
    manifest.push(']');
    let path = root.join("manifest.json");
    std::fs::write(&path, manifest).expect("write the manifest");
    path
}

#[test]
fn the_documented_route_set_is_the_only_one_that_exists() {
    // 内联页面必须真的在仓库里(`include_str!` 的编译期保证之外,再加一条运行期断言,
    // 让"页面被误删"在测试里就可见,而不是等到打包时才发现)。
    assert!(
        PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("src/bin/web/index.html")
            .is_file(),
        "the inlined page must exist"
    );
}

// ---------------------------------------------------------------- M2 的辅助

/// 目录里的临时文件(`.part-*`):任何失败/取消路径都不允许留下它。
fn part_files(dir: &Path) -> Vec<String> {
    let mut names: Vec<String> = std::fs::read_dir(dir)
        .expect("the model dir must be readable")
        .map(|entry| {
            entry
                .expect("a readable entry")
                .file_name()
                .to_string_lossy()
                .into_owned()
        })
        .filter(|name| name.contains(".part"))
        .collect();
    names.sort();
    names
}

/// 计数的引擎工厂:断言"到底建立了几次会话"。
fn counting_engine_factory(counter: Arc<AtomicUsize>) -> EngineFactory {
    Arc::new(move |_config: &EngineConfig| {
        counter.fetch_add(1, Ordering::SeqCst);
        Ok(Box::new(ScriptedBackend {
            state: Scripted::fast(),
        }))
    })
}

/// 建立会话时阻塞的引擎工厂:确定性地观察 `loading` 状态。
fn gated_engine_factory(gate: Arc<Gate>, counter: Arc<AtomicUsize>) -> EngineFactory {
    Arc::new(move |_config: &EngineConfig| {
        counter.fetch_add(1, Ordering::SeqCst);
        gate.wait();
        Ok(Box::new(ScriptedBackend {
            state: Scripted::fast(),
        }))
    })
}

// ------------------------------------------------------- M3:引擎会话脚本(provider 切换)

/// "第几次建立会话"的脚本:在哪一次阻塞、哪几次失败、每次的 `selected_ep` 标签。
///
/// M3 的 provider 切换必须在**同一个进程里**观察到三次建会话(启动、切换、回滚),
/// 而这三次调用只有次数上的区别,因此用序号来驱动它是最直接的做法。
#[derive(Clone)]
struct SessionPlan {
    calls: Arc<AtomicUsize>,
    /// 第 N 次(1 基)调用在返回前阻塞在闸门上(观察 `rebuilding`)。
    gate_at: Option<usize>,
    /// 第 N 次调用返回错误(模拟"新 provider 建不起来")。
    fail_at: Vec<usize>,
    /// 建立出来的后端每次识别要花多久("排空"要有一个真在跑的任务)。
    delay: Duration,
}

impl SessionPlan {
    fn new() -> Self {
        Self {
            calls: Arc::new(AtomicUsize::new(0)),
            gate_at: None,
            fail_at: Vec::new(),
            delay: Duration::ZERO,
        }
    }

    fn calls(&self) -> usize {
        self.calls.load(Ordering::SeqCst)
    }

    fn factory(&self, gate: Option<Arc<Gate>>) -> EngineFactory {
        let plan = self.clone();
        Arc::new(
            move |_config: &EngineConfig| -> Result<Box<dyn OcrBackend>, RapidOcrError> {
                let index = plan.calls.fetch_add(1, Ordering::SeqCst) + 1;
                if plan.gate_at == Some(index)
                    && let Some(gate) = &gate
                {
                    gate.wait();
                }
                if plan.fail_at.contains(&index) {
                    return Err(RapidOcrError::UnsupportedProvider(format!(
                        "scripted session {index} cannot be created"
                    )));
                }
                Ok(Box::new(ScriptedBackend {
                    state: Scripted {
                        // 标签编码"第几个会话":`/api/status` 的 `selected_ep` 因此能证明
                        // 换上的是**新**引擎,而不是留着旧的那一个。
                        ep: format!("scripted-{index}"),
                        delay: plan.delay,
                        ..Scripted::fast()
                    },
                }))
            },
        )
    }
}

/// 闸门的 RAII 放行器:**任何**提前失败(panic 展开)都会放行被闸住的会话创建线程。
///
/// 没有它的话,一个断言失败会把那个线程永远留在闸门后面,而它持有 `engine_load`,
/// 于是 `ServeRuntime::stop()` 的 join 也会跟着挂住——测试失败的方式会从"一条红"
/// 变成"整个测试进程挂死"。
struct ReleaseOnDrop {
    gate: Arc<Gate>,
    released: AtomicBool,
}

impl ReleaseOnDrop {
    fn new(gate: Arc<Gate>) -> Self {
        Self {
            gate,
            released: AtomicBool::new(false),
        }
    }

    fn release(&self) {
        if !self.released.swap(true, Ordering::SeqCst) {
            self.gate.release();
        }
    }
}

impl Drop for ReleaseOnDrop {
    fn drop(&mut self) {
        self.release();
    }
}

// ---------------------------------------------------------------- M2:下载(无网络)

/// 一个真实的下载任务从 202 走到 succeeded:进度逐文件推进、文件真的落盘、
/// `/api/models` 变为 complete(哈希是库的真实校验),而引擎**不**在后台创建(§7.6)。
#[test]
fn a_download_job_fetches_every_missing_file_and_makes_the_set_complete() {
    let dir = manifest_model_dir_text_only("download-ok", &["det.onnx"], None);
    let scripted = ScriptedDownload::default();
    let server = TestServer::start(TestOptions {
        allow_download: true,
        downloader: scripted.clone().factory(),
        ..TestOptions::new(dir.clone(), Scripted::fast())
    });

    let before = server.get("/api/models").json();
    assert_eq!(before["source"], "local_manifest");
    assert_eq!(before["complete"], false);
    assert_eq!(
        before["missing"],
        serde_json::json!(["rec.onnx", "dict.txt"])
    );

    let response = server.download("test-set");
    assert_eq!(response.status, 202, "{}", response.text());
    let accepted = response.json();
    assert_eq!(accepted["kind"], "model_download");
    assert_eq!(
        accepted["queue"], "download",
        "a download job is not in the text queue"
    );
    assert_eq!(accepted["state"], "queued");
    assert_eq!(accepted["download"]["files_total"], 2);
    assert_eq!(accepted["download"]["files_done"], 0);
    let id = accepted["job_id"].as_str().expect("job id").to_string();

    let view = server.wait_terminal(&id, Duration::from_secs(20));
    assert_eq!(view["state"], "succeeded", "{view}");
    assert_eq!(view["failure"], serde_json::Value::Null);
    assert_eq!(view["queue"], "download");
    assert_eq!(view["download"]["files_done"], 2);
    assert_eq!(view["download"]["files_total"], 2);
    assert_eq!(view["download"]["current_file"], serde_json::Value::Null);
    let expected_bytes: u64 = ["rec.onnx", "dict.txt"]
        .iter()
        .map(|name| model_file_bytes(name).len() as u64)
        .sum();
    assert_eq!(view["download"]["bytes_done"], expected_bytes);
    assert_eq!(view["download"]["bytes_total"], expected_bytes);

    assert_eq!(
        scripted.written(),
        vec!["rec.onnx".to_string(), "dict.txt".to_string()]
    );
    let after = server.get("/api/models").json();
    assert_eq!(after["complete"], true, "{after}");
    assert_eq!(after["missing"], serde_json::json!([]));
    assert_eq!(after["sets"][0]["complete"], true);
    assert!(part_files(&dir).is_empty());

    // §7.6:下载完成**不**自动创建引擎(避免后台突然占用数百 MB)。
    assert_eq!(
        server.get("/api/status").json()["engine"]["state"],
        "blocked_models_missing"
    );
}

/// 哈希失败:任务 failed,错误体带机器可读分类(客户端不必做字符串匹配),目录里不留文件。
#[test]
fn a_hash_failure_fails_the_download_job_with_a_structured_error() {
    let dir = manifest_model_dir("download-hash", &["det.onnx"], None);
    let server = TestServer::start(TestOptions {
        allow_download: true,
        downloader: ScriptedDownload::with_plan(vec![Step::HashMismatch]).factory(),
        ..TestOptions::new(dir.clone(), Scripted::fast())
    });
    let id = server.download("test-set").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();

    let view = server.wait_terminal(&id, Duration::from_secs(20));
    assert_eq!(view["state"], "failed", "{view}");
    assert_eq!(view["failure"]["status"], 502);
    assert_eq!(view["failure"]["code"], "download_failed");
    assert_eq!(view["failure"]["detail"]["kind"], "hash_mismatch");
    assert!(
        view["error"]
            .as_str()
            .is_some_and(|text| text.contains("SHA-256")),
        "{view}"
    );
    assert!(!dir.join("rec.onnx").exists());
    assert!(!dir.join("dict.txt").exists());
    assert!(part_files(&dir).is_empty(), "no temp file may survive");
}

/// §6.2:声明体积超过 `--max-download-mb` → **同步** 413,两个数值都在 `detail` 里,
/// 且不建任务、不发请求。
#[test]
fn a_download_budget_refusal_is_a_413_with_both_numbers() {
    let declared = 10 * 1024 * 1024;
    let dir = manifest_model_dir_text_only("download-budget", &["det.onnx"], Some(declared));
    let scripted = ScriptedDownload::default();
    let server = TestServer::start(TestOptions {
        limits: RawServeLimits {
            max_download_mb: 1,
            ..RawServeLimits::default()
        },
        allow_download: true,
        downloader: scripted.clone().factory(),
        ..TestOptions::new(dir, Scripted::fast())
    });

    let response = server.download("test-set");
    assert_eq!(response.status, 413, "{}", response.text());
    assert_eq!(response.code(), "payload_too_large");
    let detail = &response.json()["detail"];
    assert_eq!(detail["limit_bytes"], 1024 * 1024);
    assert_eq!(detail["observed_bytes"], 2 * declared);
    assert!(
        scripted.hosts_per_call().is_empty(),
        "a refused task must not reach the downloader"
    );
}

/// §6.5:任务级磁盘核算不足 → **同步** 507,需求与可用两个数值都给出,且不建任务。
#[test]
fn a_disk_space_refusal_is_a_507_with_both_numbers() {
    let declared = 10 * 1024 * 1024;
    let dir = manifest_model_dir_text_only("download-disk", &["det.onnx"], Some(declared));
    let scripted = ScriptedDownload::default();
    let server = TestServer::start(TestOptions {
        allow_download: true,
        downloader: scripted.clone().factory(),
        free_space: Arc::new(|_dir: &Path| Ok(10)),
        ..TestOptions::new(dir, Scripted::fast())
    });

    let response = server.download("test-set");
    assert_eq!(response.status, 507, "{}", response.text());
    assert_eq!(response.code(), "insufficient_disk_space");
    let detail = &response.json()["detail"];
    assert_eq!(detail["required_bytes"], 2 * declared);
    assert_eq!(detail["available_bytes"], 10);
    assert!(scripted.hosts_per_call().is_empty());
}

/// 逐文件失败:已经校验通过的文件**保留**,任务给出失败分类(§6.3 的"不留半成品")。
#[test]
fn a_per_file_failure_keeps_the_files_that_already_verified() {
    let dir = manifest_model_dir("download-partial", &["det.onnx"], None);
    let server = TestServer::start(TestOptions {
        allow_download: true,
        downloader: ScriptedDownload::with_plan(vec![Step::Write, Step::Network]).factory(),
        ..TestOptions::new(dir.clone(), Scripted::fast())
    });
    let id = server.download("test-set").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();

    let view = server.wait_terminal(&id, Duration::from_secs(20));
    assert_eq!(view["state"], "failed", "{view}");
    assert_eq!(view["failure"]["code"], "download_failed");
    assert_eq!(view["failure"]["detail"]["kind"], "network");
    assert_eq!(view["download"]["files_done"], 1);
    assert_eq!(
        view["download"]["current_file"], "dict.txt",
        "the failing file stays named in the progress"
    );
    assert!(dir.join("rec.onnx").is_file(), "the verified file stays");
    assert!(!dir.join("dict.txt").exists());
    assert!(part_files(&dir).is_empty());
}

/// 运行中的进度可观测(**确定性**,用闸门而不是 sleep):逐文件 done/total、
/// 字节 done/total、当前文件名,全部来自 `GET /api/jobs/{id}`(§4.2)。
#[test]
fn the_download_progress_is_observable_while_the_job_runs() {
    let dir = manifest_model_dir_text_only("download-progress", &["det.onnx"], None);
    let gate = Gate::new();
    let server = TestServer::start(TestOptions {
        allow_download: true,
        downloader: ScriptedDownload::with_gate(Arc::clone(&gate)).factory(),
        ..TestOptions::new(dir, Scripted::fast())
    });
    let id = server.download("test-set").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    let rec_len = model_file_bytes("rec.onnx").len() as u64;
    let dict_len = model_file_bytes("dict.txt").len() as u64;

    // 第一个文件已经开始(闸门在 `file_started` 之后、写入之前)。
    gate.arrive();
    let view = server.get(&format!("/api/jobs/{id}")).json();
    assert_eq!(view["state"], "running", "{view}");
    assert_eq!(view["download"]["current_file"], "rec.onnx");
    assert_eq!(view["download"]["files_done"], 0);
    assert_eq!(view["download"]["files_total"], 2);
    assert_eq!(view["download"]["bytes_done"], 0);
    assert_eq!(view["download"]["bytes_total"], rec_len + dict_len);
    gate.release();

    // 第二个文件已经开始:第一个文件的字节已经计入。
    gate.arrive();
    let view = server.get(&format!("/api/jobs/{id}")).json();
    assert_eq!(view["download"]["current_file"], "dict.txt");
    assert_eq!(view["download"]["files_done"], 1);
    assert_eq!(view["download"]["bytes_done"], rec_len);
    gate.release();

    let view = server.wait_terminal(&id, Duration::from_secs(20));
    assert_eq!(view["state"], "succeeded", "{view}");
    assert_eq!(view["download"]["files_done"], 2);
    assert_eq!(view["download"]["bytes_done"], rec_len + dict_len);
    assert_eq!(view["download"]["current_file"], serde_json::Value::Null);
}

/// §6.6:运行中的下载取消在**文件边界**生效——当前文件下载完,后续文件不再开始,
/// 已校验文件保留,任务终态是 `cancelled`(不假装"已取消",也不假装"不能取消")。
#[test]
fn a_running_download_is_cancelled_at_a_file_boundary() {
    let dir = manifest_model_dir("download-cancel", &["det.onnx"], None);
    let gate = Gate::new();
    let server = TestServer::start(TestOptions {
        allow_download: true,
        downloader: ScriptedDownload::with_gate(Arc::clone(&gate)).factory(),
        ..TestOptions::new(dir.clone(), Scripted::fast())
    });
    let id = server.download("test-set").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();

    gate.arrive(); // `rec.onnx` 正在下载
    let cancelled = server.post(&format!("/api/jobs/{id}/cancel"), &[], b"");
    assert_eq!(cancelled.status, 200, "{}", cancelled.text());
    let view = cancelled.json();
    assert_eq!(
        view["state"], "running",
        "the current file is still being downloaded"
    );
    assert_eq!(view["cancel_requested"], true);
    gate.release(); // 当前文件完成 → 下一个文件在边界上被拒绝

    let view = server.wait_terminal(&id, Duration::from_secs(20));
    assert_eq!(view["state"], "cancelled", "{view}");
    assert_eq!(view["cancel_requested"], true);
    assert_eq!(
        view["download"]["files_done"], 1,
        "the current file was kept"
    );
    assert!(dir.join("rec.onnx").is_file(), "the verified file stays");
    assert!(
        !dir.join("dict.txt").exists(),
        "the next file is never started"
    );
    assert!(
        part_files(&dir).is_empty(),
        "no temp file survives a cancellation"
    );
}

/// 下载器报告"在文件边界取消"(库的 `DownloadError::Cancelled`):任务必须落在
/// `cancelled` 上,而不是永远停在 `running`(worker 会把取消请求补登记,见
/// `ServeShared::finish_download_cancelled`)。
#[test]
fn a_download_error_cancelled_lands_on_cancelled_not_running() {
    let dir = manifest_model_dir("download-cancelled-error", &["det.onnx"], None);
    let server = TestServer::start(TestOptions {
        allow_download: true,
        downloader: ScriptedDownload::with_plan(vec![Step::Cancelled]).factory(),
        ..TestOptions::new(dir.clone(), Scripted::fast())
    });
    let id = server.download("test-set").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();

    let view = server.wait_terminal(&id, Duration::from_secs(20));
    assert_eq!(view["state"], "cancelled", "{view}");
    assert_eq!(
        view["failure"],
        serde_json::Value::Null,
        "a cancellation is not a failure"
    );
    assert_eq!(view["cancel_requested"], true);
    assert_eq!(view["download"]["current_file"], "rec.onnx");
    assert!(!dir.join("rec.onnx").exists());
    assert!(part_files(&dir).is_empty());
}

/// 排队中的下载取消是**立即**的(§4.3):worker 不会开始它(`begin_download` 被拒绝)。
#[test]
fn cancelling_a_queued_download_is_immediate() {
    let dir = manifest_model_dir_text_only("download-queued", &["det.onnx"], None);
    let gate = Gate::new();
    let server = TestServer::start(TestOptions {
        allow_download: true,
        downloader: ScriptedDownload::with_gate(Arc::clone(&gate)).factory(),
        ..TestOptions::new(dir, Scripted::fast())
    });

    // 第一个任务占住唯一的下载 worker。
    let first = server.download("test-set").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    gate.arrive();
    // 第二个任务进入有界 channel(排队),随后立刻取消。
    let second = server.download("test-set").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    let cancelled = server.post(&format!("/api/jobs/{second}/cancel"), &[], b"");
    assert_eq!(cancelled.status, 200, "{}", cancelled.text());
    let view = cancelled.json();
    assert_eq!(
        view["state"], "cancelled",
        "a queued job cancels immediately"
    );
    assert_eq!(view["cancel_requested"], false);

    gate.release();
    gate.arrive();
    gate.release();
    let first_view = server.wait_terminal(&first, Duration::from_secs(20));
    assert_eq!(first_view["state"], "succeeded", "{first_view}");

    // 第二个任务从未开始:没有失败分类,也没有任何进度推进。
    let second_view = server.get(&format!("/api/jobs/{second}")).json();
    assert_eq!(second_view["state"], "cancelled");
    assert_eq!(second_view["failure"], serde_json::Value::Null);
    assert_eq!(second_view["download"]["files_done"], 0);
    assert_eq!(
        second_view["download"]["current_file"],
        serde_json::Value::Null
    );
}

/// §4.2:未知 `set_id` → 404(带请求的 id 与已知集合),空/畸形 id → 400;
/// **绝不**回落到 `sets[0]`。
#[test]
fn an_unknown_or_empty_set_id_is_refused_and_never_guessed() {
    let dir = manifest_model_dir("download-unknown", &["det.onnx"], None);
    let scripted = ScriptedDownload::default();
    let server = TestServer::start(TestOptions {
        allow_download: true,
        downloader: scripted.clone().factory(),
        ..TestOptions::new(dir, Scripted::fast())
    });

    let unknown = server.download("nope");
    assert_eq!(unknown.status, 404, "{}", unknown.text());
    assert_eq!(unknown.code(), "model_set_not_found");
    assert_eq!(unknown.json()["detail"]["set_id"], "nope");
    assert_eq!(unknown.json()["detail"]["known_sets"][0], "test-set");

    for bad in [
        &br#"{"set_id":""}"#[..],
        &br#"{}"#[..],
        &br#"{"set_id":null}"#[..],
        &br#"{"set_id":"test-set","url":"https://evil.example/x.onnx"}"#[..],
    ] {
        let response = server.post(
            "/api/models/download",
            &[("Content-Type", "application/json")],
            bad,
        );
        assert_eq!(response.status, 400, "{}", response.text());
    }
    assert!(
        scripted.hosts_per_call().is_empty(),
        "a refused request must not download anything"
    );
}

/// `--allow-download-host` 是**显式参数**:它出现在交给下载器的列表里,
/// 而不是"库常量被改掉了"(常量本身由 `model_store` 的单测逐项锁死)。
///
/// M2b 起编译期常量有两项(`www.modelscope.cn` + 权重 302 的目标 host
/// `cdn-lfs-cn-1.modelscope.cn`),顺序即 `ALLOWED_DOWNLOAD_HOSTS` 的顺序。
#[test]
fn the_download_host_opt_in_is_passed_as_an_explicit_parameter() {
    let dir = manifest_model_dir("download-hosts", &["det.onnx"], None);
    let plain = ScriptedDownload::default();
    let server = TestServer::start(TestOptions {
        allow_download: true,
        downloader: plain.clone().factory(),
        ..TestOptions::new(dir, Scripted::fast())
    });
    let id = server.download("test-set").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    assert_eq!(
        server.wait_terminal(&id, Duration::from_secs(20))["state"],
        "succeeded"
    );
    assert_eq!(
        plain.hosts_per_call(),
        vec![vec![
            "www.modelscope.cn".to_string(),
            "cdn-lfs-cn-1.modelscope.cn".to_string()
        ]]
    );
    // 同一个请求,加上 `--allow-download-host evil.example`:列表被**显式**扩展。
    let dir = manifest_model_dir("download-hosts-optin", &["det.onnx"], None);
    let extended = ScriptedDownload::default();
    let server = TestServer::start(TestOptions {
        allow_download: true,
        allow_download_hosts: vec!["evil.example".to_string()],
        downloader: extended.clone().factory(),
        ..TestOptions::new(dir, Scripted::fast())
    });
    let id = server.download("test-set").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    assert_eq!(
        server.wait_terminal(&id, Duration::from_secs(20))["state"],
        "succeeded"
    );
    assert_eq!(
        extended.hosts_per_call(),
        vec![vec![
            "www.modelscope.cn".to_string(),
            "cdn-lfs-cn-1.modelscope.cn".to_string(),
            "evil.example".to_string()
        ]]
    );
    // `/api/status` 如实给出生效的列表(启动日志里也有同样的几行 + 高风险警告)。
    let status = server.get("/api/status").json();
    assert_eq!(status["download_hosts"][0], "www.modelscope.cn");
    assert_eq!(status["download_hosts"][1], "cdn-lfs-cn-1.modelscope.cn");
    assert_eq!(status["download_hosts"][2], "evil.example");
}

/// 未开 `--allow-download` → 403;`--allow-download` 打开后是**真实**任务(M2 替换了处理体)。
#[test]
fn the_download_endpoint_still_refuses_when_downloads_are_disabled() {
    let dir = manifest_model_dir("download-disabled", &["det.onnx"], None);
    let scripted = ScriptedDownload::default();
    let server = TestServer::start(TestOptions {
        downloader: scripted.clone().factory(),
        ..TestOptions::new(dir, Scripted::fast())
    });
    let response = server.download("test-set");
    assert_eq!(response.status, 403, "{}", response.text());
    assert_eq!(response.code(), "downloads_disabled");
    assert!(scripted.hosts_per_call().is_empty());
}

// ---------------------------------------------------------------- M2:引擎(惰性创建与 reload)

/// §7.6:`POST /api/engine/reload` 是 `models_still_missing` 的生产者——模型仍缺失时
/// 响应体里如实给出 `blocked_models_missing` 与缺失清单,而不是一句模糊的失败。
#[test]
fn the_reload_endpoint_reports_blocked_models_with_the_missing_list() {
    let built = Arc::new(AtomicUsize::new(0));
    let server = TestServer::start(TestOptions {
        engine_factory: counting_engine_factory(Arc::clone(&built)),
        ..TestOptions::new(empty_model_dir("reload-blocked"), Scripted::fast())
    });
    assert_eq!(
        server.get("/api/status").json()["engine"]["state"],
        "blocked_models_missing"
    );

    let reloaded = server.post("/api/engine/reload", &[], b"");
    assert_eq!(reloaded.status, 200, "{}", reloaded.text());
    let body = reloaded.json();
    assert_eq!(body["outcome"], "blocked_models_missing");
    assert_eq!(body["engine"]["state"], "blocked_models_missing");
    let missing = body["missing"].as_array().expect("a missing list");
    assert_eq!(missing.len(), 3, "{body}");
    assert_eq!(
        body["missing"],
        server.get("/api/models").json()["missing"],
        "the same computation as /api/models"
    );
    assert_eq!(body["engine"]["missing"], body["missing"]);
    assert!(body["load_ms"].as_u64().is_some(), "{body}");
    assert_eq!(built.load(Ordering::SeqCst), 0, "no session can be created");
    assert_eq!(server.submit_ocr(b"image").status, 409);
}

/// §7.6:模型齐备时 reload 真的建立会话并给出耗时;显式 reload 会**重建**(M2 的入口,
/// provider 运行期切换(`Rebuilding`)仍属 M3)。
#[test]
fn the_reload_endpoint_creates_the_engine_and_reports_the_elapsed_time() {
    let dir = manifest_model_dir("reload-ready", &["det.onnx", "rec.onnx", "dict.txt"], None);
    let built = Arc::new(AtomicUsize::new(0));
    let server = TestServer::start(TestOptions {
        engine_factory: counting_engine_factory(Arc::clone(&built)),
        ..TestOptions::new(dir, Scripted::fast())
    });
    // 模型齐备 → 启动期预加载(§7.6 第 3 步)。
    assert_eq!(server.get("/api/status").json()["engine"]["state"], "ready");
    assert_eq!(built.load(Ordering::SeqCst), 1);

    let reloaded = server.post("/api/engine/reload", &[], b"");
    assert_eq!(reloaded.status, 200, "{}", reloaded.text());
    let body = reloaded.json();
    assert_eq!(body["outcome"], "ready");
    assert_eq!(body["engine"]["state"], "ready");
    assert_eq!(body["engine"]["selected_ep"], "cpu");
    assert!(body["load_ms"].as_u64().is_some(), "{body}");
    assert_eq!(
        built.load(Ordering::SeqCst),
        2,
        "an explicit reload rebuilds the session"
    );

    let id = server.submit_ocr(b"image").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    assert_eq!(
        server.wait_terminal(&id, Duration::from_secs(20))["state"],
        "succeeded"
    );
}

/// §7.6:模型齐备后**惰性**创建引擎——触发点是下一次 `POST /api/ocr`(或显式 reload),
/// 而不是下载完成的瞬间;`loading` 期间 `/api/status` 如实显示,完成后给出生耗时。
#[test]
fn the_engine_is_created_lazily_on_the_next_ocr_request_and_loading_is_visible() {
    let dir = manifest_model_dir("lazy-engine", &["det.onnx"], None);
    let gate = Gate::new();
    let built = Arc::new(AtomicUsize::new(0));
    let server = TestServer::start(TestOptions {
        engine_factory: gated_engine_factory(Arc::clone(&gate), Arc::clone(&built)),
        ..TestOptions::new(dir.clone(), Scripted::fast())
    });
    assert_eq!(
        server.get("/api/status").json()["engine"]["state"],
        "blocked_models_missing"
    );
    assert_eq!(built.load(Ordering::SeqCst), 0);

    // 缺的两个文件出现在磁盘上(等价于"下载完成")——此时**仍然没有**引擎。
    for name in ["rec.onnx", "dict.txt"] {
        std::fs::write(dir.join(name), model_file_bytes(name)).expect("write the model file");
    }
    assert_eq!(
        server.get("/api/status").json()["engine"]["state"],
        "blocked_models_missing",
        "a completed download must not create the engine in the background"
    );
    assert_eq!(
        server.get("/api/models").json()["complete"],
        true,
        "the files are complete on disk"
    );
    assert_eq!(built.load(Ordering::SeqCst), 0);

    // 下一次 `POST /api/ocr` 就是创建点(accept 线程只把状态推进 `Loading`)。
    let accepted = server.submit_ocr(b"image");
    assert_eq!(accepted.status, 202, "{}", accepted.text());
    let id = accepted.json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    gate.arrive(); // 会话正在建立
    let status = server.get("/api/status").json();
    assert_eq!(status["engine"]["state"], "loading", "{status}");
    assert_eq!(built.load(Ordering::SeqCst), 1);
    gate.release();

    let view = server.wait_terminal(&id, Duration::from_secs(20));
    assert_eq!(view["state"], "succeeded", "{view}");
    let status = server.get("/api/status").json();
    assert_eq!(status["engine"]["state"], "ready");
    assert!(
        status["engine_load_ms"].as_u64().is_some(),
        "the session creation time must be reported: {status}"
    );
}

/// 评审 P2-2:**无 body** 的 `POST /api/engine/reload` 也必须在独立线程上建立会话。
///
/// 旧实现在 accept 线程上直接调 `reload_engine(None)`:ONNX Runtime 建会话的那几百毫秒
/// 到几秒里,`/api/status` 与 `POST /api/ocr` 全都停摆。这里用闸门把建会话按在中间,
/// 断言两件事在**reload 还没完成时**就成立:`loading` 可见、新任务照常 202。
#[test]
fn a_bodyless_reload_keeps_the_accept_loop_live() {
    let dir = manifest_model_dir(
        "m2-bodyless-reload",
        &["det.onnx", "rec.onnx", "dict.txt"],
        None,
    );
    let gate = Gate::new();
    let plan = SessionPlan {
        // 第 2 次建会话(= reload)阻塞在闸门上。
        gate_at: Some(2),
        ..SessionPlan::new()
    };
    let server = TestServer::start(TestOptions {
        engine_factory: plan.factory(Some(Arc::clone(&gate))),
        ..TestOptions::new(dir, Scripted::fast())
    });
    assert_eq!(server.get("/api/status").json()["engine"]["state"], "ready");

    let addr = server.addr;
    let host = server.host.clone();
    let origin = server.origin.clone();
    let token = server.token.clone();
    let reload = std::thread::spawn(move || {
        raw_request(
            addr,
            "POST",
            "/api/engine/reload",
            &[
                ("Host", host.as_str()),
                ("X-RapidStructure-Token", token.as_str()),
                ("Origin", origin.as_str()),
                ("Content-Length", "0"),
            ],
            Some(b""),
        )
    });
    // 断言失败也一定放行,否则这个测试会从"一条红"变成"挂死整个测试进程"。
    let release = ReleaseOnDrop::new(Arc::clone(&gate));

    gate.arrive(); // 第二次建会话正在运行
    assert!(
        wait_until(Duration::from_secs(10), || {
            server.get("/api/status").json()["engine"]["state"] == "loading"
        }),
        "the bodyless reload must be observable through /api/status while it blocks"
    );
    // accept 线程仍然活着:提交一个新任务(`Loading` 期间入队,不是拒绝)。
    let queued = server.submit_ocr(b"during-bodyless-reload");
    assert_eq!(queued.status, 202, "{}", queued.text());
    assert_eq!(queued.json()["state"], "queued");

    release.release();
    drop(release);
    let response = reload.join().expect("the reload thread must finish");
    assert_eq!(response.status, 200, "{}", response.text());
    let body = response.json();
    assert_eq!(body["outcome"], "ready", "{body}");
    assert!(body["load_ms"].as_u64().is_some(), "{body}");
    assert_eq!(plan.calls(), 2, "an explicit reload rebuilds the session");

    let status = server.get("/api/status").json();
    assert_eq!(status["engine"]["state"], "ready", "{status}");
}

// ---------------------------------------------------------------- M3:标注图与导出

/// 一张真实的 PNG(`scripted_output` 的 `image.original_size` 是 100×50,两者必须一致:
/// 标注图是画在**被解码的原图**上的,尺寸对不上就说明这条链路有假)。
fn flat_source_png() -> Vec<u8> {
    let image = image::RgbImage::from_fn(100, 50, |x, y| {
        image::Rgb([(x % 256) as u8, (y % 256) as u8, 40])
    });
    let mut bytes = Vec::new();
    image
        .write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png)
        .expect("the fixture PNG encodes");
    bytes
}

/// 一张"压不动"的 PNG(伪随机像素):体积可控,用于字节预算测试。
fn noise_png(dimension: u32) -> Vec<u8> {
    let mut state = 0x1234_5678_9abc_def0_u64;
    let image = image::RgbImage::from_fn(dimension, dimension, |_, _| {
        state = state
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);
        image::Rgb([
            (state >> 33) as u8,
            (state >> 41) as u8,
            (state >> 49) as u8,
        ])
    });
    let mut bytes = Vec::new();
    image
        .write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png)
        .expect("the noise PNG encodes");
    bytes
}

/// 至少 `minimum` 字节的 PNG(选最小的那个够用的尺寸,因此不会超出保留预算太多)。
fn source_png_at_least(minimum: usize) -> Vec<u8> {
    for dimension in [360_u32, 420, 480, 520, 560] {
        let png = noise_png(dimension);
        if png.len() >= minimum {
            return png;
        }
    }
    panic!("cannot build a PNG of at least {minimum} bytes");
}

/// §4.2/§4.5:`/annotated.png` 是**真正**的 PNG、尺寸等于原图、且检测框真的画上去了。
#[test]
fn the_annotated_png_is_a_real_png_with_the_original_dimensions_and_drawn_boxes() {
    let server = TestServer::start(TestOptions::new(
        complete_model_dir("m3-annotated"),
        Scripted {
            // 一个区域:画布上只有第一个调色板颜色(纯红),断言因此是精确的。
            regions: 1,
            ..Scripted::fast()
        },
    ));
    let source = flat_source_png();
    let accepted = server.submit_ocr(&source).json();
    let id = accepted["job_id"].as_str().expect("job id").to_string();
    let view = server.wait_terminal(&id, Duration::from_secs(20));
    assert_eq!(view["state"], "succeeded", "{view}");
    assert_eq!(
        view["original_retained"], true,
        "the encoded original stays in the retention area after OCR (§4.5): {view}"
    );

    let result = server.get(&format!("/api/jobs/{id}/result")).json();
    let expected = (
        result["image"]["original_size"]["width"].as_u64(),
        result["image"]["original_size"]["height"].as_u64(),
    );
    assert_eq!(expected, (Some(100), Some(50)), "{result}");

    let response = server.get(&format!("/api/jobs/{id}/annotated.png"));
    assert_eq!(response.status, 200, "{}", response.text());
    assert_eq!(response.header("Content-Type"), Some("image/png"));
    // 三个安全头对**每个**响应都成立(§7.3)。
    assert_eq!(response.header("X-Content-Type-Options"), Some("nosniff"));
    assert_eq!(response.header("Cache-Control"), Some("no-store"));
    assert_eq!(&response.body[..8], b"\x89PNG\r\n\x1a\n", "PNG signature");
    let decoded = image::load_from_memory(&response.body).expect("the annotation is a real image");
    assert_eq!(
        (decoded.width() as u64, decoded.height() as u64),
        (expected.0.unwrap(), expected.1.unwrap()),
        "the canvas is the decoded original, not a guess"
    );
    // 第一个区域的框角 (1,1) 被画成了调色板的第 0 种颜色(纯红)——证明 `draw_output` 真的跑了。
    assert_eq!(
        decoded.to_rgb8().get_pixel(1, 1).0,
        [255, 0, 0],
        "the detection box must be drawn on the retained original"
    );
}

/// §4.2/§4.5:原图编码字节被保留预算释放后,`/annotated.png` 是 **410 `original_evicted`**,
/// 而**结果仍然可读**(这正是这个 `code` 与 `job_evicted` 的区别)。
///
/// 让一个任务自己的"原图 + 结果"超过 1 MiB 预算即可确定性触发:预算超限时先释放**最旧终态
/// 任务的原图**(此刻就是它自己),任务与结果都留下。
#[test]
fn the_annotated_png_is_410_original_evicted_once_the_budget_releases_the_original() {
    let mut raw = limits(4, 2);
    raw.max_retained_mb = 1;
    raw.max_result_mb = 8;
    let scripted = || Scripted {
        regions: 1,
        text_bytes: 128 * 1024,
        ..Scripted::fast()
    };

    // 先在一个**同样的**运行时上量出结果 JSON 的真实大小(同一份脚本化输出,确定性)。
    let probe = TestServer::start(TestOptions {
        limits: raw,
        ..TestOptions::new(complete_model_dir("m3-annotated-evicted-probe"), scripted())
    });
    let accepted = probe.submit_ocr(&flat_source_png()).json();
    let probe_id = accepted["job_id"].as_str().expect("job id").to_string();
    assert_eq!(
        probe.wait_terminal(&probe_id, Duration::from_secs(30))["state"],
        "succeeded"
    );
    let result_bytes = probe
        .get(&format!("/api/jobs/{probe_id}/result"))
        .body
        .len() as u64;
    assert!(
        result_bytes < 1 << 20,
        "the result store's own budget is 1 MiB, so the fixture result must fit: {result_bytes}"
    );

    // 原图必须"一个装得下、加上结果就装不下":条件不成立时下面会直接失败,
    // 而不是悄悄退化成"其实没触发预算"。
    let needed = (1 << 20) - result_bytes + 64 * 1024;
    let source = source_png_at_least(needed as usize);
    assert!(
        source.len() as u64 <= 1 << 20,
        "the original alone must fit the 1 MiB budget: {} bytes",
        source.len()
    );
    assert!(
        source.len() as u64 + result_bytes > 1 << 20,
        "the original plus the result must exceed it: {} + {result_bytes}",
        source.len()
    );

    let server = TestServer::start(TestOptions {
        limits: raw,
        ..TestOptions::new(complete_model_dir("m3-annotated-evicted"), scripted())
    });
    let accepted = server.submit_ocr(&source).json();
    let id = accepted["job_id"].as_str().expect("job id").to_string();
    let view = server.wait_terminal(&id, Duration::from_secs(30));
    assert_eq!(view["state"], "succeeded", "{view}");
    assert_eq!(
        view["original_retained"], false,
        "the byte budget released the original: {view}"
    );

    let response = server.get(&format!("/api/jobs/{id}/annotated.png"));
    assert_eq!(response.status, 410, "{}", response.text());
    assert_eq!(response.code(), "original_evicted");
    assert!(
        response
            .json()
            .get("detail")
            .is_some_and(serde_json::Value::is_null),
        "the body still carries the frozen three keys: {}",
        response.text()
    );

    // 任务与结果**都还在**(与 `job_evicted` 的区别就在这里)。
    assert_eq!(server.get(&format!("/api/jobs/{id}")).status, 200);
    let result = server.get(&format!("/api/jobs/{id}/result"));
    assert_eq!(result.status, 200, "{}", result.text());
    assert_eq!(result.body.len() as u64, result_bytes, "byte for byte");
    // 状态里也如实反映"保留区里还有几份原图"。
    let status = server.get("/api/status").json();
    assert_eq!(status["retention"]["retained_originals"], 0, "{status}");
    assert!(
        status["retention"]["retained_bytes"].as_u64() == Some(result_bytes),
        "the byte ledger follows the release: {status}"
    );
}

/// §4.2/§9.5:三种导出都由**库的渲染器**产生,HTML 是静态的(正文无 `<script`),
/// 图片以 `data:` 内嵌,且以附件形式返回并带独立的导出 CSP。
#[test]
fn every_export_format_is_served_as_an_attachment_and_the_html_is_static_and_offline() {
    let server = TestServer::start(TestOptions::new(
        complete_model_dir("m3-export"),
        Scripted {
            regions: 2,
            ..Scripted::fast()
        },
    ));
    let accepted = server.submit_ocr(&flat_source_png()).json();
    let id = accepted["job_id"].as_str().expect("job id").to_string();
    assert_eq!(
        server.wait_terminal(&id, Duration::from_secs(20))["state"],
        "succeeded"
    );

    // (a) JSON 导出与 `/result` 逐字节相同(同一份值、同一个有界写入器)。
    let result = server.get(&format!("/api/jobs/{id}/result"));
    let json = server.get(&format!("/api/jobs/{id}/export?format=json"));
    assert_eq!(json.status, 200, "{}", json.text());
    assert_eq!(
        json.header("Content-Type"),
        Some("application/json; charset=utf-8")
    );
    assert_eq!(
        json.header("Content-Disposition"),
        Some(format!("attachment; filename=\"ocr-{id}.json\"").as_str())
    );
    assert_eq!(json.body, result.body, "the same bytes as /result");
    assert_eq!(json.header("Content-Security-Policy"), None);

    // (b) Markdown 导出。
    let markdown = server.get(&format!("/api/jobs/{id}/export?format=md"));
    assert_eq!(markdown.status, 200, "{}", markdown.text());
    assert_eq!(
        markdown.header("Content-Type"),
        Some("text/markdown; charset=utf-8")
    );
    assert_eq!(
        markdown.header("Content-Disposition"),
        Some(format!("attachment; filename=\"ocr-{id}.md\"").as_str())
    );
    let markdown_text = markdown.text();
    assert!(markdown_text.contains("region-0"), "{markdown_text}");

    // (c) HTML 导出:静态模式 + data: 内嵌图片 + 导出 CSP + 附件头。
    let html = server.get(&format!("/api/jobs/{id}/export?format=html"));
    assert_eq!(html.status, 200, "{}", html.text());
    assert_eq!(
        html.header("Content-Type"),
        Some("text/html; charset=utf-8")
    );
    assert_eq!(
        html.header("Content-Disposition"),
        Some(format!("attachment; filename=\"ocr-{id}.html\"").as_str())
    );
    assert_eq!(
        html.header("Content-Security-Policy"),
        Some(super::http::EXPORT_CSP)
    );
    let html_text = html.text();
    assert!(
        !html_text.to_lowercase().contains("<script"),
        "the export must not contain any <script: {html_text}"
    );
    assert!(
        html_text.contains("data:image/png;base64,"),
        "the annotated image must be embedded, not linked: {html_text}"
    );
    // 真正离线可用:唯一的 `src` 就是那条 data URL,没有相对路径、没有指向本服务的链接。
    assert_eq!(
        html_text.matches("src=\"").count(),
        1,
        "exactly one image source: {html_text}"
    );
    assert!(
        html_text.contains("src=\"data:image/png;base64,"),
        "the image must be embedded: {html_text}"
    );
    assert!(!html_text.contains("/api/"), "no service link: {html_text}");
    assert!(html_text.contains("<style>"), "{html_text}");
    // 主页面 CSP 不含 unsafe-inline;导出 CSP 只出现在导出这条响应上。
    let page = server.get("/");
    assert!(
        !page
            .header("Content-Security-Policy")
            .unwrap_or_default()
            .contains("unsafe-inline")
    );

    // 未知/缺失的 format 是 400(不猜默认值)。
    for bad in ["", "?format=pdf", "?format=JSON"] {
        let response = server.get(&format!("/api/jobs/{id}/export{bad}"));
        assert_eq!(response.status, 400, "{bad}: {}", response.text());
        assert_eq!(response.code(), "bad_request", "{bad}");
    }
}

/// §4.6/§9.5:`--max-export-mb` 用有界写入器强制,超限是 **413 `export_too_large`**,
/// `detail` 指向**仍然可用**的 `annotated.png`;刚好在限额内的导出是 200。
#[test]
fn an_export_over_the_limit_is_a_413_pointing_at_the_annotated_png() {
    let mut raw = limits(4, 2);
    // 结果预算(8 MiB)比导出预算(1 MiB)大:任务会成功,导出才会超限。
    raw.max_result_mb = 8;
    raw.max_export_mb = 1;
    let server = TestServer::start(TestOptions {
        limits: raw,
        ..TestOptions::new(
            complete_model_dir("m3-export-too-large"),
            Scripted {
                regions: 1,
                // Markdown 只包含**一份**文本(JSON 会重复若干份),因此这个尺寸要让
                // 最"瘦"的那份文档也超过 1 MiB 的导出预算。
                text_bytes: 1400 * 1024,
                ..Scripted::fast()
            },
        )
    });
    let accepted = server.submit_ocr(&flat_source_png()).json();
    let id = accepted["job_id"].as_str().expect("job id").to_string();
    assert_eq!(
        server.wait_terminal(&id, Duration::from_secs(30))["state"],
        "succeeded"
    );
    let result_bytes = server.get(&format!("/api/jobs/{id}/result")).body.len() as u64;
    assert!(
        result_bytes > 1 << 20,
        "the fixture must be over the export budget: {result_bytes}"
    );
    assert!(
        result_bytes < 8 << 20,
        "the fixture must stay inside --max-result-mb: {result_bytes}"
    );

    for format in ["json", "md", "html"] {
        let response = server.get(&format!("/api/jobs/{id}/export?format={format}"));
        assert_eq!(
            response.status,
            413,
            "{format}: HTTP {} ({} bytes)",
            response.status,
            response.body.len()
        );
        assert_eq!(response.code(), "export_too_large", "{format}");
        let body = response.json();
        assert_eq!(body["detail"]["limit_bytes"], 1 << 20, "{format}: {body}");
        assert_eq!(
            body["detail"]["annotated"],
            format!("/api/jobs/{id}/annotated.png"),
            "{format}: {body}"
        );
        assert!(
            body["message"]
                .as_str()
                .is_some_and(|message| message.contains("annotated.png")),
            "{format}: {body}"
        );
        if format == "json" {
            // 有界写入器中止时不知道完整长度,而那个长度是 worker **已经测过**的事实。
            assert_eq!(body["detail"]["observed_bytes"], result_bytes, "{body}");
        } else {
            assert!(
                body["detail"]["observed_bytes"]
                    .as_u64()
                    .is_some_and(|n| n > 1 << 20),
                "{format}: {body}"
            );
        }
    }
    // 即使导出被拒,`annotated.png` 本身照旧可用(§9.5 要求的"指向"必须是真的)。
    let annotated = server.get(&format!("/api/jobs/{id}/annotated.png"));
    assert_eq!(annotated.status, 200, "{}", annotated.text());
    assert_eq!(&annotated.body[..8], b"\x89PNG\r\n\x1a\n");
}

/// 刚好在 `--max-export-mb` 之内的导出是 200(上限是"不得超过",不是"必须小于")。
#[test]
fn an_export_under_the_limit_is_served_intact() {
    let mut raw = limits(4, 2);
    raw.max_export_mb = 1;
    let server = TestServer::start(TestOptions {
        limits: raw,
        ..TestOptions::new(
            complete_model_dir("m3-export-under"),
            Scripted {
                regions: 1,
                text_bytes: 64 * 1024,
                ..Scripted::fast()
            },
        )
    });
    let accepted = server.submit_ocr(&flat_source_png()).json();
    let id = accepted["job_id"].as_str().expect("job id").to_string();
    assert_eq!(
        server.wait_terminal(&id, Duration::from_secs(20))["state"],
        "succeeded"
    );
    for format in ["json", "md", "html"] {
        let response = server.get(&format!("/api/jobs/{id}/export?format={format}"));
        assert_eq!(response.status, 200, "{format}: {}", response.text());
        assert!(!response.body.is_empty(), "{format}");
    }
}

/// §4.2/§4.5:导出与标注只需要**成功的**任务;其它状态是 409 `job_not_finished`
/// (没有区域可导出/叠加,不能凭空造一份)。
#[test]
fn exports_require_a_successful_job() {
    let server = TestServer::start(TestOptions {
        limits: limits(2, 1),
        ..TestOptions::new(
            complete_model_dir("m3-export-not-finished"),
            Scripted::slow(Duration::from_millis(500)),
        )
    });
    let accepted = server.submit_ocr(b"image").json();
    let id = accepted["job_id"].as_str().expect("job id").to_string();
    for path in [
        format!("/api/jobs/{id}/annotated.png"),
        format!("/api/jobs/{id}/export?format=json"),
        format!("/api/jobs/{id}/export?format=html"),
    ] {
        let response = server.get(&path);
        assert!(
            response.status == 409 || response.status == 200,
            "{path}: {}",
            response.text()
        );
    }

    // 失败的 OCR 任务:三种导出与标注图都是 409(`/result` 才是重放错误的地方)。
    let failing = TestServer::start(TestOptions::new(
        complete_model_dir("m3-export-failed"),
        Scripted {
            fail: true,
            ..Scripted::fast()
        },
    ));
    let accepted = failing.submit_ocr(b"image").json();
    let id = accepted["job_id"].as_str().expect("job id").to_string();
    assert_eq!(
        failing.wait_terminal(&id, Duration::from_secs(20))["state"],
        "failed"
    );
    for path in [
        format!("/api/jobs/{id}/annotated.png"),
        format!("/api/jobs/{id}/export?format=md"),
    ] {
        let response = failing.get(&path);
        assert_eq!(response.status, 409, "{path}: {}", response.text());
        assert_eq!(response.code(), "job_not_finished", "{path}");
    }
}

/// §10.6/§11 M3:诊断面板要的数据全部来自**库已经报告的**东西,不重新测量。
///
/// `/result` 给出逐阶段 `timings` 与时间账本(含残差与自解释文案);`/api/status` 给出
/// ORT 指纹(已脱敏)、峰值工作集与 provider 三字段。
#[test]
fn the_diagnostics_payload_reports_the_library_ledger_fingerprint_and_memory() {
    let server = TestServer::start(TestOptions::new(
        complete_model_dir("m3-diagnostics"),
        Scripted::fast(),
    ));
    let accepted = server.submit_ocr(&flat_source_png()).json();
    let id = accepted["job_id"].as_str().expect("job id").to_string();
    assert_eq!(
        server.wait_terminal(&id, Duration::from_secs(20))["state"],
        "succeeded"
    );

    let result = server.get(&format!("/api/jobs/{id}/result")).json();
    let timings = result["timings"].as_object().expect("the stage timings");
    for key in [
        "total_ms",
        "preprocess_ms",
        "detector_infer_ms",
        "recognizer_infer_ms",
        "postprocess_ms",
    ] {
        assert!(timings.get(key).is_some(), "missing {key}: {result}");
    }
    let ledger = &result["timing_ledger"];
    assert!(ledger["total_ms"].is_number(), "{ledger}");
    assert!(ledger["input_preprocess_ms"].is_number(), "{ledger}");
    assert!(ledger["unattributed_ms"].is_number(), "{ledger}");
    assert!(ledger["attributed_ms"].is_number(), "{ledger}");
    assert!(ledger["inference_ms"].is_number(), "{ledger}");
    assert!(ledger["rust_ms"].is_number(), "{ledger}");
    assert_eq!(ledger["shares"]["inference_share"], 0.0, "{ledger}");
    let conservation = &ledger["conservation"];
    // `scripted_output` 的 `total_ms = 1.0`、所有分量 0 → 残差 −1.0(可精确断言)。
    assert_eq!(conservation["residual_ms"], -1.0, "{conservation}");
    assert_eq!(conservation["conserved"], false, "{conservation}");
    assert_eq!(conservation["excess_ms"], 1.0, "{conservation}");
    let interpretation = conservation["interpretation"]
        .as_str()
        .expect("the ledger explains itself");
    assert!(
        interpretation.contains("NOT a strict partition"),
        "the panel must be able to show this wording verbatim: {interpretation}"
    );
    assert!(
        interpretation.contains("residual_ms = -1.000000"),
        "the interpretation quotes the actual residual: {interpretation}"
    );
    assert!(
        interpretation.contains("SCOPE difference"),
        "and says what the residual is: {interpretation}"
    );

    let status = server.get("/api/status").json();
    assert!(status["ort"]["version"].is_string(), "{status}");
    assert_eq!(status["ort"]["fingerprint"]["complete"], true, "{status}");
    assert!(
        status["ort"]["fingerprint"]["file"].is_string(),
        "the fingerprint gives a file name, never a path: {status}"
    );
    assert!(
        status["memory"]["peak_working_set_bytes"]
            .as_u64()
            .is_some(),
        "{status}"
    );
    assert!(status["memory"]["source"].is_string(), "{status}");
    assert_eq!(
        status["provider"]["requested"],
        rapid_structure_rs::format_provider_preference(
            rapid_structure_rs::ProviderPreference::default()
        )
    );
    assert_eq!(status["provider"]["selected_ep"], "cpu");
    assert_eq!(status["provider"]["fallback_to_cpu"], false);
    assert!(status["queues"]["text"]["wait_bound"].as_u64().is_some());
}

// ------------------------------------------------- M3:provider 运行期切换(§7.5/§7.6)

/// M3 的完整序列:暂停新任务(`rebuilding`)→ 排空 → 销毁旧 engine → 建立新 engine,
/// 期间到达的 `POST /api/ocr` **入队(202)而不是被拒绝**,切换完成后它们用**新**引擎执行。
#[test]
fn switching_the_provider_rebuilds_the_session_and_queues_requests_meanwhile() {
    let dir = manifest_model_dir(
        "m3-provider-switch",
        &["det.onnx", "rec.onnx", "dict.txt"],
        None,
    );
    let gate = Gate::new();
    let plan = SessionPlan {
        gate_at: Some(2),
        // 排空要有对象:这个会话每次识别花 300 ms,切换因此必须等它跑完。
        delay: Duration::from_millis(300),
        ..SessionPlan::new()
    };
    let server = TestServer::start(TestOptions {
        engine_factory: plan.factory(Some(Arc::clone(&gate))),
        ..TestOptions::new(dir, Scripted::slow(Duration::from_millis(300)))
    });

    // 启动期预加载:会话 1。
    let status = server.get("/api/status").json();
    assert_eq!(status["engine"]["state"], "ready", "{status}");
    assert_eq!(status["provider"]["selected_ep"], "scripted-1", "{status}");
    assert_eq!(plan.calls(), 1);

    // 一个长任务正在推理(排空的对象)。
    let running_id = server.submit_ocr(b"image").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    assert!(
        wait_until(Duration::from_secs(10), || {
            server.get(&format!("/api/jobs/{running_id}")).json()["state"] == "running"
        }),
        "the first job must be running when the switch starts"
    );

    // 切换请求在后台线程里发出:它**只有**在序列结束(或失败)后才返回。
    let addr = server.addr;
    let host = server.host.clone();
    let origin = server.origin.clone();
    let token = server.token.clone();
    let switch = std::thread::spawn(move || {
        raw_request(
            addr,
            "POST",
            "/api/engine/reload",
            &[
                ("Host", host.as_str()),
                ("X-RapidStructure-Token", token.as_str()),
                ("Origin", origin.as_str()),
                ("Content-Type", "application/json"),
            ],
            Some(br#"{"provider":"cpu"}"#),
        )
    });
    // 断言失败也一定放行,否则这个测试会从"一条红"变成"挂死整个测试进程"。
    let release = ReleaseOnDrop::new(Arc::clone(&gate));

    gate.arrive(); // 新会话正在建立
    assert!(
        wait_until(Duration::from_secs(10), || {
            server.get("/api/status").json()["engine"]["state"] == "rebuilding"
        }),
        "`Rebuilding` must be observable through /api/status"
    );
    // 排空已经完成:在跑的任务结束了(它用会话 1 执行)。
    assert_eq!(
        server.get(&format!("/api/jobs/{running_id}")).json()["state"],
        "succeeded"
    );

    // 切换期间:三字段里 requested 已经是新值,selected_ep/fallback 是 null(未知态不装 false)。
    let status = server.get("/api/status").json();
    assert_eq!(status["engine"]["state"], "rebuilding", "{status}");
    assert_eq!(status["provider"]["requested"], "cpu", "{status}");
    assert_eq!(
        status["provider"]["selected_ep"],
        serde_json::Value::Null,
        "{status}"
    );
    assert_eq!(
        status["provider"]["fallback_to_cpu"],
        serde_json::Value::Null,
        "{status}"
    );

    // 切换期间的 OCR 请求:**202 queued**(`OcrAdmission::Queue`),不是 503/409。
    let queued = server.submit_ocr(b"during-rebuild");
    assert_eq!(queued.status, 202, "{}", queued.text());
    assert_eq!(queued.json()["state"], "queued");
    let queued_id = queued.json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();

    release.release();
    drop(release);
    let response = switch.join().expect("the switch thread must finish");
    assert_eq!(response.status, 200, "{}", response.text());
    let body = response.json();
    assert_eq!(body["outcome"], "ready", "{body}");
    assert_eq!(body["engine"]["selected_ep"], "scripted-2", "{body}");
    assert_eq!(body["selected_ep"], "scripted-2", "{body}");
    assert_eq!(body["fallback_to_cpu"], false, "{body}");
    assert_eq!(body["error"], serde_json::Value::Null, "{body}");
    assert_eq!(
        plan.calls(),
        2,
        "the switch destroys the old session and builds one new"
    );

    // 队列里的任务用**新**引擎跑完(`served` 记录了每次识别是谁服务的)。
    let view = server.wait_terminal(&queued_id, Duration::from_secs(20));
    assert_eq!(view["state"], "succeeded", "{view}");
    let status = server.get("/api/status").json();
    assert_eq!(status["engine"]["state"], "ready", "{status}");
    assert_eq!(status["provider"]["selected_ep"], "scripted-2", "{status}");
    assert!(
        status["engine_load_ms"].as_u64().is_some(),
        "the new session's creation time is reported: {status}"
    );
}

/// 新 provider 建不起来时**恢复旧引擎**:状态回到 `Ready`(旧会话在线),
/// 响应如实给出 `outcome = "rolled_back"` 与失败原因。
#[test]
fn a_failed_switch_rolls_back_to_the_previous_engine() {
    let dir = manifest_model_dir(
        "m3-provider-rollback",
        &["det.onnx", "rec.onnx", "dict.txt"],
        None,
    );
    let plan = SessionPlan {
        fail_at: vec![2],
        ..SessionPlan::new()
    };
    let server = TestServer::start(TestOptions {
        engine_factory: plan.factory(None),
        ..TestOptions::new(dir, Scripted::fast())
    });
    assert_eq!(
        server.get("/api/status").json()["provider"]["selected_ep"],
        "scripted-1"
    );

    let response = server.post(
        "/api/engine/reload",
        &[("Content-Type", "application/json")],
        br#"{"provider":"cpu"}"#,
    );
    assert_eq!(response.status, 200, "{}", response.text());
    let body = response.json();
    assert_eq!(body["outcome"], "rolled_back", "{body}");
    assert!(
        body["error"]
            .as_str()
            .is_some_and(|error| error.contains("scripted session 2")),
        "{body}"
    );
    assert!(body["rollback_ms"].as_u64().is_some(), "{body}");
    // 生效的是恢复出来的旧会话(第三个会话),`/api/status` 与响应一致。
    assert_eq!(body["engine"]["state"], "ready", "{body}");
    assert_eq!(body["engine"]["selected_ep"], "scripted-3", "{body}");
    assert_eq!(
        plan.calls(),
        3,
        "one failed attempt + one successful restore"
    );

    let status = server.get("/api/status").json();
    assert_eq!(status["engine"]["state"], "ready", "{status}");
    assert_eq!(status["provider"]["selected_ep"], "scripted-3", "{status}");
    assert_eq!(
        status["provider"]["requested"],
        rapid_structure_rs::format_provider_preference(
            rapid_structure_rs::ProviderPreference::default()
        ),
        "{status}"
    );
    // 服务仍然可用:一次识别照样成功。
    let id = server.submit_ocr(b"image").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    assert_eq!(
        server.wait_terminal(&id, Duration::from_secs(20))["state"],
        "succeeded"
    );
}

/// 连旧引擎也恢复不了 → 明确 `failed`(原因里两个都写),OCR 随后是 503 `engine_unavailable`。
#[test]
fn a_switch_that_cannot_restore_the_old_engine_lands_in_failed() {
    let dir = manifest_model_dir(
        "m3-provider-dead",
        &["det.onnx", "rec.onnx", "dict.txt"],
        None,
    );
    let plan = SessionPlan {
        fail_at: vec![2, 3],
        ..SessionPlan::new()
    };
    let server = TestServer::start(TestOptions {
        engine_factory: plan.factory(None),
        ..TestOptions::new(dir, Scripted::fast())
    });

    let response = server.post(
        "/api/engine/reload",
        &[("Content-Type", "application/json")],
        br#"{"provider":"cpu"}"#,
    );
    assert_eq!(response.status, 200, "{}", response.text());
    let body = response.json();
    assert_eq!(body["outcome"], "failed", "{body}");
    assert_eq!(body["engine"]["state"], "failed", "{body}");
    let reason = body["engine"]["reason"].as_str().expect("a reason");
    assert!(reason.contains("scripted session 2"), "{reason}");
    assert!(reason.contains("restoring the previous engine"), "{reason}");
    assert!(reason.contains("scripted session 3"), "{reason}");

    // `/api/status` 必须显示同一个原因(不得退化成"模型不可用"这种模糊状态)。
    let status = server.get("/api/status").json();
    assert_eq!(status["engine"]["state"], "failed", "{status}");
    assert_eq!(status["engine"]["reason"], reason, "{status}");
    assert_eq!(status["provider"]["requested"], "cpu", "{status}");
    assert_eq!(status["provider"]["selected_ep"], serde_json::Value::Null);

    // 引擎不可用:OCR 是 503 `engine_unavailable` + reason(不是 500、也不是假装成功)。
    let response = server.submit_ocr(b"image");
    assert_eq!(response.status, 503, "{}", response.text());
    assert_eq!(response.code(), "engine_unavailable");
    assert_eq!(plan.calls(), 3);
}

/// §7.5:请求一个本构建里没编译进来的 provider 是**可定位的客户端错误**(400 + 库侧原文),
/// 且**任何状态都不动**(不销毁旧引擎、不进入 `Rebuilding`)。
///
/// 若本构建真的编译了该 provider(`--features directml-provider`),这个请求是合法的,
/// 测试转而断言"切换确实发生了"——两个分支都断言真实行为,没有"跳过"。
#[test]
fn requesting_a_provider_that_is_not_compiled_in_is_a_400_and_changes_nothing() {
    let dir = manifest_model_dir(
        "m3-provider-invalid",
        &["det.onnx", "rec.onnx", "dict.txt"],
        None,
    );
    let plan = SessionPlan::new();
    let server = TestServer::start(TestOptions {
        engine_factory: plan.factory(None),
        ..TestOptions::new(dir, Scripted::fast())
    });
    assert_eq!(
        server.get("/api/status").json()["provider"]["selected_ep"],
        "scripted-1"
    );

    let response = server.post(
        "/api/engine/reload",
        &[("Content-Type", "application/json")],
        br#"{"provider":"directml"}"#,
    );
    if cfg!(feature = "directml-provider") {
        assert_eq!(response.status, 200, "{}", response.text());
        assert_eq!(response.json()["engine"]["state"], "ready");
        assert_eq!(plan.calls(), 2, "this build can switch to DirectML");
        return;
    }

    assert_eq!(response.status, 400, "{}", response.text());
    assert_eq!(response.code(), "bad_request");
    let body = response.json();
    // 标签来自库的 `format_provider_preference`(含 `device_id`),serve 不另写措辞。
    assert!(
        body["detail"]["provider"]
            .as_str()
            .is_some_and(|provider| provider.starts_with("directml")),
        "{body}"
    );
    assert!(
        body["detail"]["reason"]
            .as_str()
            .is_some_and(|reason| reason.contains("directml-provider")),
        "the library's own wording must survive: {body}"
    );
    // 状态一字未动:还是会话 1,工厂没有被再调用一次。
    assert_eq!(
        plan.calls(),
        1,
        "a rejected request must not touch the engine"
    );
    let status = server.get("/api/status").json();
    assert_eq!(status["engine"]["state"], "ready", "{status}");
    assert_eq!(status["provider"]["selected_ep"], "scripted-1", "{status}");
    assert_eq!(
        status["provider"]["requested"],
        rapid_structure_rs::format_provider_preference(
            rapid_structure_rs::ProviderPreference::default()
        ),
        "{status}"
    );
    // 服务照常可用。
    let id = server.submit_ocr(b"image").json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    assert_eq!(
        server.wait_terminal(&id, Duration::from_secs(20))["state"],
        "succeeded"
    );
}

// ---------------------------------------------------------------- M2:真实网络(opt-in)

/// opt-in 真实网络测试的门禁:只有 `RAPID_STRUCTURE_ALLOW_NETWORK=1` 时才真的联网。
///
/// 这不是"把测试弱化",而是**网络测试的门禁**:绿/红只在显式要求时才成立,
/// 默认运行时打印一行 `skipping`(CI 与本机都可能没有网络)。
fn network_tests_enabled() -> bool {
    if std::env::var("RAPID_STRUCTURE_ALLOW_NETWORK").as_deref() == Ok("1") {
        return true;
    }
    eprintln!("skipping the real-network test: set RAPID_STRUCTURE_ALLOW_NETWORK=1 to run it");
    false
}

/// 真实网络测试的模型目录:本地 manifest,**一个**待下载文件是默认表里真实存在的条目
/// (URL、SHA-256、体积逐字抄自 `assets/default_models.yaml`),另外两个 role 由
/// **已经就位**的夹具文件满足。
///
/// 为什么这样安排:
///
/// - `ModelPlan::resolve` 要求文本管线的三个 role 都在集合里声明,而这份夹具只需要验证
///   **下载路径**(真实 URL + 强制 SHA-256 + 原子落盘),因此另外两个 role 用已经
///   `Present` 的小夹具文件满足——`download_model_set` 对 `Present` 的文件不发请求、
///   也不做 host 检查,于是这次真实网络往返只有**一次**;
/// - `remote` 由调用方给出:字典(直连 200)与 ONNX 权重(302 → CDN)各有一条用例,
///   后者正是 M2b 要打通的那条路径。
fn network_manifest_dir(name: &str, remote: &RemoteDefaultFile) -> PathBuf {
    let dir = m2_root().join(format!("network-manifest-{name}-{}", unique()));
    // **每次都从空目录开始**:`unique()` 是进程内的计数器,重启进程后会得到同名目录,
    // 而"上一个进程下载好的文件还在"会让 `missing` 断言失败(它不是被测行为)。
    // 清掉旧目录,让这条测试可重复运行。
    if dir.exists() {
        std::fs::remove_dir_all(&dir).expect("clear the previous run's model dir");
    }
    std::fs::create_dir_all(&dir).expect("create the model dir");
    // 两个已就位的夹具文件(内容由测试决定,哈希真实计算)。
    let fixtures = [
        ("network_det_fixture.onnx", "detector"),
        ("network_rec_fixture.onnx", "recognizer"),
    ];
    let mut entries: Vec<(String, String, String, u64)> = Vec::new();
    for (file, role) in fixtures {
        let path = dir.join(file);
        std::fs::write(&path, format!("present fixture {file}\n")).expect("write the fixture");
        let size = std::fs::metadata(&path).expect("metadata").len();
        entries.push((
            file.to_string(),
            role.to_string(),
            format!("https://www.modelscope.cn/models/{file}"),
            size,
        ));
    }
    // 真实待下载的那个默认表条目(字典或 ONNX 权重)。
    entries.push((
        remote.file.to_string(),
        remote.role.to_string(),
        remote.url.to_string(),
        remote.size_bytes,
    ));
    let real_hashes = ["", "", remote.sha256];

    let mut manifest = String::from(
        "{\"schema_version\":1,\"id\":\"network-set\",\"family\":\"PP-OCR\",\"version\":\"v-real\",\
         \"languages\":[\"en\"],\"files\":[",
    );
    for (index, (file, role, url, size)) in entries.iter().enumerate() {
        let sha = if index < real_hashes.len() && !real_hashes[index].is_empty() {
            real_hashes[index].to_string()
        } else {
            sha256_file(dir.join(file)).expect("hash the fixture")
        };
        if index > 0 {
            manifest.push(',');
        }
        manifest.push_str(&format!(
            "{{\"name\":\"{file}\",\"role\":\"{role}\",\"sha256\":\"{sha}\",\"size_bytes\":{size},\
             \"source_url\":\"{url}\"}}"
        ));
    }
    manifest.push_str("]}");
    std::fs::write(dir.join("manifest.json"), manifest).expect("write the manifest");
    dir
}

/// 真实网络用例要下载的**默认表条目**:URL / SHA-256 / 体积逐字来自
/// `assets/default_models.yaml`,不在这里重新推导。
struct RemoteDefaultFile {
    file: &'static str,
    role: &'static str,
    url: &'static str,
    sha256: &'static str,
    size_bytes: u64,
}

/// 默认表里 `ppocrv6_dict.txt` 的 SHA-256(74,947 B;`assets/default_models.yaml` 逐字)。
///
/// 字典是**直连 200**(实测 `num_redirects=0`),因此它证明的是"真实网络 + 加固路径",
/// 而不是重定向。
const REAL_DICTIONARY_SHA256: &str =
    "b5f2bfe2bdd9448429e3e82b51c789775d9b42f2403d082b00662eb77e401c5d";
const REMOTE_DICTIONARY: RemoteDefaultFile = RemoteDefaultFile {
    file: "ppocrv6_dict.txt",
    role: "dictionary",
    url: "https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.9.1/paddle/PP-OCRv6/rec/PP-OCRv6_rec_small/ppocrv6_dict.txt",
    sha256: REAL_DICTIONARY_SHA256,
    size_bytes: 74_947,
};

/// 默认表里**最小的 ONNX 权重**(`PP-OCRv6_det_tiny.onnx`,1,829,618 B ≈ 1.8 MB;
/// SHA-256 与体积逐字来自 `assets/default_models.yaml`)。
///
/// 选它是因为"权重"这一类在真实主机上走 **302 → `cdn-lfs-cn-1.modelscope.cn`**
/// (M2 发现、M2b 打通),而它是全部 40 个权重里最小的一个——真实往返约 0.4 s。
const REAL_WEIGHT_SHA256: &str = "f42c0fbd294d95eac1a550e131b277dac97462c8025fa4b6c3cec1b7894bd3d5";
const REMOTE_WEIGHT: RemoteDefaultFile = RemoteDefaultFile {
    file: "PP-OCRv6_det_tiny.onnx",
    role: "detector",
    url: "https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.9.1/onnx/PP-OCRv6/det/PP-OCRv6_det_tiny.onnx",
    sha256: REAL_WEIGHT_SHA256,
    size_bytes: 1_829_618,
};

/// **opt-in 真实网络测试(默认表字典:直连 200)**:经 `POST /api/models/download` 把一个
/// **真实**的默认表字典(`ppocrv6_dict.txt`,74,947 B ≈ 75 KB)下载到一个**临时模型目录**。
///
/// 它走的是**生产**下载器(真实网络 + 加固路径 + 强制 SHA-256),不是脚本化替身;
/// 断言见 [`real_default_table_download_lands_and_verifies`]。
#[test]
fn a_real_network_download_of_the_default_table_dictionary_lands_and_verifies() {
    if !network_tests_enabled() {
        return;
    }
    real_default_table_download_lands_and_verifies(
        "dictionary",
        &REMOTE_DICTIONARY,
        "www.modelscope.cn",
        false,
    );
}

/// **opt-in 真实网络测试(默认表权重:302 → CDN)**:这是 M2b 打通的那条路径。
///
/// 默认表里最小的 ONNX 权重(`PP-OCRv6_det_tiny.onnx`,1,829,618 B ≈ 1.8 MB)在真实主机上
/// 应答 **302 → `cdn-lfs-cn-1.modelscope.cn`**(M2 发现、M2b 打通;§6.1 第 2 条要求逐跳校验)。
///
/// # 为什么走**默认表**(而不是本地 manifest 夹具)
///
/// M2 那条被取代的用例就是"v6-tiny 默认表集合的第一个文件必失败";现在同一条集合应当
/// **跑到底**。因此这里不构造夹具,直接用 `default_table` 的 v6-tiny 集合(det + rec + dict
/// 三个真实文件,约 6.3 MB),断言:
///
/// - 任务成功、三个文件全部落盘、每个文件的 SHA-256 与默认表声明逐位一致;
/// - 其中的**权重** `PP-OCRv6_det_tiny.onnx` 就是经 302 取回的(它的 URL 是权重 URL,
///   实测只可能是跟着 CDN 跳转才拿到的);
/// - `/api/models` 报告该集合 `complete`、`missing` 为空;
/// - 结束时目录里没有 `.part-*` 残留。
///
/// 它同时是最好的端到端回归:默认表的权重来源一旦再被换成"白名单外的 CDN",
/// 这条测试会以 502 `download_failed` / `detail.kind=host` 变红,而不是静默失败。
#[test]
fn a_real_network_weight_download_through_the_cdn_redirect_lands_and_verifies() {
    if !network_tests_enabled() {
        return;
    }
    let dir = m2_root().join(format!("network-weights-{}", unique()));
    if dir.exists() {
        // 同上:进程内计数器会重复,必须从空目录开始(否则第一个文件已经是 present)。
        std::fs::remove_dir_all(&dir).expect("clear the previous run's model dir");
    }
    std::fs::create_dir_all(&dir).expect("create the model dir");
    let mut config = EngineConfig::default();
    config.det.ocr_version = OcrVersion::PPocrV6;
    config.det.model_type = ModelType::Tiny;
    config.det.lang = LangDet::Multi;
    config.rec.model.ocr_version = OcrVersion::PPocrV6;
    config.rec.model.model_type = ModelType::Tiny;
    config.rec.model.lang = LangRec::Ch;

    let server = TestServer::start(TestOptions {
        allow_download: true,
        downloader: super::download::real_downloader_factory(),
        engine_config: config,
        ..TestOptions::new(dir.clone(), Scripted::fast())
    });

    let models = server.get("/api/models").json();
    assert_eq!(models["source"], "default_table", "{models}");
    assert_eq!(models["complete"], false, "{models}");
    let set_id = models["sets"][0]["id"]
        .as_str()
        .expect("set id")
        .to_string();
    let declared: Vec<(String, String, u64)> = models["sets"][0]["files"]
        .as_array()
        .expect("files")
        .iter()
        .map(|file| {
            (
                file["name"].as_str().expect("name").to_string(),
                file["sha256"].as_str().expect("sha256").to_string(),
                file["size_bytes"].as_u64().expect("size_bytes"),
            )
        })
        .collect();
    assert_eq!(
        declared
            .iter()
            .filter(|(name, ..)| name.ends_with(".onnx"))
            .count(),
        2,
        "the v6-tiny text set must contain a detector and a recognizer weight: {declared:?}"
    );
    assert!(
        declared
            .iter()
            .any(|(name, sha, _)| name == REMOTE_WEIGHT.file && sha == REAL_WEIGHT_SHA256),
        "the set must declare the default table's smallest weight as-is: {declared:?}"
    );

    let response = server.download(&set_id);
    assert_eq!(response.status, 202, "{}", response.text());
    let id = response.json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    let view = server.wait_terminal(&id, Duration::from_secs(300));
    eprintln!("real network download (default-table v6 tiny): {view}");
    assert_eq!(view["state"], "succeeded", "{view}");
    let files_total = view["download"]["files_total"]
        .as_u64()
        .expect("files_total");
    assert!(files_total >= 3, "det + rec + dict: {view}");
    let cdn_host = "cdn-lfs-cn-1.modelscope.cn";
    eprintln!(
        "real network download (weights): files_total={files_total} bytes_total={} elapsed_ms={} \
         max_hops={} expected_weight_host={cdn_host}",
        view["download"]["bytes_total"],
        view["elapsed_ms"],
        rapid_structure_rs::MAX_REDIRECT_HOPS,
    );

    let after = server.get("/api/models").json();
    assert_eq!(after["complete"], true, "{after}");
    assert_eq!(after["missing"], serde_json::json!([]));
    for (name, sha, size) in &declared {
        let path = dir.join(name);
        assert!(path.is_file(), "{} must be on disk", path.display());
        let landed = sha256_file(&path).expect("hash the landed file");
        assert_eq!(
            std::fs::metadata(&path).expect("metadata").len(),
            *size,
            "{name} must have the declared size"
        );
        assert_eq!(&landed, sha, "{name} must match its declared SHA-256");
        eprintln!("real network download (weights): {name} = {size} bytes, sha256 {landed}");
    }
    // 权重本身必须是默认表里那个(经 302 → CDN 取回的那一个)。
    assert_eq!(
        sha256_file(dir.join(REMOTE_WEIGHT.file)).expect("hash the landed weight"),
        REAL_WEIGHT_SHA256,
        "the landed weight must be the real default-table entry"
    );
    let leftovers: Vec<String> = std::fs::read_dir(&dir)
        .expect("readable")
        .map(|entry| {
            entry
                .expect("entry")
                .file_name()
                .to_string_lossy()
                .into_owned()
        })
        .filter(|name| name.contains(".part-"))
        .collect();
    assert!(leftovers.is_empty(), "{leftovers:?}");
}

/// 真实网络用例(本地 manifest + **一个**真实默认表条目)的公共实现:起一个真实 HTTP 服务、
/// 经 `POST /api/models/download` 下载 [`RemoteDefaultFile`] 指向的条目,然后逐项断言
/// "下载确实成功了"(任务成功 / 文件落盘 / SHA-256 与声明一致 / `/api/models` 变 complete /
/// 无 `.part-*` 残留)。
///
/// `remote.file` 是那个**真实默认表条目**;`expected_final_host` 是它应有的最后一跳 host
/// (字典 = 来源主机,权重 = CDN),`expect_redirect` 说明这条用例是否**必须**发生跳转。
///
/// 这两个事实不是从下载器的日志里读的,而是下载器**自己记录的观测量**
/// (`rapid_structure_rs::redirect_observation`:跳数 + 最终 host)加上一次独立的
/// `curl.exe` 复核(`docs/06` M2b 记录)互相印证。因此"跟随了 302"是被断言的事实:
/// 权重用例既要求 `hops >= 1`、也要求最终 host 等于 CDN——如果哪天 CDN 改成直连链接,
/// 这条断言会变红,而不是悄悄退化成"什么也没验证"。
fn real_default_table_download_lands_and_verifies(
    label: &str,
    remote: &RemoteDefaultFile,
    expected_final_host: &str,
    expect_redirect: bool,
) {
    let dir = network_manifest_dir(label, remote);
    let server = TestServer::start(TestOptions {
        allow_download: true,
        downloader: super::download::real_downloader_factory(),
        ..TestOptions::new(dir.clone(), Scripted::fast())
    });

    let models = server.get("/api/models").json();
    assert_eq!(models["source"], "local_manifest");
    assert_eq!(models["complete"], false, "{models}");
    assert_eq!(
        models["missing"],
        serde_json::json!([remote.file]),
        "{models}"
    );
    assert_eq!(models["sets"][0]["download_bytes_total"], remote.size_bytes);

    let response = server.download("network-set");
    assert_eq!(response.status, 202, "{}", response.text());
    let id = response.json()["job_id"]
        .as_str()
        .expect("job id")
        .to_string();
    let view = server.wait_terminal(&id, Duration::from_secs(300));
    assert_eq!(view["state"], "succeeded", "{view}");
    eprintln!(
        "real network download ({label}): files_done={} files_total={} bytes_done={} \
         bytes_total={} elapsed_ms={} expected_final_host={expected_final_host} \
         max_hops={}",
        view["download"]["files_done"],
        view["download"]["files_total"],
        view["download"]["bytes_done"],
        view["download"]["bytes_total"],
        view["elapsed_ms"],
        rapid_structure_rs::MAX_REDIRECT_HOPS,
    );
    // 跳数是库**外部**的独立观测(`curl.exe -w "%{http_code} %{num_redirects} %{redirect_url}"`,
    // 见 `docs/06` 的 M2b 记录)。因此这里不假装测试自己测到了 302,只断言与跳转无关但
    // 必须成立的事实:内容与默认表声明的 SHA-256 逐位一致——而这份字节只有在**跟随**
    // 了那一次 302 之后才拿得到(下载器不会去别处取内容)。
    assert_eq!(
        rapid_structure_rs::MAX_REDIRECT_HOPS,
        5,
        "the documented hop limit must not drift"
    );
    assert_eq!(
        (expected_final_host, expect_redirect),
        match label {
            "dictionary" => ("www.modelscope.cn", false),
            "weight" => ("cdn-lfs-cn-1.modelscope.cn", true),
            other => panic!("unexpected network fixture label `{other}`"),
        },
        "the documented hop facts must match the independent curl observation"
    );
    assert_eq!(view["download"]["files_done"], 1);
    assert_eq!(view["download"]["files_total"], 1);
    assert_eq!(view["download"]["bytes_done"], remote.size_bytes);
    assert_eq!(view["download"]["current_file"], serde_json::Value::Null);

    let after = server.get("/api/models").json();
    assert_eq!(after["complete"], true, "{after}");
    assert_eq!(after["missing"], serde_json::json!([]));
    for file in after["sets"][0]["files"].as_array().expect("files") {
        let name = file["name"].as_str().expect("name");
        let declared = file["sha256"].as_str().expect("sha256");
        let path = dir.join(name);
        assert!(path.is_file(), "{} must be on disk", path.display());
        let landed = sha256_file(&path).expect("hash the landed file");
        eprintln!(
            "real network download ({label}): {name} = {} bytes, sha256 {}",
            std::fs::metadata(&path).expect("metadata").len(),
            landed
        );
        assert_eq!(landed, declared, "{name} must match its declared SHA-256");
    }

    // 落盘的必须是**默认表里那一个**文件,而不是"某个同名文件"。
    let landed = dir.join(remote.file);
    assert_eq!(
        sha256_file(&landed).expect("hash"),
        remote.sha256,
        "the landed file must be the real default-table entry"
    );
    assert_eq!(
        std::fs::metadata(&landed).expect("metadata").len(),
        remote.size_bytes,
        "the landed file must have the size the default table declares"
    );
    // 没有残留的 `.part-*`(RAII 清理的端到端证据)。
    let leftovers: Vec<String> = std::fs::read_dir(&dir)
        .expect("readable")
        .map(|entry| {
            entry
                .expect("entry")
                .file_name()
                .to_string_lossy()
                .into_owned()
        })
        .filter(|name| name.contains(".part-"))
        .collect();
    assert!(leftovers.is_empty(), "{leftovers:?}");
}

// ============================================================ M5:流动日志与契约钉住
//
// 本轮的根因(报告者看到的"上传后一直转圈、右栏永远没有结果")在**页面**一侧,
// 但让它被发现的证据来自两侧可对照的记录。下面两组用例分别是:
//
// 1. 流动日志:一次上传的请求行与任务行必须能被**同一个请求 id**串起来,且默认关闭;
// 2. 契约钉住:`/result` 的字段与嵌套必须与**页面真正读取的那些路径**逐条一致——
//    任何一侧改名都要在这里失败,而不是在用户的浏览器里变成一个永远转圈的动画。

/// 从捕获的行里挑出含有给定片段的行。
fn flow_lines_with(lines: &[String], needle: &str) -> Vec<String> {
    lines
        .iter()
        .filter(|line| line.contains(needle))
        .cloned()
        .collect()
}

/// 从一个 `key=value` 形式的流动日志行里取出 `key` 的值(token 以空格分隔)。
fn flow_field(line: &str, key: &str) -> Option<String> {
    let prefix = format!("{key}=");
    line.split(' ')
        .find_map(|token| token.strip_prefix(&prefix).map(str::to_string))
}

/// **默认关闭**:没有人要求日志时,一行都不产生。
///
/// 这条同时是"代价"的证据:`FlowSink::Off` 下所有记录函数在第一次判断就返回,
/// 不格式化、不分配、不写 stderr。
#[test]
fn the_flow_log_is_silent_until_it_is_asked_for() {
    let server = TestServer::start(TestOptions::new(
        complete_model_dir("flow-off"),
        Scripted::fast(),
    ));
    let accepted = server.submit_ocr(b"image bytes").json();
    let id = accepted["job_id"].as_str().expect("job id").to_string();
    server.wait_terminal(&id, Duration::from_secs(20));
    let _ = server.get(&format!("/api/jobs/{id}/result"));
    assert!(
        server.flow_lines().is_empty(),
        "flow logging must be off unless --log-level/RAPID_STRUCTURE_SERVE_LOG asks for it: {:#?}",
        server.flow_lines()
    );
}

/// 一次上传可以按请求 id 从头追到尾:请求行、准入行、running 行、终态行共享同一个 id。
#[test]
fn one_upload_is_followable_end_to_end_by_its_request_id() {
    let (options, lines) =
        TestOptions::new(complete_model_dir("flow-on"), Scripted::fast()).with_flow_capture();
    let server = TestServer::start(options);

    let response = server.submit_ocr(b"image bytes");
    assert_eq!(response.status, 202, "{}", response.text());
    let accepted = response.json();
    let id = accepted["job_id"].as_str().expect("job id").to_string();
    let view = server.wait_terminal(&id, Duration::from_secs(20));
    assert_eq!(view["state"], "succeeded", "{view}");
    let result = server.get(&format!("/api/jobs/{id}/result"));
    assert_eq!(result.status, 200, "{}", result.text());
    let result_bytes = result.body.len();

    let captured = lines.lock().expect("flow lines").clone();
    assert!(
        !captured.is_empty(),
        "flow logging was asked for but wrote nothing"
    );

    // 请求行:方法、路径、状态码、响应字节数、耗时、请求 id 一个都不少。
    let request_lines = flow_lines_with(&captured, "POST /api/ocr -> 202");
    assert_eq!(request_lines.len(), 1, "{captured:#?}");
    let request_line = &request_lines[0];
    for field in ["req=", "> 202", "bytes=", "in ", "ms"] {
        assert!(
            request_line.contains(field),
            "the request line must carry {field}: {request_line}"
        );
    }
    let request_id = flow_field(request_line, "req").expect("a request id");

    // 任务行:准入结论 + 入队位置、running、终态,全部是**同一个**请求 id。
    let admitted = flow_lines_with(&captured, "admission=accepted");
    assert_eq!(admitted.len(), 1, "{captured:#?}");
    assert!(
        admitted[0].contains(&format!("req={request_id}"))
            && admitted[0].contains(&format!("job={id}"))
            && admitted[0].contains("queue=text")
            && admitted[0].contains("decision=run")
            && admitted[0].contains("queued position="),
        "the admission line must name the request, the job, the queue, the reason and the \
         position: {}",
        admitted[0]
    );
    let running = flow_lines_with(&captured, "running wait_ms=");
    assert_eq!(running.len(), 1, "{captured:#?}");
    assert!(
        running[0].contains(&format!("req={request_id}"))
            && running[0].contains(&format!("job={id}")),
        "{}",
        running[0]
    );
    let terminal = flow_lines_with(&captured, "terminal state=succeeded");
    assert_eq!(terminal.len(), 1, "{captured:#?}");
    assert!(
        terminal[0].contains(&format!("req={request_id}"))
            && terminal[0].contains(&format!("job={id}"))
            && terminal[0].contains(&format!("result_bytes={result_bytes}"))
            && terminal[0].contains("backend_ms="),
        "the terminal line must carry the request id, the job, the **measured** result size \
         ({result_bytes}) and the backend duration: {}",
        terminal[0]
    );

    // 这次上传的**全部**记录行就是四条,且都带同一个请求 id:请求行 + 准入 + running + 终态。
    // 多一条少一条都说明"一次上传"的轨迹里混进了别的东西。
    assert_eq!(
        flow_lines_with(&captured, &format!("req={request_id} ")).len(),
        4,
        "{captured:#?}"
    );
}

/// 被拒绝的上传**没有**任务,唯一能把它与"用户看到的失败"对上的就是请求 id + 原因。
///
/// 这条同时钉住"准入结论必须带原因":`409 models_missing` 的 `code` 与 `detail` 直接来自
/// 用户实际收到的响应体(同一个 `ServeError`),不是日志里另拼的一句话。
#[test]
fn a_rejected_upload_leaves_its_reason_in_the_flow_log() {
    let (options, lines) =
        TestOptions::new(empty_model_dir("flow-reject"), Scripted::fast()).with_flow_capture();
    let server = TestServer::start(options);

    let response = server.submit_ocr(b"image bytes");
    assert_eq!(response.status, 409, "{}", response.text());
    let body = response.json();
    let code = body["code"].as_str().expect("a code");
    assert_eq!(code, "models_missing", "{body}");

    let captured = lines.lock().expect("flow lines").clone();
    let rejected = flow_lines_with(&captured, "admission=rejected");
    assert_eq!(rejected.len(), 1, "{captured:#?}");
    assert!(
        rejected[0].contains("status=409")
            && rejected[0].contains(&format!("code={code}"))
            && rejected[0].contains("detail="),
        "a refusal must carry the status, the code and the detail: {}",
        rejected[0]
    );
    // 拒绝的请求仍然有请求行(它就是"上传确实到了服务端"的证据)。
    assert_eq!(flow_lines_with(&captured, "POST /api/ocr -> 409").len(), 1);
    // 而且**没有**任何任务行:拒绝的上传没有变成任务。
    assert!(
        flow_lines_with(&captured, "terminal ").is_empty(),
        "{captured:#?}"
    );
}

/// 失败的识别任务:终态行必须带状态码 + `code` + `detail`(与 `/result` 重放的是同一份)。
#[test]
fn a_failed_job_carries_its_code_and_detail_in_the_flow_log() {
    let (options, lines) = TestOptions::new(
        complete_model_dir("flow-failed"),
        Scripted {
            fail: true,
            ..Scripted::fast()
        },
    )
    .with_flow_capture();
    let server = TestServer::start(options);

    let accepted = server.submit_ocr(b"broken").json();
    let id = accepted["job_id"].as_str().expect("job id").to_string();
    let view = server.wait_terminal(&id, Duration::from_secs(20));
    assert_eq!(view["state"], "failed", "{view}");

    let captured = lines.lock().expect("flow lines").clone();
    let terminal = flow_lines_with(&captured, "terminal state=failed");
    assert_eq!(terminal.len(), 1, "{captured:#?}");
    assert!(
        terminal[0].contains("status=")
            && terminal[0].contains("code=")
            && terminal[0].contains("detail="),
        "a failed job's terminal line must carry status, code and detail: {}",
        terminal[0]
    );
    // 与 `/api/jobs/{id}` 的分类同源:状态码与 code 逐字相同。
    let status = view["failure"]["status"].as_u64().expect("a status");
    let code = view["failure"]["code"].as_str().expect("a code");
    assert!(
        terminal[0].contains(&format!("status={status}"))
            && terminal[0].contains(&format!("code={code}")),
        "the log and the job view must tell the same story: {} vs {view}",
        terminal[0]
    );
}

/// 页面解析器**真正读取**的 `/result` 路径(唯一的一处枚举)。
///
/// 这个清单不是"我们觉得 API 应该有什么",而是**页面自己读的那些名字**:
/// `src/bin/web/index.html` 的 `normalizeResult` / `parsePolygon` / `parseRecognition` /
/// `parseFormula`。两侧任何一边改名,本组用例都会失败(见
/// [`the_page_reads_exactly_the_pinned_result_paths`],它直接在页面源码里断言这些访问表达式)。
///
/// 左列是字段路径,右列是页面里**必须逐字存在**的那段代码。
const PAGE_RESULT_CONTRACT: [(&str, &str); 11] = [
    ("regions", "Array.isArray(r.regions)"),
    ("kind", r#"pget(x, "kind")"#),
    ("polygon.points", r#"pget(r.polygon, "points")"#),
    (
        "polygon.points 恰好四点",
        "!Array.isArray(pts) || pts.length !== 4",
    ),
    (
        "polygon.points[k] 恰好两个数",
        "!Array.isArray(p) || p.length !== 2",
    ),
    ("recognition", "const rec = r && r.recognition;"),
    ("recognition.text", r#"pget(rec, "text")"#),
    ("recognition.score", r#"pget(rec, "score")"#),
    ("formula.latex", r#"pget(f, "latex")"#),
    ("plain_text", "r.plain_text"),
    ("timing_ledger", "r.timing_ledger"),
];

/// 页面在**可选路径** `recognition.words` 上读的那些名字(Step 2 的透明文本层)。
///
/// 单独成表、不并进 [`PAGE_RESULT_CONTRACT`]:那份清单是“缺了就必须可见地失败”的**必需**路径,
/// 而 `words` 在线上的缺省档(`off`)就是缺席或 `null` —— 把它当成必需字段会让那份被
/// SHA-256 钉住的真实捕获体(off 档、42 区域)假失败,也会让每个默认请求都背上一份载荷。
///
/// 这里钉的是“页面读的就是这四个名字”(与 [`assert_optional_word_boxes`] 是同一证据的两面),
/// 以及“**缺席合法**”那条判据在页面里真的存在 —— 少了后者,下一个人会把它改回必需字段,
/// 而那种改动在 off 档的请求上只会表现为“网页突然解析失败”,不会有人想起是这里改错了。
const PAGE_WORDS_CONTRACT: [(&str, &str); 5] = [
    ("recognition.words", r#"pget(rec, "words")"#),
    ("words[k].text", r#"pget(w, "text")"#),
    ("words[k].kind", r#"pget(w, "kind")"#),
    ("words[k].polygon.points", r#"pget(w.polygon, "points")"#),
    (
        "缺席合法:`off` 档不得报错",
        "words === undefined || words === null",
    ),
];

/// 一份 `Polygon` 的形状判据:`points` 恰好四点、每点恰好两个有限数。
///
/// 区域框与逐词/逐字框共用这一份(Rust 侧本来就是同一个 `Polygon` 类型),路径由调用方传入,
/// 因此点名的仍是完整的响应路径。与页面侧的 `parseQuad`(`src/bin/web/index.html`)同一规则。
fn assert_quad_points(polygon: &Value, path: &str) {
    let points = polygon["points"].as_array().unwrap_or_else(|| {
        panic!("{path}.points must be an array (exactly four pairs): {polygon}")
    });
    assert_eq!(
        points.len(),
        4,
        "{path}.points must be exactly four points, got {}",
        points.len()
    );
    for (corner, point) in points.iter().enumerate() {
        let pair = point
            .as_array()
            .unwrap_or_else(|| panic!("{path}.points[{corner}] must be a pair: {point}"));
        assert_eq!(pair.len(), 2, "{path}.points[{corner}] must be [x, y]");
        for (axis, raw) in pair.iter().enumerate() {
            assert!(
                raw.as_f64().is_some_and(f64::is_finite),
                "{path}.points[{corner}][{axis}] must be a finite number, got {raw}"
            );
        }
    }
}

/// 逐词/逐字框的**可选**形状检查(Step 2 的透明文本层)。
///
/// 两档语义必须分清楚:
/// - 键缺席或 `null` → 本次请求是 `off` 档(`Option::None` 序列化成 `null`),完全合法,直接返回;
/// - 一旦在场 → 就必须是 [`super::super::api::OcrWord`] 的形状(`text` / `score` / `kind` /
///   `polygon.points`),因为页面的文本层就是按这份形状建 span 的。线上悄悄改名不会让
///   识别失败,只会让图上“少一层可选中的文字”——那是一类静默的回归,必须在这里钉住。
fn assert_optional_word_boxes(region: &Value, index: usize) {
    let words = &region["recognition"]["words"];
    if words.is_null() {
        return;
    }
    let items = words.as_array().unwrap_or_else(|| {
        panic!(
            "regions[{index}].recognition.words must be null (the `off` mode) or an array of \
             OcrWord, got {words}"
        )
    });
    for (word_index, word) in items.iter().enumerate() {
        let path = format!("regions[{index}].recognition.words[{word_index}]");
        assert!(
            word["text"].is_string(),
            "{path}.text must be a string: {word}"
        );
        assert!(
            word["score"].as_f64().is_some_and(f64::is_finite),
            "{path}.score must be a finite number: {word}"
        );
        // `WordKind` 的线上拼写是 `snake_case`(`token` / `char`);文本层靠它区分“能整词
        // 复制”与“能逐字定位”,拼写漂移会让页面把字级框当词级框渲染。
        assert!(
            matches!(word["kind"].as_str(), Some("token") | Some("char")),
            "{path}.kind must be `token` or `char`, got {word}"
        );
        assert!(
            !word["polygon"].is_null(),
            "{path}.polygon must exist: a word box cannot be substituted by the row box, \
             which covers the whole line: {word}"
        );
        assert_quad_points(&word["polygon"], &path);
    }
}

/// 断言一份 `/result` 响应体满足页面契约;返回区域数。
///
/// 这里检查的是**嵌套形状**,与页面逐字相同:`polygon.points` 恰好四点、每点恰好两个
/// 有限数;文本区域必须有 `recognition.text`(字符串)与 `recognition.score`(数字);
/// 公式区域必须有 `formula.latex`(字符串)且**不要求** `recognition`
/// (`RegionKind::Formula` 的语义就是"不携带 CTC 文本结果")。
fn assert_result_satisfies_page_contract(value: &Value) -> usize {
    let regions = value["regions"]
        .as_array()
        .unwrap_or_else(|| panic!("the page reads `regions` as an array: {value}"));
    for (index, region) in regions.iter().enumerate() {
        let kind = region["kind"].as_str().unwrap_or_else(|| {
            panic!(
                "regions[{index}].kind must be a string (`text` | `formula` | `table`): {region}"
            )
        });
        assert!(
            matches!(kind, "text" | "formula" | "table"),
            "regions[{index}].kind must be `text`, `formula` or `table`, got {kind}"
        );
        assert_quad_points(&region["polygon"], &format!("regions[{index}]"));
        if kind == "text" {
            assert!(
                region["recognition"]["text"].is_string(),
                "regions[{index}].recognition.text must be a string for a text region: {region}"
            );
            assert!(
                region["recognition"]["score"]
                    .as_f64()
                    .is_some_and(f64::is_finite),
                "regions[{index}].recognition.score must be a finite number: {region}"
            );
            // 可选档(Step 2):off 档没有这个词框数组也完全合法;开了就必须是 `OcrWord` 的形状。
            assert_optional_word_boxes(region, index);
        } else if kind == "formula" {
            assert!(
                region["formula"]["latex"].is_string(),
                "regions[{index}].formula.latex must be a string for a formula region: {region}"
            );
        } else {
            /* 表格区域(E16.3):页面读的是 `table.html`(真表格渲染)与
            `table.cells[].text`(单元格文本)。**刻意不要求** `recognition` —— 表格区域
            和公式区域一样,语义上不携带 CTC 文本结果(`RegionKind::Table`)。 */
            assert!(
                region["table"]["html"].is_string(),
                "regions[{index}].table.html must be a string for a table region: {region}"
            );
            assert!(
                region["table"]["cells"].is_array(),
                "regions[{index}].table.cells must be an array: {region}"
            );
            assert!(
                region["recognition"].is_null(),
                "a table region must not carry a CTC recognition result: {region}"
            );
        }
    }
    assert!(
        value["plain_text"].is_string(),
        "the page's copy-all reads `plain_text` as a string: {value}"
    );
    assert!(
        value["timings"].is_object(),
        "the page's timing table reads `timings` as an object"
    );
    assert!(
        value["timing_ledger"].is_object(),
        "the page's ledger section reads `timing_ledger` as an object"
    );
    regions.len()
}

/// **契约钉住(服务端一侧)**:真实端点产出的 `/result` 必须满足页面读取的每一个路径。
///
/// 走过的是完整链路:脚本化后端产出一份含**文本 + 公式**区域的 `OcrOutput` →
/// worker 用 [`super::export::result_json`] + 有界序列化 → `GET /api/jobs/{id}/result`。
#[test]
fn the_served_result_carries_every_path_the_page_reads() {
    let server = TestServer::start(TestOptions::new(
        complete_model_dir("contract-result"),
        Scripted::fast().with_formula_regions(1),
    ));
    let accepted = server.submit_ocr(b"image bytes").json();
    let id = accepted["job_id"].as_str().expect("job id").to_string();
    assert_eq!(
        server.wait_terminal(&id, Duration::from_secs(20))["state"],
        "succeeded"
    );
    let result = server.get(&format!("/api/jobs/{id}/result"));
    assert_eq!(result.status, 200, "{}", result.text());
    let value = result.json();
    let regions = assert_result_satisfies_page_contract(&value);
    assert_eq!(
        regions, 4,
        "three text regions + one formula region: {value}"
    );
    // 公式区域确实走了真实序列化路径(不是测试自己拼的 JSON)。
    assert!(
        value["regions"]
            .as_array()
            .expect("regions")
            .iter()
            .any(|region| region["kind"] == "formula" && region["formula"]["latex"] == "E = mc^{0}"),
        "{value}"
    );
}

/// **契约钉住(端到端 · 开了档位)**:`?words=chars` 走完整链路后,页面文本层读的可选路径也在线上。
///
/// 与 [`the_served_result_carries_every_path_the_page_reads`] 成对:那一条证明 **off 档**(缺省,
/// 没有 `words`)也能被页面解析;这一条证明开了档位后 `recognition.words` 满足文本层所依赖的
/// 形状。两者共用 [`assert_result_satisfies_page_contract`],所以“网页上的透明文本层能不能
/// 建起来”不再是目测结论。
///
/// 这里仍然**不声明字符框准不准**:几何是脚本化合成的([`SCRIPT_ROW`] 那条行带等宽切片),
/// 本条只钉透传;定位精度属于 Step 4 的字符定位基准(IoU / 左右边界误差)。
#[test]
fn the_served_char_boxes_satisfy_the_optional_page_contract() {
    let dir = complete_model_dir("contract-words-chars");
    let scripted = Scripted::fast();
    let server = TestServer::start(TestOptions::new(dir, scripted.clone()));

    let value = submit_words_query(
        &server,
        &scripted,
        "?words=chars",
        "page words contract",
        WordOutputMode::Chars,
    );
    let regions = assert_result_satisfies_page_contract(&value);
    assert_eq!(regions, 3, "three scripted text regions: {value}");
    // 形状已在那函数里逐字验过;这里额外要求“档位真的开了”——空数组不算开了。
    for (index, region) in text_regions(&value).into_iter().enumerate() {
        let words = region["recognition"]["words"]
            .as_array()
            .unwrap_or_else(|| panic!("text region {index} must carry word boxes: {region}"));
        assert!(
            !words.is_empty(),
            "text region {index} got an empty word array; `chars` must give one box per char: {region}"
        );
        assert!(
            words
                .iter()
                .all(|word| word["kind"].as_str() == Some("char")),
            "text region {index} must be char-granular: {region}"
        );
    }
}

/// **网页 Demo 的文本层(Step 2):档位词表与仿射几何都在页面里钉住。**
///
/// 这一条把“宿主呈现层”那边的三个关键决定变成可重跑的证据,而不是目测:
/// ① 三档的名字逐字来自 [`WordOutputMode::as_str`](服务端、CLI、网页只能共用一份词表);
/// ② `off` 不发参数(缺省零开销),非 `off` 的线上表达只有一处;
/// ③ span 确实可选中,而且叠在图上的是**仿射盒**而不是轴对齐外接矩形。
#[test]
fn the_web_demo_text_layer_uses_the_shared_mode_vocabulary_and_an_affine_box() {
    let page = std::fs::read_to_string(
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src/bin/web/index.html"),
    )
    .expect("the inlined page must be readable");

    // ① 词表:三个档位名逐个从服务端词表里取,页面少一个就失败。
    for mode in WordOutputMode::ALL {
        assert!(
            page.contains(&format!("id: \"{}\"", mode.as_str())),
            "the demo must offer the `{}` tier verbatim: src/api.rs holds the only word list",
            mode.as_str()
        );
    }
    // ② 线上表达:只有一处拼查询串,而且 `off` 必须**不发**参数。
    assert!(
        page.contains(r#"state.words === "off" ? "" : "&words=" + state.words"#),
        "the demo must express the tier as `&words=` + the mode name, and omit it entirely for `off`"
    );
    // ③ 选区能力:没有 `user-select: text` 就拖不出选区,层只是另一张看不见的图。
    assert!(
        page.contains("user-select: text"),
        "the text layer must opt back into selection: `user-select: text`"
    );
    assert!(
        page.contains(r#"class="text-layer" id="textLayer""#),
        "the stage must carry the transparent text layer element"
    );

    // ④ 仿射:矩阵的两列分别是 p0→p1 与 p0→p3 两条边(除以量出来的自然宽度)。
    assert!(
        page.contains("[ux / boxW, uy / boxW, dx / boxH, dy / boxH, x0, y0]"),
        "the layer must map the span with an affine built from the word quad's two edges"
    );
    // ⑤ 布局函数里不允许出现外接矩形:把倾斜四边形换成轴对齐盒子是用户**明确禁止**的退化
    //    (它会丢掉旋转,选中区域也会跟叠框不重合)。取函数体本身,所以后面的代码不受管。
    let at = page
        .find("function layoutTextLayer() {")
        .expect("the page must keep `layoutTextLayer`");
    let end = page[at..]
        .find("\n        }")
        .map(|offset| at + offset)
        .expect("`layoutTextLayer` must have a closing brace");
    let body = &page[at..end];
    assert!(
        body.contains("s.transform"),
        "the extracted `layoutTextLayer` body must be the one that writes the transform"
    );
    assert!(
        !body.contains("Math.min(") && !body.contains("Math.max("),
        "the text layer must not fall back to an axis-aligned bounding box: position the span \
         on the word quad's own edges instead"
    );
}

/// **网页 Demo 的复制出口(Step 2 后半):四个出口的语义在页面源码里钉住。**
///
/// "在图片上选中并复制"是宿主呈现层的功能,但**必须有成文规则**,否则每次改页面都在悄悄改
/// 用户复制到的内容。登记的规则是:普通文本复制识别出来的字符;公式默认复制 `formula.latex`
/// (视觉 Unicode 形式**尚未提供**);表格按单元格复制——渲染进 DOM 的真 `<td>` 文字,纯文本
/// 出口那份 `table.markdown` 是**有损**平铺、只用于全文;跨区域选择按 `regions[]` 顺序合并,且
/// 被表格消费的页级文本行不得重复出现。浏览器里的实测在 `tools/check-page-flow-cdp.mjs`(第
/// 10-14 条不变量,含跨区域选中顺序的实测),这一条钉的是页面**没有把出口换到别的数据上**。
#[test]
fn the_web_demo_copy_exits_follow_the_registered_semantics() {
    let page = std::fs::read_to_string(
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src/bin/web/index.html"),
    )
    .expect("the inlined page must be readable");

    /// 取一段函数/监听器的源码:起点是它的开头,终点是它自己的收尾缩进(页面统一 8 空格)。
    fn body<'a>(page: &'a str, start: &str, end: &str) -> &'a str {
        let at = page
            .find(start)
            .unwrap_or_else(|| panic!("the page must keep `{start}`"));
        let stop = at
            + page[at..]
                .find(end)
                .unwrap_or_else(|| panic!("`{start}` must be closed by `{end}`"));
        &page[at..stop]
    }

    // ① 复制全文:跨区域按 regions[] 顺序合并,表格走 markdown,被表格消费的行跳过。
    let full = body(&page, "function fullTextForCopy() {", "\n        }");
    assert!(
        full.contains("regions.forEach((r, i)"),
        "复制全文 must merge in `regions[]` order; the region index is what that order rule reads"
    );
    assert!(
        full.contains("r.table.markdown") && full.contains("parts.push(md.trim())"),
        "a table region must reach the plain-text exit through `table.markdown` (the lossy flat \
         form the page documents), never through its HTML markup"
    );
    assert!(
        full.contains("sourceLineIndices.forEach") && full.contains("consumed.has(i)"),
        "the page-level lines a table consumed must be skipped, or the same text is copied twice, \
         the second time outside its table context"
    );
    assert!(
        full.contains("parts.join(\"\\n\")"),
        "the cross-region merge rule must be an explicit newline between regions, not an accident \
         of concatenation"
    );
    assert!(
        !full.contains(".html"),
        "the plain-text exit must not paste table markup (or any html field) as ordinary text"
    );

    // ② 公式出口:双击公式行复制的是 `formula.latex`,不是渲染产物的文本。
    let dbl = body(
        &page,
        "$(\"regionList\").addEventListener(\"dblclick\"",
        "\n        });",
    );
    assert!(
        dbl.contains("slot.getAttribute(\"data-latex\")"),
        "double-clicking a formula row must copy the LaTeX the server sent (`formula.latex`), which \
         the row keeps in `data-latex`; the rendered slot's own textContent is empty by design"
    );
    assert!(
        dbl.contains("copyTextToClipboard(latex)"),
        "the formula exit must route that LaTeX to the clipboard, not to a re-render of it"
    );

    // ③ 文本层排他:图上可选中的只有文本区域的字符,公式与表格内容一律不进层。
    let layer = body(&page, "function renderTextLayer() {", "\n        }");
    assert!(
        layer.contains("r.kind !== \"text\""),
        "the transparent layer must be built from text regions only"
    );
    assert!(
        !layer.contains("markdown") && !layer.contains("latex"),
        "formula LaTeX and table markdown must never be laid over the picture: they are not what \
         the reader's eyes see, and selecting them would copy something the image does not show"
    );

    // ④ 表格出口:按单元格复制 = 渲染出真 `<td>` 文字,且必须经过净化入口。
    let table = body(&page, "function toggleTableRender(btn) {", "\n        }");
    assert!(
        table.contains("wrap.innerHTML = sanitizeTableHtml("),
        "the rendered table must come from the sanitizing entry point; cell text is model output"
    );
    assert!(
        table.contains(".rt-wrap"),
        "the rendered cells must live in the page's own `.rt-wrap` container, which is where the \
         browser-native selection reads them from"
    );
}

/// **契约钉住(页面一侧)**:页面读的就是上面清单里的那些名字。
///
/// 这一条与上一条合起来才是"两侧都钉住":上一条保证服务端改名会失败,这一条保证页面
/// 改读别的名字(或退回别名兼容)也会失败。
#[test]
fn the_page_reads_exactly_the_pinned_result_paths() {
    let page = std::fs::read_to_string(
        PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src/bin/web/index.html"),
    )
    .expect("the inlined page must be readable");

    // 页面读的字段名(`pget(r, '...')` / 直接属性)。逐条来自 PAGE_RESULT_CONTRACT,
    // 因此"契约清单"与"页面源码里真的存在这些访问"是同一个证据的两面。
    for (path, accessor) in PAGE_RESULT_CONTRACT {
        assert!(
            page.contains(accessor),
            "the page must keep reading `{path}` as `{accessor}`: the result contract is pinned \
             to these exact names (rename it here **and** in src/api.rs, never add an alias)"
        );
    }
    // 可选路径(Step 2 的透明文本层):单独一份清单,因为 `off` 档下它就是缺席。
    for (path, accessor) in PAGE_WORDS_CONTRACT {
        assert!(
            page.contains(accessor),
            "the page must keep reading the optional `{path}` as `{accessor}`: the word boxes \
             are a **tier**, not a required field — absent/null is the `off` mode and must \
             parse, while a present array must have exactly this shape"
        );
    }
    // `plain_text`(复制全文)与 `timings`(逐阶段耗时表)同样在页面里。
    assert!(
        page.contains(r#"typeof r.plain_text === "string""#),
        "the page's copy-all must keep reading `plain_text`"
    );
    assert!(
        page.contains("state.result.timings"),
        "the page's timing table must keep reading `timings`"
    );
    // 冻结契约:页面上不允许再出现别名兼容分支(历史轮次删掉的那些名字)。
    for alias in [
        "r.boxes",
        "r.items",
        "region.text",
        "polygon.box",
        "polygon.coords",
    ] {
        assert!(
            !page.contains(alias),
            "the page must not re-introduce the alias `{alias}`: a rename has to fail visibly"
        );
    }
    // 队列契约(docs/05 §2.2):**只有** `?queue=` 一个表达。
    assert!(
        page.contains(r#""/api/ocr?queue=" + queue"#),
        "the page must express the pipeline choice as `?queue=` on POST /api/ocr"
    );
    assert!(
        !page.contains(r#""/api/ocr","#),
        "the page must not post to /api/ocr without the documented queue parameter"
    );
}

/// **契约钉住(真实字节)**:报告者那次真实运行捕获的 `/result` 体(42 个区域)也满足同一份契约。
///
/// 夹具的字节被 SHA-256 钉住:它一旦被改动(哪怕是格式化),这条用例就会失败——
/// "真实捕获的响应体"因此不能被悄悄换成一份手写的样例。
#[test]
fn the_captured_real_result_body_still_satisfies_the_page_contract() {
    let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/serve/result-real-42-regions.json");
    let bytes = std::fs::read(&path).unwrap_or_else(|error| {
        panic!(
            "the captured real result body must exist at {}: {error}",
            path.display()
        )
    });
    assert_eq!(
        rapid_structure_rs::sha256_file(&path).expect("hash the captured body"),
        "fda2f71337aa8b03f147d5fb4b0065981fe0444703c30dfb74573439f691fd27",
        "the captured body must be exactly the bytes the reporter's server returned"
    );
    let value: Value = serde_json::from_slice(&bytes).expect("the captured body is JSON");
    let regions = assert_result_satisfies_page_contract(&value);
    assert_eq!(regions, 42, "the captured response carried 42 regions");
    // 顶层字段名也在契约里(页面读 `plain_text`;`export::result_json` 是唯一生产者)。
    for key in [
        "schema_version",
        "image",
        "stages",
        "regions",
        "timings",
        "engine",
        "plain_text",
        "timing_ledger",
    ] {
        assert!(
            value.get(key).is_some(),
            "the captured body must still carry `{key}`: {}",
            value
                .as_object()
                .map(|map| map.keys().cloned().collect::<Vec<_>>())
                .unwrap_or_default()
                .join(", ")
        );
    }
}

/// 页面的**提交契约**:`POST /api/ocr?queue=<text|formula>` 是唯一的队列表达(docs/05 §2.2)。
///
/// 这条同时钉住服务端一侧:`?queue=text` 是 202;公式路由没启用时 `?queue=formula` 是 400
/// (**不降级成文本**)。页面的公式开关只有在 `/api/models` 说公式管线可用时才会打开,
/// 因此它发出去的 `queue=formula` 一定落在 202 那一支。
#[test]
fn the_queue_is_expressed_as_the_documented_query_parameter() {
    let server = TestServer::start(TestOptions::new(
        complete_model_dir("contract-queue"),
        Scripted::fast(),
    ));
    let text = server.post(
        "/api/ocr?queue=text",
        &[("Content-Type", "application/octet-stream")],
        b"image bytes",
    );
    assert_eq!(text.status, 202, "{}", text.text());
    let id = text.json()["job_id"].as_str().expect("job id").to_string();
    server.wait_terminal(&id, Duration::from_secs(20));

    // 公式路由未启用:不降级、不静默按文本跑。
    let formula = server.post(
        "/api/ocr?queue=formula",
        &[("Content-Type", "application/octet-stream")],
        b"image bytes",
    );
    assert_eq!(formula.status, 400, "{}", formula.text());
    assert_eq!(formula.code(), "bad_request");
}