crcbl-hal 0.2.0

Crucible graphics HAL: backend seam traits and POD descriptors
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
//! Unit tests for the null backend.
//!
//! The "is the seam usable from outside the crate" property is checked by
//! `tests/seam_from_outside.rs` instead — an in-crate test can reach private
//! items and so cannot prove anything about leakage.

use super::*;

use crate::{
    BindGroupLayoutEntry, BindingKind, BindingModel, BufferUsage, ClearValue, ColorAttachment,
    ColorTargetState, DepthStencilState, Extent3d, GeometryPath, ImageAspect,
    ImageSubresourceRange, ImageViewType, LightingPath, LoadOp, MultisampleState, PrimitiveState,
    PushConstantRange, ResourceState, SampleType, SemaphoreSignal, ShaderEntry, StoreOp, depth,
};

/// The SPIR-V magic number, so test modules look like modules.
const SPIRV: [u32; 5] = [0x0723_0203, 0x0001_0600, 0, 0, 0];

/// A stand-in DXIL container. The null backend compiles nothing, so only its
/// presence is ever read — but it opens with the container magic so a reader
/// does not mistake it for arbitrary bytes.
const DXIL: &[u8] = b"DXBC\x00";

fn boxed(instance: NullInstance) -> (Recorder, Box<dyn Instance>) {
    let recorder = instance.recorder();
    (recorder, Box::new(instance))
}

/// Opens a device that enables everything the adapter offers.
///
/// `DeviceDesc::for_adapter` alone enables only `GPU_DRIVEN`; optional features
/// must be *asked* for, which is the behaviour a real backend has and the reason
/// this helper spells it out.
fn open(instance: &dyn Instance) -> Box<dyn Device> {
    let adapters = instance.adapters();
    instance
        .create_device(&DeviceDesc {
            optional_features: Features::all(),
            ..DeviceDesc::for_adapter(adapters[0].id)
        })
        .expect("the gpu_driven adapter has compute and a timeline semaphore")
}

#[test]
fn the_two_presets_select_the_documented_paths() {
    let a = NullInstance::gpu_driven();
    let b = NullInstance::portable();
    let (a_caps, b_caps) = (a.adapters()[0].caps, b.adapters()[0].caps);
    assert_eq!(a_caps.binding_model(), BindingModel::Bindless);
    assert_eq!(a_caps.geometry_path(), GeometryPath::IndirectCount);
    assert_eq!(b_caps.binding_model(), BindingModel::ArrayPages);
    assert_eq!(b_caps.geometry_path(), GeometryPath::IndirectPerBatch);
    // Neither preset reports ray tracing, so neither may select it. When a
    // preset grows the flags this is the assertion that has to be revisited.
    assert_eq!(a_caps.lighting_path(), LightingPath::Rasterised);
    assert_eq!(b_caps.lighting_path(), LightingPath::Rasterised);
    assert_eq!(a.backend(), BackendKind::Null);

    let caps = b.adapters()[0].caps;
    for absent in [
        Features::DESCRIPTOR_INDEXING,
        Features::BUFFER_DEVICE_ADDRESS,
        Features::DRAW_INDIRECT_COUNT,
        Features::MULTI_DRAW_INDIRECT,
        Features::PUSH_CONSTANTS,
        Features::TIMELINE_SEMAPHORE,
    ] {
        assert!(
            !caps.supports(absent),
            "the portable preset must not claim {absent:?} — it models WebGPU"
        );
    }
    assert!(
        caps.supports(Features::COMPUTE),
        "GPU culling runs on the portable preset"
    );
}

/// `required` has to be able to fail, and it has to name the gap — a
/// requirement that cannot be refused is not a gate. The portable preset lacks a
/// timeline semaphore, which the headless default does require, so this is the
/// refusal the seam owes with nothing contrived to provoke it.
#[test]
fn the_portable_preset_refuses_the_headless_default_and_names_the_gap() {
    let instance = NullInstance::portable();
    let error = instance
        .create_device(&DeviceDesc::for_adapter(AdapterId(0)))
        .expect_err("the portable preset has no timeline semaphore");
    let HalError::UnsupportedFeatures { missing } = error else {
        panic!("expected UnsupportedFeatures, got {error:?}");
    };
    assert!(missing.contains(Features::TIMELINE_SEMAPHORE));
    assert!(
        !missing.contains(Features::COMPUTE),
        "the portable preset has compute"
    );
    // The bindless half is *optional* now: absent, and not a reason to refuse.
    assert!(
        !missing.contains(Features::DESCRIPTOR_INDEXING),
        "an optional feature must never appear in the gap"
    );
}

#[test]
fn unknown_adapters_are_rejected() {
    let instance = NullInstance::gpu_driven();
    let error = instance
        .create_device(&DeviceDesc {
            adapter: AdapterId(7),
            ..DeviceDesc::for_adapter(AdapterId(7))
        })
        .expect_err("there is one adapter");
    assert!(matches!(error, HalError::NoSuchAdapter(7)), "{error:?}");
}

#[test]
fn queue_families_follow_the_adapter_features() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    assert!(device.queue(QueueKind::Graphics).is_some());
    assert!(device.queue(QueueKind::Compute).is_some());
    assert!(device.queue(QueueKind::Transfer).is_some());
    assert_ne!(
        device.queue(QueueKind::Graphics),
        device.queue(QueueKind::Compute),
        "distinct families must have distinct handles"
    );

    let instance = NullInstance::portable();
    let device = instance
        .create_device(&DeviceDesc {
            required_features: Features::COMPUTE,
            ..DeviceDesc::for_adapter(AdapterId(0))
        })
        .expect("the portable preset has compute");
    assert!(
        device.queue(QueueKind::Graphics).is_some(),
        "the graphics queue always exists"
    );
    assert!(device.queue(QueueKind::Compute).is_none());
    assert!(device.queue(QueueKind::Transfer).is_none());
}

#[test]
fn buffers_round_trip_through_the_host_and_reject_the_wrong_memory() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);

    let upload = device
        .create_buffer(&BufferDesc {
            label: Some("staging"),
            size: 16,
            usage: crate::BufferUsage::TRANSFER_SRC,
            memory: MemoryLocation::HostUpload,
        })
        .expect("staging buffer");
    device
        .write_buffer(upload, 4, &[1, 2, 3, 4])
        .expect("write");

    // Out-of-range writes are caught, not silently truncated.
    let error = device
        .write_buffer(upload, 14, &[0; 8])
        .expect_err("write past the end");
    assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");

    // Device-local memory is not host-writable.
    let device_local = device
        .create_buffer(&BufferDesc {
            label: Some("vertex pool"),
            size: 16,
            usage: crate::BufferUsage::STORAGE,
            memory: MemoryLocation::DeviceLocal,
        })
        .expect("device local buffer");
    let error = device
        .write_buffer(device_local, 0, &[0; 4])
        .expect_err("device-local memory is not mappable");
    assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");

    // A zero-size buffer is a descriptor bug.
    let error = device
        .create_buffer(&BufferDesc {
            label: None,
            size: 0,
            usage: crate::BufferUsage::STORAGE,
            memory: MemoryLocation::DeviceLocal,
        })
        .expect_err("zero size");
    assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");
}

/// The bytes a host write left behind are readable, which is what lets a test
/// check the *content* of an upload rather than only its offset and length.
///
/// A packed record written to the wrong offset is caught by
/// [`Event::BufferWritten`]; one written to the right offset with its fields
/// permuted is not, and that is the failure this exists for.
#[test]
fn a_written_buffer_reports_the_bytes_that_landed_in_it() {
    let recorder = Recorder::new();
    let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
    let device = open(&instance);
    let buffer = device
        .create_buffer(&BufferDesc {
            label: Some("table"),
            size: 8,
            usage: crate::BufferUsage::STORAGE,
            memory: MemoryLocation::HostUpload,
        })
        .expect("buffer");

    assert_eq!(
        recorder.buffer_bytes(buffer),
        Some(vec![0u8; 8]),
        "a fresh buffer reads as zeroes, so a slot nothing wrote is \
         distinguishable from one that was written"
    );
    device
        .write_buffer(buffer, 4, &[1, 2, 3, 4])
        .expect("write");
    assert_eq!(
        recorder.buffer_bytes(buffer),
        Some(vec![0, 0, 0, 0, 1, 2, 3, 4]),
        "the write must land at its offset and nowhere else"
    );

    device.destroy_buffer(buffer);
    assert_eq!(
        recorder.buffer_bytes(buffer),
        None,
        "a destroyed buffer holds nothing, rather than the bytes of whatever \
         takes its slot next"
    );
}

#[test]
fn destroyed_handles_are_rejected_rather_than_aliased() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    let buffer = device
        .create_buffer(&BufferDesc {
            label: None,
            size: 8,
            usage: crate::BufferUsage::STORAGE,
            memory: MemoryLocation::HostUpload,
        })
        .expect("buffer");
    device.destroy_buffer(buffer);

    let error = device
        .write_buffer(buffer, 0, &[0])
        .expect_err("stale handle");
    let HalError::InvalidHandle { kind, bits } = error else {
        panic!("expected InvalidHandle, got {error:?}");
    };
    assert_eq!(kind, "buffer");
    assert_eq!(bits, buffer.to_bits());

    // The slot is recycled with a new generation, so the old handle stays dead
    // even though a new buffer now occupies the same index.
    let fresh = device
        .create_buffer(&BufferDesc {
            label: None,
            size: 8,
            usage: crate::BufferUsage::STORAGE,
            memory: MemoryLocation::HostUpload,
        })
        .expect("buffer");
    assert_eq!(fresh.index(), buffer.index());
    assert_ne!(fresh.to_bits(), buffer.to_bits());
    assert!(device.write_buffer(buffer, 0, &[0]).is_err());
    assert!(device.write_buffer(fresh, 0, &[0]).is_ok());
}

#[test]
fn shader_modules_reject_non_spirv() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    let error = device
        .create_shader_module(&ShaderModuleDesc {
            label: None,
            spirv: &[0xDEAD_BEEF],
            wgsl: None,
            msl: None,
            dxil: &[],
        })
        .expect_err("not SPIR-V");
    assert!(matches!(error, HalError::ShaderCompilation(_)), "{error:?}");
    assert!(
        device
            .create_shader_module(&ShaderModuleDesc {
                label: None,
                spirv: &[],
                wgsl: None,
                msl: None,
                dxil: &[],
            })
            .is_err()
    );
    assert!(
        device
            .create_shader_module(&ShaderModuleDesc {
                label: Some("cull"),
                spirv: &SPIRV,
                wgsl: None,
                msl: None,
                dxil: &[],
            })
            .is_ok()
    );
}

/// The null backend compiles nothing, so it accepts any artifact format on its
/// own — including a text one with no SPIR-V beside it, which is a legal
/// descriptor the SPIR-V magic-number check must not reject.
#[test]
fn shader_modules_accept_a_text_artifact_with_or_without_spirv() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    assert!(
        device
            .create_shader_module(&ShaderModuleDesc {
                label: Some("wgsl only"),
                spirv: &[],
                wgsl: Some("@fragment fn main() {}"),
                msl: None,
                dxil: &[],
            })
            .is_ok()
    );
    assert!(
        device
            .create_shader_module(&ShaderModuleDesc {
                label: Some("msl only"),
                spirv: &[],
                wgsl: None,
                msl: Some("[[fragment]] float4 main() { return 0; }"),
                dxil: &[],
            })
            .is_ok(),
        "MSL alone is a legal descriptor; crcbl-mtl is the backend that reads it"
    );
    assert!(
        device
            .create_shader_module(&ShaderModuleDesc {
                label: Some("dxil only"),
                spirv: &[],
                wgsl: None,
                msl: None,
                dxil: &[("vertexMain", DXIL)],
            })
            .is_ok(),
        "DXIL alone is a legal descriptor; crcbl-dx12 is the backend that reads it"
    );
    assert!(
        device
            .create_shader_module(&ShaderModuleDesc {
                label: Some("all four"),
                spirv: &SPIRV,
                wgsl: Some("@fragment fn main() {}"),
                msl: Some("[[fragment]] float4 main() { return 0; }"),
                dxil: &[("vertexMain", DXIL)],
            })
            .is_ok()
    );
}

/// A descriptor carrying no artifact at all names the gap rather than producing
/// a module handle no pipeline could use.
#[test]
fn a_shader_module_with_no_artifact_names_the_gap() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    let error = device
        .create_shader_module(&ShaderModuleDesc {
            label: Some("empty.slang"),
            spirv: &[],
            wgsl: None,
            msl: None,
            dxil: &[],
        })
        .expect_err("a descriptor with no artifact is not a shader");
    let text = error.to_string();
    assert!(text.contains("empty.slang"), "{text}");
    assert!(text.contains("was given nothing"), "{text}");
}

/// What each call site supplied survives the module's destruction, which is
/// what makes "did this caller offer every format it has" assertable at all —
/// every real caller destroys its modules the moment its pipelines exist.
#[test]
fn created_shader_modules_are_logged_with_the_formats_they_carried() {
    let instance = NullInstance::gpu_driven();
    let recorder = instance.recorder();
    let device = open(&instance);
    let module = device
        .create_shader_module(&ShaderModuleDesc {
            label: Some("mesh.slang"),
            spirv: &SPIRV,
            wgsl: Some("@vertex fn vertexMain() {}"),
            msl: Some("[[vertex]] void vertexMain() {}"),
            dxil: &[("vertexMain", DXIL)],
        })
        .expect("every format");
    device.destroy_shader_module(module);
    assert_eq!(
        recorder.shader_modules_created(),
        vec![(Some("mesh.slang".to_string()), ShaderSources::all())]
    );
    recorder.clear();
    assert!(recorder.shader_modules_created().is_empty());
}

/// **A module that offers DXIL must offer it for every stage it is used at, and
/// the refusal names the entry point.**
///
/// A DXIL container is compiled for one entry point, so this is the one
/// artifact format a call site can under-supply: offer the vertex container and
/// not the fragment one and the SPIR-V, WGSL and MSL backends keep drawing
/// while D3D12 has no bytecode for half the pipeline. This backend compiles
/// nothing, so what it checks is the claim — and checking it here is what puts
/// the failure in the no-GPU suite rather than on the one machine with a D3D12
/// driver.
#[test]
fn a_stage_whose_entry_point_has_no_dxil_container_is_refused_by_name() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    let layout = device
        .create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("ui"),
            bind_group_layouts: &[],
            push_constants: None,
        })
        .expect("pipeline layout");
    let targets = [ColorTargetState::opaque(Format::Rgba16Float)];
    let pipeline = |module| GraphicsPipelineDesc {
        label: Some("ui compositing"),
        layout,
        vertex: ShaderEntry {
            module,
            entry_point: "vertexMain",
        },
        fragment: Some(ShaderEntry {
            module,
            entry_point: "fragmentMain",
        }),
        primitive: PrimitiveState::default(),
        depth_stencil: None,
        multisample: MultisampleState::default(),
        color_targets: &targets,
    };
    let module = |dxil| ShaderModuleDesc {
        label: Some("ui.slang"),
        spirv: &SPIRV,
        wgsl: None,
        msl: None,
        dxil,
    };

    let half = device
        .create_shader_module(&module(&[("vertexMain", DXIL)]))
        .expect("one container is still a module");
    let error = device
        .create_graphics_pipeline(&pipeline(half))
        .expect_err("the fragment stage has no container");
    assert!(matches!(error, HalError::ShaderCompilation(_)), "{error:?}");
    let text = error.to_string();
    assert!(text.contains("ui.slang"), "{text}");
    assert!(text.contains("fragmentMain"), "{text}");
    assert!(text.contains("vertexMain"), "{text}");

    // The same pipeline over a module carrying both containers is built, so the
    // refusal above is the missing container and not something else about the
    // descriptor.
    let both = device
        .create_shader_module(&module(&[("vertexMain", DXIL), ("fragmentMain", DXIL)]))
        .expect("module");
    device
        .create_graphics_pipeline(&pipeline(both))
        .expect("both stages have a container");

    // And a module that offered no DXIL at all is held to nothing: it made no
    // claim, and each of the other three artifacts carries every entry point.
    let none = device
        .create_shader_module(&module(&[]))
        .expect("SPIR-V alone is a module");
    device
        .create_graphics_pipeline(&pipeline(none))
        .expect("a module offering no DXIL claims nothing");
}

/// The trap the seam exists to make visible: a layout that asks for
/// push constants on a device without them fails at *creation*, not by silently
/// dropping the writes at record time.
#[test]
fn push_constants_and_bindless_fail_loudly_on_the_portable_preset() {
    let instance = NullInstance::portable();
    let device = instance
        .create_device(&DeviceDesc {
            required_features: Features::COMPUTE,
            ..DeviceDesc::for_adapter(AdapterId(0))
        })
        .expect("the portable preset opens");

    let layout = device
        .create_bind_group_layout(&BindGroupLayoutDesc {
            label: Some("frame"),
            entries: &[BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::ALL,
                kind: BindingKind::UniformBuffer { dynamic: true },
                count: 1,
                flags: crate::BindingFlags::empty(),
            }],
        })
        .expect("a plain layout is fine without push constants");

    let error = device
        .create_pipeline_layout(&PipelineLayoutDesc {
            label: None,
            bind_group_layouts: &[layout],
            push_constants: Some(PushConstantRange {
                stages: ShaderStages::ALL,
                offset: 0,
                size: 64,
            }),
        })
        .expect_err("the portable preset has no push constants");
    assert!(matches!(error, HalError::Unsupported { .. }), "{error:?}");

    // Bindless flags are refused for the same reason.
    let error = device
        .create_bind_group_layout(&BindGroupLayoutDesc {
            label: Some("bindless textures"),
            entries: &[BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::FRAGMENT,
                kind: BindingKind::SampledImage {
                    view_type: ImageViewType::D2,
                    sample_type: SampleType::Float,
                },
                count: 1 << 16,
                flags: crate::BindingFlags::PARTIALLY_BOUND
                    | crate::BindingFlags::UPDATE_AFTER_BIND
                    | crate::BindingFlags::VARIABLE_COUNT,
            }],
        })
        .expect_err("the portable preset has no descriptor indexing");
    assert!(matches!(error, HalError::Unsupported { .. }), "{error:?}");

    // And so are timeline semaphores.
    let error = device
        .create_semaphore(&SemaphoreDesc {
            label: None,
            kind: SemaphoreKind::Timeline { initial_value: 0 },
        })
        .expect_err("the portable preset has no timeline semaphores");
    assert!(matches!(error, HalError::Unsupported { .. }), "{error:?}");
}

/// Opens a null device reporting exactly `extra` beyond the `gpu_driven`
/// preset, plus a shader module and a pipeline layout to build pipelines from.
///
/// The preset deliberately omits both mesh flags, so this is what lets one test
/// model a device that has the capability and another model a device that does
/// not — the two sides of topic 39's rule.
fn mesh_fixture(extra: Features) -> (Box<dyn Device>, ShaderModuleHandle, PipelineLayoutHandle) {
    let mut caps = NullInstance::gpu_driven().adapters()[0].caps;
    caps.features |= extra;
    let instance = NullInstance::new(caps);
    let device = instance
        .create_device(&DeviceDesc {
            optional_features: caps.features,
            ..DeviceDesc::for_adapter(AdapterId(0))
        })
        .expect("the preset opens");
    let module = device
        .create_shader_module(&ShaderModuleDesc {
            label: Some("mesh_shader.slang"),
            spirv: &SPIRV,
            wgsl: None,
            msl: None,
            dxil: &[],
        })
        .expect("module");
    let layout = device
        .create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("mesh"),
            bind_group_layouts: &[],
            push_constants: None,
        })
        .expect("pipeline layout");
    (device, module, layout)
}

/// A mesh pipeline descriptor over `module`, with `task` optional.
fn mesh_desc<'a>(
    module: ShaderModuleHandle,
    layout: PipelineLayoutHandle,
    task: Option<ShaderEntry<'a>>,
) -> MeshPipelineDesc<'a> {
    MeshPipelineDesc {
        label: Some("mesh triangle"),
        layout,
        task,
        // `mesh_shader.slang`'s own numbers: `[numthreads(3, 1, 1)]` on both
        // mesh entry points, `[numthreads(1, 1, 1)]` on `taskMain`.
        task_workgroup_size: [1, 1, 1],
        mesh: ShaderEntry {
            module,
            entry_point: "meshMain",
        },
        mesh_workgroup_size: [3, 1, 1],
        fragment: Some(ShaderEntry {
            module,
            entry_point: "fragmentMain",
        }),
        primitive: PrimitiveState::default(),
        depth_stencil: None,
        multisample: MultisampleState::default(),
        color_targets: &[],
    }
}

/// **The capability guard.** A device that does not report `MESH_SHADER` must
/// refuse a mesh pipeline at creation, by name — not accept it and fail at the
/// draw, where the diagnosis is a frame away from the mistake.
///
/// The `gpu_driven` preset omits both mesh flags on purpose, so this is the
/// device the majority of the suite already runs against.
#[test]
fn a_device_without_mesh_shader_refuses_a_mesh_pipeline() {
    let (device, module, layout) = mesh_fixture(Features::empty());
    assert!(!device.caps().supports(Features::MESH_SHADER));
    let error = device
        .create_mesh_pipeline(&mesh_desc(module, layout, None))
        .expect_err("the preset reports no MESH_SHADER");
    let HalError::Unsupported { backend, what } = error else {
        panic!("the refusal must name the capability, not be a generic failure");
    };
    assert_eq!(backend, BackendKind::Null);
    assert!(what.contains("MESH_SHADER"), "{what}");
}

/// A query set of no queries is refused, and refused as a bad descriptor
/// rather than as a missing capability.
///
/// Every backend in the workspace refuses this, each for its own API's reason,
/// and until 2026-08-23 the seam did not say so and nothing checked it — a
/// contract held by four coincidences. The handle such a call would return
/// names a set whose every read is out of range, so the mistake would surface
/// at the read instead of at the descriptor.
///
/// The device is opened *with* the feature, because that is the case with one
/// right answer: without it, backends check the count and the capability in
/// different orders and either refusal is correct.
#[test]
fn a_query_set_of_no_queries_is_refused_as_a_bad_descriptor() {
    let mut caps = NullInstance::gpu_driven().adapters()[0].caps;
    caps.features |= Features::TIMESTAMP_QUERY;
    let instance = NullInstance::new(caps);
    let device = instance
        .create_device(&DeviceDesc {
            optional_features: caps.features,
            ..DeviceDesc::for_adapter(AdapterId(0))
        })
        .expect("the preset opens");
    assert!(
        device.caps().supports(Features::TIMESTAMP_QUERY),
        "the fixture must have the feature, or this checks the wrong refusal"
    );

    let desc = |count| QuerySetDesc {
        label: Some("pass timers"),
        kind: QueryKind::Timestamp,
        count,
    };
    let set = device
        .create_query_set(&desc(2))
        .expect("a set of two queries is fine on this device");
    device.destroy_query_set(set);

    let error = device
        .create_query_set(&desc(0))
        .expect_err("a set of no queries must not be created");
    assert!(
        matches!(error, HalError::InvalidDescriptor(_)),
        "a zero count is a bad descriptor, not an absent capability: {error:?}"
    );
}

/// A view of mips or layers the image does not have is refused, and a 3D
/// image's depth is not mistaken for its layer count.
///
/// **The reference backend could not state this rule at all.** `create_image`
/// filed `Detail::None`, so neither the mip count nor the layer count was
/// recorded anywhere, and `create_image_view` checked only that the handle was
/// live — `crcbl-mtl` and `crcbl-dx12` refused these from their own copies of
/// the rules while this backend, `crcbl-vk` and `crcbl-webgpu` served them.
/// [`ImageViewDesc::check`] is where the rule lives now; `Detail::Image` is the
/// slot that lets this backend ask it.
///
/// The volume case is the one a wrong reading of
/// [`Extent3d::depth_or_layers`](crate::Extent3d::depth_or_layers) inverts:
/// filing the raw field would make a 64-deep 3D image look 64 layers deep, so
/// the second layer of it would be served instead of refused.
///
/// The accepted views are what stop the refusals going vacuous: a backend that
/// refused every view would satisfy every `expect_err` below.
#[test]
fn a_view_of_mips_or_layers_the_image_lacks_is_refused() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    let format = Format::Rgba8Unorm;
    let image = |image_type, extent, mip_levels| {
        device
            .create_image(&ImageDesc {
                label: Some("view subject"),
                image_type,
                extent,
                format,
                mip_levels,
                samples: 1,
                usage: ImageUsage::SAMPLED,
            })
            .expect("the descriptor is one this device serves")
    };
    let view = |image, base_mip, mip_count, base_layer, layer_count| {
        device.create_image_view(&ImageViewDesc {
            label: Some("subrange"),
            image,
            view_type: ImageViewType::D2Array,
            format,
            range: ImageSubresourceRange {
                aspect: ImageAspect::COLOR,
                base_mip,
                mip_count,
                base_layer,
                layer_count,
            },
        })
    };
    let all = ImageSubresourceRange::ALL;

    // Four mips over three array layers: no two of the image's numbers agree,
    // so a body comparing mips against layers would not pass by coincidence.
    let array = image(
        ImageType::D2,
        Extent3d {
            width: 8,
            height: 8,
            depth_or_layers: 3,
        },
        4,
    );
    // A 64-deep volume, which has one array layer.
    let volume = image(
        ImageType::D3,
        Extent3d {
            width: 8,
            height: 8,
            depth_or_layers: 64,
        },
        1,
    );

    for (handle, base_mip, mip_count, base_layer, layer_count, what) in [
        (
            array,
            0,
            all,
            0,
            all,
            "the whole image through both sentinels",
        ),
        (array, 3, all, 2, all, "the last mip of the last layer"),
        (array, 1, 2, 1, 2, "a subrange ending exactly at the end"),
        (volume, 0, all, 0, all, "the whole volume"),
    ] {
        let handle = view(handle, base_mip, mip_count, base_layer, layer_count)
            .unwrap_or_else(|error| panic!("{what} is a legal view: {error:?}"));
        device.destroy_image_view(handle);
    }

    for (handle, base_mip, mip_count, base_layer, layer_count, what) in [
        (array, 4, all, 0, all, "a view starting past the last mip"),
        (array, 0, all, 3, all, "a view starting past the last layer"),
        (array, 0, 0, 0, all, "a view of no mip levels"),
        (array, 0, all, 0, 0, "a view of no layers"),
        (array, 2, 3, 0, all, "a mip range running past the last mip"),
        (array, 0, all, 1, 3, "a layer range past the last layer"),
        (
            volume,
            0,
            all,
            1,
            all,
            "the second array layer of a 64-deep volume, which has one",
        ),
    ] {
        let error = view(handle, base_mip, mip_count, base_layer, layer_count)
            .expect_err(&format!("{what} must be refused"));
        assert!(
            matches!(error, HalError::InvalidDescriptor(_)),
            "{what}: {error:?}"
        );
    }

    device.destroy_image(array);
    device.destroy_image(volume);
}

/// A device that does not report [`Features::COMPUTE`] refuses a compute
/// pipeline, and takes a graphics one from the same module and layout.
///
/// Neither [`NullInstance`] preset can reach this arm — both carry `COMPUTE` —
/// so until this test the refusal was code no run had ever entered, and the bit
/// existed only for a device nothing constructed. The graphics half is what
/// makes it a *targeted* refusal rather than a device that fails at everything:
/// a fixture broken in some unrelated way would satisfy the first assertion on
/// its own.
#[test]
fn a_device_without_compute_refuses_a_compute_pipeline() {
    let mut caps = NullInstance::gpu_driven().adapters()[0].caps;
    caps.features.remove(Features::COMPUTE);
    let instance = NullInstance::new(caps);
    // `DeviceDesc::for_adapter` requires `COMPUTE` outright — it is one of the
    // two flags the engine cannot work without — so the baseline has to be
    // written out here rather than spread from it. That is also why neither
    // preset can reach this arm: nothing in the engine opens such a device.
    let device = instance
        .create_device(&DeviceDesc {
            required_features: Features::TIMELINE_SEMAPHORE,
            optional_features: caps.features,
            ..DeviceDesc::for_adapter(AdapterId(0))
        })
        .expect("a device with no compute still opens");
    assert!(
        !device.caps().supports(Features::COMPUTE),
        "the fixture was meant to withhold COMPUTE"
    );

    let module = device
        .create_shader_module(&ShaderModuleDesc {
            label: Some("cull.slang"),
            spirv: &SPIRV,
            wgsl: None,
            msl: None,
            dxil: &[],
        })
        .expect("module");
    let layout = device
        .create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("cull"),
            bind_group_layouts: &[],
            push_constants: None,
        })
        .expect("pipeline layout");

    let error = device
        .create_compute_pipeline(&ComputePipelineDesc {
            label: Some("cull"),
            layout,
            compute: ShaderEntry {
                module,
                entry_point: "cull_main",
            },
            workgroup_size: [64, 1, 1],
        })
        .expect_err("this device reports no COMPUTE");
    let HalError::Unsupported { backend, what } = error else {
        panic!("the refusal must name the capability, not be a generic failure");
    };
    assert_eq!(backend, BackendKind::Null);
    assert!(what.contains("compute"), "{what}");

    device
        .create_graphics_pipeline(&GraphicsPipelineDesc {
            label: Some("opaque"),
            layout,
            vertex: ShaderEntry {
                module,
                entry_point: "vs_main",
            },
            fragment: Some(ShaderEntry {
                module,
                entry_point: "fs_main",
            }),
            primitive: PrimitiveState::default(),
            depth_stencil: None,
            multisample: MultisampleState::default(),
            color_targets: &[ColorTargetState::opaque(Format::Rgba16Float)],
        })
        .expect("the refusal is the compute stage's, not the whole device's");
}

/// The two mesh stages are reported separately, so they are refused
/// separately: a device with the mesh stage and no task stage takes a mesh
/// pipeline and refuses one carrying a task entry point.
#[test]
fn the_task_stage_is_refused_on_its_own_flag() {
    let (device, module, layout) = mesh_fixture(Features::MESH_SHADER);
    device
        .create_mesh_pipeline(&mesh_desc(module, layout, None))
        .expect("MESH_SHADER alone is enough for a mesh + fragment pipeline");

    let task = ShaderEntry {
        module,
        entry_point: "taskMain",
    };
    let error = device
        .create_mesh_pipeline(&mesh_desc(module, layout, Some(task)))
        .expect_err("this device has no task stage");
    let HalError::Unsupported { what, .. } = error else {
        panic!("the refusal must name the capability");
    };
    assert!(what.contains("TASK_SHADER"), "{what}");
}

/// One storage-buffer binding visible to `stage`, which is the shape
/// `mesh_shader.slang` pulls its vertices through.
fn visible_to(stage: ShaderStages) -> [BindGroupLayoutEntry; 1] {
    [BindGroupLayoutEntry {
        binding: 0,
        visibility: stage,
        kind: BindingKind::StorageBuffer {
            read_only: true,
            dynamic: false,
            stride: 4,
        },
        count: 1,
        flags: crate::BindingFlags::empty(),
    }]
}

/// The two capability-gated stages, each with a device that has it and a device
/// that does not — so one loop covers both sides of both flags.
///
/// The "lacks it" device for `TASK` still has `MESH_SHADER`, because that is
/// the device the split exists for: a real adapter reports the task stage only
/// alongside the mesh stage, and what is being checked is that the *second*
/// flag is read on its own rather than implied by the first.
const GATED_STAGES: [(ShaderStages, Features, Features, &str); 2] = [
    (
        ShaderStages::MESH,
        Features::MESH_SHADER,
        Features::empty(),
        "MESH_SHADER",
    ),
    (
        ShaderStages::TASK,
        Features::MESH_SHADER.union(Features::TASK_SHADER),
        Features::MESH_SHADER,
        "TASK_SHADER",
    ),
];

/// **The visibility guard**, which is what lets a mesh shader read a buffer at
/// all: a bind-group layout may name a mesh stage, and only on a device that
/// reports it.
///
/// Both halves are load-bearing. Refused on a capable device, the mesh path
/// could only ever draw constants; accepted on an incapable one, the layout
/// carries `VK_SHADER_STAGE_MESH_BIT_EXT` into `vkCreateDescriptorSetLayout`,
/// where the refusal names neither the binding nor the missing capability.
#[test]
fn a_mesh_visible_layout_needs_the_matching_capability() {
    for (stage, with, without, name) in GATED_STAGES {
        let entries = visible_to(stage);
        let desc = BindGroupLayoutDesc {
            label: Some("mesh shader vertices"),
            entries: &entries,
        };

        let (device, ..) = mesh_fixture(with);
        device
            .create_bind_group_layout(&desc)
            .unwrap_or_else(|error| panic!("a device reporting {name} must accept it: {error}"));

        let (device, ..) = mesh_fixture(without);
        let error = device
            .create_bind_group_layout(&desc)
            .expect_err("this device does not report the stage");
        let HalError::Unsupported { backend, what } = error else {
            panic!("the refusal must name the capability, not be a generic failure");
        };
        assert_eq!(backend, BackendKind::Null);
        assert!(what.contains(name), "{what}");
    }
}

/// The same rule on the other surface that names stages: a push-constant range
/// read by a mesh stage.
///
/// Vulkan refuses `VK_SHADER_STAGE_MESH_BIT_EXT` in a `VkPushConstantRange` on
/// a device without the feature exactly as it refuses one in a set layout, so
/// the two are checked together or the layout path is the only one policed.
#[test]
fn a_push_constant_range_naming_a_mesh_stage_needs_the_capability() {
    for (stage, with, without, name) in GATED_STAGES {
        let describe = |stages| PipelineLayoutDesc {
            label: Some("mesh shader constants"),
            bind_group_layouts: &[],
            push_constants: Some(PushConstantRange {
                stages,
                offset: 0,
                size: 16,
            }),
        };

        let (device, ..) = mesh_fixture(with);
        device
            .create_pipeline_layout(&describe(stage))
            .unwrap_or_else(|error| panic!("a device reporting {name} must accept it: {error}"));

        let (device, ..) = mesh_fixture(without);
        let error = device
            .create_pipeline_layout(&describe(stage))
            .expect_err("this device does not report the stage");
        let HalError::Unsupported { what, .. } = error else {
            panic!("the refusal must name the capability");
        };
        assert!(what.contains(name), "{what}");
    }
}

/// The guard must be invisible to everything that came before it: a layout and
/// a push-constant range naming only the stages every device has are accepted
/// on a device with both mesh flags, one of them, and neither.
///
/// This is the assertion that would have caught folding the mesh bits into
/// `ShaderStages::ALL` — which is why the stage set here is `ALL` rather than
/// `VERTEX | FRAGMENT`.
#[test]
fn the_guaranteed_stages_are_unaffected_on_every_device() {
    for extra in [
        Features::empty(),
        Features::MESH_SHADER,
        Features::MESH_SHADER | Features::TASK_SHADER,
    ] {
        let (device, ..) = mesh_fixture(extra);
        let entries = visible_to(ShaderStages::ALL);
        let layout = device
            .create_bind_group_layout(&BindGroupLayoutDesc {
                label: Some("frame"),
                entries: &entries,
            })
            .unwrap_or_else(|error| panic!("{extra:?} must not disturb a raster layout: {error}"));
        device
            .create_pipeline_layout(&PipelineLayoutDesc {
                label: Some("frame"),
                bind_group_layouts: &[layout],
                push_constants: Some(PushConstantRange {
                    stages: ShaderStages::ALL,
                    offset: 0,
                    size: 16,
                }),
            })
            .unwrap_or_else(|error| panic!("{extra:?} must not disturb a raster layout: {error}"));
    }
}

/// The whole path on a device that has both stages: create, bind, dispatch,
/// destroy — and the dispatch lands in the command stream as its own command,
/// the way `draw` and `draw_indexed` do, so a frame's shape stays assertable
/// with no GPU in the room.
///
/// **Both forms of the dispatch**, because they are the two halves of one
/// claim: the CPU-counted one carries its extents and the indirect one carries
/// the buffer and offset a driver would read them from. A renderer that moved
/// its dispatch onto the GPU records the second, and a stream that could only
/// show the first would report the move as a missing draw.
#[test]
fn a_mesh_dispatch_is_recorded_like_any_other_draw() {
    let mut caps = NullInstance::gpu_driven().adapters()[0].caps;
    caps.features |= Features::MESH_SHADER | Features::TASK_SHADER;
    let instance = NullInstance::new(caps);
    let recorder = instance.recorder();
    let device = instance
        .create_device(&DeviceDesc {
            optional_features: caps.features,
            ..DeviceDesc::for_adapter(AdapterId(0))
        })
        .expect("the preset opens");
    assert_eq!(
        device.caps().geometry_path(),
        GeometryPath::MeshShader,
        "a device with the flag must select the path the flag is for"
    );
    let queue = device.queue(QueueKind::Graphics).expect("graphics queue");
    let module = device
        .create_shader_module(&ShaderModuleDesc {
            label: Some("mesh_shader.slang"),
            spirv: &SPIRV,
            wgsl: None,
            msl: None,
            dxil: &[],
        })
        .expect("module");
    let layout = device
        .create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("mesh"),
            bind_group_layouts: &[],
            push_constants: None,
        })
        .expect("pipeline layout");
    let task = ShaderEntry {
        module,
        entry_point: "taskMain",
    };
    let pipeline = device
        .create_mesh_pipeline(&mesh_desc(module, layout, Some(task)))
        .expect("both stages are reported");
    // Two argument structures of three `u32` group counts each, which is what
    // the seam documents one structure to be. Two rather than one because the
    // draw below reads the structure at `MESH_DISPATCH_ARGS_BYTES`, and a
    // buffer holding only the first one ends exactly where that read begins —
    // which is what this fixture asked for until `plan_mesh_indirect` gained a
    // caller and said so.
    let mesh_args = device
        .create_buffer(&BufferDesc {
            label: Some("mesh dispatch args"),
            size: crate::MESH_DISPATCH_ARGS_BYTES * 2,
            usage: BufferUsage::INDIRECT | BufferUsage::STORAGE,
            memory: MemoryLocation::DeviceLocal,
        })
        .expect("buffer");
    recorder.clear();

    let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
        label: Some("mesh frame"),
        queue,
    });
    encoder.begin_render_pass(&RenderPassDesc {
        label: Some("mesh"),
        color_attachments: &[],
        depth_stencil_attachment: None,
        render_area: Rect2d::from_size(16, 16),
        timestamp_writes: None,
    });
    // The same `bind_graphics_pipeline` a raster pipeline uses: the seam gives
    // both kinds one handle type, so there is no second bind to get wrong.
    encoder.bind_graphics_pipeline(pipeline);
    encoder.draw_mesh_tasks(3, 2, 1);
    let indirect = DrawIndirect {
        args: mesh_args,
        offset: crate::MESH_DISPATCH_ARGS_BYTES,
        draw_count: 1,
        stride: u32::try_from(crate::MESH_DISPATCH_ARGS_BYTES).expect("three words fit a u32"),
    };
    encoder.draw_mesh_tasks_indirect(&indirect);
    encoder.end_render_pass();
    let commands = encoder.finish().expect("recording succeeded");

    assert_eq!(
        recorder.command_names(),
        vec![
            "BeginRenderPass",
            "BindGraphicsPipeline",
            "DrawMeshTasks",
            "DrawMeshTasksIndirect",
            "EndRenderPass",
        ]
    );
    assert!(
        recorder
            .commands()
            .contains(&Command::DrawMeshTasks { x: 3, y: 2, z: 1 }),
        "the workgroup counts must survive into the stream, not merely the \
         command's name: {:?}",
        recorder.commands()
    );
    assert!(
        recorder
            .commands()
            .contains(&Command::DrawMeshTasksIndirect(indirect)),
        "the argument buffer and its offset must survive into the stream too — \
         they are the whole of what the indirect form says: {:?}",
        recorder.commands()
    );

    device.destroy_command_buffer(commands);
    device.destroy_buffer(mesh_args);
    // One destroy for both pipeline kinds, which is the other half of sharing
    // the handle type — a mesh pipeline left in the pool here would show up as
    // a leak at teardown.
    device.destroy_graphics_pipeline(pipeline);
    device.destroy_pipeline_layout(layout);
    device.destroy_shader_module(module);
}

/// A mesh dispatch outside a render pass is the same mistake as a `draw`
/// outside one, and must be reported the same way.
///
/// The indirect form is held to one rule more, and it is the rule that form
/// adds: the argument buffer is the whole of what the call says, so a handle
/// that names nothing is a dispatch reading its group counts from a dead
/// allocation. Both are asserted from one recording, because the null backend
/// records every violation rather than stopping at the first.
#[test]
fn a_mesh_dispatch_outside_a_render_pass_is_refused() {
    let mut caps = NullInstance::gpu_driven().adapters()[0].caps;
    caps.features |= Features::MESH_SHADER;
    let instance = NullInstance::new(caps);
    let device = instance
        .create_device(&DeviceDesc {
            optional_features: caps.features,
            ..DeviceDesc::for_adapter(AdapterId(0))
        })
        .expect("the preset opens");
    let recorder = instance.recorder();
    let queue = device.queue(QueueKind::Graphics).expect("graphics queue");
    let mut encoder = device.create_command_encoder(&CommandEncoderDesc { label: None, queue });
    encoder.draw_mesh_tasks(1, 1, 1);
    // Created and destroyed before the call, so the handle is well-formed and
    // names nothing — which is what `need_live` is for and what a handle the
    // test never created could not distinguish.
    let dead = device
        .create_buffer(&BufferDesc {
            label: Some("mesh dispatch args"),
            size: 12,
            usage: BufferUsage::INDIRECT,
            memory: MemoryLocation::DeviceLocal,
        })
        .expect("buffer");
    device.destroy_buffer(dead);
    encoder.draw_mesh_tasks_indirect(&DrawIndirect {
        args: dead,
        offset: 0,
        draw_count: 1,
        stride: 12,
    });
    let commands = encoder.finish().expect("recorded, and carried past");
    let errors = recorder.validation_errors();
    for command in ["DrawMeshTasks", "DrawMeshTasksIndirect"] {
        assert!(
            errors.iter().any(|error| matches!(
                error,
                ValidationError::OutsidePass {
                    command: outside,
                    expected: "render",
                } if *outside == command
            )),
            "{command} outside a pass went unreported: {errors:?}"
        );
    }
    assert!(
        errors.iter().any(|error| matches!(
            error,
            ValidationError::DeadHandle {
                command: "DrawMeshTasksIndirect",
                kind: ObjectKind::Buffer,
                ..
            }
        )),
        "{errors:?}"
    );
    device.destroy_command_buffer(commands);
}

/// Vulkan permits a runtime-sized array only on the **highest-numbered** binding
/// of a set, and both backends additionally require it to be the last element of
/// the slice so "the variable binding is `entries.last()`" is a true reading.
/// The seam doc now states both halves; this pins them.
#[test]
fn variable_count_must_be_the_last_and_highest_binding() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    let plain = BindGroupLayoutEntry {
        binding: 0,
        visibility: ShaderStages::FRAGMENT,
        kind: BindingKind::Sampler { comparison: false },
        count: 4,
        flags: crate::BindingFlags::empty(),
    };
    let bindless = BindGroupLayoutEntry {
        binding: 1,
        visibility: ShaderStages::FRAGMENT,
        kind: BindingKind::SampledImage {
            view_type: ImageViewType::D2,
            sample_type: SampleType::Float,
        },
        count: 1 << 16,
        flags: crate::BindingFlags::VARIABLE_COUNT | crate::BindingFlags::PARTIALLY_BOUND,
    };
    let error = device
        .create_bind_group_layout(&BindGroupLayoutDesc {
            label: None,
            entries: &[bindless, plain],
        })
        .expect_err("VARIABLE_COUNT must come last");
    assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");

    // Last in the slice but *not* the highest binding number: Vulkan refuses
    // this, and the null backend used to accept it.
    let error = device
        .create_bind_group_layout(&BindGroupLayoutDesc {
            label: None,
            entries: &[
                BindGroupLayoutEntry {
                    binding: 7,
                    ..plain
                },
                BindGroupLayoutEntry {
                    binding: 2,
                    ..bindless
                },
            ],
        })
        .expect_err("VARIABLE_COUNT must be the highest binding number");
    assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");

    assert!(
        device
            .create_bind_group_layout(&BindGroupLayoutDesc {
                label: None,
                entries: &[plain, bindless],
            })
            .is_ok()
    );
}

/// A duplicated binding number is a caller bug `crcbl-vk` names and the null
/// backend used to wave through.
#[test]
fn a_duplicated_binding_number_is_refused() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    let entry = BindGroupLayoutEntry {
        binding: 3,
        visibility: ShaderStages::FRAGMENT,
        kind: BindingKind::Sampler { comparison: false },
        count: 1,
        flags: crate::BindingFlags::empty(),
    };
    let error = device
        .create_bind_group_layout(&BindGroupLayoutDesc {
            label: None,
            entries: &[entry, entry],
        })
        .expect_err("binding 3 twice");
    assert!(error.to_string().contains("twice"), "{error}");
}

/// A device with timeline semaphores gets binary acquire/present semaphores;
/// the portable preset, modelling WebGPU's implicit `getCurrentTexture`, gets
/// `None` for both. The renderer's splice is
/// the same code in each case — see [`crate::swapchain`].
#[test]
fn swapchain_acquire_matches_each_presets_sync_model() {
    for (instance, features, expect_semaphores) in [
        (NullInstance::gpu_driven(), Features::GPU_DRIVEN, true),
        (NullInstance::portable(), Features::COMPUTE, false),
    ] {
        let device = instance
            .create_device(&DeviceDesc {
                required_features: features,
                ..DeviceDesc::for_adapter(AdapterId(0))
            })
            .expect("device");
        // SAFETY: the offscreen target holds no pointers, so the contract on
        // `create_surface` is vacuous for it.
        let surface = unsafe { instance.create_surface(&SurfaceTarget::Offscreen) }
            .expect("offscreen surface");

        let caps = instance
            .surface_caps(surface, AdapterId(0))
            .expect("surface caps");
        let format = caps.preferred_format().expect("a format");
        let swapchain = device
            .create_swapchain(&SwapchainDesc {
                label: Some("main"),
                surface,
                format,
                extent: (320, 200),
                image_count: 3,
                present_mode: caps.choose_present_mode(&[PresentMode::Mailbox, PresentMode::Fifo]),
                composite_alpha: CompositeAlpha::Opaque,
            })
            .expect("swapchain");

        let first = device.acquire_next_frame(swapchain).expect("acquire");
        assert_eq!(first.index, 0);
        assert!(!first.suboptimal);
        assert_eq!(first.acquire_semaphore.is_some(), expect_semaphores);
        assert_eq!(first.present_semaphore.is_some(), expect_semaphores);
        // The image, the view and the extent are never optional: every backend
        // has all three, which is why they sit beside the semaphores instead of
        // being rebuilt by every caller.
        assert_eq!(first.extent, (320, 200));

        // The ring rotates and eventually wraps.
        let second = device.acquire_next_frame(swapchain).expect("acquire");
        assert_eq!(second.index, 1);
        assert_ne!(second.image, first.image);
        assert_ne!(
            second.view, first.view,
            "one view per ring image, not one shared view"
        );
        let third = device.acquire_next_frame(swapchain).expect("acquire");
        assert_eq!(third.index, 2);
        let wrapped = device.acquire_next_frame(swapchain).expect("acquire");
        assert_eq!(wrapped.index, 0);
        assert_eq!(wrapped.image, first.image);

        let queue = device.queue(QueueKind::Graphics).expect("graphics queue");
        let waits: Vec<_> = wrapped.present_semaphore.into_iter().collect();
        device
            .present(
                queue,
                &PresentInfo {
                    swapchain,
                    waits: &waits,
                    present_id: None,
                },
            )
            .expect("present");

        // Reconfiguring keeps the handle valid and restarts the ring.
        device
            .reconfigure_swapchain(
                swapchain,
                &SwapchainDesc {
                    label: Some("main"),
                    surface,
                    format,
                    extent: (640, 400),
                    image_count: 3,
                    present_mode: PresentMode::Fifo,
                    composite_alpha: CompositeAlpha::Opaque,
                },
            )
            .expect("reconfigure");
        let after = device.acquire_next_frame(swapchain).expect("acquire");
        assert_eq!(after.index, 0);
        // Obligation 3: the frame reports the size it was configured at, and a
        // reconfigure shows up in it immediately.
        assert_eq!(after.extent, (640, 400));
        // A reconfigure reissues the images *and* their views, so anything held
        // across it is dead — the generational handle turning a stale reference
        // into a clean failure rather than an alias. `crcbl-vk` must do the
        // same, and this is the cheap place to find out that a caller cached
        // one.
        assert_ne!(after.image, first.image);
        assert_ne!(after.view, first.view);
        assert!(
            device
                .create_image_view(&ImageViewDesc {
                    label: None,
                    image: first.image,
                    view_type: ImageViewType::D2,
                    format,
                    range: ImageSubresourceRange::all(format),
                })
                .is_err(),
            "an image handle must not survive a reconfigure"
        );

        device.destroy_swapchain(swapchain);
        instance.destroy_surface(surface);
    }
}

/// Regression test. `reconfigure_swapchain` used to replace only the images and
/// their views, leaving the acquire/present semaphore vectors at their original
/// length — so growing the image count and acquiring past the old length
/// indexed off the end of them and panicked. The four vectors are one
/// invariant; `build_ring` is what keeps them so.
#[test]
fn reconfiguring_to_a_larger_ring_reissues_the_semaphores_too() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    // SAFETY: an offscreen target holds no platform pointers.
    let surface = unsafe { instance.create_surface(&SurfaceTarget::Offscreen) }.expect("surface");
    let desc = SwapchainDesc {
        label: None,
        surface,
        format: Format::Bgra8UnormSrgb,
        extent: (8, 8),
        image_count: 2,
        present_mode: PresentMode::Fifo,
        composite_alpha: CompositeAlpha::Opaque,
    };
    let swapchain = device.create_swapchain(&desc).expect("swapchain");
    device
        .reconfigure_swapchain(
            swapchain,
            &SwapchainDesc {
                image_count: 3,
                ..desc
            },
        )
        .expect("reconfigure");

    // The third acquire is the one that used to panic.
    for expected in 0..3 {
        let frame = device.acquire_next_frame(swapchain).expect("acquire");
        assert_eq!(frame.index, expected);
        assert!(
            frame.acquire_semaphore.is_some() && frame.present_semaphore.is_some(),
            "a semaphore-carrying ring has a pair per slot, for every slot"
        );
    }

    device.destroy_swapchain(swapchain);
    instance.destroy_surface(surface);
}

/// The seam's answer for a device that cannot observe presents: the wait is
/// answered rather than refused, it still resolves what it was given, and not
/// even an injected timeout makes it refuse.
///
/// All three halves matter. A refusal would put a branch on every frame of
/// every caller for a condition that cannot change after device creation, and
/// the caller that skipped the branch would turn a missing capability into a
/// failed frame. Answering it without looking at the handle would let a wait on
/// a destroyed swapchain — a real ordering bug in a frame loop — pass unnoticed
/// on the one backend whose whole job is noticing. And
/// [`Recorder::report_present_wait_timeouts`] must not reach past the
/// capability: a device that cannot observe presents cannot observe one being
/// late either, so the report stays owed until a device that claims
/// [`Features::PRESENT_FEEDBACK`] takes it — which is what the second device
/// below is for, and what proves the first one refrained rather than having
/// nothing to refrain from.
#[test]
fn a_present_wait_is_answered_not_refused_and_still_checks_its_swapchain() {
    let instance = NullInstance::gpu_driven();
    let recorder = instance.recorder();
    let device = open(&instance);
    assert!(
        !device.caps().features.contains(Features::PRESENT_FEEDBACK),
        "there is no display under this backend, so it must not claim to see one"
    );
    // SAFETY: an offscreen target holds no platform pointers.
    let surface = unsafe { instance.create_surface(&SurfaceTarget::Offscreen) }.expect("surface");
    let swapchain = device
        .create_swapchain(&SwapchainDesc {
            label: None,
            surface,
            format: Format::Bgra8UnormSrgb,
            extent: (8, 8),
            image_count: 2,
            present_mode: PresentMode::Fifo,
            composite_alpha: CompositeAlpha::Opaque,
        })
        .expect("swapchain");

    device
        .wait_until_presented(swapchain, 7, Duration::from_secs(30))
        .expect("a device without the capability answers, it does not refuse");
    assert!(
        recorder.events().contains(&Event::PresentWaited {
            swapchain,
            present_id: 7,
            timed_out: false,
        }),
        "the request is what a test of a caller's pacing reads, so it is recorded"
    );

    // Nor can a timeout be injected onto a device that cannot observe presents:
    // the seam's `Ok` is unconditional there, so the injection is left owed
    // rather than spent by a device that had no business honouring it.
    recorder.report_present_wait_timeouts(1);
    device
        .wait_until_presented(swapchain, 7, Duration::from_secs(30))
        .expect("still no capability, so still no refusal to make");
    let capable = NullInstance::gpu_driven()
        .with_present_feedback()
        .with_recorder(recorder.clone());
    let paced = open(&capable);
    assert!(
        paced.caps().features.contains(Features::PRESENT_FEEDBACK),
        "the builder is what makes the injection above reachable at all"
    );
    // SAFETY: an offscreen target holds no platform pointers.
    let other_surface =
        unsafe { capable.create_surface(&SurfaceTarget::Offscreen) }.expect("surface");
    let other_swapchain = paced
        .create_swapchain(&SwapchainDesc {
            label: None,
            surface: other_surface,
            format: Format::Bgra8UnormSrgb,
            extent: (8, 8),
            image_count: 2,
            present_mode: PresentMode::Fifo,
            composite_alpha: CompositeAlpha::Opaque,
        })
        .expect("swapchain");
    let lapsed = paced
        .wait_until_presented(other_swapchain, 7, Duration::from_secs(30))
        .expect_err("the report was still owed, so the first device that can honour it does");
    assert!(matches!(lapsed, SurfaceError::Timeout), "{lapsed}");
    paced.destroy_swapchain(other_swapchain);
    capable.destroy_surface(other_surface);

    device.destroy_swapchain(swapchain);
    let error = device
        .wait_until_presented(swapchain, 8, Duration::from_secs(30))
        .expect_err("the swapchain is gone");
    assert!(
        matches!(error, SurfaceError::Hal(HalError::InvalidHandle { .. })),
        "{error}"
    );
    instance.destroy_surface(surface);
}

/// **An instance can report a list of adapters, and every id in it works.**
///
/// One adapter is the default and stays the default, because it is what every
/// other test in this workspace has been written against. What matters here is
/// that the list is not the only shape: `crcbl/src/engine.rs` walks it, and a
/// walk over one element has one outcome.
///
/// The ids and the *names* are both asserted, and the names are not decoration:
/// the engine logs the adapter it took, and a list whose entries all read "null
/// adapter" would leave that line unable to say which one that was.
#[test]
fn an_instance_reports_the_adapters_it_was_built_with() {
    let one = NullInstance::gpu_driven();
    let listed = one.adapters();
    assert_eq!(listed.len(), 1, "one adapter is still the default");
    assert_eq!(listed[0].id, AdapterId(0));
    assert_eq!(
        listed[0].name, "null adapter",
        "a lone adapter keeps the preset's plain name"
    );

    let many = NullInstance::gpu_driven().with_adapters(3);
    let listed = many.adapters();
    assert_eq!(
        listed.iter().map(|adapter| adapter.id).collect::<Vec<_>>(),
        vec![AdapterId(0), AdapterId(1), AdapterId(2)],
        "the ids are the indices, which is what `AdapterId` means"
    );
    assert_eq!(
        listed
            .iter()
            .map(|adapter| &*adapter.name)
            .collect::<Vec<_>>(),
        vec!["null adapter #0", "null adapter #1", "null adapter #2"],
        "distinguishable, or the engine's adapter line names nothing"
    );

    // SAFETY: an offscreen target holds no platform pointers.
    let surface = unsafe { many.create_surface(&SurfaceTarget::Offscreen) }.expect("surface");
    for adapter in &listed {
        many.surface_caps(surface, adapter.id)
            .unwrap_or_else(|error| panic!("{:?} serves this surface: {error}", adapter.name));
        many.create_device(&DeviceDesc::for_adapter(adapter.id))
            .unwrap_or_else(|error| panic!("{:?} opens a device: {error}", adapter.name));
    }
    // One past the end is still no adapter at all, on both calls.
    let past = AdapterId(3);
    assert!(
        matches!(
            many.surface_caps(surface, past),
            Err(HalError::NoSuchAdapter(3))
        ),
        "an id off the end of the list must not resolve"
    );
    assert!(matches!(
        many.create_device(&DeviceDesc::for_adapter(past)),
        Err(HalError::NoSuchAdapter(3))
    ));
    many.destroy_surface(surface);

    assert!(
        NullInstance::gpu_driven()
            .with_adapters(0)
            .adapters()
            .is_empty(),
        "a machine with no GPU is a real state, and the engine has an answer for it"
    );
}

/// **A refused adapter never serves a surface, and its neighbours are
/// untouched.**
///
/// The injection `crcbl/src/engine.rs`'s adapter walk exists for: an `Err` from
/// [`Instance::surface_caps`] means "not this one", so the engine's loop is
/// only a loop if some adapter can say it and some other adapter can still say
/// `Ok`. Both halves are asserted here, and the baseline before the injection
/// too — without it a `refuse_surface_on` that did nothing at all would be
/// indistinguishable from one that refused everything, since the assertion
/// below would be reading an adapter that never worked.
///
/// The latch is the third half: [`Recorder::refuse_surface_on`] is permanent by
/// design, so the second ask gets the same answer as the first. A counted
/// refusal would be spent by start-up's own walk and let the rejected adapter
/// answer the engine's next question — the resize-time `surface_caps` — as if
/// it had been serving all along.
#[test]
fn a_refused_adapter_never_serves_a_surface_while_its_neighbours_do() {
    let instance = NullInstance::gpu_driven().with_adapters(2);
    let recorder = instance.recorder();
    // SAFETY: an offscreen target holds no platform pointers.
    let surface = unsafe { instance.create_surface(&SurfaceTarget::Offscreen) }.expect("surface");
    for id in [AdapterId(0), AdapterId(1)] {
        assert!(
            instance.surface_caps(surface, id).is_ok(),
            "the baseline: both adapters serve before anything is injected"
        );
    }

    recorder.refuse_surface_on(AdapterId(0));
    let refused = instance
        .surface_caps(surface, AdapterId(0))
        .expect_err("the refused adapter has no path to this surface");
    assert!(
        matches!(
            refused,
            HalError::Unsupported {
                backend: BackendKind::Null,
                ..
            }
        ),
        "the variant `crcbl-vk` refuses with, so the engine's arm sees the real shape: {refused}"
    );
    assert!(
        instance
            .surface_caps(surface, AdapterId(0))
            .is_err_and(|error| matches!(error, HalError::Unsupported { .. })),
        "latched: asking again does not clear it"
    );

    let served = instance
        .surface_caps(surface, AdapterId(1))
        .expect("the refusal is keyed to an adapter, not to the instance");
    assert!(
        served.preferred_format().is_some(),
        "a serving adapter offers a format, which is what makes the engine take it"
    );

    // Only `surface_caps` refuses. Documented on the injector, and asserted so
    // that widening it later is a decision rather than an accident.
    instance
        .create_device(&DeviceDesc::for_adapter(AdapterId(0)))
        .expect("a device from a refused adapter still opens");
    instance.destroy_surface(surface);
}

/// The out-of-date injection, from the seam's side: while the latch is set,
/// A present needs a frame to present, on the backend whose whole purpose is to
/// model the seam's rules with no driver in the room.
///
/// This was the last of those rules the null backend could not state: it kept a
/// ring cursor but no record of the outstanding acquire, so it had nothing to
/// refuse a present against, while `crcbl-vk`, `crcbl-mtl` and `crcbl-dx12` had
/// each been answering "present without a matching `acquire_next_frame`" all
/// along. `a_present_without_an_acquire_is_refused` in
/// `crates/crcbl/tests/hal_seam_e2e.rs` is the same assertions against a real
/// device; this is the half that needs no ICD.
///
/// The reconfigure arm is the one with teeth. A reconfigure reissues the whole
/// ring, so an index acquired before it points into images that no longer
/// exist — presenting it is a use-after-free rather than a stale number.
#[test]
fn a_present_without_a_matching_acquire_is_refused() {
    let instance = NullInstance::gpu_driven();
    let recorder = instance.recorder();
    let device = open(&instance);
    let queue = device
        .queue(QueueKind::Graphics)
        .expect("every device has a graphics queue");
    // SAFETY: an offscreen target holds no platform pointers.
    let surface = unsafe { instance.create_surface(&SurfaceTarget::Offscreen) }.expect("surface");
    let desc = |extent| SwapchainDesc {
        label: None,
        surface,
        format: Format::Bgra8UnormSrgb,
        extent,
        image_count: 2,
        present_mode: PresentMode::Fifo,
        composite_alpha: CompositeAlpha::Opaque,
    };
    let swapchain = device.create_swapchain(&desc((8, 8))).expect("swapchain");
    let present_now = || {
        device.present(
            queue,
            &PresentInfo {
                swapchain,
                waits: &[],
                present_id: None,
            },
        )
    };
    let refused = |error: SurfaceError, case: &str| {
        let SurfaceError::Hal(HalError::InvalidDescriptor(message)) = error else {
            panic!("{case} was refused as the wrong kind of error: {error}");
        };
        assert!(
            message.contains("without a matching acquire_next_frame"),
            "{case}: {message}"
        );
    };

    recorder.clear();
    refused(
        present_now().expect_err("nothing has been acquired yet"),
        "a present before any acquire",
    );
    assert_eq!(
        recorder.events().len(),
        0,
        "a refused present must record nothing: {:?}",
        recorder.events()
    );

    // Acquired, so it goes through — a backend that refused every present would
    // satisfy the assertion above and fail this one.
    device.acquire_next_frame(swapchain).expect("acquire");
    present_now().expect("an acquired frame is one to present");

    // The present took the slot, so the same frame cannot go twice.
    refused(
        present_now().expect_err("that frame has already been presented"),
        "a second present of the same frame",
    );

    // And a reconfigure reissues the ring the index pointed into.
    device.acquire_next_frame(swapchain).expect("acquire");
    device
        .reconfigure_swapchain(swapchain, &desc((16, 16)))
        .expect("reconfigure");
    refused(
        present_now().expect_err("the reconfigure destroyed the frame that was acquired"),
        "a present across a reconfigure",
    );

    device.destroy_swapchain(swapchain);
    instance.destroy_surface(surface);
}

/// **all three** of the calls a frame makes on a swapchain report
/// [`SurfaceError::OutOfDate`], and only a reconfigure that actually rebuilt
/// something clears it.
///
/// All three, because a resize does not pick one: a frame loop that handles it
/// at acquire and not at present — or the reverse — works on the driver it was
/// written against and stalls on the next one. And a *failed* reconfigure must
/// not clear it, or a caller whose rebuild ran out of memory would go straight
/// back to presenting against a swapchain the surface has outgrown.
#[test]
fn an_out_of_date_swapchain_fails_every_presentation_call_until_a_reconfigure_clears_it() {
    let instance = NullInstance::gpu_driven();
    let recorder = instance.recorder();
    let device = open(&instance);
    let queue = device
        .queue(QueueKind::Graphics)
        .expect("every device has a graphics queue");
    // SAFETY: an offscreen target holds no platform pointers.
    let surface = unsafe { instance.create_surface(&SurfaceTarget::Offscreen) }.expect("surface");
    let desc = SwapchainDesc {
        label: None,
        surface,
        format: Format::Bgra8UnormSrgb,
        extent: (8, 8),
        image_count: 2,
        present_mode: PresentMode::Fifo,
        composite_alpha: CompositeAlpha::Opaque,
    };
    let swapchain = device.create_swapchain(&desc).expect("swapchain");

    // The control: a swapchain nobody has resized answers all three.
    let frame = device.acquire_next_frame(swapchain).expect("acquire");
    device
        .present(
            queue,
            &PresentInfo {
                swapchain,
                waits: frame.present_semaphore.as_slice(),
                present_id: Some(1),
            },
        )
        .expect("present");
    device
        .wait_until_presented(swapchain, 1, Duration::from_secs(30))
        .expect("wait");

    recorder.clear();
    recorder.report_swapchain_out_of_date();

    let acquire = device
        .acquire_next_frame(swapchain)
        .expect_err("the surface moved under the swapchain");
    assert!(matches!(acquire, SurfaceError::OutOfDate), "{acquire}");
    let present = device
        .present(
            queue,
            &PresentInfo {
                swapchain,
                waits: frame.present_semaphore.as_slice(),
                present_id: Some(2),
            },
        )
        .expect_err("and present is where a resize is usually noticed");
    assert!(matches!(present, SurfaceError::OutOfDate), "{present}");
    let wait = device
        .wait_until_presented(swapchain, 1, Duration::from_secs(30))
        .expect_err("and the pacing wait cannot wait for a frame that will not land");
    assert!(matches!(wait, SurfaceError::OutOfDate), "{wait}");
    assert_eq!(
        recorder.events().len(),
        0,
        "a refused presentation call must record nothing: {:?}",
        recorder.events()
    );

    // The handle is still resolved first, so a swapchain the caller destroyed
    // reports the caller's own bug rather than the resize sitting on top of it.
    let doomed = device.create_swapchain(&desc).expect("swapchain");
    device.destroy_swapchain(doomed);
    let dead = device
        .acquire_next_frame(doomed)
        .expect_err("a destroyed swapchain hands out nothing");
    assert!(
        matches!(dead, SurfaceError::Hal(HalError::InvalidHandle { .. })),
        "an out-of-date latch must not mask a stale handle: {dead}"
    );

    // A reconfigure that failed rebuilt nothing, so it clears nothing.
    recorder.fail_next_reconfigures(1);
    device
        .reconfigure_swapchain(swapchain, &desc)
        .expect_err("the injected fault");
    let still = device
        .acquire_next_frame(swapchain)
        .expect_err("a rebuild that did not happen has not fixed anything");
    assert!(matches!(still, SurfaceError::OutOfDate), "{still}");

    // One that succeeded does.
    device
        .reconfigure_swapchain(swapchain, &desc)
        .expect("reconfigure");
    device
        .acquire_next_frame(swapchain)
        .expect("the rebuilt swapchain matches the surface again");

    device.destroy_swapchain(swapchain);
    instance.destroy_surface(surface);
}

/// The suboptimal injection, from the seam's side: it reaches
/// [`AcquiredFrame::suboptimal`], every presentation call keeps working while it
/// is owed, and **it runs out**.
///
/// Running out is the half that had to be decided rather than copied. Its
/// sibling [`Recorder::report_swapchain_out_of_date`] latches, because a
/// driver's out-of-date swapchain stays out of date until something rebuilds it
/// and a caller that ignores it has to keep being told. A latch here would
/// behave the other way round: the engine answers a suboptimal frame by
/// reconfiguring, so a latch would have a driven loop rebuild on every frame it
/// ever ran, and a test of that loop would hang instead of failing. A count
/// cannot do that.
#[test]
fn a_suboptimal_acquire_is_counted_out_and_presents_all_the_same() {
    let instance = NullInstance::gpu_driven();
    let recorder = instance.recorder();
    let device = open(&instance);
    let queue = device
        .queue(QueueKind::Graphics)
        .expect("every device has a graphics queue");
    // SAFETY: an offscreen target holds no platform pointers.
    let surface = unsafe { instance.create_surface(&SurfaceTarget::Offscreen) }.expect("surface");
    let desc = SwapchainDesc {
        label: None,
        surface,
        format: Format::Bgra8UnormSrgb,
        extent: (8, 8),
        image_count: 2,
        present_mode: PresentMode::Fifo,
        composite_alpha: CompositeAlpha::Opaque,
    };
    let swapchain = device.create_swapchain(&desc).expect("swapchain");

    // The control: nothing has moved under this swapchain.
    assert!(
        !device
            .acquire_next_frame(swapchain)
            .expect("acquire")
            .suboptimal,
        "a swapchain nobody has disturbed still matches its surface"
    );

    const OWED: u32 = 2;
    recorder.report_suboptimal_acquires(OWED);
    for spent in 0..OWED {
        let frame = device
            .acquire_next_frame(swapchain)
            .expect("a suboptimal swapchain hands out frames; it does not refuse them");
        assert!(frame.suboptimal, "acquire {spent} of the {OWED} injected");
        let present_id = u64::from(spent) + 1;
        device
            .present(
                queue,
                &PresentInfo {
                    swapchain,
                    waits: frame.present_semaphore.as_slice(),
                    present_id: Some(present_id),
                },
            )
            .expect("and presents them, which is the whole difference from out of date");
        device
            .wait_until_presented(swapchain, present_id, Duration::from_secs(30))
            .expect("a frame that reached the swapchain can be waited for");
    }

    assert!(
        !device
            .acquire_next_frame(swapchain)
            .expect("acquire")
            .suboptimal,
        "the injection is spent; a report that did not run out would reconfigure forever"
    );

    // A refused acquire spends none of it: the out-of-date latch answers before
    // the count is read, so what a caller is owed outlives the resize it is
    // about to handle rather than being eaten by it.
    recorder.report_suboptimal_acquires(1);
    recorder.report_swapchain_out_of_date();
    let refused = device
        .acquire_next_frame(swapchain)
        .expect_err("the surface moved under the swapchain");
    assert!(matches!(refused, SurfaceError::OutOfDate), "{refused}");
    device
        .reconfigure_swapchain(swapchain, &desc)
        .expect("reconfigure");
    assert!(
        device
            .acquire_next_frame(swapchain)
            .expect("acquire")
            .suboptimal,
        "the refused acquire consumed nothing"
    );

    device.destroy_swapchain(swapchain);
    instance.destroy_surface(surface);
}

/// The present-wait timeout, from the seam's side: a device that claims
/// [`Features::PRESENT_FEEDBACK`] can be made to let a wait lapse, the frame it
/// was waiting on is still there to be acquired and presented, and **it runs
/// out**.
///
/// The capability is half the mechanism. `wait_until_presented` has two legal
/// answers and the flag is what picks between them, so a null device that never
/// claimed the flag could only ever give the immediate one — which is why the
/// timeout arm of every frame loop in this workspace was unreachable until
/// [`NullInstance::with_present_feedback`] existed.
/// [`a_present_wait_is_answered_not_refused_and_still_checks_its_swapchain`]
/// covers the other side, that the flag is load-bearing rather than decorative:
/// the same injection reaches nothing on a device that does not claim it.
///
/// Running out rather than latching is the decision this injector owed. A latch
/// would not spin the way a latched suboptimal report would — the caller's
/// answer to a timeout is to render the frame anyway, so nothing rebuilds and
/// nothing retries — but nothing would clear it either: a resize is cleared by
/// the rebuild that answers it, and no caller has an action that makes a
/// stalled compositor catch up. The seam calls a timeout expected traffic that
/// the next wait catches up from, so the recovery is part of the behaviour, and
/// only a count lets a test watch it happen.
#[test]
fn a_present_wait_times_out_while_it_is_owed_and_is_counted_out() {
    let instance = NullInstance::gpu_driven().with_present_feedback();
    let recorder = instance.recorder();
    let device = open(&instance);
    assert!(
        device.caps().features.contains(Features::PRESENT_FEEDBACK),
        "the injection below reaches nothing on a device that cannot observe presents"
    );
    let queue = device
        .queue(QueueKind::Graphics)
        .expect("every device has a graphics queue");
    // SAFETY: an offscreen target holds no platform pointers.
    let surface = unsafe { instance.create_surface(&SurfaceTarget::Offscreen) }.expect("surface");
    let desc = SwapchainDesc {
        label: None,
        surface,
        format: Format::Bgra8UnormSrgb,
        extent: (8, 8),
        image_count: 2,
        present_mode: PresentMode::Fifo,
        composite_alpha: CompositeAlpha::Opaque,
    };
    let swapchain = device.create_swapchain(&desc).expect("swapchain");

    // The control: nothing has been injected, so the capable device answers
    // exactly as the featureless one did.
    device
        .wait_until_presented(swapchain, 1, Duration::from_secs(30))
        .expect("a wait nobody delayed is answered at once");
    assert_eq!(
        recorder.events().last(),
        Some(&Event::PresentWaited {
            swapchain,
            present_id: 1,
            timed_out: false,
        }),
        "and is recorded as answered, which is what the injected ones are read against"
    );

    const OWED: u32 = 2;
    recorder.report_present_wait_timeouts(OWED);
    for spent in 0..OWED {
        let present_id = u64::from(spent) + 1;
        let lapsed = device
            .wait_until_presented(swapchain, present_id, Duration::from_secs(30))
            .expect_err("a timeout is still owed, so this wait must lapse");
        assert!(
            matches!(lapsed, SurfaceError::Timeout),
            "wait {spent} of the {OWED} injected: {lapsed}"
        );
        assert_eq!(
            recorder.events().last(),
            Some(&Event::PresentWaited {
                swapchain,
                present_id,
                timed_out: true,
            }),
            "the refusal is recorded beside the request, or a caller that renders \
             the frame anyway leaves a stream indistinguishable from never waiting"
        );

        // And the swapchain is untouched by it: a compositor that is behind has
        // not taken the frame loop's images away, which is the whole reason the
        // seam says to render anyway rather than to skip or to fail.
        let frame = device
            .acquire_next_frame(swapchain)
            .expect("a late display is not a swapchain that refuses images");
        device
            .present(
                queue,
                &PresentInfo {
                    swapchain,
                    waits: frame.present_semaphore.as_slice(),
                    present_id: Some(present_id),
                },
            )
            .expect("nor one that refuses presents");
    }

    device
        .wait_until_presented(swapchain, 2, Duration::from_secs(30))
        .expect("the injection is spent, so the next wait catches up");

    // A refused wait spends none of it: the out-of-date latch answers before the
    // count is read, so what a caller is owed outlives the resize rather than
    // being eaten by it — and the refused wait records nothing at all.
    recorder.report_present_wait_timeouts(1);
    recorder.report_swapchain_out_of_date();
    let events = recorder.events().len();
    let refused = device
        .wait_until_presented(swapchain, 2, Duration::from_secs(30))
        .expect_err("the surface moved under the swapchain");
    assert!(matches!(refused, SurfaceError::OutOfDate), "{refused}");
    assert_eq!(
        recorder.events().len(),
        events,
        "a wait that was never answered is not a wait that happened"
    );
    device
        .reconfigure_swapchain(swapchain, &desc)
        .expect("reconfigure");
    let lapsed = device
        .wait_until_presented(swapchain, 2, Duration::from_secs(30))
        .expect_err("the refused wait consumed nothing");
    assert!(matches!(lapsed, SurfaceError::Timeout), "{lapsed}");

    device.destroy_swapchain(swapchain);
    instance.destroy_surface(surface);
}

/// The device-loss injection, from the seam's side: it reaches every call that
/// can report it, it does not wear off, and it is not the out-of-band error
/// channel wearing a different hat.
///
/// The last two are the point. `report_device_error` is one-shot and
/// recoverable by contract — `crcbl/src/engine.rs` asserts that taking the error
/// clears it — so a hook that latched *there* would have broken the caller it
/// was meant to leave alone. These are two states with two lifetimes, and the
/// assertions below are what keep them apart.
#[test]
fn a_lost_device_reports_it_from_every_call_that_can_and_never_recovers() {
    let instance = NullInstance::gpu_driven();
    let recorder = instance.recorder();
    let device = open(&instance);
    let queue = device
        .queue(QueueKind::Graphics)
        .expect("every device has a graphics queue");
    // SAFETY: an offscreen target holds no platform pointers.
    let surface = unsafe { instance.create_surface(&SurfaceTarget::Offscreen) }.expect("surface");
    let swapchain = device
        .create_swapchain(&SwapchainDesc {
            label: None,
            surface,
            format: Format::Bgra8UnormSrgb,
            extent: (8, 8),
            image_count: 2,
            present_mode: PresentMode::Fifo,
            composite_alpha: CompositeAlpha::Opaque,
        })
        .expect("swapchain");
    let buffer = device
        .create_buffer(&BufferDesc {
            label: Some("uploads"),
            size: 64,
            usage: BufferUsage::STORAGE,
            memory: MemoryLocation::HostUpload,
        })
        .expect("create");
    let encoder = device.create_command_encoder(&CommandEncoderDesc { label: None, queue });
    let command_buffer = encoder.finish().expect("an empty command buffer");

    recorder.lose_device("gpu hang: the driver reset the adapter");

    // A handle-taking call, a queue-taking call, the one that takes neither,
    // and a presentation call — the four shapes a caller has.
    let write = device
        .write_buffer(buffer, 0, &[1u8; 4])
        .expect_err("the device is gone");
    let submit = device
        .submit(
            queue,
            &SubmitInfo {
                command_buffers: &[command_buffer],
                waits: &[],
                signals: &[],
            },
        )
        .expect_err("the device is gone");
    let idle = device.wait_idle().expect_err("the device is gone");
    let acquire = device
        .acquire_next_frame(swapchain)
        .expect_err("the device is gone");
    for error in [write, submit, idle] {
        assert!(
            matches!(&error, HalError::DeviceLost(message) if message.contains("gpu hang")),
            "the driver's own words have to survive to the caller: {error}"
        );
    }
    assert!(
        matches!(
            &acquire,
            SurfaceError::Hal(HalError::DeviceLost(message)) if message.contains("gpu hang")
        ),
        "a presentation call reports it in the presentation vocabulary, as `crcbl-vk` does: \
         {acquire}"
    );

    // A queue call naming no work at all still reports it. `vkQueueSubmit` with
    // an empty batch is still a queue operation, and a dead queue cannot
    // perform one — this is the only call whose sole gate is the queue's.
    let bare = device
        .submit(
            queue,
            &SubmitInfo {
                command_buffers: &[],
                waits: &[],
                signals: &[],
            },
        )
        .expect_err("the device is gone");
    assert!(
        matches!(&bare, HalError::DeviceLost(message) if message.contains("gpu hang")),
        "{bare}"
    );

    // It stays lost. `report_device_error` is the one that clears when taken;
    // this is the one that cannot be waited out.
    for attempt in 0..4 {
        assert!(
            device.wait_idle().is_err(),
            "attempt {attempt} succeeded on a device that is gone for good"
        );
    }

    // And it is not the out-of-band channel: nothing was queued there, so a
    // caller draining it hears nothing and learns of the loss from its next
    // real call, which is where a driver puts it.
    assert!(
        device.take_error().is_none(),
        "device loss must not be delivered as a recoverable out-of-band error"
    );

    // Teardown still works, as it does on a real driver: a caller holding
    // objects when the device died must be able to release them.
    let live = recorder.total_live_objects();
    device.destroy_buffer(buffer);
    device.destroy_command_buffer(command_buffer);
    device.destroy_swapchain(swapchain);
    instance.destroy_surface(surface);
    assert!(
        recorder.total_live_objects() < live,
        "a lost device that refuses to let go of its objects leaks every one of them"
    );
}

/// Regression test. `reconfigure_swapchain` used to destroy the old ring before
/// building the new one, so a reconfigure that *failed* left the swapchain
/// naming destroyed images and views — a call that returned `Err` having broken
/// the object it was handed. The seam's promise is that a frame's image and
/// view are usable; a failed call must not be able to break it.
#[test]
fn a_failed_reconfigure_leaves_the_swapchain_usable() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    // SAFETY: an offscreen target holds no platform pointers.
    let surface = unsafe { instance.create_surface(&SurfaceTarget::Offscreen) }.expect("surface");
    let desc = SwapchainDesc {
        label: None,
        surface,
        format: Format::Bgra8UnormSrgb,
        extent: (8, 8),
        image_count: 2,
        present_mode: PresentMode::Fifo,
        composite_alpha: CompositeAlpha::Opaque,
    };
    let swapchain = device.create_swapchain(&desc).expect("swapchain");
    let before = device.acquire_next_frame(swapchain).expect("acquire");

    // Past `max_image_2d`, so the ring cannot be built.
    let limit = device.caps().limits.max_image_2d;
    device
        .reconfigure_swapchain(
            swapchain,
            &SwapchainDesc {
                extent: (limit + 1, limit + 1),
                ..desc
            },
        )
        .expect_err("an oversized extent cannot be configured");

    // The old ring is untouched. The handle `before` named is still alive —
    // which is the whole property: the failed call destroyed nothing.
    let probe = device
        .create_image_view(&ImageViewDesc {
            label: None,
            image: before.image,
            view_type: ImageViewType::D2,
            format: Format::Bgra8UnormSrgb,
            range: ImageSubresourceRange::all(Format::Bgra8UnormSrgb),
        })
        .expect("the image the earlier frame named must still exist");
    device.destroy_image_view(probe);

    // And the ring still comes round to exactly the slot it did before, with
    // the same handles and the same extent, rather than to a reissued one.
    let mut wrapped = device.acquire_next_frame(swapchain).expect("acquire");
    while wrapped.index != before.index {
        wrapped = device.acquire_next_frame(swapchain).expect("acquire");
    }
    assert_eq!(
        (wrapped.image, wrapped.view, wrapped.extent),
        (before.image, before.view, before.extent),
        "a failed reconfigure must change nothing"
    );

    device.destroy_swapchain(swapchain);
    instance.destroy_surface(surface);
}

#[test]
fn destroying_a_swapchain_releases_its_images_and_semaphores() {
    let instance = NullInstance::gpu_driven();
    let recorder = instance.recorder();
    let device = open(&instance);
    // SAFETY: an offscreen target holds no platform pointers.
    let surface = unsafe { instance.create_surface(&SurfaceTarget::Offscreen) }.expect("surface");
    let before_images = recorder.live_objects(ObjectKind::Image);
    let before_views = recorder.live_objects(ObjectKind::ImageView);
    let before_semaphores = recorder.live_objects(ObjectKind::Semaphore);

    let swapchain = device
        .create_swapchain(&SwapchainDesc {
            label: None,
            surface,
            format: Format::Bgra8UnormSrgb,
            extent: (8, 8),
            image_count: 2,
            present_mode: PresentMode::Fifo,
            composite_alpha: CompositeAlpha::Opaque,
        })
        .expect("swapchain");
    assert_eq!(recorder.live_objects(ObjectKind::Image), before_images + 2);
    assert_eq!(
        recorder.live_objects(ObjectKind::ImageView),
        before_views + 2,
        "the swapchain owns a view per image, handed out on AcquiredFrame"
    );
    assert_eq!(
        recorder.live_objects(ObjectKind::Semaphore),
        before_semaphores + 4,
        "two images, each with an acquire and a present semaphore"
    );

    device.destroy_swapchain(swapchain);
    instance.destroy_surface(surface);
    assert_eq!(recorder.live_objects(ObjectKind::Image), before_images);
    assert_eq!(recorder.live_objects(ObjectKind::ImageView), before_views);
    assert_eq!(
        recorder.live_objects(ObjectKind::Semaphore),
        before_semaphores
    );
    assert_eq!(recorder.total_live_objects(), 0, "nothing leaked");
}

#[test]
fn a_swapchain_needs_a_live_surface_and_a_real_extent() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    // SAFETY: an offscreen target holds no platform pointers.
    let surface = unsafe { instance.create_surface(&SurfaceTarget::Offscreen) }.expect("surface");
    let desc = SwapchainDesc {
        label: None,
        surface,
        format: Format::Bgra8UnormSrgb,
        extent: (0, 8),
        image_count: 2,
        present_mode: PresentMode::Fifo,
        composite_alpha: CompositeAlpha::Opaque,
    };
    assert!(device.create_swapchain(&desc).is_err(), "zero extent");

    instance.destroy_surface(surface);
    let desc = SwapchainDesc {
        extent: (8, 8),
        ..desc
    };
    let error = device.create_swapchain(&desc).expect_err("dead surface");
    assert!(
        matches!(error, SurfaceError::Hal(HalError::InvalidHandle { .. })),
        "{error:?}"
    );
}

/// Scope violations are recorded, not panicked on, so one run reports every
/// problem in a frame instead of only the first.
#[test]
fn scope_violations_are_recorded() {
    let (recorder, instance) = boxed(NullInstance::gpu_driven());
    let device = open(instance.as_ref());
    let queue = device.queue(QueueKind::Graphics).expect("queue");

    let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
        label: Some("bad frame"),
        queue,
    });
    // A draw with no render pass open.
    encoder.draw(0..3, 0..1);
    // A dispatch with no compute pass open.
    encoder.dispatch(1, 1, 1);
    // Closing a pass that was never opened.
    encoder.end_render_pass();
    // A pass left open at finish.
    encoder.begin_compute_pass(&ComputePassDesc {
        label: Some("cull"),
        timestamp_writes: None,
    });
    // A copy inside a pass.
    encoder.clear_buffer(
        crcbl_core::Handle::from_bits(1 << 32).expect("non-zero generation"),
        0,
        4,
    );
    // An unclosed pass is the one violation that is *also* an `Err`: the seam's
    // `finish` doc names it and `crcbl-vk` returns one, because
    // `vkEndCommandBuffer` inside a rendering scope is itself illegal. Every
    // other violation above is recorded and carried past.
    let error = encoder
        .finish()
        .expect_err("a pass left open must fail the finish, not just be recorded");
    assert!(
        error.to_string().contains("still open"),
        "{error}: the error must name the unclosed pass"
    );

    let errors = recorder.validation_errors();
    assert!(
        errors.iter().any(|error| matches!(
            error,
            ValidationError::OutsidePass {
                command: "Draw",
                ..
            }
        )),
        "{errors:?}"
    );
    assert!(
        errors.iter().any(|error| matches!(
            error,
            ValidationError::OutsidePass {
                command: "Dispatch",
                ..
            }
        )),
        "{errors:?}"
    );
    assert!(
        errors
            .iter()
            .any(|error| matches!(error, ValidationError::UnopenedPass { .. })),
        "{errors:?}"
    );
    assert!(
        errors.iter().any(|error| matches!(
            error,
            ValidationError::InsidePass {
                command: "ClearBuffer"
            }
        )),
        "{errors:?}"
    );
    assert!(
        errors
            .iter()
            .any(|error| matches!(error, ValidationError::UnclosedPass)),
        "{errors:?}"
    );
    assert!(
        errors
            .iter()
            .any(|error| matches!(error, ValidationError::DeadHandle { .. })),
        "a made-up buffer handle must be caught: {errors:?}"
    );
}

#[test]
fn nested_passes_are_rejected() {
    let (recorder, instance) = boxed(NullInstance::gpu_driven());
    let device = open(instance.as_ref());
    let queue = device.queue(QueueKind::Graphics).expect("queue");
    let mut encoder = device.create_command_encoder(&CommandEncoderDesc { label: None, queue });
    encoder.begin_compute_pass(&ComputePassDesc {
        label: Some("outer"),
        timestamp_writes: None,
    });
    encoder.begin_compute_pass(&ComputePassDesc {
        label: Some("inner"),
        timestamp_writes: None,
    });
    encoder.end_compute_pass();
    let _ = encoder.finish().expect("finish");

    let errors = recorder.validation_errors();
    assert!(
        errors
            .iter()
            .any(|error| matches!(error, ValidationError::NestedPass { .. })),
        "{errors:?}"
    );
    assert_eq!(
        recorder.pass_labels(),
        vec!["outer".to_string(), "inner".to_string()],
        "both passes are still recorded — the stream is complete even when invalid"
    );
}

/// A frame recorded exactly the way topic 03 describes: cull in compute, then
/// draw indirect with a GPU-side count, then present. This is the shape the
/// render graph's own suite will assert on at P1.
#[test]
fn a_gpu_driven_frame_records_the_expected_stream() {
    /// Bytes the frame's argument buffer holds.
    ///
    /// It is also what bounds the draw's `max_draw_count` below, which is why
    /// the two are derived from one constant rather than written twice:
    /// `max_draw_count` is the ceiling on what the GPU *could* read whatever
    /// the count buffer ends up saying, so every structure it names has to be
    /// inside this. The frame used to name 4096 draws — this figure read as a
    /// count rather than a size — which is twenty times the buffer it reads
    /// from, and every byte of the overrun is somebody else's memory.
    const ARGS_BUFFER_BYTES: u64 = 1 << 12;

    let (recorder, instance) = boxed(NullInstance::gpu_driven());
    let device = open(instance.as_ref());
    let queue = device.queue(QueueKind::Graphics).expect("queue");

    // Resources.
    let instances = device
        .create_buffer(&BufferDesc {
            label: Some("instances"),
            size: 1 << 16,
            usage: crate::BufferUsage::STORAGE,
            memory: MemoryLocation::DeviceLocal,
        })
        .expect("instances");
    let draw_args = device
        .create_buffer(&BufferDesc {
            label: Some("draw args"),
            size: ARGS_BUFFER_BYTES,
            usage: crate::BufferUsage::INDIRECT | crate::BufferUsage::STORAGE,
            memory: MemoryLocation::DeviceLocal,
        })
        .expect("draw args");
    let draw_count = device
        .create_buffer(&BufferDesc {
            label: Some("draw count"),
            size: 4,
            usage: crate::BufferUsage::INDIRECT
                | crate::BufferUsage::STORAGE
                | crate::BufferUsage::TRANSFER_DST,
            memory: MemoryLocation::DeviceLocal,
        })
        .expect("draw count");
    let indices = device
        .create_buffer(&BufferDesc {
            label: Some("index pool"),
            size: 1 << 16,
            usage: crate::BufferUsage::INDEX,
            memory: MemoryLocation::DeviceLocal,
        })
        .expect("indices");

    let color = device
        .create_image(&ImageDesc {
            label: Some("hdr"),
            image_type: ImageType::D2,
            extent: crate::Extent3d::d2(1920, 1080),
            format: Format::Rgba16Float,
            mip_levels: 1,
            samples: 1,
            usage: ImageUsage::COLOR_ATTACHMENT | ImageUsage::SAMPLED,
        })
        .expect("hdr target");
    let color_view = device
        .create_image_view(&ImageViewDesc {
            label: Some("hdr view"),
            image: color,
            view_type: crate::ImageViewType::D2,
            format: Format::Rgba16Float,
            range: crate::ImageSubresourceRange::all(Format::Rgba16Float),
        })
        .expect("hdr view");
    let depth_image = device
        .create_image(&ImageDesc {
            label: Some("depth"),
            image_type: ImageType::D2,
            extent: crate::Extent3d::d2(1920, 1080),
            format: Format::D32Float,
            mip_levels: 1,
            samples: 1,
            usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT,
        })
        .expect("depth target");
    let depth_view = device
        .create_image_view(&ImageViewDesc {
            label: Some("depth view"),
            image: depth_image,
            view_type: crate::ImageViewType::D2,
            format: Format::D32Float,
            range: crate::ImageSubresourceRange::all(Format::D32Float),
        })
        .expect("depth view");

    // Pipelines.
    let module = device
        .create_shader_module(&ShaderModuleDesc {
            label: Some("frame"),
            spirv: &SPIRV,
            wgsl: None,
            msl: None,
            dxil: &[],
        })
        .expect("module");
    let set_layout = device
        .create_bind_group_layout(&BindGroupLayoutDesc {
            label: Some("frame set"),
            entries: &[BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::ALL,
                kind: BindingKind::StorageBuffer {
                    read_only: true,
                    dynamic: false,
                    stride: 4,
                },
                count: 1,
                flags: crate::BindingFlags::empty(),
            }],
        })
        .expect("set layout");
    let bind_group = device
        .create_bind_group(&BindGroupDesc {
            label: Some("frame"),
            layout: set_layout,
            entries: &[BindGroupEntry {
                binding: 0,
                array_index: 0,
                resource: crate::BindingResource::whole_buffer(instances),
            }],
            variable_count: None,
        })
        .expect("bind group");
    let pipeline_layout = device
        .create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("frame"),
            bind_group_layouts: &[set_layout],
            push_constants: None,
        })
        .expect("pipeline layout");
    let cull = device
        .create_compute_pipeline(&ComputePipelineDesc {
            label: Some("cull"),
            layout: pipeline_layout,
            compute: ShaderEntry {
                module,
                entry_point: "cull_main",
            },
            workgroup_size: [64, 1, 1],
        })
        .expect("cull pipeline");
    let opaque = device
        .create_graphics_pipeline(&GraphicsPipelineDesc {
            label: Some("opaque"),
            layout: pipeline_layout,
            vertex: ShaderEntry {
                module,
                entry_point: "vs_main",
            },
            fragment: Some(ShaderEntry {
                module,
                entry_point: "fs_main",
            }),
            primitive: PrimitiveState::default(),
            depth_stencil: Some(DepthStencilState::default()),
            multisample: MultisampleState::default(),
            color_targets: &[ColorTargetState::opaque(Format::Rgba16Float)],
        })
        .expect("opaque pipeline");

    let timers = device
        .create_query_set(&QuerySetDesc {
            label: Some("pass timers"),
            kind: QueryKind::Timestamp,
            count: 4,
        })
        .expect("timers");

    recorder.clear();

    // The frame itself.
    let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
        label: Some("frame"),
        queue,
    });
    encoder.reset_query_set(timers, 0..4);
    encoder.clear_buffer(draw_count, 0, 4);
    encoder.pipeline_barrier(&Barriers {
        buffers: &[crate::BufferBarrier::new(
            draw_count,
            ResourceState::TransferDst,
            ResourceState::ShaderReadWrite,
        )],
        images: &[],
        global: false,
    });

    encoder.begin_compute_pass(&ComputePassDesc {
        label: Some("cull"),
        timestamp_writes: Some(crate::PassTimestampWrites {
            set: timers,
            beginning_of_pass: 0,
            end_of_pass: 1,
        }),
    });
    encoder.bind_compute_pipeline(cull);
    encoder.bind_group(0, bind_group, &[], pipeline_layout);
    encoder.dispatch(64, 1, 1);
    encoder.end_compute_pass();

    encoder.pipeline_barrier(&Barriers {
        buffers: &[
            crate::BufferBarrier::new(
                draw_args,
                ResourceState::ShaderWrite,
                ResourceState::IndirectArgument,
            ),
            crate::BufferBarrier::new(
                draw_count,
                ResourceState::ShaderReadWrite,
                ResourceState::IndirectArgument,
            ),
        ],
        images: &[crate::ImageBarrier::new(
            color,
            crate::ImageSubresourceRange::all(Format::Rgba16Float),
            ResourceState::Undefined,
            ResourceState::ColorAttachment,
        )],
        global: false,
    });

    encoder.begin_render_pass(&RenderPassDesc {
        label: Some("opaque"),
        color_attachments: &[ColorAttachment {
            view: color_view,
            resolve: None,
            load: LoadOp::Clear,
            store: StoreOp::Store,
            clear: ClearValue::color([0.0, 0.0, 0.0, 1.0]),
        }],
        depth_stencil_attachment: Some(crate::DepthStencilAttachment {
            view: depth_view,
            read_only: false,
            depth_load: LoadOp::Clear,
            depth_store: StoreOp::Store,
            stencil_load: LoadOp::DontCare,
            stencil_store: StoreOp::Discard,
            clear: ClearValue::default(),
        }),
        render_area: Rect2d::from_size(1920, 1080),
        timestamp_writes: Some(crate::PassTimestampWrites {
            set: timers,
            beginning_of_pass: 2,
            end_of_pass: 3,
        }),
    });
    encoder.set_viewport(&Viewport::from_size(1920, 1080));
    encoder.set_scissor(&Rect2d::from_size(1920, 1080));
    encoder.bind_graphics_pipeline(opaque);
    encoder.bind_group(0, bind_group, &[], pipeline_layout);
    encoder.bind_index_buffer(indices, 0, IndexFormat::Uint32);
    encoder.draw_indexed_indirect_count(&DrawIndirectCount {
        args: draw_args,
        args_offset: 0,
        count_buffer: draw_count,
        count_offset: 0,
        max_draw_count: u32::try_from(ARGS_BUFFER_BYTES / crate::DRAW_INDEXED_ARGS_BYTES)
            .expect("the structures that fit the argument buffer"),
        stride: u32::try_from(crate::DRAW_INDEXED_ARGS_BYTES).expect("five words"),
    });
    encoder.end_render_pass();

    let command_buffer = encoder.finish().expect("finish");
    device
        .submit(queue, &SubmitInfo::new(&[command_buffer]))
        .expect("submit");

    recorder.assert_valid();
    assert_eq!(
        recorder.command_names(),
        vec![
            "ResetQuerySet",
            "ClearBuffer",
            "Barrier",
            "BeginComputePass",
            "BindComputePipeline",
            "BindGroup",
            "Dispatch",
            "EndComputePass",
            "Barrier",
            "BeginRenderPass",
            "SetViewport",
            "SetScissor",
            "BindGraphicsPipeline",
            "BindGroup",
            "BindIndexBuffer",
            "DrawIndexedIndirectCount",
            "EndRenderPass",
        ]
    );
    assert_eq!(
        recorder.pass_labels(),
        vec!["cull".to_string(), "opaque".to_string()],
        "cull runs before the draws that consume its output"
    );

    // The clear value that reached the backend is the reversed-Z far plane.
    let depth_clear = recorder
        .commands()
        .into_iter()
        .find_map(|command| match command {
            Command::BeginRenderPass {
                depth_stencil_attachment: Some(attachment),
                ..
            } => Some(attachment.clear.depth),
            _ => None,
        })
        .expect("the opaque pass has a depth attachment");
    assert_eq!(depth_clear, depth::CLEAR);
    assert_eq!(depth_clear, 0.0);

    let events = recorder.events();
    assert!(
        events
            .iter()
            .any(|event| matches!(event, Event::Submitted { .. })),
        "the submit must appear in the stream"
    );
    let finished_at = events
        .iter()
        .position(|event| matches!(event, Event::Finished { .. }))
        .expect("finish event");
    let submitted_at = events
        .iter()
        .position(|event| matches!(event, Event::Submitted { .. }))
        .expect("submit event");
    assert!(finished_at < submitted_at, "recording precedes submission");
}

#[test]
fn timestamp_queries_read_back_zeros_without_failing() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    let timers = device
        .create_query_set(&QuerySetDesc {
            label: None,
            kind: QueryKind::Timestamp,
            count: 2,
        })
        .expect("timers");
    let mut results = [7u64; 2];
    device.query_results(timers, 0, &mut results).expect("read");
    assert_eq!(results, [0, 0]);
    device.destroy_query_set(timers);
    assert!(
        device.query_results(timers, 0, &mut results).is_err(),
        "a destroyed query set must not resolve"
    );
}

/// **A pass's timestamp pair is checked here, because there is nowhere else
/// left to check it without a GPU.**
///
/// The seam has no free-standing timestamp call: the two queries are named by
/// the pass descriptor, so a mis-aimed pair is a malformed *descriptor* and this
/// recorder is what the render graph's unit suite catches it with. Both rules
/// are WebGPU's own — `beginningOfPassWriteIndex` and `endOfPassWriteIndex` must
/// differ, and both must be queries the set holds — and both would otherwise
/// surface as a browser validation error a frame away from the pass that caused
/// it, or on Vulkan as a pass whose two writes landed in one query and measured
/// nothing.
///
/// Recorded and carried past rather than failing the encoder, which is this
/// recorder's rule for every rule violation: one run reports the whole frame's
/// worth.
#[test]
fn a_passs_timestamp_pair_is_checked_against_the_set_it_names() {
    let (recorder, instance) = boxed(NullInstance::gpu_driven());
    let device = open(instance.as_ref());
    let queue = device.queue(QueueKind::Graphics).expect("queue");
    let timers = device
        .create_query_set(&QuerySetDesc {
            label: Some("timers"),
            kind: QueryKind::Timestamp,
            count: 4,
        })
        .expect("the gpu-driven preset has timestamp queries");

    let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
        label: Some("mis-aimed timestamps"),
        queue,
    });
    // Both ends into one query: a pass that measures nothing.
    encoder.begin_compute_pass(&ComputePassDesc {
        label: Some("coincident"),
        timestamp_writes: Some(crate::PassTimestampWrites {
            set: timers,
            beginning_of_pass: 2,
            end_of_pass: 2,
        }),
    });
    encoder.end_compute_pass();
    // And one past the end of the set.
    encoder.begin_compute_pass(&ComputePassDesc {
        label: Some("out of range"),
        timestamp_writes: Some(crate::PassTimestampWrites {
            set: timers,
            beginning_of_pass: 0,
            end_of_pass: 4,
        }),
    });
    encoder.end_compute_pass();
    // A legal pair records nothing, or the two above would pass against a
    // recorder that complained about every pair it saw.
    encoder.begin_compute_pass(&ComputePassDesc {
        label: Some("legal"),
        timestamp_writes: Some(crate::PassTimestampWrites {
            set: timers,
            beginning_of_pass: 0,
            end_of_pass: 1,
        }),
    });
    encoder.end_compute_pass();
    encoder.finish().expect("a rule violation is not a failure");

    let errors = recorder.validation_errors();
    assert_eq!(
        errors.len(),
        2,
        "exactly the two mis-aimed pairs, and nothing for the legal one: {errors:?}"
    );
    assert!(
        errors.iter().any(|error| matches!(
            error,
            ValidationError::CoincidentTimestamps {
                command: "BeginComputePass",
                index: 2,
            }
        )),
        "{errors:?}"
    );
    assert!(
        errors.iter().any(|error| matches!(
            error,
            ValidationError::TimestampOutOfRange {
                command: "BeginComputePass",
                index: 4,
                count: 4,
            }
        )),
        "{errors:?}"
    );

    device.destroy_query_set(timers);
}

#[test]
fn the_portable_preset_refuses_query_kinds_it_lacks() {
    let instance = NullInstance::portable();
    let device = instance
        .create_device(&DeviceDesc {
            required_features: Features::COMPUTE,
            ..DeviceDesc::for_adapter(AdapterId(0))
        })
        .expect("device");
    let error = device
        .create_query_set(&QuerySetDesc {
            label: None,
            kind: QueryKind::Timestamp,
            count: 1,
        })
        .expect_err("no timestamp support");
    assert!(matches!(error, HalError::Unsupported { .. }), "{error:?}");
}

/// **The occlusion kind is refused on a preset that granted the feature**, which
/// is the difference between this refusal and every other one in this backend.
///
/// `Features::OCCLUSION_QUERY` is in `NullInstance::gpu_driven`'s bundle and the
/// device opened with it, so a gate on the flag would hand a set back. What
/// refuses is `QueryKind::check_supported`: the seam has no verb that would ever
/// write into the pool, so there is nothing for a preset to grant. The
/// declaration is checked beside the call because the two are one answer — a
/// `Support::Yes` here with a refusing `create_query_set` is exactly the
/// mismatch the parity report exists to catch.
///
/// **What turns it red.** The refusal going back to a feature gate, which on
/// this preset means a handle comes back; or `supports` answering anything but
/// `Support::No`, since a `NotOnThisDevice` would blame a device that granted
/// the flag.
#[test]
fn the_occlusion_kind_is_refused_even_where_the_preset_granted_it() {
    let (_recorder, instance) = boxed(NullInstance::gpu_driven());
    let device = open(instance.as_ref());
    assert!(
        device.caps().features.contains(Features::OCCLUSION_QUERY),
        "this preset is the one that grants the flag, so the refusal below is not the flag"
    );
    let error = device
        .create_query_set(&QuerySetDesc {
            label: Some("visibility"),
            kind: QueryKind::Occlusion,
            count: 4,
        })
        .expect_err("no seam verb writes an occlusion query");
    assert!(
        matches!(
            error,
            HalError::Unsupported {
                backend: BackendKind::Null,
                what
            } if what == crate::NO_OCCLUSION_QUERY_VERB
        ),
        "{error:?}"
    );
    assert!(
        matches!(
            device.supports(Capability::OcclusionQuery),
            Support::No(why) if why == crate::NO_OCCLUSION_QUERY_VERB
        ),
        "the declaration and the refusal are one answer"
    );
}

#[test]
fn wait_idle_and_semaphore_waits_are_recorded_and_satisfied() {
    let (recorder, instance) = boxed(NullInstance::gpu_driven());
    let device = open(instance.as_ref());
    let semaphore = device
        .create_semaphore(&SemaphoreDesc {
            label: Some("frame"),
            kind: SemaphoreKind::Timeline { initial_value: 0 },
        })
        .expect("semaphore");
    assert_eq!(device.semaphore_value(semaphore).expect("value"), 0);
    assert!(
        device
            .wait_semaphores(
                &[SemaphoreWait {
                    semaphore,
                    value: 0
                }],
                0
            )
            .expect("wait"),
        "the timeline was created holding 0, so a wait for 0 is already satisfied"
    );
    device.wait_idle().expect("wait idle");
    assert!(
        recorder
            .events()
            .iter()
            .any(|event| matches!(event, Event::WaitedIdle))
    );
}

/// A host signal moves the timeline, a host wait answers against where it got
/// to, and a signal that would move it backwards is refused rather than
/// accepted.
///
/// **What turns it red.** Dropping the `<=` check makes the second half return
/// `Ok`, which is the whole failure: a timeline that goes backwards leaves every
/// waiter past the higher value asleep on a device that reports nothing wrong.
/// Reporting the value as a constant — which this backend did until
/// [`Device::signal_semaphore`] existed — turns the first half red, and so does
/// ignoring `initial_value`, which is why the semaphore is not created at zero.
///
/// The waits are here rather than in a test of their own because they are what
/// makes the signal observable: a `wait_semaphores` that answered `Ok(true)`
/// unconditionally — which this backend did, on the grounds that nothing is ever
/// outstanding — passes both of them while reading the counter not at all, so
/// the value above and the value below have to be asked for together. Widening
/// the comparison to `>=` turns the `9` case red; narrowing it away turns the
/// `10` case red.
///
/// Refusing with anything but [`HalError::InvalidDescriptor`] is red too: the
/// seam splits "a number you can correct" from "a capability this backend
/// lacks", and a caller branching on `Unsupported` to pick a fallback would take
/// the fallback for a typo.
#[test]
fn a_host_signal_moves_a_timeline_forwards_and_only_forwards() {
    let (_recorder, instance) = boxed(NullInstance::gpu_driven());
    let device = open(instance.as_ref());
    let semaphore = device
        .create_semaphore(&SemaphoreDesc {
            label: Some("frame"),
            kind: SemaphoreKind::Timeline { initial_value: 5 },
        })
        .expect("the gpu_driven preset has timeline semaphores");
    assert_eq!(
        device.semaphore_value(semaphore).expect("value"),
        5,
        "the timeline did not start where it was created"
    );

    device.signal_semaphore(semaphore, 9).expect("forwards");
    assert_eq!(device.semaphore_value(semaphore).expect("value"), 9);

    // The host wait, against the value the timeline actually holds. `0` is the
    // timeout, and it is ignored: nothing here is outstanding, so the answer is
    // immediate in both directions rather than after a wait.
    for reached in [0, 5, 9] {
        assert!(
            device
                .wait_semaphores(
                    &[SemaphoreWait {
                        semaphore,
                        value: reached
                    }],
                    0
                )
                .expect("wait"),
            "the timeline holds 9, so a wait for {reached} has been satisfied"
        );
    }
    assert!(
        !device
            .wait_semaphores(
                &[SemaphoreWait {
                    semaphore,
                    value: 10
                }],
                u64::MAX
            )
            .expect("a timeout is not an error"),
        "nothing has signalled 10, so the wait timed out — `Ok(false)`, not the \
         `Ok(true)` that would tell a caller a value it will never receive had arrived"
    );

    for backwards in [0, 5, 9] {
        let error = device
            .signal_semaphore(semaphore, backwards)
            .expect_err("a timeline only moves forwards");
        assert!(
            matches!(error, HalError::InvalidDescriptor(_)),
            "signalling {backwards} over 9: {error:?}"
        );
    }
    assert_eq!(
        device.semaphore_value(semaphore).expect("value"),
        9,
        "a refused signal must leave the counter where it was"
    );

    // A binary semaphore has no value to signal, exactly as it has none to
    // read — and it is the kind every device must still hand out.
    let binary = device
        .create_semaphore(&SemaphoreDesc {
            label: Some("acquire"),
            kind: SemaphoreKind::Binary,
        })
        .expect("WSI acquire needs one on every device");
    let error = device
        .signal_semaphore(binary, 1)
        .expect_err("a binary semaphore carries no value");
    assert!(matches!(error, HalError::Unsupported { .. }), "{error:?}");
    // And the same from the waiting side, which this backend used to answer
    // `Ok(true)` to. Every real backend refuses it; a null device that reported
    // the wait satisfied taught a caller reading its behaviour that a call no
    // device accepts is one that works.
    let error = device
        .wait_semaphores(
            &[SemaphoreWait {
                semaphore: binary,
                value: 0,
            }],
            0,
        )
        .expect_err("a binary semaphore carries no value to wait for either");
    assert!(matches!(error, HalError::Unsupported { .. }), "{error:?}");

    device.destroy_semaphore(binary);
    device.destroy_semaphore(semaphore);
    let error = device
        .signal_semaphore(semaphore, 10)
        .expect_err("the handle is dead");
    assert!(
        matches!(error, HalError::InvalidHandle { kind, .. } if kind == "semaphore"),
        "{error:?}"
    );
}

/// A submission's signal advances the timeline it names, so a host wait on that
/// value is then satisfied.
///
/// **The half that separates this backend's model from "the host signal is the
/// only thing that counts".** Nothing here signals from the host at all: the
/// counter moves because a submission said it would, which is the whole of
/// [`Capability::TimelineSemaphore`] — "a backend that hands out a handle whose
/// value never moves has not got this, whatever its return codes say". This
/// backend claims that capability on every preset granting
/// [`Features::TIMELINE_SEMAPHORE`], and until `submit` applied the signals the
/// claim was not true.
///
/// **What turns it red.** Recording [`Event::Submitted`] without applying the
/// signals — what `submit` used to do — leaves the counter at its initial value,
/// so the value and the wait both go red while the event assertion still passes.
/// The binary semaphore rides along to prove the apply *skips* what carries no
/// value rather than refusing it: the swapchain's present semaphore is in every
/// frame's signal list, so a `submit` that refused one would break the engine's
/// frame loop.
#[test]
fn a_submissions_signal_advances_the_timeline_it_names() {
    let (recorder, instance) = boxed(NullInstance::gpu_driven());
    let device = open(instance.as_ref());
    let queue = device.queue(QueueKind::Graphics).expect("queue");
    let timeline = device
        .create_semaphore(&SemaphoreDesc {
            label: Some("frame"),
            kind: SemaphoreKind::Timeline { initial_value: 5 },
        })
        .expect("the gpu_driven preset has timeline semaphores");
    let present = device
        .create_semaphore(&SemaphoreDesc {
            label: Some("present"),
            kind: SemaphoreKind::Binary,
        })
        .expect("every device hands one out for WSI");
    assert!(
        !device
            .wait_semaphores(
                &[SemaphoreWait {
                    semaphore: timeline,
                    value: 9
                }],
                0
            )
            .expect("wait"),
        "nothing has signalled 9 yet, so the wait must not already be satisfied"
    );

    device
        .submit(
            queue,
            &SubmitInfo {
                command_buffers: &[],
                waits: &[],
                signals: &[
                    SemaphoreSignal {
                        semaphore: present,
                        value: 0,
                    },
                    SemaphoreSignal {
                        semaphore: timeline,
                        value: 9,
                    },
                ],
            },
        )
        .expect("a signal-only submission");

    assert_eq!(
        device.semaphore_value(timeline).expect("value"),
        9,
        "the submission signalled 9, and work that never executes has already finished"
    );
    assert!(
        device
            .wait_semaphores(
                &[SemaphoreWait {
                    semaphore: timeline,
                    value: 9
                }],
                0
            )
            .expect("wait"),
        "a host wait must see the value a submission signalled"
    );
    assert!(
        recorder
            .events()
            .iter()
            .any(|event| matches!(event, Event::Submitted { .. })),
        "advancing the counter must not cost the recorded submission"
    );

    device.destroy_semaphore(present);
    device.destroy_semaphore(timeline);
}

/// A submission whose signal does not move a timeline forwards is refused, and
/// leaves no event behind.
///
/// The rule [`Device::signal_semaphore`] already enforces, applied to the other
/// way a timeline can be driven — otherwise `submit` is the one path on this
/// backend that can move one backwards, and a caller whose values collide finds
/// out on a real driver instead of on the recorder.
///
/// **What turns it red.** Dropping the check turns the refusal assertions red.
/// Applying the signals or pushing [`Event::Submitted`] *before* validating them
/// turns the counter or the event assertion red instead: a call that answered
/// `Err` must leave the stream and the objects as it found them, which is the
/// property `reconfigure_swapchain` puts its own failure first for.
#[test]
fn a_submission_signalling_a_timeline_backwards_is_refused_and_records_nothing() {
    let (recorder, instance) = boxed(NullInstance::gpu_driven());
    let device = open(instance.as_ref());
    let queue = device.queue(QueueKind::Graphics).expect("queue");
    let semaphore = device
        .create_semaphore(&SemaphoreDesc {
            label: Some("frame"),
            kind: SemaphoreKind::Timeline { initial_value: 9 },
        })
        .expect("the gpu_driven preset has timeline semaphores");

    for backwards in [0, 5, 9] {
        let error = device
            .submit(
                queue,
                &SubmitInfo {
                    command_buffers: &[],
                    waits: &[],
                    signals: &[SemaphoreSignal {
                        semaphore,
                        value: backwards,
                    }],
                },
            )
            .expect_err("a timeline only moves forwards");
        assert!(
            matches!(error, HalError::InvalidDescriptor(_)),
            "a submission signalling {backwards} onto a timeline holding 9: {error:?}"
        );
    }
    assert_eq!(
        device.semaphore_value(semaphore).expect("value"),
        9,
        "a refused submission must leave the counter where it was"
    );
    let events = recorder.events();
    assert!(
        !events
            .iter()
            .any(|event| matches!(event, Event::Submitted { .. })),
        "a refused submission must record nothing: {events:?}"
    );

    device.destroy_semaphore(semaphore);
}

#[test]
fn images_are_validated_against_the_devices_limits() {
    let instance = NullInstance::portable();
    let device = instance
        .create_device(&DeviceDesc {
            required_features: Features::COMPUTE,
            ..DeviceDesc::for_adapter(AdapterId(0))
        })
        .expect("device");
    let too_big = ImageDesc {
        label: None,
        image_type: ImageType::D2,
        // Above the 8192 floor that `Limits::minimum` reports.
        extent: crate::Extent3d::d2(16384, 16384),
        format: Format::Rgba8Unorm,
        mip_levels: 1,
        samples: 1,
        usage: ImageUsage::SAMPLED,
    };
    assert!(device.create_image(&too_big).is_err());
    assert!(
        device
            .create_image(&ImageDesc {
                extent: crate::Extent3d::d2(0, 8),
                ..too_big
            })
            .is_err(),
        "a zero extent is a descriptor bug"
    );
    assert!(
        device
            .create_image(&ImageDesc {
                extent: crate::Extent3d::d2(4096, 4096),
                mip_levels: 0,
                ..too_big
            })
            .is_err(),
        "an image needs at least one mip level"
    );
}

// --- object-lifetime contract (see `crate::device`) --------------------------

/// Rule 3: a surface from one instance must not be usable by a device from
/// another. Handle *bits* collide freely — both instances issue slot 0,
/// generation 1 — so this can only be caught by the owner side table, which is
/// exactly the point of the obligation.
#[test]
fn a_surface_from_another_instance_is_a_foreign_object() {
    // One shared recorder, so both instances' objects live in the same pools —
    // the hardest case, and the one a naive "does the handle resolve?" check
    // gets wrong.
    let recorder = Recorder::new();
    let first = NullInstance::gpu_driven().with_recorder(recorder.clone());
    let second = NullInstance::gpu_driven().with_recorder(recorder.clone());

    // SAFETY: an offscreen target holds no platform pointers.
    let foreign = unsafe { second.create_surface(&SurfaceTarget::Offscreen) }.expect("surface");

    let error = first
        .surface_caps(foreign, AdapterId(0))
        .expect_err("the surface belongs to the other instance");
    assert!(
        matches!(
            error,
            HalError::ForeignObject {
                kind: "surface",
                ..
            }
        ),
        "{error:?}"
    );

    let error = first
        .create_device(&DeviceDesc {
            compatible_surface: Some(foreign),
            ..DeviceDesc::for_adapter(AdapterId(0))
        })
        .expect_err("foreign compatible_surface");
    assert!(matches!(error, HalError::ForeignObject { .. }), "{error:?}");

    let device = open(&first);
    let error = device
        .create_swapchain(&SwapchainDesc {
            label: None,
            surface: foreign,
            format: Format::Bgra8UnormSrgb,
            extent: (8, 8),
            image_count: 2,
            present_mode: PresentMode::Fifo,
            composite_alpha: CompositeAlpha::Opaque,
        })
        .expect_err("foreign surface");
    assert!(
        matches!(error, SurfaceError::Hal(HalError::ForeignObject { .. })),
        "{error:?}"
    );

    // And destroying it through the wrong instance must be a no-op, not a
    // silent free of someone else's object.
    first.destroy_surface(foreign);
    assert!(
        second.surface_caps(foreign, AdapterId(0)).is_ok(),
        "the owning instance's surface survived the foreign destroy"
    );
    second.destroy_surface(foreign);
}

/// Rule 3, device scope: two devices from the *same* instance still do not
/// share resources.
#[test]
fn a_buffer_from_another_device_is_a_foreign_object() {
    let instance = NullInstance::gpu_driven();
    let first = open(&instance);
    let second = open(&instance);

    let buffer = first
        .create_buffer(&BufferDesc {
            label: Some("first device's"),
            size: 16,
            usage: crate::BufferUsage::STORAGE,
            memory: MemoryLocation::HostUpload,
        })
        .expect("buffer");

    let error = second
        .write_buffer(buffer, 0, &[0; 4])
        .expect_err("the buffer belongs to the other device");
    assert!(
        matches!(error, HalError::ForeignObject { kind: "buffer", .. }),
        "{error:?}"
    );
    // The owning device is unaffected.
    first.write_buffer(buffer, 0, &[0; 4]).expect("write");

    // Destroying through the wrong device must not free it.
    second.destroy_buffer(buffer);
    first.write_buffer(buffer, 0, &[0; 4]).expect("still alive");
    first.destroy_buffer(buffer);
    assert!(first.write_buffer(buffer, 0, &[0; 4]).is_err());
}

/// A recorded command naming another device's handle is a validation error
/// distinct from a dead one — the fixes differ.
#[test]
fn commands_naming_a_foreign_handle_are_recorded_as_such() {
    let (recorder, instance) = boxed(NullInstance::gpu_driven());
    let first = open(instance.as_ref());
    let second = open(instance.as_ref());
    let queue = first.queue(QueueKind::Graphics).expect("queue");

    let foreign = second
        .create_buffer(&BufferDesc {
            label: None,
            size: 16,
            usage: crate::BufferUsage::TRANSFER_DST,
            memory: MemoryLocation::DeviceLocal,
        })
        .expect("buffer");

    let mut encoder = first.create_command_encoder(&CommandEncoderDesc { label: None, queue });
    encoder.clear_buffer(foreign, 0, 4);
    let _ = encoder.finish().expect("finish");

    let errors = recorder.validation_errors();
    assert!(
        errors.iter().any(|error| matches!(
            error,
            ValidationError::ForeignHandle {
                command: "ClearBuffer",
                ..
            }
        )),
        "{errors:?}"
    );
    assert!(
        !errors
            .iter()
            .any(|error| matches!(error, ValidationError::DeadHandle { .. })),
        "a live-but-foreign handle is not a dead one: {errors:?}"
    );
}

/// Rule 2: destroying the surface invalidates its *handle* immediately and
/// leaves the swapchain built on it working, which is what
/// `Instance::destroy_surface` promises. The caller owes no teardown order.
///
/// The two halves are asserted separately because they fail for different
/// reasons: a whole frame still goes through the swapchain, while the dead
/// handle refuses to have anything new built on it — an error, never undefined
/// behaviour.
#[test]
fn destroying_a_surface_first_leaves_its_swapchain_working() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    let queue = device
        .queue(QueueKind::Graphics)
        .expect("every device has a graphics queue");
    // SAFETY: an offscreen target holds no platform pointers.
    let surface = unsafe { instance.create_surface(&SurfaceTarget::Offscreen) }.expect("surface");
    let desc = SwapchainDesc {
        label: None,
        surface,
        format: Format::Bgra8UnormSrgb,
        extent: (8, 8),
        image_count: 2,
        present_mode: PresentMode::Fifo,
        composite_alpha: CompositeAlpha::Opaque,
    };
    let swapchain = device.create_swapchain(&desc).expect("swapchain");

    // The surface handle dies here, mid-life of the swapchain on it.
    instance.destroy_surface(surface);

    // A whole frame still goes through: the backend deferred the real teardown
    // and the swapchain never consults the surface table again.
    let frame = device
        .acquire_next_frame(swapchain)
        .expect("still acquirable");
    device
        .present(
            queue,
            &PresentInfo {
                swapchain,
                waits: frame.present_semaphore.as_slice(),
                present_id: Some(1),
            },
        )
        .expect("still presentable");
    device
        .wait_until_presented(swapchain, 1, Duration::from_secs(30))
        .expect("the frame landed");

    // But nothing new can be built on the dead surface handle.
    let error = device.create_swapchain(&desc).expect_err("dead surface");
    assert!(
        matches!(error, SurfaceError::Hal(HalError::InvalidHandle { .. })),
        "{error:?}"
    );

    device.destroy_swapchain(swapchain);
    let error = device
        .acquire_next_frame(swapchain)
        .expect_err("dead swapchain");
    assert!(
        matches!(error, SurfaceError::Hal(HalError::InvalidHandle { .. })),
        "{error:?}"
    );
}

/// Rule 1: a device keeps working after its instance is dropped. If the null
/// backend held a borrow rather than a shared handle, this would not compile;
/// if it held a raw pointer, it would be a use-after-free.
#[test]
fn a_device_outlives_its_instance() {
    let recorder = Recorder::new();
    let device = {
        let instance: Box<dyn Instance> =
            Box::new(NullInstance::gpu_driven().with_recorder(recorder.clone()));
        let adapters = instance.adapters();
        instance
            .create_device(&DeviceDesc {
                optional_features: Features::all(),
                ..DeviceDesc::for_adapter(adapters[0].id)
            })
            .expect("device")
        // `instance` is dropped here.
    };

    let buffer = device
        .create_buffer(&BufferDesc {
            label: Some("after the instance went away"),
            size: 32,
            usage: crate::BufferUsage::STORAGE,
            memory: MemoryLocation::HostUpload,
        })
        .expect("the device still works");
    device
        .write_buffer(buffer, 0, &[1, 2, 3, 4])
        .expect("write");
    device.destroy_buffer(buffer);
    device.wait_idle().expect("wait idle");
    assert_eq!(recorder.total_live_objects(), 0);
}

// --- readback ---------------------------------------------------------------

#[test]
fn readback_completes_and_yields_the_buffers_bytes() {
    let (recorder, instance) = boxed(NullInstance::gpu_driven());
    let device = open(instance.as_ref());
    let buffer = device
        .create_buffer(&BufferDesc {
            label: Some("culling stats"),
            size: 16,
            usage: crate::BufferUsage::TRANSFER_DST,
            memory: MemoryLocation::HostReadback,
        })
        .expect("readback buffer");

    let request = device
        .request_readback(&ReadbackDesc {
            label: Some("stats"),
            buffer,
            offset: 4,
            size: 8,
            after: None,
        })
        .expect("request");

    let mut out = [0xFFu8; 8];
    assert_eq!(
        device.poll_readback(request, &mut out).expect("poll"),
        ReadbackState::Ready
    );
    assert_eq!(out, [0; 8], "nothing executed, so the bytes are zeros");

    // Polling again is legal and idempotent until the request is destroyed.
    assert_eq!(
        device.poll_readback(request, &mut out).expect("poll"),
        ReadbackState::Ready
    );

    device.destroy_readback(request);
    assert!(
        device.poll_readback(request, &mut out).is_err(),
        "a destroyed readback must not resolve"
    );
    device.destroy_buffer(buffer);
    assert_eq!(recorder.total_live_objects(), 0);
}

/// The property a blocking API could never have: a caller must be able to be
/// told "not yet" and come back next frame. This is what the browser's
/// `mapAsync` does on every readback, so the poll loop has to be exercised.
#[test]
fn a_pending_readback_reports_pending_and_leaves_the_output_untouched() {
    let (recorder, instance) = boxed(NullInstance::gpu_driven());
    let device = open(instance.as_ref());
    recorder.set_readback_latency(3);

    let buffer = device
        .create_buffer(&BufferDesc {
            label: None,
            size: 4,
            usage: crate::BufferUsage::TRANSFER_DST,
            memory: MemoryLocation::HostReadback,
        })
        .expect("readback buffer");
    let request = device
        .request_readback(&ReadbackDesc {
            label: None,
            buffer,
            offset: 0,
            size: 4,
            after: None,
        })
        .expect("request");

    let mut out = [0xAAu8; 4];
    for poll in 0..3 {
        assert_eq!(
            device.poll_readback(request, &mut out).expect("poll"),
            ReadbackState::Pending,
            "poll {poll}"
        );
        assert_eq!(out, [0xAA; 4], "a pending poll must not write the output");
    }
    assert_eq!(
        device.poll_readback(request, &mut out).expect("poll"),
        ReadbackState::Ready
    );
    assert_eq!(out, [0; 4]);

    device.destroy_readback(request);
    device.destroy_buffer(buffer);
}

#[test]
fn readback_validates_its_buffer_memory_range_and_output_length() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);

    // Wrong memory location: WebGPU would reject the MAP_READ usage too.
    let upload = device
        .create_buffer(&BufferDesc {
            label: None,
            size: 8,
            usage: crate::BufferUsage::TRANSFER_SRC,
            memory: MemoryLocation::HostUpload,
        })
        .expect("buffer");
    let error = device
        .request_readback(&ReadbackDesc {
            label: None,
            buffer: upload,
            offset: 0,
            size: 8,
            after: None,
        })
        .expect_err("not host-readable");
    assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");

    let readable = device
        .create_buffer(&BufferDesc {
            label: None,
            size: 8,
            usage: crate::BufferUsage::TRANSFER_DST,
            memory: MemoryLocation::HostReadback,
        })
        .expect("buffer");

    // Out of range.
    let error = device
        .request_readback(&ReadbackDesc {
            label: None,
            buffer: readable,
            offset: 4,
            size: 8,
            after: None,
        })
        .expect_err("past the end");
    assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");

    // Output slice must match the requested size exactly.
    let request = device
        .request_readback(&ReadbackDesc {
            label: None,
            buffer: readable,
            offset: 0,
            size: 8,
            after: None,
        })
        .expect("request");
    let error = device
        .poll_readback(request, &mut [0; 4])
        .expect_err("wrong output length");
    assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");

    // Destroying the source between request and poll is caught, not read.
    device.destroy_buffer(readable);
    let error = device
        .poll_readback(request, &mut [0; 8])
        .expect_err("source is gone");
    assert!(matches!(error, HalError::InvalidHandle { .. }), "{error:?}");
    device.destroy_readback(request);
}

#[test]
fn a_readback_may_name_an_explicit_completion_point() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    let semaphore = device
        .create_semaphore(&SemaphoreDesc {
            label: Some("frame"),
            kind: SemaphoreKind::Timeline { initial_value: 0 },
        })
        .expect("semaphore");
    let buffer = device
        .create_buffer(&BufferDesc {
            label: None,
            size: 4,
            usage: crate::BufferUsage::TRANSFER_DST,
            memory: MemoryLocation::HostReadback,
        })
        .expect("buffer");

    let request = device
        .request_readback(&ReadbackDesc {
            label: None,
            buffer,
            offset: 0,
            size: 4,
            after: Some(SemaphoreWait {
                semaphore,
                value: 3,
            }),
        })
        .expect("request");
    assert_eq!(
        device.poll_readback(request, &mut [0; 4]).expect("poll"),
        ReadbackState::Ready
    );

    // A dead semaphore in `after` is caught at request time.
    device.destroy_semaphore(semaphore);
    let error = device
        .request_readback(&ReadbackDesc {
            label: None,
            buffer,
            offset: 0,
            size: 4,
            after: Some(SemaphoreWait {
                semaphore,
                value: 3,
            }),
        })
        .expect_err("dead semaphore");
    assert!(matches!(error, HalError::InvalidHandle { .. }), "{error:?}");

    device.destroy_readback(request);
    device.destroy_buffer(buffer);
}

// --- validation the null backend used to skip --------------------------------
//
// The null backend is documented as the reference validator the graph suite
// runs against, so anything it accepts that `crcbl-vk` rejects lets CI
// green-light a command stream Vulkan refuses. These pin the gaps closed.

/// A bind group must be checked against the layout it claims to conform to:
/// the binding must exist, the array index must be inside it, and the resource
/// must be the right *kind*. None of that used to happen here.
#[test]
fn a_bind_group_is_checked_against_its_layout() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);

    let layout = device
        .create_bind_group_layout(&BindGroupLayoutDesc {
            label: Some("frame"),
            entries: &[BindGroupLayoutEntry {
                binding: 0,
                visibility: ShaderStages::ALL,
                kind: BindingKind::StorageBuffer {
                    read_only: true,
                    dynamic: false,
                    stride: 4,
                },
                count: 2,
                flags: crate::BindingFlags::empty(),
            }],
        })
        .expect("set layout");
    let buffer = device
        .create_buffer(&BufferDesc {
            label: None,
            size: 64,
            usage: crate::BufferUsage::STORAGE,
            memory: MemoryLocation::DeviceLocal,
        })
        .expect("buffer");
    let sampler = device
        .create_sampler(&crate::SamplerDesc::default())
        .expect("sampler");

    let entry = |binding, array_index, resource| BindGroupEntry {
        binding,
        array_index,
        resource,
    };
    fn group<'a>(
        layout: crate::BindGroupLayoutHandle,
        entries: &'a [BindGroupEntry],
    ) -> BindGroupDesc<'a> {
        BindGroupDesc {
            label: None,
            layout,
            entries,
            variable_count: None,
        }
    }

    device
        .create_bind_group(&group(
            layout,
            &[entry(0, 1, crate::BindingResource::whole_buffer(buffer))],
        ))
        .expect("index 1 of a two-element binding is in range");

    let error = device
        .create_bind_group(&group(
            layout,
            &[entry(7, 0, crate::BindingResource::whole_buffer(buffer))],
        ))
        .expect_err("binding 7 is not declared");
    assert!(error.to_string().contains("does not declare"), "{error}");

    let error = device
        .create_bind_group(&group(
            layout,
            &[entry(0, 2, crate::BindingResource::whole_buffer(buffer))],
        ))
        .expect_err("index 2 of a two-element binding is out of range");
    assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");

    let error = device
        .create_bind_group(&group(
            layout,
            &[entry(0, 0, crate::BindingResource::Sampler(sampler))],
        ))
        .expect_err("a sampler cannot fill a storage-buffer binding");
    assert!(error.to_string().contains('0'), "{error}");
}

/// **A host-visible buffer cannot fill a binding a shader writes**, and it can
/// still fill every read-only one.
///
/// The seam rule [`MemoryLocation`] states: D3D12's upload and readback heaps
/// admit no unordered access view, so the combination the other three backends
/// permit is one that removes a D3D12 device. `crcbl-dx12` refuses it at the
/// view it would have built; the null backend refuses the class, so a call site
/// meets it in the no-GPU suite instead of on a WARP run.
///
/// The read-only half is the assertion that keeps the refusal honest. Every
/// uniform block and every staged instance and material table in the engine is a
/// host-visible buffer behind a read-only binding, so a check that refused those
/// too would take the engine down rather than the bug.
#[test]
fn a_host_visible_buffer_cannot_fill_a_writable_storage_binding() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);

    let layout_of = |read_only| {
        device
            .create_bind_group_layout(&BindGroupLayoutDesc {
                label: Some("staged instances"),
                entries: &[BindGroupLayoutEntry {
                    binding: 3,
                    visibility: ShaderStages::COMPUTE,
                    kind: BindingKind::StorageBuffer {
                        read_only,
                        dynamic: false,
                        stride: 4,
                    },
                    count: 1,
                    flags: crate::BindingFlags::empty(),
                }],
            })
            .expect("a storage-buffer layout")
    };
    let writable = layout_of(false);
    let readable = layout_of(true);

    let buffer_in = |memory| {
        device
            .create_buffer(&BufferDesc {
                label: Some("instances"),
                size: 64,
                usage: BufferUsage::STORAGE,
                memory,
            })
            .expect("the null backend always allocates")
    };
    let group_of = |layout, buffer| {
        device.create_bind_group(&BindGroupDesc {
            label: None,
            layout,
            entries: &[BindGroupEntry {
                binding: 3,
                array_index: 0,
                resource: crate::BindingResource::whole_buffer(buffer),
            }],
            variable_count: None,
        })
    };

    // What the rule forbids, in both host-visible locations.
    for memory in [MemoryLocation::HostUpload, MemoryLocation::HostReadback] {
        let buffer = buffer_in(memory);
        let error =
            group_of(writable, buffer).expect_err("a host-visible buffer bound for writing");
        let text = error.to_string();
        assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");
        assert!(text.contains("binding 3"), "{memory:?}: {text}");
        assert!(text.contains(&format!("{memory:?}")), "{memory:?}: {text}");
        assert!(text.contains("DeviceLocal"), "{memory:?}: {text}");
        assert!(
            text.contains("ALLOW_UNORDERED_ACCESS"),
            "{memory:?}: {text}"
        );

        // ...and the same buffer through a read-only binding is the engine's
        // own staged-table shape, which must stay legal.
        let group = group_of(readable, buffer).unwrap_or_else(|why| {
            panic!("a read-only binding of a {memory:?} buffer is legal everywhere: {why}")
        });
        device.destroy_bind_group(group);
        device.destroy_buffer(buffer);
    }

    // And the location the rule requires passes through both.
    let device_local = buffer_in(MemoryLocation::DeviceLocal);
    for layout in [writable, readable] {
        let group = group_of(layout, device_local).expect("a device-local storage buffer");
        device.destroy_bind_group(group);
    }

    device.destroy_buffer(device_local);
    device.destroy_bind_group_layout(writable);
    device.destroy_bind_group_layout(readable);
}

/// `update_bind_group` on a layout without `UPDATE_AFTER_BIND` is the error
/// `Device::update_bind_group` promises, and `crcbl-vk` produces. The null
/// backend used to accept it, which made the doc untestable.
#[test]
fn updating_a_group_without_update_after_bind_is_refused() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    let slot = |flags| BindGroupLayoutEntry {
        binding: 0,
        visibility: ShaderStages::ALL,
        kind: BindingKind::SampledImage {
            view_type: ImageViewType::D2,
            sample_type: SampleType::Float,
        },
        count: 1,
        flags,
    };

    let plain = device
        .create_bind_group_layout(&BindGroupLayoutDesc {
            label: None,
            entries: &[slot(crate::BindingFlags::empty())],
        })
        .expect("layout");
    let plain_group = device
        .create_bind_group(&BindGroupDesc {
            label: None,
            layout: plain,
            entries: &[],
            variable_count: None,
        })
        .expect("group");
    let error = device
        .update_bind_group(plain_group, &[])
        .expect_err("no UPDATE_AFTER_BIND");
    assert!(matches!(error, HalError::Unsupported { .. }), "{error:?}");

    let bindless = device
        .create_bind_group_layout(&BindGroupLayoutDesc {
            label: None,
            entries: &[slot(crate::BindingFlags::UPDATE_AFTER_BIND)],
        })
        .expect("layout");
    let bindless_group = device
        .create_bind_group(&BindGroupDesc {
            label: None,
            layout: bindless,
            entries: &[],
            variable_count: None,
        })
        .expect("group");
    device
        .update_bind_group(bindless_group, &[])
        .expect("UPDATE_AFTER_BIND is what the flag is for");
}

/// `PushConstantRange { offset: u32::MAX, size: 1 }` panicked in debug and
/// wrapped to `0` in release — which then *passed* the limit check it was
/// supposed to fail.
#[test]
fn a_push_constant_range_that_overflows_is_refused_not_wrapped() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    let error = device
        .create_pipeline_layout(&PipelineLayoutDesc {
            label: None,
            bind_group_layouts: &[],
            push_constants: Some(PushConstantRange {
                stages: ShaderStages::ALL,
                offset: u32::MAX,
                size: 1,
            }),
        })
        .expect_err("the range ends past every possible budget");
    assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");
}

/// The range check `Device::query_results` documents, which was impossible
/// before: `first_query` was ignored and the set's size was never stored.
#[test]
fn query_results_are_bounded_by_the_sets_size() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    let set = device
        .create_query_set(&QuerySetDesc {
            label: Some("timers"),
            kind: QueryKind::Timestamp,
            count: 4,
        })
        .expect("query set");

    let mut out = [1u64; 2];
    device
        .query_results(set, 2, &mut out)
        .expect("2..4 is inside a four-query set");
    assert_eq!(out, [0, 0], "a device with no timestamps reports zeros");

    let error = device
        .query_results(set, 3, &mut out)
        .expect_err("3..5 runs off the end");
    assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");
}

/// This backend checked the anisotropy ceiling and never the floor, so a value
/// below the one that disables anisotropy — and a `NAN`, which no backend's
/// `< 1.0` caught — were served here while `crcbl-vk`, `crcbl-mtl` and
/// `crcbl-dx12` refused them.
///
/// The `gpu_driven` preset rather than `portable`: the latter reports
/// `max_sampler_anisotropy: 1.0`, where the floor and the ceiling are the same
/// number and neither refusal is distinguishable from the other's.
#[test]
fn a_samplers_anisotropy_is_held_to_the_floor_as_well_as_the_ceiling() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    let ceiling = device.caps().limits.max_sampler_anisotropy;
    assert!(
        ceiling > 1.0,
        "this preset must report a real ceiling, got {ceiling}"
    );
    let sampler = |anisotropy| crate::SamplerDesc {
        label: Some("anisotropy"),
        anisotropy,
        ..crate::SamplerDesc::default()
    };

    // The accepting arms first, so a `create_sampler` that refused everything
    // could not satisfy the refusals below unnoticed.
    for (case, anisotropy) in [("the floor exactly", 1.0), ("the ceiling exactly", ceiling)] {
        device
            .create_sampler(&sampler(anisotropy))
            .unwrap_or_else(|error| panic!("{case} is a sampler this device can make: {error}"));
    }

    for (case, anisotropy) in [
        ("below the floor", 0.5),
        // `NAN < 1.0` and `NAN > ceiling` are both `false`, so the two
        // comparison-shaped checks this backend and every other one had let it
        // through to the driver.
        ("a NaN", f32::NAN),
        ("past the ceiling", ceiling + 1.0),
    ] {
        let error = device
            .create_sampler(&sampler(anisotropy))
            .expect_err(&format!("{case} must be refused"));
        assert!(
            matches!(error, HalError::InvalidDescriptor(_)),
            "{case}: {error:?}"
        );
    }
}

/// Image validation used to compare `max(width, height)` against
/// `max_image_2d` for every image type, leaving `max_image_3d` read by nothing,
/// a volume's depth checked against nothing, and `samples` unvalidated.
#[test]
fn images_are_validated_per_type_and_sample_count() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    let limits = device.caps().limits;
    let base = ImageDesc {
        label: None,
        image_type: ImageType::D3,
        extent: crate::Extent3d {
            width: 4,
            height: 4,
            depth_or_layers: limits.max_image_3d + 1,
        },
        format: Format::Rgba8Unorm,
        mip_levels: 1,
        samples: 1,
        usage: ImageUsage::SAMPLED,
    };

    let error = device
        .create_image(&base)
        .expect_err("a volume's depth is bounded by max_image_3d");
    assert!(error.to_string().contains("max_image_3d"), "{error}");

    let legal_extent = crate::Extent3d {
        width: 4,
        height: 4,
        depth_or_layers: 4,
    };
    device
        .create_image(&ImageDesc {
            extent: legal_extent,
            ..base
        })
        .expect("a 4x4x4 volume is fine");

    // A sample count is a mask underneath, so `3` is `TYPE_1 | TYPE_2`.
    let error = device
        .create_image(&ImageDesc {
            extent: legal_extent,
            samples: 3,
            ..base
        })
        .expect_err("3 is not a power of two");
    assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");
    let error = device
        .create_image(&ImageDesc {
            extent: legal_extent,
            samples: limits.max_sample_count * 2,
            ..base
        })
        .expect_err("past the device's ceiling");
    assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");

    // An image nothing may ever do anything with is a caller bug.
    let error = device
        .create_image(&ImageDesc {
            extent: legal_extent,
            usage: ImageUsage::empty(),
            ..base
        })
        .expect_err("no usage flags");
    assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");

    // A volume's depth joins the mip chain; a 4x4x4 one has three levels.
    let error = device
        .create_image(&ImageDesc {
            extent: legal_extent,
            mip_levels: 4,
            ..base
        })
        .expect_err("a 4x4x4 volume has three mip levels, not four");
    assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");
}

/// Obligation 3 covers queues too. `submit`, `present` and
/// `create_command_encoder` used to ignore the queue argument entirely, so
/// another device's handle — synthesised from the kind index alone, and
/// therefore *identical* — submitted happily.
#[test]
fn a_queue_from_another_device_is_foreign() {
    let (recorder, instance) = boxed(NullInstance::gpu_driven());
    let first = open(instance.as_ref());
    let second = open(instance.as_ref());

    let mine = first.queue(QueueKind::Graphics).expect("queue");
    let theirs = second.queue(QueueKind::Graphics).expect("queue");
    assert_ne!(
        mine, theirs,
        "two devices must not synthesise the same queue handle"
    );

    let error = first
        .submit(theirs, &SubmitInfo::new(&[]))
        .expect_err("that queue belongs to the other device");
    assert!(
        matches!(error, HalError::ForeignObject { kind: "queue", .. }),
        "{error:?}"
    );

    // An encoder created against a foreign queue reports it at `finish`, where
    // there is an error path — `create_command_encoder` has none.
    let encoder = first.create_command_encoder(&CommandEncoderDesc {
        label: None,
        queue: theirs,
    });
    let error = encoder.finish().expect_err("foreign queue");
    assert!(
        matches!(error, HalError::ForeignObject { kind: "queue", .. }),
        "{error:?}"
    );

    // The device's own queue still works.
    first.submit(mine, &SubmitInfo::new(&[])).expect("submit");
    let _ = recorder;
}

/// A rejected poll must not consume one of the simulated latency's polls: the
/// caller would otherwise observe a shorter latency than it configured, which
/// makes the latency it is being tested against a lie.
#[test]
fn a_rejected_poll_does_not_advance_the_simulated_readback() {
    let (recorder, instance) = boxed(NullInstance::gpu_driven());
    let device = open(instance.as_ref());
    recorder.set_readback_latency(2);

    let buffer = device
        .create_buffer(&BufferDesc {
            label: None,
            size: 8,
            usage: crate::BufferUsage::TRANSFER_DST,
            memory: MemoryLocation::HostReadback,
        })
        .expect("buffer");
    let readback = device
        .request_readback(&ReadbackDesc {
            label: None,
            buffer,
            offset: 0,
            size: 8,
            after: None,
        })
        .expect("readback");

    // Three polls with the wrong slice length. Each must be rejected and change
    // nothing.
    let mut wrong = [0u8; 4];
    for _ in 0..3 {
        let error = device
            .poll_readback(readback, &mut wrong)
            .expect_err("the slice is the wrong length");
        assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");
    }

    let mut right = [0u8; 8];
    for poll in 0..2 {
        assert_eq!(
            device.poll_readback(readback, &mut right).expect("poll"),
            ReadbackState::Pending,
            "poll {poll} must still be pending: the configured latency is 2"
        );
    }
    assert_eq!(
        device.poll_readback(readback, &mut right).expect("poll"),
        ReadbackState::Ready
    );
}

/// `SwapchainDesc::format` must be one of `SurfaceCaps::formats`, and the ring
/// size must be clamped to the min/max the same backend reports.
#[test]
fn a_swapchain_format_must_be_one_the_surface_offers() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    // SAFETY: `Offscreen` names no platform object.
    let surface = unsafe { instance.create_surface(&SurfaceTarget::Offscreen) }.expect("surface");
    let caps = instance
        .surface_caps(surface, AdapterId(0))
        .expect("surface caps");

    let desc = |format| SwapchainDesc {
        label: None,
        surface,
        format,
        extent: (64, 48),
        image_count: 99,
        present_mode: PresentMode::Fifo,
        composite_alpha: CompositeAlpha::Opaque,
    };

    let error = device
        .create_swapchain(&desc(Format::D32Float))
        .expect_err("no surface presents a depth format");
    assert!(
        matches!(error, SurfaceError::Hal(HalError::InvalidDescriptor(_))),
        "{error:?}"
    );

    let swapchain = device
        .create_swapchain(&desc(caps.formats[0]))
        .expect("a reported format is accepted");

    // 99 images is clamped to the reported maximum, not to a literal that
    // happens to agree with it.
    let mut seen = std::collections::HashSet::new();
    for _ in 0..(caps.max_image_count + 1) {
        let frame = device
            .acquire_next_frame(swapchain)
            .expect("the ring hands out images");
        seen.insert(frame.image);
        device
            .present(
                device.queue(QueueKind::Graphics).expect("queue"),
                &PresentInfo {
                    swapchain,
                    waits: &[],
                    present_id: None,
                },
            )
            .expect("present");
    }
    assert!(
        seen.len() as u32 <= caps.max_image_count,
        "the ring must hold at most {} images, saw {}",
        caps.max_image_count,
        seen.len()
    );

    device.destroy_swapchain(swapchain);
    instance.destroy_surface(surface);
}

/// The simulated device latency applies to requests made *after* it is set, and
/// each request counts down on its own — the same contract
/// `set_readback_latency` carries, and the one a test that opens two devices in
/// one process depends on.
#[test]
fn device_latency_applies_per_request_and_only_after_it_is_set() {
    let (recorder, instance) = boxed(NullInstance::gpu_driven());
    let adapter = instance.adapters()[0].id;

    // Requested before the latency is set: unaffected.
    let mut instant = instance
        .request_device(&DeviceDesc::for_adapter(adapter))
        .expect("request");
    recorder.set_device_latency(2);
    assert!(
        instant.poll().expect("poll").is_ready(),
        "a request already in flight must not pick up a latency set later"
    );

    // Two requests after it: both count down independently.
    let mut first = instance
        .request_device(&DeviceDesc::for_adapter(adapter))
        .expect("request");
    let mut second = instance
        .request_device(&DeviceDesc::for_adapter(adapter))
        .expect("request");
    for _ in 0..2 {
        assert!(!first.poll().expect("poll").is_ready());
        assert!(!second.poll().expect("poll").is_ready());
    }
    assert!(first.poll().expect("poll").is_ready());
    assert!(second.poll().expect("poll").is_ready());
}

/// A device that arrived through the polled path is the same device the
/// blocking wrapper would have produced, ownership stamping included: a buffer
/// from one is foreign to the other.
#[test]
fn a_polled_device_stamps_its_own_ownership_like_any_other() {
    let (_recorder, instance) = boxed(NullInstance::gpu_driven());
    let adapter = instance.adapters()[0].id;

    let mut request = instance
        .request_device(&DeviceDesc::for_adapter(adapter))
        .expect("request");
    let polled = request
        .poll()
        .expect("poll")
        .into_device()
        .expect("ready on the first poll");
    let blocking = instance
        .create_device(&DeviceDesc::for_adapter(adapter))
        .expect("the blocking wrapper");

    let buffer = polled
        .create_buffer(&BufferDesc {
            label: Some("polled device's buffer"),
            size: 64,
            usage: BufferUsage::STORAGE,
            memory: MemoryLocation::DeviceLocal,
        })
        .expect("create");
    let error = blocking
        .write_buffer(buffer, 0, &[0u8; 4])
        .expect_err("another device's buffer is foreign");
    assert!(matches!(error, HalError::ForeignObject { .. }), "{error:?}");
    polled.destroy_buffer(buffer);
}

/// A buffer range longer than the slot's limit is refused, in both spellings.
///
/// The two range limits are the ones a caller walks into by accident rather
/// than by asking for something exotic: the uniform ceiling is 64 KiB on the
/// desktop preset, small enough that an ordinary table outgrows it, and the
/// buffer itself is created without complaint because a buffer that size is
/// perfectly legal — binding *all of it* to a uniform slot is what is not.
///
/// Both spellings are checked because `WHOLE_BUFFER` is the commoner one and
/// carries no number to compare: a check reading only explicit sizes would pass
/// every `whole_buffer` binding, which is most of them. The `offset` case is
/// what shows the sentinel is resolved against what is actually bound — one
/// alignment in, the same over-large buffer fits.
///
/// The step is the slot's own
/// [`Limits::min_uniform_buffer_offset_alignment`](crate::Limits::min_uniform_buffer_offset_alignment)
/// or
/// [`min_storage_buffer_offset_alignment`](crate::Limits::min_storage_buffer_offset_alignment)
/// rather than one byte, because a binding offset is held to that alignment
/// too — see
/// [`check_binding_offset_alignment`](crate::check_binding_offset_alignment).
/// A one-byte step is a binding no device this backend stands in for accepts,
/// so it is not the way to spell "a little way into the buffer".
#[test]
fn a_buffer_range_over_the_slots_limit_is_refused() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    let limits = device.caps().limits;

    for (kind, ceiling, named, alignment) in [
        (
            BindingKind::UniformBuffer { dynamic: false },
            limits.max_uniform_buffer_range,
            "max_uniform_buffer_range",
            limits.min_uniform_buffer_offset_alignment,
        ),
        (
            BindingKind::StorageBuffer {
                read_only: true,
                dynamic: false,
                stride: 4,
            },
            limits.max_storage_buffer_range,
            "max_storage_buffer_range",
            limits.min_storage_buffer_offset_alignment,
        ),
    ] {
        let layout = device
            .create_bind_group_layout(&BindGroupLayoutDesc {
                label: Some("one buffer"),
                entries: &[BindGroupLayoutEntry {
                    binding: 0,
                    visibility: ShaderStages::COMPUTE,
                    kind,
                    count: 1,
                    flags: crate::BindingFlags::empty(),
                }],
            })
            .expect("a single-buffer layout");
        let buffer = device
            .create_buffer(&BufferDesc {
                label: Some("one aligned step too long"),
                size: ceiling + alignment,
                usage: BufferUsage::UNIFORM | BufferUsage::STORAGE,
                memory: MemoryLocation::DeviceLocal,
            })
            .expect("a buffer of any size is legal; binding all of it is not");
        let group_of = |offset, size| {
            device.create_bind_group(&BindGroupDesc {
                label: None,
                layout,
                entries: &[BindGroupEntry {
                    binding: 0,
                    array_index: 0,
                    resource: crate::BindingResource::Buffer {
                        buffer,
                        offset,
                        size,
                    },
                }],
                variable_count: None,
            })
        };

        // `bound` is what each spelling actually binds, which is the number the
        // refusal has to name: the sentinel covers the whole buffer, the
        // explicit size covers what it says.
        for (case, offset, size, bound) in [
            (
                "whole buffer",
                0,
                crate::BindingResource::WHOLE_BUFFER,
                ceiling + alignment,
            ),
            ("explicit size", 0, ceiling + 1, ceiling + 1),
        ] {
            let error = group_of(offset, size).expect_err("a range over the ceiling");
            let text = error.to_string();
            assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");
            assert!(text.contains("binding 0"), "{case}: {text}");
            assert!(text.contains(named), "{case}: {text}");
            assert!(text.contains(&bound.to_string()), "{case}: {text}");
            assert!(text.contains(&ceiling.to_string()), "{case}: {text}");
        }

        // Exactly the ceiling is allowed, by either spelling.
        group_of(alignment, crate::BindingResource::WHOLE_BUFFER)
            .expect("one aligned step in, the rest of the buffer is exactly the ceiling");
        group_of(0, ceiling).expect("a range of exactly the ceiling");
    }
}

/// **A mesh dispatch's arguments are stepped by the same rules a draw's are.**
///
/// `plan_mesh_indirect` had been on the seam with no caller since the argument
/// rules moved there: `draw_mesh_tasks_indirect` recorded whatever offset,
/// stride and count it was handed. The structure is three words rather than a
/// draw's four or five, and every other rule is the same one, because they are
/// all rules about stepping an array of structures in a buffer.
///
/// **What turns it red.** Dropping the call — the first refusal. Measuring the
/// arguments against a draw structure rather than a mesh one — the third, where
/// a stride of twelve is one whole mesh structure and less than a draw's
/// sixteen. The accepting arm is what stops the refusals going vacuous.
#[test]
fn a_mesh_dispatch_is_held_to_the_seams_argument_rules() {
    let (recorder, instance) = boxed(NullInstance::gpu_driven());
    let device = open(instance.as_ref());
    let queue = device.queue(QueueKind::Graphics).expect("graphics queue");
    let args = device
        .create_buffer(&BufferDesc {
            label: Some("mesh dispatch args"),
            size: 64,
            usage: BufferUsage::INDIRECT | BufferUsage::STORAGE,
            memory: MemoryLocation::DeviceLocal,
        })
        .expect("buffer");
    let pass = RenderPassDesc {
        label: Some("mesh indirect"),
        color_attachments: &[],
        depth_stencil_attachment: None,
        render_area: Rect2d::from_size(16, 16),
        timestamp_writes: None,
    };
    let record = |draw: DrawIndirect| {
        let mut encoder = device.create_command_encoder(&CommandEncoderDesc { label: None, queue });
        encoder.begin_render_pass(&pass);
        encoder.draw_mesh_tasks_indirect(&draw);
        encoder.end_render_pass();
        encoder.finish()
    };
    let stride = u32::try_from(crate::MESH_DISPATCH_ARGS_BYTES).expect("three words fit a u32");

    recorder.clear();
    // Two tightly packed structures from an aligned offset: the last byte read
    // is 4 + 12 + 12 = 28, inside 64.
    record(DrawIndirect {
        args,
        offset: 4,
        draw_count: 2,
        stride,
    })
    .expect("a mesh dispatch inside its buffer obeys the seam's rules");

    for (draw, what) in [
        (
            DrawIndirect {
                args,
                offset: 2,
                draw_count: 1,
                stride: 0,
            },
            "an offset that is not a multiple of four",
        ),
        (
            DrawIndirect {
                args,
                offset: 0,
                draw_count: 2,
                stride: stride - 4,
            },
            "a stride below one three-word structure",
        ),
        (
            DrawIndirect {
                args,
                offset: 56,
                draw_count: 1,
                stride: 0,
            },
            "one structure that starts eight bytes from the end",
        ),
    ] {
        let error = record(draw).expect_err(&format!(
            "{what} must fail the finish with an InvalidDescriptor"
        ));
        assert!(
            matches!(error, HalError::InvalidDescriptor(_)),
            "{what}: {error:?}"
        );
    }
}

/// **An indirect draw is held to the seam's argument rules, all three of them,
/// with no device in the room.**
///
/// [`crate::indirect`] states them once — a four-byte-aligned offset, a stride
/// no smaller than one argument structure, and structures that fit inside the
/// buffer — and this backend is the only one that can answer all three in a
/// unit test: it recorded the buffer's size when it created it, where
/// `crcbl-vk` needs a device and `crcbl-webgpu`'s encoder cannot reach a length
/// at all. None of the three is a mistake an API reports: a misaligned indirect
/// offset is `VUID-vkCmdDrawIndirect-offset-02710`, which has no error code —
/// the driver reads the arguments from the wrong bytes and draws something else.
///
/// **The legal draws are half the test.** A check that refused every indirect
/// draw would satisfy the refusals below and break every frame in the
/// workspace, so the accepting side runs first: a multi-draw at a padded
/// stride and a one-draw caller's `stride: 0`, which the seam accepts because
/// a single draw never strides.
///
/// **What turns it red.** Dropping the check from `draw_indirect` or
/// `draw_indexed_indirect` turns its refusals green; using
/// [`structure_bytes`](crate::structure_bytes)`(false)` for the indexed form
/// accepts a 16-byte stride that skips a word of every structure after the
/// first; measuring the buffer by its recorded `bytes` rather than its `size`
/// refuses the legal draws too, because a device-local buffer keeps no
/// contents.
#[test]
fn an_indirect_draw_is_held_to_the_seams_argument_rules() {
    let (recorder, instance) = boxed(NullInstance::gpu_driven());
    let device = open(instance.as_ref());
    let queue = device.queue(QueueKind::Graphics).expect("graphics queue");
    let args = device
        .create_buffer(&BufferDesc {
            label: Some("draw args"),
            size: 64,
            usage: BufferUsage::INDIRECT | BufferUsage::STORAGE,
            memory: MemoryLocation::DeviceLocal,
        })
        .expect("buffer");
    // Attachment-less: this test is about the arguments, and a pass with no
    // views to resolve keeps the recorded stream to the draws themselves.
    let pass = RenderPassDesc {
        label: Some("indirect"),
        color_attachments: &[],
        depth_stencil_attachment: None,
        render_area: Rect2d::from_size(16, 16),
        timestamp_writes: None,
    };

    recorder.clear();
    let mut encoder = device.create_command_encoder(&CommandEncoderDesc { label: None, queue });
    encoder.begin_render_pass(&pass);
    // Two structures 32 bytes apart from offset 4: a padded stride, which is
    // what `Capability::IndirectArgumentPaddedStride` promises is honoured
    // rather than tightened. Last byte read is 4 + 32 + 16 = 52, inside 64.
    encoder.draw_indirect(&DrawIndirect {
        args,
        offset: 4,
        draw_count: 2,
        stride: 32,
    });
    // One draw never strides, so `stride: 0` is legal and never told to an API.
    encoder.draw_indexed_indirect(&DrawIndirect {
        args,
        offset: 0,
        draw_count: 1,
        stride: 0,
    });
    encoder.end_render_pass();
    encoder.finish().expect("both draws obey the seam's rules");
    recorder.assert_valid();
    assert_eq!(
        recorder.command_names(),
        vec![
            "BeginRenderPass",
            "DrawIndirect",
            "DrawIndexedIndirect",
            "EndRenderPass",
        ]
    );

    // One encoder per refusal: the first hard failure is the one `finish`
    // reports, so a second on the same encoder would be masked.
    for (what, command, indexed, draw) in [
        (
            "an offset that is not a multiple of four",
            "DrawIndirect",
            false,
            DrawIndirect {
                args,
                offset: 2,
                draw_count: 1,
                stride: 16,
            },
        ),
        (
            "a stride below one 16-byte structure",
            "DrawIndirect",
            false,
            DrawIndirect {
                args,
                offset: 0,
                draw_count: 2,
                stride: 12,
            },
        ),
        (
            "a stride below one 20-byte indexed structure",
            "DrawIndexedIndirect",
            true,
            DrawIndirect {
                args,
                offset: 0,
                draw_count: 2,
                stride: 16,
            },
        ),
        (
            "two structures 32 bytes apart from offset 32 of a 64-byte buffer",
            "DrawIndirect",
            false,
            DrawIndirect {
                args,
                offset: 32,
                draw_count: 2,
                stride: 32,
            },
        ),
    ] {
        recorder.clear();
        let mut encoder = device.create_command_encoder(&CommandEncoderDesc { label: None, queue });
        encoder.begin_render_pass(&pass);
        if indexed {
            encoder.draw_indexed_indirect(&draw);
        } else {
            encoder.draw_indirect(&draw);
        }
        encoder.end_render_pass();

        let Err(HalError::InvalidDescriptor(reported)) = encoder.finish() else {
            panic!("{what} must fail the finish with an InvalidDescriptor");
        };
        let errors = recorder.validation_errors();
        let Some(ValidationError::InvalidIndirectArguments {
            command: recorded_command,
            message,
        }) = errors
            .iter()
            .find(|error| matches!(error, ValidationError::InvalidIndirectArguments { .. }))
        else {
            panic!("{what} must be recorded as well as reported: {errors:?}");
        };
        assert_eq!(*recorded_command, command, "{what}");
        assert_eq!(
            *message, reported,
            "{what}: `finish` reports the seam's own message, unchanged"
        );
        // A `finish` that fails publishes no stream at all — it returns before
        // the commands reach the recorder — so the refusal above is the whole
        // of what a test can read back, which is why it is recorded and not
        // only returned.
        assert!(
            recorder.command_names().is_empty(),
            "{what}: a failed finish commits nothing"
        );
    }

    device.destroy_buffer(args);
}

/// **A count-limited draw is held to the seam's rules too — the argument array
/// its plain form already had, and the count word's own offset and bound.**
///
/// [`crate::indirect::plan_count_structures`] states them, and this backend is
/// again the only one that can answer every one without a device: `crcbl-vk`
/// needs a live device to measure either buffer and `crcbl-webgpu` refuses the
/// call outright, WebGPU having no count-buffer draw. None of these is a
/// mistake an API reports: `vkCmdDrawIndirectCount` states `countBufferOffset`'s
/// alignment and range as valid-usage conditions with no error code behind them,
/// so a count word past the end of its buffer means the driver fetches a draw
/// count out of whatever is there and issues that many draws.
///
/// **The legal draws are half the test.** `crcbl-render`'s `EmitTail::Count`
/// path records one of these per bucket every frame, so a check that refused
/// them all would satisfy every refusal below and break the engine. The
/// accepting side runs first, and it includes the case that would go red if the
/// buffers were measured by their recorded `bytes` rather than their `size`:
/// both are device-local, so `bytes` is empty and every count-limited draw
/// would be refused.
///
/// **What turns it red.** Dropping the check from `draw_indirect_count` or
/// `draw_indexed_indirect_count` turns its refusals green; measuring the
/// *argument* buffer where the *count* buffer belongs accepts the count word
/// hanging off the end of the smaller one; using
/// [`structure_bytes`](crate::structure_bytes)`(false)` for the indexed form
/// accepts a 16-byte stride that skips a word of every structure after the
/// first.
#[test]
fn a_count_limited_draw_is_held_to_the_seams_argument_rules() {
    let (recorder, instance) = boxed(NullInstance::gpu_driven());
    let device = open(instance.as_ref());
    let queue = device.queue(QueueKind::Graphics).expect("graphics queue");
    let indirect_buffer = |label, size| {
        device
            .create_buffer(&BufferDesc {
                label: Some(label),
                size,
                usage: BufferUsage::INDIRECT | BufferUsage::STORAGE,
                memory: MemoryLocation::DeviceLocal,
            })
            .expect("buffer")
    };
    let args = indirect_buffer("count draw args", 64);
    // Two `u32` counts, so an offset of 4 is the last one that fits.
    let counts = indirect_buffer("count draw counts", 8);
    let pass = RenderPassDesc {
        label: Some("indirect count"),
        color_attachments: &[],
        depth_stencil_attachment: None,
        render_area: Rect2d::from_size(16, 16),
        timestamp_writes: None,
    };

    recorder.clear();
    let mut encoder = device.create_command_encoder(&CommandEncoderDesc { label: None, queue });
    encoder.begin_render_pass(&pass);
    // Two structures 32 bytes apart from offset 0 — a padded stride — with the
    // count at the last offset its 8-byte buffer has room for. Last argument
    // byte read is 32 + 16 = 48, inside 64.
    encoder.draw_indirect_count(&DrawIndirectCount {
        args,
        args_offset: 0,
        count_buffer: counts,
        count_offset: 4,
        max_draw_count: 2,
        stride: 32,
    });
    // Up to one draw never strides, so `stride: 0` is legal here for the reason
    // it is legal in the plain form.
    encoder.draw_indexed_indirect_count(&DrawIndirectCount {
        args,
        args_offset: 44,
        count_buffer: counts,
        count_offset: 0,
        max_draw_count: 1,
        stride: 0,
    });
    encoder.end_render_pass();
    encoder.finish().expect("both draws obey the seam's rules");
    recorder.assert_valid();
    assert_eq!(
        recorder.command_names(),
        vec![
            "BeginRenderPass",
            "DrawIndirectCount",
            "DrawIndexedIndirectCount",
            "EndRenderPass",
        ]
    );

    // One encoder per refusal: the first hard failure is the one `finish`
    // reports, so a second on the same encoder would be masked.
    for (what, command, indexed, draw) in [
        (
            "a count offset that is not a multiple of four",
            "DrawIndirectCount",
            false,
            DrawIndirectCount {
                args,
                args_offset: 0,
                count_buffer: counts,
                count_offset: 2,
                max_draw_count: 1,
                stride: 16,
            },
        ),
        (
            "a count word whose last byte is past its 8-byte buffer",
            "DrawIndirectCount",
            false,
            DrawIndirectCount {
                args,
                args_offset: 0,
                count_buffer: counts,
                count_offset: 8,
                max_draw_count: 1,
                stride: 16,
            },
        ),
        (
            "an argument offset that is not a multiple of four",
            "DrawIndirectCount",
            false,
            DrawIndirectCount {
                args,
                args_offset: 2,
                count_buffer: counts,
                count_offset: 0,
                max_draw_count: 1,
                stride: 16,
            },
        ),
        (
            "a stride below one 20-byte indexed structure",
            "DrawIndexedIndirectCount",
            true,
            DrawIndirectCount {
                args,
                args_offset: 0,
                count_buffer: counts,
                count_offset: 0,
                max_draw_count: 2,
                stride: 16,
            },
        ),
        (
            "two structures 32 bytes apart from offset 32 of a 64-byte buffer",
            "DrawIndirectCount",
            false,
            DrawIndirectCount {
                args,
                args_offset: 32,
                count_buffer: counts,
                count_offset: 0,
                max_draw_count: 2,
                stride: 32,
            },
        ),
    ] {
        recorder.clear();
        let mut encoder = device.create_command_encoder(&CommandEncoderDesc { label: None, queue });
        encoder.begin_render_pass(&pass);
        if indexed {
            encoder.draw_indexed_indirect_count(&draw);
        } else {
            encoder.draw_indirect_count(&draw);
        }
        encoder.end_render_pass();

        let Err(HalError::InvalidDescriptor(reported)) = encoder.finish() else {
            panic!("{what} must fail the finish with an InvalidDescriptor");
        };
        let errors = recorder.validation_errors();
        let Some(ValidationError::InvalidIndirectArguments {
            command: recorded_command,
            message,
        }) = errors
            .iter()
            .find(|error| matches!(error, ValidationError::InvalidIndirectArguments { .. }))
        else {
            panic!("{what} must be recorded as well as reported: {errors:?}");
        };
        assert_eq!(*recorded_command, command, "{what}");
        assert_eq!(
            *message, reported,
            "{what}: `finish` reports the seam's own message, unchanged"
        );
        assert!(
            recorder.command_names().is_empty(),
            "{what}: a failed finish commits nothing"
        );
    }

    device.destroy_buffer(args);
    device.destroy_buffer(counts);
}

/// **A buffer binding's offset is held to the alignment its slot requires, with
/// no device in the room.**
///
/// [`Limits`] says outright that
/// [`min_uniform_buffer_offset_alignment`](crate::Limits::min_uniform_buffer_offset_alignment)
/// and
/// [`min_storage_buffer_offset_alignment`](crate::Limits::min_storage_buffer_offset_alignment)
/// are alignments a binding offset must be a multiple of rather than ceilings,
/// and until [`crate::check_binding_offset_alignment`] existed only `crcbl-vk`
/// and the two deferred backends read either field — so the reference
/// implementation, which is what every no-GPU test measures a backend against,
/// could not state the rule at all. Vulkan reports the violation as
/// `VUID-VkWriteDescriptorSet-descriptorType-00327`: a validation message
/// naming a descriptor type rather than the caller's binding, and only with the
/// layers loaded.
///
/// **The accepting half runs first.** The two alignments differ on the desktop
/// preset — 64 for uniform, 16 for storage — so an offset legal in one slot is
/// refused in the other, which is what shows the check reads the slot rather
/// than one shared number.
#[test]
fn a_binding_offset_is_held_to_its_slots_alignment() {
    let instance = NullInstance::gpu_driven();
    let device = open(&instance);
    let limits = device.caps().limits;
    assert_eq!(limits.min_uniform_buffer_offset_alignment, 64);
    assert_eq!(limits.min_storage_buffer_offset_alignment, 16);

    let slot = |binding, kind| BindGroupLayoutEntry {
        binding,
        visibility: ShaderStages::COMPUTE,
        kind,
        count: 1,
        flags: crate::BindingFlags::empty(),
    };
    let layout = device
        .create_bind_group_layout(&BindGroupLayoutDesc {
            label: Some("one of each buffer kind"),
            entries: &[
                slot(0, BindingKind::UniformBuffer { dynamic: false }),
                slot(
                    1,
                    BindingKind::StorageBuffer {
                        read_only: true,
                        dynamic: false,
                        stride: 4,
                    },
                ),
            ],
        })
        .expect("a two-buffer layout");
    let buffer = device
        .create_buffer(&BufferDesc {
            label: Some("bound at several offsets"),
            size: 1024,
            usage: BufferUsage::UNIFORM | BufferUsage::STORAGE,
            memory: MemoryLocation::DeviceLocal,
        })
        .expect("buffer");
    let group_of = |uniform_offset, storage_offset| {
        let at = |binding, offset| BindGroupEntry {
            binding,
            array_index: 0,
            resource: crate::BindingResource::Buffer {
                buffer,
                offset,
                size: 256,
            },
        };
        device.create_bind_group(&BindGroupDesc {
            label: None,
            layout,
            entries: &[at(0, uniform_offset), at(1, storage_offset)],
            variable_count: None,
        })
    };

    let group = group_of(128, 32).expect("128 is a multiple of 64 and 32 of 16");
    device.destroy_bind_group(group);

    // 32 is a legal *storage* offset and an illegal uniform one.
    let error = group_of(32, 32).expect_err("32 is not a multiple of 64");
    let text = error.to_string();
    assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");
    assert!(text.contains("binding 0"), "{text}");
    assert!(text.contains("64-byte"), "{text}");

    let error = group_of(128, 8).expect_err("8 is not a multiple of 16");
    let text = error.to_string();
    assert!(matches!(error, HalError::InvalidDescriptor(_)), "{error:?}");
    assert!(text.contains("binding 1"), "{text}");
    assert!(text.contains("16-byte"), "{text}");

    device.destroy_buffer(buffer);
    device.destroy_bind_group_layout(layout);
}

/// **A bind's dynamic offsets are held to the same alignment, and to the count
/// the layout declares.**
///
/// The bind-time half of the rule above — [`crate::check_dynamic_offsets`]. A
/// dynamic offset is added to the descriptor's own offset before the shader
/// sees it, so it satisfies the same alignment, and Vulkan reports a violation
/// as `VUID-vkCmdBindDescriptorSets-pDynamicOffsets-01971`. The count is the
/// worse of the two to get wrong and is not a violation of anything: the
/// offsets are positional, so one too few silently shifts every later offset
/// onto the wrong slot and the shader reads the wrong bytes with nothing
/// objecting anywhere.
///
/// This backend answers both out of what it already recorded — the layout a
/// bind group was created against, and the slots that layout declares — where
/// `crcbl-vk` needs a device and a `VkDescriptorSetLayout` to reach the same
/// verdict and `crcbl-webgpu`'s encoder cannot reach a layout at all.
///
/// **The accepting bind runs first**, and it is the shape `crcbl-render` uses
/// for per-draw data: a dynamic uniform buffer stepped by a multiple of the
/// device's own alignment.
#[test]
fn a_binds_dynamic_offsets_are_held_to_the_layouts_slots() {
    let (recorder, instance) = boxed(NullInstance::gpu_driven());
    let device = open(instance.as_ref());
    let queue = device.queue(QueueKind::Compute).expect("compute queue");
    let limits = device.caps().limits;

    let slot = |binding, kind| BindGroupLayoutEntry {
        binding,
        visibility: ShaderStages::COMPUTE,
        kind,
        count: 1,
        flags: crate::BindingFlags::empty(),
    };
    let layout = device
        .create_bind_group_layout(&BindGroupLayoutDesc {
            label: Some("two dynamic slots"),
            entries: &[
                slot(0, BindingKind::UniformBuffer { dynamic: true }),
                slot(
                    1,
                    BindingKind::StorageBuffer {
                        read_only: true,
                        dynamic: true,
                        stride: 4,
                    },
                ),
            ],
        })
        .expect("a two-slot dynamic layout");
    let pipeline_layout = device
        .create_pipeline_layout(&PipelineLayoutDesc {
            label: Some("dynamic"),
            bind_group_layouts: &[layout],
            push_constants: None,
        })
        .expect("pipeline layout");
    let buffer = device
        .create_buffer(&BufferDesc {
            label: Some("per-draw data"),
            size: 1024,
            usage: BufferUsage::UNIFORM | BufferUsage::STORAGE,
            memory: MemoryLocation::DeviceLocal,
        })
        .expect("buffer");
    let at = |binding| BindGroupEntry {
        binding,
        array_index: 0,
        resource: crate::BindingResource::Buffer {
            buffer,
            offset: 0,
            size: 256,
        },
    };
    let group = device
        .create_bind_group(&BindGroupDesc {
            label: Some("dynamic"),
            layout,
            entries: &[at(0), at(1)],
            variable_count: None,
        })
        .expect("both offsets are zero, which every alignment divides");

    let pass = ComputePassDesc {
        label: Some("dynamic"),
        timestamp_writes: None,
    };

    recorder.clear();
    let mut encoder = device.create_command_encoder(&CommandEncoderDesc { label: None, queue });
    encoder.begin_compute_pass(&pass);
    encoder.bind_group(
        0,
        group,
        &[
            u32::try_from(limits.min_uniform_buffer_offset_alignment * 2).expect("64 fits a u32"),
            u32::try_from(limits.min_storage_buffer_offset_alignment * 2).expect("16 fits a u32"),
        ],
        pipeline_layout,
    );
    encoder.end_compute_pass();
    encoder
        .finish()
        .expect("both offsets are aligned and counted");
    recorder.assert_valid();
    assert_eq!(
        recorder.command_names(),
        vec!["BeginComputePass", "BindGroup", "EndComputePass"]
    );

    // One encoder per refusal: the first hard failure is the one `finish`
    // reports, so a second on the same encoder would be masked.
    for (what, offsets, expected) in [
        (
            "32 is a legal storage offset and an illegal uniform one",
            &[32u32, 32][..],
            "binding 0",
        ),
        ("8 is not a multiple of 16", &[128, 8][..], "binding 1"),
        (
            "one offset short shifts every later one onto the wrong slot",
            &[128][..],
            "dynamic-offset binding(s)",
        ),
        ("no offsets at all", &[][..], "dynamic-offset binding(s)"),
    ] {
        recorder.clear();
        let mut encoder = device.create_command_encoder(&CommandEncoderDesc { label: None, queue });
        encoder.begin_compute_pass(&pass);
        encoder.bind_group(0, group, offsets, pipeline_layout);
        encoder.end_compute_pass();

        let Err(HalError::InvalidDescriptor(reported)) = encoder.finish() else {
            panic!("{what} must fail the finish with an InvalidDescriptor");
        };
        assert!(reported.contains(expected), "{what}: {reported}");
        let errors = recorder.validation_errors();
        let Some(ValidationError::InvalidDynamicOffsets {
            command, message, ..
        }) = errors
            .iter()
            .find(|error| matches!(error, ValidationError::InvalidDynamicOffsets { .. }))
        else {
            panic!("{what} must be recorded as well as reported: {errors:?}");
        };
        assert_eq!(*command, "BindGroup", "{what}");
        assert_eq!(
            *message, reported,
            "{what}: `finish` reports the seam's own message, unchanged"
        );
        assert!(
            recorder.command_names().is_empty(),
            "{what}: a failed finish commits nothing"
        );
    }

    device.destroy_bind_group(group);
    device.destroy_buffer(buffer);
    device.destroy_pipeline_layout(pipeline_layout);
    device.destroy_bind_group_layout(layout);
}