crcbl-hal 0.3.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
//! `NullBackend` — a complete, recording implementation of the seam that talks
//! to no GPU.
//!
//! It exists for three jobs, in increasing order of usefulness:
//!
//! 1. **Prove the seam compiles and leaks nothing.** If a trait method could
//!    not be implemented without naming a backend type, this module would not
//!    build. The foundations stage named exactly this as its deliverable
//!    check (`docs/notes/backends.md`).
//! 2. **Be the substrate for the graph-compile suite.** `docs/notes/process.md`
//!    assigns `crcbl-hal`/`crcbl-vk`/`crcbl-webgpu` a "graph-compile unit suite on
//!    NullBackend"; the render graph that lands at P1 compiles its pass list
//!    against this backend in CI, with no GPU and no window.
//! 3. **Answer questions about a frame.** Every call is recorded, so a test can
//!    assert which passes ran in which order, which barriers separated them,
//!    and that nothing leaked. See [`Recorder`].
//!
//! # It can also be slow on purpose
//!
//! Two things the seam defers — readback and device creation — are instant
//! here, which would leave every caller's *poll loop* untested. [`Recorder`]
//! therefore takes a latency for each:
//! [`set_readback_latency`](Recorder::set_readback_latency) and
//! [`set_device_latency`](Recorder::set_device_latency) make N polls report
//! `Pending` before completing, which is what a browser's `mapAsync` and
//! `requestDevice` promises do and what no amount of native hardware will
//! reproduce.
//!
//! # And it can fail on purpose
//!
//! For the same reason, one step further: this backend never fails on its own,
//! so a caller's *error* paths would never run either.
//! [`report_device_error`](Recorder::report_device_error) queues an out-of-band
//! failure, [`fail_next_reconfigures`](Recorder::fail_next_reconfigures) refuses
//! a swapchain rebuild, [`report_swapchain_out_of_date`](Recorder::report_swapchain_out_of_date)
//! resizes the window out from under the frame loop,
//! [`report_suboptimal_acquires`](Recorder::report_suboptimal_acquires) hands
//! out a frame the surface has outgrown but will still take,
//! [`report_present_wait_timeouts`](Recorder::report_present_wait_timeouts)
//! leaves a pacing wait unanswered until its deadline passes — on a device that
//! claims [`Features::PRESENT_FEEDBACK`], which is what
//! [`NullInstance::with_present_feedback`] is for — and
//! [`lose_device`](Recorder::lose_device) kills the device for good. The
//! swapchain ones and the loss exist because the conditions they model — a
//! resize, a stale extent, a stalled compositor and a TDR — are otherwise
//! reachable only on a real driver at a moment nobody can schedule.
//!
//! # Always compiled
//!
//! Not behind a feature. See the crate docs for the argument — briefly: other
//! crates' *tests* depend on it, so a feature gate would have to be turned on
//! from their dev-dependencies, and feature unification would then make
//! `cargo test -p x` and `cargo build -p x` disagree.
//!
//! # It validates
//!
//! The backend checks pass nesting, that commands appear in the right scope, and
//! that every handle a command names is still alive. Violations are *recorded*,
//! not panicked on, so a failing test reports the whole frame's problems at once.
//! See [`ValidationError`] and [`Recorder::assert_valid`].
//!
//! # Two presets
//!
//! [`NullInstance::gpu_driven`] reports a full desktop device holding
//! [`Features::GPU_DRIVEN`] and most of what sits beside it;
//! [`NullInstance::portable`] reports the WebGPU-shaped floor — no bindless, no
//! `draw_indirect_count`, no buffer device address, no push constants, no
//! timeline semaphores, and an implicit swapchain acquire. They are two points
//! in the capability space rather than two tiers, and running the same renderer
//! code against both is how degradation gets tested before `crcbl-webgpu` runs
//! in a browser.
//!
//! ```
//! use crcbl_hal::null::{NullInstance, Recorder};
//! use crcbl_hal::{BindingModel, GeometryPath, Instance};
//!
//! let recorder = Recorder::new();
//! let instance: Box<dyn Instance> =
//!     Box::new(NullInstance::portable().with_recorder(recorder.clone()));
//!
//! let adapter = instance.adapters()[0].clone();
//! assert_eq!(adapter.caps.binding_model(), BindingModel::ArrayPages);
//! assert_eq!(adapter.caps.geometry_path(), GeometryPath::IndirectPerBatch);
//! assert_eq!(recorder.total_live_objects(), 0);
//! ```

mod record;

pub use record::{
    Command, Event, ObjectKind, PipelineRecord, Recorder, StageRecord, ValidationError,
};

use record::Detail;

use core::ops::Range;
use core::sync::atomic::{AtomicU64, Ordering};
use core::time::Duration;

use crcbl_core::{Handle, SurfaceTarget};

use crate::indirect::{
    IndirectPlan, plan_count_structures, plan_mesh_indirect, plan_structures, structure_bytes,
};
use crate::{
    AcquiredFrame, AdapterId, AdapterInfo, BackendKind, Barriers, BindGroupDesc, BindGroupEntry,
    BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry, BindGroupLayoutHandle, BindingKind,
    BufferCopy, BufferDesc, BufferHandle, BufferImageCopy, Capability, CommandBufferHandle,
    CommandEncoder, CommandEncoderDesc, CompositeAlpha, ComputePassDesc, ComputePipelineDesc,
    ComputePipelineHandle, Device, DeviceCaps, DeviceDesc, DeviceRequestState, DeviceType,
    DisplayTiming, DrawIndirect, DrawIndirectCount, Features, Format, GraphicsPipelineDesc,
    GraphicsPipelineHandle, HalError, ImageCopy, ImageDesc, ImageHandle, ImageType, ImageUsage,
    ImageViewDesc, ImageViewHandle, IndexFormat, Instance, Limits, MemoryLocation,
    MeshPipelineDesc, PassTimestampWrites, PendingDevice, PipelineLayoutDesc, PipelineLayoutHandle,
    PresentInfo, PresentMode, QueryKind, QuerySetDesc, QuerySetHandle, QueueHandle, QueueKind,
    ReadbackDesc, ReadbackHandle, ReadbackState, Rect2d, RenderPassDesc, SamplerDesc,
    SamplerHandle, SemaphoreDesc, SemaphoreHandle, SemaphoreKind, SemaphoreWait, ShaderModuleDesc,
    ShaderModuleHandle, ShaderSources, ShaderStages, SubmitInfo, Support, SurfaceCaps,
    SurfaceError, SurfaceHandle, SwapchainDesc, SwapchainHandle, Viewport,
};

/// Formats a null surface reports, and therefore the only ones a swapchain on
/// one may be configured with. `SwapchainDesc::format` says it must be one of
/// [`SurfaceCaps::formats`], so the two lists are one constant rather than two
/// that drift.
const SURFACE_FORMATS: &[Format] = &[Format::Bgra8UnormSrgb, Format::Bgra8Unorm];

/// Fewest images a null swapchain ring holds — [`SurfaceCaps::min_image_count`].
const RING_MIN_IMAGES: u32 = 2;
/// Most images a null swapchain ring holds — [`SurfaceCaps::max_image_count`].
const RING_MAX_IMAGES: u32 = 3;

/// Low bits of a synthesised queue handle that name the queue kind. The rest
/// carry the owning device's tag — see [`queue_handle`].
const QUEUE_KIND_BITS: u32 = 8;

/// The owning device's identity, squeezed into a queue handle's index field.
///
/// Queue handles are not pooled, so nothing else can record who issued one. 24
/// bits is more device identity than a process will ever use and leaves the low
/// byte for the kind.
fn queue_tag(device_id: u64) -> u32 {
    #[allow(clippy::cast_possible_truncation)]
    {
        (device_id % (1 << 24)) as u32
    }
}

/// Deterministic queue handles.
///
/// Queues are not pooled objects — they exist for the device's lifetime and
/// carry no state — so their handles are synthesised rather than allocated.
/// They still carry the **issuing device's tag**, because obligation 3 applies
/// to every handle and a queue handle from another device would otherwise be
/// indistinguishable from this device's own.
fn queue_handle(device_id: u64, index: u32) -> QueueHandle {
    let raw = (queue_tag(device_id) << QUEUE_KIND_BITS) | index;
    Handle::from_bits((1u64 << 32) | u64::from(raw)).expect("generation 1 is non-zero")
}

/// The queue-kind index behind a handle *this* device issued, or `None` if the
/// handle came from somewhere else.
fn queue_index_of(device_id: u64, queue: QueueHandle) -> Option<u32> {
    let raw = queue.index();
    (queue.generation() == 1 && (raw >> QUEUE_KIND_BITS) == queue_tag(device_id))
        .then_some(raw & ((1 << QUEUE_KIND_BITS) - 1))
}

/// Source of owner ids for instances and devices.
///
/// A [`Handle`] has no room for an owner (32-bit index + 32-bit generation are
/// fully spoken for), so ownership lives in the object side table instead. This
/// is the mechanism `crate::device`'s rule 3 obliges every backend to provide;
/// a real backend would key it off its `VkInstance`/`VkDevice` pointer instead
/// of a counter.
static NEXT_OWNER_ID: AtomicU64 = AtomicU64::new(1);

fn next_owner_id() -> u64 {
    NEXT_OWNER_ID.fetch_add(1, Ordering::Relaxed)
}

/// A no-op, recording [`Instance`].
///
/// Share its [`Recorder`] with [`NullInstance::with_recorder`] to inspect the
/// stream after running a frame entirely through `dyn` traits.
#[derive(Clone, Debug)]
pub struct NullInstance {
    recorder: Recorder,
    caps: DeviceCaps,
    name: String,
    /// Owner id stamped into every surface this instance creates. Cloning a
    /// `NullInstance` keeps the id, because a clone *is* the same instance;
    /// a separately constructed one gets a fresh id and its surfaces are
    /// therefore foreign to this one's devices.
    id: u64,
    /// How many adapters [`Instance::adapters`] reports. See
    /// [`NullInstance::with_adapters`].
    adapter_count: u32,
    geometry_preference: Option<crate::GeometryPath>,
}

impl NullInstance {
    /// A null instance reporting one adapter with `caps`.
    #[must_use]
    pub fn new(caps: DeviceCaps) -> Self {
        Self {
            recorder: Recorder::new(),
            caps,
            name: "null adapter".to_string(),
            id: next_owner_id(),
            adapter_count: 1,
            geometry_preference: None,
        }
    }

    /// Prefers a supported geometry tail while retaining the capability ceiling.
    /// If a device request omits that tail's feature, uses its granted ceiling.
    ///
    /// # Panics
    /// Panics if this instance's capabilities cannot run `path`.
    #[must_use]
    pub fn with_geometry_preference(mut self, path: crate::GeometryPath) -> Self {
        assert!(supports_geometry_path(self.caps.features, path));
        self.geometry_preference = Some(path);
        self
    }

    /// A full desktop device: everything in [`Features::GPU_DRIVEN`] —
    /// bindless, buffer device address, `draw_indirect_count`, multi-draw,
    /// compute, timeline semaphores — plus push constants, timestamps, the
    /// other query kinds and a draw index.
    ///
    /// [`Features::DRAW_INDEX`] is outside the default request, like
    /// [`Features::POLYGON_MODE_LINE`]: a device opened with
    /// [`DeviceDesc::for_adapter`](crate::DeviceDesc::for_adapter) is not
    /// granted it, and a test that wants a renderer drawing a range of buckets
    /// per call asks for it by name.
    ///
    /// Not mesh shaders and not ray tracing: those are separate selector axes,
    /// and a preset that held every flag would leave
    /// [`GeometryPath::MeshShader`](crate::GeometryPath::MeshShader) as the only
    /// answer any test could get.
    #[must_use]
    pub fn gpu_driven() -> Self {
        Self::new(DeviceCaps {
            features: Features::GPU_DRIVEN
                | Features::INDIRECT_FIRST_INSTANCE
                | Features::TIMESTAMP_QUERY
                | Features::PIPELINE_STATISTICS_QUERY
                | Features::OCCLUSION_QUERY
                | Features::ASYNC_COMPUTE_QUEUE
                | Features::TRANSFER_QUEUE
                | Features::PUSH_CONSTANTS
                | Features::DEPTH_CLAMP
                | Features::DEPTH_BIAS_CLAMP
                | Features::POLYGON_MODE_LINE
                | Features::TEXTURE_COMPRESSION_BC
                | Features::SAMPLER_ANISOTROPY
                | Features::DEBUG_MARKERS
                | Features::DRAW_INDEX,
            limits: Limits::desktop(),
        })
    }

    /// The floor every backend clears, shaped like WebGPU: compute only.
    ///
    /// No descriptor indexing, no buffer device address, no
    /// `draw_indirect_count`, no multi-draw, no push constants, no timeline
    /// semaphores, and — the shape that matters most — an **implicit swapchain
    /// acquire**, so [`AcquiredFrame`] comes back with no semaphores at all.
    /// Every selector lands on its lowest value here. Renderer code that works
    /// against both presets works against `crcbl-vk` and `crcbl-webgpu`.
    #[must_use]
    pub fn portable() -> Self {
        let mut instance = Self::new(DeviceCaps {
            features: Features::COMPUTE | Features::TEXTURE_COMPRESSION_BC,
            limits: Limits::minimum(),
        });
        instance.name = "null adapter (portable)".to_string();
        instance
    }

    /// This instance's adapter, plus [`Features::PRESENT_FEEDBACK`].
    ///
    /// Neither preset advertises it and neither should: there is no display
    /// under this backend, so an adapter that claimed by default to observe
    /// presents would be telling every test that opened one something untrue.
    /// But the capability is the switch on the seam's two answers for
    /// [`Device::wait_until_presented`] — without it the wait must return `Ok`
    /// at once, with it the wait may lapse — so a caller's timed-out-wait path
    /// needs a device that claims it, and until this existed such a device had
    /// to be assembled from [`DeviceCaps`] by hand in each test that wanted
    /// one.
    ///
    /// Claiming it is only half of what makes a wait lapse: nothing here is
    /// slow, so the timeout itself comes from
    /// [`Recorder::report_present_wait_timeouts`]. And this is the *adapter's*
    /// capability, so a device still gets it only by asking, as it would from a
    /// real backend.
    #[must_use]
    pub fn with_present_feedback(mut self) -> Self {
        self.caps.features.insert(Features::PRESENT_FEEDBACK);
        self
    }

    /// Reports `count` adapters instead of one, all with this instance's caps,
    /// each named with its index once there is more than one to tell apart.
    ///
    /// The switch on the seam's **adapter selection** loop, which needs more
    /// than one adapter before it is a loop at all. `crcbl/src/engine.rs`'s
    /// `start_device` walks the list asking each adapter for
    /// [`SurfaceCaps`] and takes the first that answers, because
    /// `crates/crcbl/tests/windowed_e2e.rs` found a discrete RADV GPU that
    /// enumerates first under Xvfb and cannot present to the window at all
    /// while the software rasteriser behind it can. With one adapter that walk
    /// has one outcome, so neither "the first refused and the second served"
    /// nor "every one refused" could be driven from any backend here.
    ///
    /// Reporting more than one is only half of it: nothing here makes an
    /// adapter *refuse*, so the refusal comes from
    /// [`Recorder::refuse_surface_on`]. The adapters are otherwise identical —
    /// same caps, same [`DeviceType::Cpu`] — because this backend has one set
    /// of capabilities and an adapter here claiming to be a discrete GPU would
    /// be telling every test that opened one something untrue.
    ///
    /// `count` may be `0`, which is a real state a real instance reaches — a
    /// machine with no GPU, a browser with no WebGPU — and the one the engine
    /// answers with "no adapter" before it walks anything.
    #[must_use]
    pub fn with_adapters(mut self, count: u32) -> Self {
        self.adapter_count = count;
        self
    }

    /// Uses `recorder` instead of this instance's own, so a caller can keep a
    /// handle on the stream after the instance is boxed as `dyn Instance`.
    #[must_use]
    pub fn with_recorder(mut self, recorder: Recorder) -> Self {
        self.recorder = recorder;
        self
    }

    /// A clone of this instance's recorder.
    #[must_use]
    pub fn recorder(&self) -> Recorder {
        self.recorder.clone()
    }

    /// Whether this backend models an implicit (WebGPU-style) swapchain
    /// acquire, in which case [`AcquiredFrame`] carries no semaphores.
    fn implicit_acquire(&self) -> bool {
        !self.caps.features.contains(Features::TIMELINE_SEMAPHORE)
    }

    /// Resolves a surface handle against *this* instance.
    fn check_surface(&self, surface: SurfaceHandle) -> Result<(), HalError> {
        let state = self.recorder.lock();
        if state.is_owned_by(ObjectKind::Surface, surface.to_bits(), self.id) {
            Ok(())
        } else if state.is_live(ObjectKind::Surface, surface.to_bits()) {
            Err(HalError::ForeignObject {
                kind: "surface",
                bits: surface.to_bits(),
            })
        } else {
            Err(HalError::invalid_handle("surface", surface))
        }
    }
}

impl Instance for NullInstance {
    fn backend(&self) -> BackendKind {
        BackendKind::Null
    }

    fn adapters(&self) -> Vec<AdapterInfo> {
        (0..self.adapter_count)
            .map(|index| AdapterInfo {
                id: AdapterId(index),
                // A lone adapter keeps the preset's plain name; a list suffixes
                // the index, so a log line or an assertion can say *which* one
                // was taken rather than only that one was.
                name: if self.adapter_count == 1 {
                    self.name.clone()
                } else {
                    format!("{} #{index}", self.name)
                },
                vendor_id: 0,
                device_id: 0,
                device_type: DeviceType::Cpu,
                driver: format!("crcbl-hal {}", env!("CARGO_PKG_VERSION")),
                backend: BackendKind::Null,
                caps: self.caps,
            })
            .collect()
    }

    unsafe fn create_surface(&self, target: &SurfaceTarget) -> Result<SurfaceHandle, HalError> {
        // Nothing is dereferenced, which is why this implementation is sound for
        // any input — the `unsafe` on the trait method is a contract real
        // backends need, not one this one uses.
        let mut state = self.recorder.lock();
        Ok(state.insert_owned(
            ObjectKind::Surface,
            self.id,
            Some(target.platform_name().to_string()),
            Detail::None,
        ))
    }

    fn destroy_surface(&self, surface: SurfaceHandle) {
        // Only this instance's surfaces; another instance's handle may collide
        // on bits and must not be destroyed by mistake. One lock, not two: a
        // check-then-act pair on a non-reentrant mutex is both racy and a
        // deadlock waiting for a scoping change.
        let mut state = self.recorder.lock();
        if state.is_owned_by(ObjectKind::Surface, surface.to_bits(), self.id) {
            state.remove(ObjectKind::Surface, surface.to_bits());
        }
    }

    fn surface_caps(
        &self,
        surface: SurfaceHandle,
        adapter: AdapterId,
    ) -> Result<SurfaceCaps, HalError> {
        if adapter.0 >= self.adapter_count {
            return Err(HalError::NoSuchAdapter(adapter.0));
        }
        self.check_surface(surface)?;
        // After the checks and outside their lock, as every other injection
        // point in this backend is: `check_surface` takes the recorder's mutex
        // and it is not reentrant.
        if self.recorder.refuses_surface(adapter) {
            return Err(HalError::Unsupported {
                backend: BackendKind::Null,
                what: "this adapter cannot present to this surface",
            });
        }
        Ok(SurfaceCaps {
            formats: SURFACE_FORMATS.to_vec(),
            present_modes: if self.implicit_acquire() {
                vec![PresentMode::Fifo]
            } else {
                vec![
                    PresentMode::Fifo,
                    PresentMode::Mailbox,
                    PresentMode::Immediate,
                ]
            },
            composite_alpha: vec![CompositeAlpha::Opaque],
            min_image_count: RING_MIN_IMAGES,
            max_image_count: RING_MAX_IMAGES,
            current_extent: None,
        })
    }

    fn request_device(&self, desc: &DeviceDesc<'_>) -> Result<Box<dyn PendingDevice>, HalError> {
        if desc.adapter.0 >= self.adapter_count {
            return Err(HalError::NoSuchAdapter(desc.adapter.0));
        }
        let missing = self.caps.missing(desc.required_features);
        if !missing.is_empty() {
            return Err(HalError::UnsupportedFeatures { missing });
        }
        if let Some(surface) = desc.compatible_surface {
            self.check_surface(surface)?;
        }
        // Optional features are granted only where the adapter has them, which
        // is the behaviour a caller must handle on a real backend. The union
        // with `required_features` that used to be here was dead: anything
        // required and absent left through `missing` above.
        let caps = DeviceCaps {
            features: self
                .caps
                .features
                .intersection(desc.required_features.union(desc.optional_features)),
            limits: self.caps.limits,
        };
        // Everything checkable is checked above, synchronously, which is the
        // seam's rule: only what depends on a driver answering may be deferred.
        // The null backend has no driver, so all that is left to defer is the
        // simulated latency.
        let device = NullDevice {
            recorder: self.recorder.clone(),
            instance_id: self.id,
            device_id: next_owner_id(),
            // The *device's* granted features decide the acquire shape, not the
            // adapter's. A caller that never asked for timeline semaphores gets
            // the implicit-acquire shape even on a fully featured adapter,
            // which is
            // exactly what it would get from a real backend.
            implicit_acquire: !caps.features.contains(Features::TIMELINE_SEMAPHORE),
            caps,
            adapter_features: self.caps.features,
            geometry_preference: self
                .geometry_preference
                .filter(|path| supports_geometry_path(caps.features, *path)),
        };
        let polls_remaining = self.recorder.lock().device_latency;
        Ok(Box::new(NullPendingDevice {
            polls_remaining,
            device: Some(Box::new(device)),
        }))
    }
}

/// A null device request in flight.
///
/// Reached through `dyn PendingDevice` from
/// [`Instance::request_device`]. The device is
/// built up front — nothing about it can fail late — and handed over once the
/// simulated latency from
/// [`Recorder::set_device_latency`] has elapsed, which is how a caller's poll
/// loop gets exercised with no GPU and no browser.
#[derive(Debug)]
struct NullPendingDevice {
    polls_remaining: u32,
    /// `None` once the device has been handed over, so a second poll is the
    /// caller bug it is rather than a second device.
    device: Option<Box<dyn Device>>,
}

impl PendingDevice for NullPendingDevice {
    fn backend(&self) -> BackendKind {
        BackendKind::Null
    }

    fn poll(&mut self) -> Result<DeviceRequestState, HalError> {
        let Some(device) = self.device.take() else {
            return Err(HalError::InvalidDescriptor(
                "this device request already produced its device".to_string(),
            ));
        };
        if self.polls_remaining > 0 {
            self.polls_remaining -= 1;
            self.device = Some(device);
            return Ok(DeviceRequestState::Pending);
        }
        Ok(DeviceRequestState::Ready(device))
    }
}

/// A no-op, recording [`Device`].
///
/// Reached through `dyn Device` from [`Instance::request_device`] — and from
/// `Instance::create_device`, which wraps it and does not exist on `wasm32`;
/// there is no reason for a test to name this type.
#[derive(Debug)]
struct NullDevice {
    recorder: Recorder,
    /// Id of the instance that created this device. Surfaces are checked
    /// against this, so any device from that instance may use them.
    instance_id: u64,
    /// Id stamped into every object this device creates.
    device_id: u64,
    caps: DeviceCaps,
    /// Everything the adapter can do, which may exceed what this device
    /// enabled. Used to decide which queues exist.
    adapter_features: Features,
    implicit_acquire: bool,
    geometry_preference: Option<crate::GeometryPath>,
}

impl NullDevice {
    /// Resolves a handle against an expected owner.
    ///
    /// Three outcomes, kept distinct because their fixes differ: resolved,
    /// resolved-but-someone-else's ([`HalError::ForeignObject`]), and gone
    /// ([`HalError::InvalidHandle`]).
    fn check_owner(
        &self,
        kind: ObjectKind,
        bits: u64,
        name: &'static str,
        owner: u64,
    ) -> Result<(), HalError> {
        self.check_lost()?;
        let state = self.recorder.lock();
        if state.is_owned_by(kind, bits, owner) {
            Ok(())
        } else if state.is_live(kind, bits) {
            Err(HalError::ForeignObject { kind: name, bits })
        } else {
            Err(HalError::InvalidHandle { kind: name, bits })
        }
    }

    /// Resolves a device-owned handle.
    fn check(&self, kind: ObjectKind, bits: u64, name: &'static str) -> Result<(), HalError> {
        self.check_owner(kind, bits, name, self.device_id)
    }

    /// Fails once [`Recorder::lose_device`] has been called, and thereafter.
    ///
    /// One insertion point rather than one per method: [`check_owner`] and
    /// [`check_queue`] are the two funnels every fallible call that names a
    /// handle already passes through, so gating them is what makes a lost
    /// device lost everywhere at once — and it lands the error in the right
    /// vocabulary for free, since the presentation calls wrap what they return
    /// in [`SurfaceError::Hal`], which is exactly what `crcbl-vk`'s
    /// `surface_error` does with `VK_ERROR_DEVICE_LOST`.
    ///
    /// [`check_owner`]: Self::check_owner
    /// [`check_queue`]: Self::check_queue
    fn check_lost(&self) -> Result<(), HalError> {
        match self.recorder.lock().lost_device.clone() {
            Some(message) => Err(HalError::DeviceLost(message)),
            None => Ok(()),
        }
    }

    /// Resolves a swapchain handle for one of the three calls a frame makes on
    /// it, and reports the out-of-date latch first.
    ///
    /// `acquire_next_frame`, `present` and `wait_until_presented` all have to
    /// answer the same way while the surface has moved under the swapchain —
    /// that is what makes a resize storm a storm rather than one bad call — so
    /// they ask in one place instead of three.
    ///
    /// The handle is resolved *before* the latch is read, so a swapchain that
    /// was destroyed still reports its own bug rather than an out-of-date one;
    /// and a lost device beats both, through [`check_lost`](Self::check_lost)
    /// inside the resolve.
    fn check_current(&self, swapchain: SwapchainHandle) -> Result<(), SurfaceError> {
        self.check(ObjectKind::Swapchain, swapchain.to_bits(), "swapchain")
            .map_err(SurfaceError::Hal)?;
        if self.recorder.lock().swapchain_out_of_date {
            return Err(SurfaceError::OutOfDate);
        }
        Ok(())
    }

    /// Resolves an instance-owned handle — surfaces, and only surfaces.
    fn check_instance_owned(
        &self,
        kind: ObjectKind,
        bits: u64,
        name: &'static str,
    ) -> Result<(), HalError> {
        self.check_owner(kind, bits, name, self.instance_id)
    }

    /// Resolves one pipeline stage: its module handle, and that the module can
    /// actually supply the entry point the stage names.
    ///
    /// The second half only bites a module that offered DXIL. That is the one
    /// artifact format with a container *per entry point*, so it is the one a
    /// call site can under-supply — offering the vertex container and not the
    /// fragment one leaves every other backend working and D3D12 with no
    /// bytecode for half the pipeline. Every real backend that consumes DXIL
    /// refuses that; saying so here means the no-GPU suite catches it on a
    /// machine with no D3D12, which is where these call sites are written.
    ///
    /// A module with no DXIL at all is not held to anything: it made no claim,
    /// and the backends that read its SPIR-V, WGSL or MSL find every entry
    /// point inside the one artifact.
    fn check_stage(&self, stage: crate::ShaderEntry<'_>) -> Result<(), HalError> {
        let bits = stage.module.to_bits();
        self.check(ObjectKind::ShaderModule, bits, "shader module")?;
        let state = self.recorder.lock();
        let Some(Detail::ShaderModule { dxil }) = state
            .get(ObjectKind::ShaderModule, bits)
            .map(|object| &object.detail)
        else {
            return Ok(());
        };
        if dxil.is_empty() || dxil.iter().any(|(name, _)| name == stage.entry_point) {
            return Ok(());
        }
        Err(HalError::ShaderCompilation(format!(
            "shader module `{label}` offers DXIL for {held}, and this stage names `{wanted}`; a \
             DXIL container is compiled for one entry point, so a module used at two stages has \
             to offer a container for each",
            label = state
                .get(ObjectKind::ShaderModule, bits)
                .and_then(|object| object.label.as_deref())
                .unwrap_or("<unlabelled>"),
            held = dxil
                .iter()
                .map(|(name, _)| name.as_str())
                .collect::<Vec<_>>()
                .join(", "),
            wanted = stage.entry_point,
        )))
    }

    /// Files a pipeline that has passed every check in
    /// [`Recorder::pipelines_created`], resolving its layout's sets and each
    /// stage's DXIL container while the handles are still live.
    fn record_pipeline(
        &self,
        label: Option<&str>,
        layout: PipelineLayoutHandle,
        stages: &[(ShaderStages, crate::ShaderEntry<'_>)],
    ) {
        let mut state = self.recorder.lock();
        let (sets, push_constants) = match state
            .get(ObjectKind::PipelineLayout, layout.to_bits())
            .map(|object| &object.detail)
        {
            Some(Detail::PipelineLayout {
                sets,
                push_constants,
            }) => (sets.clone(), *push_constants),
            _ => unreachable!("every caller checked the pipeline layout handle first"),
        };
        let stages = stages
            .iter()
            .map(|(stage, entry)| StageRecord {
                stage: *stage,
                entry_point: entry.entry_point.to_owned(),
                dxil: match state
                    .get(ObjectKind::ShaderModule, entry.module.to_bits())
                    .map(|object| &object.detail)
                {
                    Some(Detail::ShaderModule { dxil }) => dxil
                        .iter()
                        .find(|(name, _)| name == entry.entry_point)
                        .map(|(_, bytes)| bytes.clone()),
                    _ => None,
                },
            })
            .collect();
        state.pipelines_created.push(PipelineRecord {
            label: label.map(ToOwned::to_owned),
            sets,
            push_constants,
            stages,
        });
    }

    fn insert<T>(&self, kind: ObjectKind, label: Option<&str>, detail: Detail) -> Handle<T> {
        self.recorder.lock().insert_owned(
            kind,
            self.device_id,
            label.map(ToOwned::to_owned),
            detail,
        )
    }

    /// Destroys a handle, but only if this device owns it.
    ///
    /// One lock for the check and the removal — see `destroy_surface`.
    fn remove(&self, kind: ObjectKind, bits: u64) {
        let mut state = self.recorder.lock();
        if state.is_owned_by(kind, bits, self.device_id) {
            state.remove(kind, bits);
        }
    }

    fn unsupported(&self, what: &'static str) -> HalError {
        HalError::Unsupported {
            backend: BackendKind::Null,
            what,
        }
    }

    /// The checks a raster and a mesh pipeline share.
    ///
    /// Everything after the geometry stages is identical between the two —
    /// same layout, same fragment stage, same attachment formats, same
    /// rasteriser state — so the two `create_*_pipeline` methods differ only in
    /// the stages they resolve and the capability they demand. Splitting it
    /// this way is what keeps a fix to one of these checks from landing in one
    /// pipeline kind and not the other.
    fn check_raster_state(
        &self,
        layout: PipelineLayoutHandle,
        fragment: Option<crate::ShaderEntry<'_>>,
        color_targets: &[crate::ColorTargetState],
        primitive: crate::PrimitiveState,
        depth_stencil: Option<crate::DepthStencilState>,
    ) -> Result<(), HalError> {
        self.check(
            ObjectKind::PipelineLayout,
            layout.to_bits(),
            "pipeline layout",
        )?;
        if let Some(fragment) = fragment {
            self.check_stage(fragment)?;
        }
        if color_targets.len() > self.caps.limits.max_color_attachments as usize {
            return Err(HalError::InvalidDescriptor(format!(
                "{} colour targets exceeds max_color_attachments {}",
                color_targets.len(),
                self.caps.limits.max_color_attachments
            )));
        }
        if primitive.polygon_mode == crate::PolygonMode::Line
            && !self.caps.features.contains(Features::POLYGON_MODE_LINE)
        {
            return Err(self.unsupported("wireframe polygon mode"));
        }
        if primitive.depth_clamp && !self.caps.features.contains(Features::DEPTH_CLAMP) {
            return Err(self.unsupported("depth clamping"));
        }
        if let Some(depth) = depth_stencil
            && !depth.format.is_depth_stencil()
        {
            return Err(HalError::InvalidDescriptor(format!(
                "{:?} is not a depth/stencil format",
                depth.format
            )));
        }
        Ok(())
    }

    /// Whether this device has a queue of `kind` at all.
    fn has_queue(&self, kind: QueueKind) -> bool {
        match kind {
            QueueKind::Graphics => true,
            QueueKind::Compute => self
                .adapter_features
                .contains(Features::ASYNC_COMPUTE_QUEUE),
            QueueKind::Transfer => self.adapter_features.contains(Features::TRANSFER_QUEUE),
        }
    }

    /// Resolves a queue handle against *this* device.
    ///
    /// Obligation 3 covers queues too. `submit`, `present` and
    /// `create_command_encoder` used to ignore the argument entirely, so a
    /// handle from another device — or a hand-made one — submitted happily.
    fn check_queue(&self, queue: QueueHandle) -> Result<(), HalError> {
        self.check_lost()?;
        let bits = queue.to_bits();
        let Some(index) = queue_index_of(self.device_id, queue) else {
            // Another device's queue handle is well-formed but not ours; a
            // hand-made one is neither, and there is no way to tell them apart
            // from the bits, so the more specific error is the honest one only
            // when the shape is right.
            return Err(if queue.generation() == 1 {
                HalError::ForeignObject {
                    kind: "queue",
                    bits,
                }
            } else {
                HalError::InvalidHandle {
                    kind: "queue",
                    bits,
                }
            });
        };
        let kind = match index {
            0 => QueueKind::Graphics,
            1 => QueueKind::Compute,
            2 => QueueKind::Transfer,
            _ => {
                return Err(HalError::InvalidHandle {
                    kind: "queue",
                    bits,
                });
            }
        };
        if self.has_queue(kind) {
            Ok(())
        } else {
            Err(HalError::InvalidHandle {
                kind: "queue",
                bits,
            })
        }
    }
}

/// The refusal both signalling paths share: a timeline only moves forwards.
///
/// One wording for [`Device::signal_semaphore`] and [`Device::submit`], because
/// the rule is the semaphore's rather than either call's — a caller that learns
/// it from the host signal meets the same rule the moment a submission carries
/// one, and two spellings of it would read as two different rules.
fn timeline_goes_backwards(value: u64, held: u64) -> HalError {
    HalError::InvalidDescriptor(format!(
        "a timeline semaphore signalled with {value} already holds {held}; a timeline only moves \
         forwards and a waiter on the higher value would never wake"
    ))
}

/// The index a queue kind occupies in a synthesised handle.
const fn queue_kind_index(kind: QueueKind) -> u32 {
    match kind {
        QueueKind::Graphics => 0,
        QueueKind::Compute => 1,
        QueueKind::Transfer => 2,
    }
}

fn supports_geometry_path(features: Features, path: crate::GeometryPath) -> bool {
    match path {
        crate::GeometryPath::MeshShader => features.contains(Features::MESH_SHADER),
        crate::GeometryPath::IndirectCount => features.contains(Features::DRAW_INDIRECT_COUNT),
        crate::GeometryPath::IndirectPerBatch => true,
    }
}

impl Device for NullDevice {
    fn backend(&self) -> BackendKind {
        BackendKind::Null
    }

    fn caps(&self) -> DeviceCaps {
        self.caps
    }

    fn preferred_geometry_path(&self) -> crate::GeometryPath {
        self.geometry_preference
            .unwrap_or_else(|| self.caps.geometry_path())
    }

    /// What this recorder does with each seam behaviour.
    ///
    /// **"Supported" here means recorded faithfully, not executed.** This
    /// backend has no GPU, so a [`Support::Yes`] is the claim that the call is
    /// accepted with all of its arguments and appears in the stream a test reads
    /// back — which is exactly the property the graph's unit suite asserts
    /// against, and all a recorder can promise.
    ///
    /// The refusals are the ones this backend already has, and every one of them
    /// is a feature the preset did not grant: `NullInstance::portable` and
    /// `NullInstance::gpu_driven` differ, so this answer differs between two
    /// devices of the same backend, which is the shape a real backend's answer
    /// has too.
    ///
    /// Exhaustive with no wildcard arm, and `deny`-ed as such: a capability
    /// added to the enum has to be answered here as well as in the five GPU
    /// backends, because a recorder that silently accepted a command nothing
    /// implements would be the first place the rot could hide.
    #[deny(clippy::wildcard_enum_match_arm)]
    fn supports(&self, capability: Capability) -> Support {
        let has = self.caps.features;
        // One place the "the preset did not grant it" sentence is written, so
        // fourteen arms cannot word it fourteen ways.
        let gated = |feature: Features, why: &'static str| -> Support {
            Support::granted(has, feature, why)
        };

        match capability {
            // Recorded verbatim, arguments and all.
            Capability::BufferFillZero
            | Capability::ImageToImageCopy
            | Capability::DepthImageCopy
            | Capability::MsaaResolveAttachment
            | Capability::StencilReference
            | Capability::IndirectArgumentPaddedStride
            | Capability::BinarySemaphore
            | Capability::TimelineWaitBeforeSignal
            | Capability::StorageImageBinding => Support::Yes,
            // `update_bind_group` is refused per *layout*, on the UPDATE_AFTER_BIND
            // flag it was built with, so the backend has the operation.
            Capability::UpdateBindGroup => Support::Yes,
            Capability::DrawIndirectCount => gated(
                Features::DRAW_INDIRECT_COUNT,
                "this preset did not grant DRAW_INDIRECT_COUNT",
            ),
            Capability::MeshShading => gated(
                Features::MESH_SHADER,
                "this preset did not grant MESH_SHADER",
            ),
            Capability::TaskShaderStage => gated(
                Features::TASK_SHADER,
                "this preset did not grant TASK_SHADER",
            ),
            Capability::PushConstants => gated(
                Features::PUSH_CONSTANTS,
                "this preset did not grant PUSH_CONSTANTS",
            ),
            Capability::BindlessDescriptorArray => gated(
                Features::DESCRIPTOR_INDEXING,
                "this preset did not grant DESCRIPTOR_INDEXING",
            ),
            Capability::PolygonModeLine => gated(
                Features::POLYGON_MODE_LINE,
                "this preset did not grant POLYGON_MODE_LINE",
            ),
            Capability::DepthClamp => gated(
                Features::DEPTH_CLAMP,
                "this preset did not grant DEPTH_CLAMP",
            ),
            Capability::SamplerAnisotropy => gated(
                Features::SAMPLER_ANISOTROPY,
                "this preset did not grant SAMPLER_ANISOTROPY",
            ),
            Capability::TimestampQuery => gated(
                Features::TIMESTAMP_QUERY,
                "this preset did not grant TIMESTAMP_QUERY",
            ),
            // Not a preset question, unlike every gate around it: this
            // recorder refuses the kind whatever it was granted, because what
            // is missing is a verb on `CommandEncoder` rather than a feature on
            // a device. See `crate::NO_OCCLUSION_QUERY_VERB`, and
            // `create_query_set` below, which refuses the same set.
            Capability::OcclusionQuery => Support::No(crate::NO_OCCLUSION_QUERY_VERB),
            Capability::PipelineStatisticsQuery => gated(
                Features::PIPELINE_STATISTICS_QUERY,
                "this preset did not grant PIPELINE_STATISTICS_QUERY",
            ),
            Capability::TimelineSemaphore
            | Capability::CpuTimelineWait
            | Capability::CpuTimelineSignal => gated(
                Features::TIMELINE_SEMAPHORE,
                "this preset did not grant TIMELINE_SEMAPHORE",
            ),
        }
    }

    /// Whatever [`Recorder::report_device_error`] queued, oldest first.
    ///
    /// Nothing in this backend fails on its own — it is a recorder, not a
    /// driver — so every error here was put there by a test that wants to see
    /// what its caller does with one.
    fn take_error(&self) -> Option<String> {
        self.recorder.take_device_error()
    }

    fn queue(&self, kind: QueueKind) -> Option<QueueHandle> {
        self.has_queue(kind)
            .then(|| queue_handle(self.device_id, queue_kind_index(kind)))
    }

    // --- resources ---

    fn create_buffer(&self, desc: &BufferDesc<'_>) -> Result<BufferHandle, HalError> {
        if desc.size == 0 {
            return Err(HalError::InvalidDescriptor(
                "buffer size must be non-zero".to_string(),
            ));
        }
        let bytes = if desc.memory.is_mappable() {
            vec![
                0u8;
                usize::try_from(desc.size).map_err(|_| {
                    HalError::InvalidDescriptor("mappable buffer larger than usize".to_string())
                })?
            ]
        } else {
            Vec::new()
        };
        Ok(self.insert(
            ObjectKind::Buffer,
            desc.label,
            Detail::Buffer {
                size: desc.size,
                memory: desc.memory,
                bytes,
            },
        ))
    }

    fn destroy_buffer(&self, buffer: BufferHandle) {
        self.remove(ObjectKind::Buffer, buffer.to_bits());
    }

    fn write_buffer(&self, buffer: BufferHandle, offset: u64, data: &[u8]) -> Result<(), HalError> {
        self.check(ObjectKind::Buffer, buffer.to_bits(), "buffer")?;
        let mut state = self.recorder.lock();
        let Some(object) = state.get_mut(ObjectKind::Buffer, buffer.to_bits()) else {
            return Err(HalError::invalid_handle("buffer", buffer));
        };
        let Detail::Buffer {
            size,
            memory,
            bytes,
        } = &mut object.detail
        else {
            unreachable!("a buffer handle always carries buffer detail");
        };
        if *memory != MemoryLocation::HostUpload {
            return Err(HalError::InvalidDescriptor(format!(
                "write_buffer needs HostUpload memory, buffer is {memory:?}"
            )));
        }
        let start = usize::try_from(offset)
            .map_err(|_| HalError::InvalidDescriptor("offset exceeds usize".to_string()))?;
        let end = start
            .checked_add(data.len())
            .ok_or_else(|| HalError::InvalidDescriptor("offset + len overflows".to_string()))?;
        if end as u64 > *size {
            return Err(HalError::InvalidDescriptor(format!(
                "write of {} bytes at {offset} exceeds the {size}-byte buffer",
                data.len(),
            )));
        }
        bytes[start..end].copy_from_slice(data);
        state.events.push(Event::BufferWritten {
            buffer,
            offset,
            len: data.len(),
        });
        Ok(())
    }

    fn request_readback(&self, desc: &ReadbackDesc<'_>) -> Result<ReadbackHandle, HalError> {
        self.check(ObjectKind::Buffer, desc.buffer.to_bits(), "buffer")?;
        if let Some(wait) = desc.after {
            self.check(ObjectKind::Semaphore, wait.semaphore.to_bits(), "semaphore")?;
        }
        // Re-resolved under a fresh lock, so a concurrent `destroy_buffer` in
        // the gap since `check` is an `InvalidHandle` rather than a panic:
        // `Device` is `&self + Send + Sync`, so that gap is reachable.
        let (memory, buffer_size) = {
            let state = self.recorder.lock();
            let Some(object) = state.get(ObjectKind::Buffer, desc.buffer.to_bits()) else {
                return Err(HalError::invalid_handle("buffer", desc.buffer));
            };
            let Detail::Buffer { size, memory, .. } = &object.detail else {
                unreachable!("a buffer handle always carries buffer detail");
            };
            (*memory, *size)
        };
        if memory != MemoryLocation::HostReadback {
            return Err(HalError::InvalidDescriptor(format!(
                "readback needs HostReadback memory, buffer is {memory:?}"
            )));
        }
        let end = desc
            .offset
            .checked_add(desc.size)
            .ok_or_else(|| HalError::InvalidDescriptor("offset + size overflows".to_string()))?;
        if end > buffer_size {
            return Err(HalError::InvalidDescriptor(format!(
                "readback of {} bytes at {} exceeds the {buffer_size}-byte buffer",
                desc.size, desc.offset
            )));
        }
        let mut state = self.recorder.lock();
        let polls_remaining = state.readback_latency;
        let handle = state.insert_owned(
            ObjectKind::Readback,
            self.device_id,
            desc.label.map(ToOwned::to_owned),
            Detail::Readback {
                buffer: desc.buffer,
                offset: desc.offset,
                size: desc.size,
                polls_remaining,
            },
        );
        state.events.push(Event::ReadbackRequested {
            buffer: desc.buffer,
            offset: desc.offset,
            size: desc.size,
        });
        Ok(handle)
    }

    fn poll_readback(
        &self,
        readback: ReadbackHandle,
        out: &mut [u8],
    ) -> Result<ReadbackState, HalError> {
        self.check(ObjectKind::Readback, readback.to_bits(), "readback")?;
        let (buffer, offset, ready) = {
            let mut state = self.recorder.lock();
            let Some(object) = state.get_mut(ObjectKind::Readback, readback.to_bits()) else {
                return Err(HalError::invalid_handle("readback", readback));
            };
            let Detail::Readback {
                buffer,
                offset,
                size,
                polls_remaining,
            } = &mut object.detail
            else {
                unreachable!("a readback handle always carries readback detail");
            };
            // The descriptor check happens *before* the simulated latency
            // advances. A rejected poll must not consume one: a caller whose
            // slice is the wrong length would otherwise see the configured
            // latency shortened by however many times it got the length wrong,
            // which makes the latency it is being tested against a lie.
            if out.len() as u64 != *size {
                return Err(HalError::InvalidDescriptor(format!(
                    "poll_readback needs a {size}-byte slice, got {}",
                    out.len()
                )));
            }
            let ready = *polls_remaining == 0;
            if !ready {
                *polls_remaining -= 1;
            }
            (*buffer, *offset, ready)
        };
        if !ready {
            return Ok(ReadbackState::Pending);
        }
        // The source buffer may have been destroyed between request and poll,
        // which is a caller bug and must be reported rather than read.
        self.check(ObjectKind::Buffer, buffer.to_bits(), "buffer")?;
        let mut state = self.recorder.lock();
        let Some(object) = state.get(ObjectKind::Buffer, buffer.to_bits()) else {
            return Err(HalError::invalid_handle("buffer", buffer));
        };
        let Detail::Buffer { bytes, .. } = &object.detail else {
            unreachable!("a buffer handle always carries buffer detail");
        };
        let start = usize::try_from(offset)
            .map_err(|_| HalError::InvalidDescriptor("offset exceeds usize".to_string()))?;
        out.copy_from_slice(&bytes[start..start + out.len()]);
        let len = out.len();
        state.events.push(Event::BufferRead {
            buffer,
            offset,
            len,
        });
        Ok(ReadbackState::Ready)
    }

    fn destroy_readback(&self, readback: ReadbackHandle) {
        self.remove(ObjectKind::Readback, readback.to_bits());
    }

    fn create_image(&self, desc: &ImageDesc<'_>) -> Result<ImageHandle, HalError> {
        // Every rule this used to spell out inline is now `ImageDesc::check`,
        // on the seam, so a backend that wants them does not copy them. The
        // messages are the ones that were here; this backend is the reference
        // the others are compared against, so they had to stay exact.
        desc.check(&self.caps.limits)?;
        // `depth_or_layers` is the *depth* of a 3D image and the array-layer
        // count of every other type, so a volume has one array layer however
        // deep it is. Filing the raw field would make every 3D image look
        // `depth` layers deep to `ImageViewDesc::check`, which is the one
        // reading of this field that turns the rule into nonsense.
        let layers = if desc.image_type == ImageType::D3 {
            1
        } else {
            desc.extent.depth_or_layers
        };
        Ok(self.insert(
            ObjectKind::Image,
            desc.label,
            Detail::Image {
                format: desc.format,
                mip_levels: desc.mip_levels,
                layers,
            },
        ))
    }

    fn destroy_image(&self, image: ImageHandle) {
        self.remove(ObjectKind::Image, image.to_bits());
    }

    fn create_image_view(&self, desc: &ImageViewDesc<'_>) -> Result<ImageViewHandle, HalError> {
        self.check(ObjectKind::Image, desc.image.to_bits(), "image")?;
        // The seam's subresource rule, which this backend could not state
        // before: `create_image` filed `Detail::None`, so neither count was
        // anywhere to be read and a view of mips the image never had was
        // served here while `crcbl-mtl` and `crcbl-dx12` refused it.
        let (image_format, mip_levels, layers) = {
            let state = self.recorder.lock();
            let Some(object) = state.get(ObjectKind::Image, desc.image.to_bits()) else {
                return Err(HalError::invalid_handle("image", desc.image));
            };
            let Detail::Image {
                format,
                mip_levels,
                layers,
            } = &object.detail
            else {
                unreachable!("an image handle always carries image detail");
            };
            (*format, *mip_levels, *layers)
        };
        desc.check(image_format, mip_levels, layers)?;
        Ok(self.insert(ObjectKind::ImageView, desc.label, Detail::None))
    }

    fn destroy_image_view(&self, view: ImageViewHandle) {
        self.remove(ObjectKind::ImageView, view.to_bits());
    }

    fn create_sampler(&self, desc: &SamplerDesc<'_>) -> Result<SamplerHandle, HalError> {
        // The ceiling is the rule this backend already had, now stated once on
        // the seam with the message that was here. The floor is the one it did
        // not: `crcbl-vk`, `crcbl-mtl` and `crcbl-dx12` all refused an
        // anisotropy below the value that disables it while this backend — the
        // reference the others are compared against — served it.
        desc.check_anisotropy_floor()?;
        desc.check_anisotropy_ceiling(&self.caps.limits)?;
        Ok(self.insert(ObjectKind::Sampler, desc.label, Detail::None))
    }

    fn destroy_sampler(&self, sampler: SamplerHandle) {
        self.remove(ObjectKind::Sampler, sampler.to_bits());
    }

    // --- shaders and pipelines ---

    /// Accepts every format the seam defines and records which ones it was
    /// handed.
    ///
    /// The null backend compiles nothing, so it is the one backend with no
    /// reason to prefer a format — and that is what makes it the place a test
    /// asserts what a *caller* supplied. See
    /// [`Recorder::shader_modules_created`](crate::null::Recorder::shader_modules_created).
    fn create_shader_module(
        &self,
        desc: &ShaderModuleDesc<'_>,
    ) -> Result<ShaderModuleHandle, HalError> {
        let sources = desc.provided();
        if sources.is_empty() {
            // Every real backend rejects this too; saying so here means the
            // no-GPU suite catches a call site that stopped passing artifacts.
            return Err(desc.unusable(ShaderSources::all()));
        }
        // The SPIR-V magic number. Checking it costs nothing and catches the
        // classic "passed bytes where words were wanted" mistake, which
        // otherwise surfaces as a driver error at P1. Only when SPIR-V was
        // offered at all: a WGSL-only module is legal and has no magic number.
        const SPIRV_MAGIC: u32 = 0x0723_0203;
        if let Some(&word) = desc.spirv.first()
            && word != SPIRV_MAGIC
        {
            return Err(HalError::ShaderCompilation(format!(
                "not SPIR-V: first word is {word:#010x}, expected {SPIRV_MAGIC:#010x}"
            )));
        }
        self.recorder
            .lock()
            .shader_modules_created
            .push((desc.label.map(ToOwned::to_owned), sources));
        Ok(self.insert(
            ObjectKind::ShaderModule,
            desc.label,
            Detail::ShaderModule {
                dxil: desc
                    .dxil
                    .iter()
                    .map(|(entry_point, bytes)| ((*entry_point).to_owned(), bytes.to_vec()))
                    .collect(),
            },
        ))
    }

    fn destroy_shader_module(&self, module: ShaderModuleHandle) {
        self.remove(ObjectKind::ShaderModule, module.to_bits());
    }

    fn create_bind_group_layout(
        &self,
        desc: &BindGroupLayoutDesc<'_>,
    ) -> Result<BindGroupLayoutHandle, HalError> {
        desc.check_entries(&self.caps, BackendKind::Null)?;
        let update_after_bind = desc
            .entries
            .iter()
            .any(|entry| entry.flags.contains(crate::BindingFlags::UPDATE_AFTER_BIND));
        let variable_binding = desc
            .entries
            .iter()
            .find(|entry| entry.flags.contains(crate::BindingFlags::VARIABLE_COUNT))
            .map(|entry| entry.binding);
        self.recorder
            .lock()
            .bind_group_layouts_created
            .push((desc.label.map(ToOwned::to_owned), desc.entries.to_vec()));
        Ok(self.insert(
            ObjectKind::BindGroupLayout,
            desc.label,
            Detail::BindGroupLayout {
                entries: desc.entries.to_vec(),
                update_after_bind,
                variable_binding,
            },
        ))
    }

    fn destroy_bind_group_layout(&self, layout: BindGroupLayoutHandle) {
        self.remove(ObjectKind::BindGroupLayout, layout.to_bits());
    }

    fn create_bind_group(&self, desc: &BindGroupDesc<'_>) -> Result<BindGroupHandle, HalError> {
        self.check(
            ObjectKind::BindGroupLayout,
            desc.layout.to_bits(),
            "bind group layout",
        )?;
        let layout = self.layout_of(desc.layout)?;
        // `variable_count` is what the *pool* is sized with on a real backend,
        // so an over-large one fails `vkAllocateDescriptorSets` with a VUID
        // rather than the named error the rest of the seam produces.
        if let Some(count) = desc.variable_count {
            let Some(binding) = layout.variable_binding else {
                return Err(HalError::InvalidDescriptor(
                    "BindGroupDesc::variable_count on a layout with no VARIABLE_COUNT binding"
                        .to_string(),
                ));
            };
            let ceiling = layout.binding_ceiling(binding, &self.caps);
            if count > ceiling {
                return Err(HalError::InvalidDescriptor(format!(
                    "variable_count {count} exceeds the {ceiling} descriptors binding {binding} \
                     declares"
                )));
            }
        }
        self.check_entries_against(&layout, desc.entries)?;
        Ok(self.insert(
            ObjectKind::BindGroup,
            desc.label,
            Detail::BindGroup {
                layout: desc.layout,
                update_after_bind: layout.update_after_bind,
            },
        ))
    }

    fn update_bind_group(
        &self,
        group: BindGroupHandle,
        entries: &[BindGroupEntry],
    ) -> Result<(), HalError> {
        self.check(ObjectKind::BindGroup, group.to_bits(), "bind group")?;
        let (layout_handle, update_after_bind) = {
            let state = self.recorder.lock();
            let Some(object) = state.get(ObjectKind::BindGroup, group.to_bits()) else {
                return Err(HalError::invalid_handle("bind group", group));
            };
            let Detail::BindGroup {
                layout,
                update_after_bind,
            } = &object.detail
            else {
                unreachable!("a bind group handle always carries bind group detail");
            };
            (*layout, *update_after_bind)
        };
        if !update_after_bind {
            // The error `Device::update_bind_group` promises. Without the flag,
            // writing a set a pending command buffer might reference is
            // undefined behaviour, so refusing is the only safe answer — and
            // the null backend accepting it made the seam's own doc untestable.
            return Err(self.unsupported("update_bind_group on a layout without UPDATE_AFTER_BIND"));
        }
        let layout = self.layout_of(layout_handle)?;
        self.check_entries_against(&layout, entries)
    }

    fn destroy_bind_group(&self, group: BindGroupHandle) {
        self.remove(ObjectKind::BindGroup, group.to_bits());
    }

    fn create_pipeline_layout(
        &self,
        desc: &PipelineLayoutDesc<'_>,
    ) -> Result<PipelineLayoutHandle, HalError> {
        for layout in desc.bind_group_layouts {
            self.check(
                ObjectKind::BindGroupLayout,
                layout.to_bits(),
                "bind group layout",
            )?;
        }
        if desc.bind_group_layouts.len() > self.caps.limits.max_bind_groups as usize {
            return Err(HalError::InvalidDescriptor(format!(
                "{} bind groups exceeds max_bind_groups {}",
                desc.bind_group_layouts.len(),
                self.caps.limits.max_bind_groups
            )));
        }
        if let Some(range) = desc.push_constants {
            if !self.caps.features.contains(Features::PUSH_CONSTANTS) {
                // Loudly, at layout creation — not by silently dropping the
                // writes later. This is the trap the seam exists to make
                // visible.
                return Err(self.unsupported("push constants"));
            }
            range
                .stages
                .check_supported(self.caps.features, BackendKind::Null)?;
            // Saturating, not wrapping: `PushConstantRange { offset: u32::MAX,
            // size: 1 }` panicked in debug and wrapped to 0 in release, and 0
            // then *passed* the check it was supposed to fail.
            let end = range.offset.saturating_add(range.size);
            if end > self.caps.limits.max_push_constant_size {
                return Err(HalError::InvalidDescriptor(format!(
                    "push constant range ends at {end} but max_push_constant_size is {}",
                    self.caps.limits.max_push_constant_size
                )));
            }
        }
        let sets = desc
            .bind_group_layouts
            .iter()
            .map(|layout| self.layout_of(*layout).map(|record| record.entries))
            .collect::<Result<_, _>>()?;
        Ok(self.insert(
            ObjectKind::PipelineLayout,
            desc.label,
            Detail::PipelineLayout {
                sets,
                push_constants: desc.push_constants,
            },
        ))
    }

    fn destroy_pipeline_layout(&self, layout: PipelineLayoutHandle) {
        self.remove(ObjectKind::PipelineLayout, layout.to_bits());
    }

    fn create_graphics_pipeline(
        &self,
        desc: &GraphicsPipelineDesc<'_>,
    ) -> Result<GraphicsPipelineHandle, HalError> {
        self.check_stage(desc.vertex)?;
        self.check_raster_state(
            desc.layout,
            desc.fragment,
            desc.color_targets,
            desc.primitive,
            desc.depth_stencil,
        )?;
        let mut stages = vec![(ShaderStages::VERTEX, desc.vertex)];
        stages.extend(desc.fragment.map(|entry| (ShaderStages::FRAGMENT, entry)));
        self.record_pipeline(desc.label, desc.layout, &stages);
        // **The vertex stage is filed rather than dropped**, which is what makes
        // "this pass runs that entry point" a question with a no-GPU answer —
        // see [`Detail::GraphicsPipeline`], which carries the argument.
        Ok(self.insert(
            ObjectKind::GraphicsPipeline,
            desc.label,
            Detail::GraphicsPipeline {
                vertex_entry: desc.vertex.entry_point.to_owned(),
            },
        ))
    }

    fn create_mesh_pipeline(
        &self,
        desc: &MeshPipelineDesc<'_>,
    ) -> Result<GraphicsPipelineHandle, HalError> {
        // Before anything else, so a device modelling the absent capability
        // refuses for the reason the caller needs to hear rather than tripping
        // over a stale handle first.
        if !self.caps.features.contains(Features::MESH_SHADER) {
            return Err(self.unsupported("mesh shading without Features::MESH_SHADER"));
        }
        if desc.task.is_some() && !self.caps.features.contains(Features::TASK_SHADER) {
            return Err(self.unsupported("a task stage without Features::TASK_SHADER"));
        }
        // The half of a workgroup-size check that needs no device, which this
        // recorder is exactly the shape to perform; see
        // `MeshPipelineDesc::check_workgroup_sizes`.
        desc.check_workgroup_sizes()?;
        self.check_stage(desc.mesh)?;
        if let Some(task) = desc.task {
            self.check_stage(task)?;
        }
        self.check_raster_state(
            desc.layout,
            desc.fragment,
            desc.color_targets,
            desc.primitive,
            desc.depth_stencil,
        )?;
        let mut stages: Vec<_> = desc
            .task
            .map(|entry| (ShaderStages::TASK, entry))
            .into_iter()
            .collect();
        stages.push((ShaderStages::MESH, desc.mesh));
        stages.extend(desc.fragment.map(|entry| (ShaderStages::FRAGMENT, entry)));
        self.record_pipeline(desc.label, desc.layout, &stages);
        // The same pool as a raster pipeline, because the seam gives the two
        // one handle type — see `MeshPipelineDesc`'s decision note. `Detail::None`
        // beside the raster arm's `Detail::GraphicsPipeline` and it is not an
        // omission: this pipeline has no vertex stage to record.
        Ok(self.insert(ObjectKind::GraphicsPipeline, desc.label, Detail::None))
    }

    fn destroy_graphics_pipeline(&self, pipeline: GraphicsPipelineHandle) {
        self.remove(ObjectKind::GraphicsPipeline, pipeline.to_bits());
    }

    fn create_compute_pipeline(
        &self,
        desc: &ComputePipelineDesc<'_>,
    ) -> Result<ComputePipelineHandle, HalError> {
        if !self.caps.features.contains(Features::COMPUTE) {
            return Err(self.unsupported("compute shaders"));
        }
        self.check(
            ObjectKind::PipelineLayout,
            desc.layout.to_bits(),
            "pipeline layout",
        )?;
        self.check_stage(desc.compute)?;
        // This recorder has no module contents to compare the declared size
        // against, so it checks the half that needs none: a size the device's
        // own limits could not launch.
        desc.check_workgroup_size(&self.caps.limits)?;
        self.record_pipeline(
            desc.label,
            desc.layout,
            &[(ShaderStages::COMPUTE, desc.compute)],
        );
        Ok(self.insert(ObjectKind::ComputePipeline, desc.label, Detail::None))
    }

    fn destroy_compute_pipeline(&self, pipeline: ComputePipelineHandle) {
        self.remove(ObjectKind::ComputePipeline, pipeline.to_bits());
    }

    // --- queries ---

    fn create_query_set(&self, desc: &QuerySetDesc<'_>) -> Result<QuerySetHandle, HalError> {
        desc.kind.check_supported(BackendKind::Null)?;
        let required = match desc.kind {
            QueryKind::Timestamp => Features::TIMESTAMP_QUERY,
            QueryKind::Occlusion => Features::OCCLUSION_QUERY,
            QueryKind::PipelineStatistics => Features::PIPELINE_STATISTICS_QUERY,
        };
        if !self.caps.features.contains(required) {
            return Err(self.unsupported("this query kind"));
        }
        if desc.count == 0 {
            return Err(HalError::InvalidDescriptor(
                "query set must hold at least one query".to_string(),
            ));
        }
        Ok(self.insert(
            ObjectKind::QuerySet,
            desc.label,
            Detail::QuerySet { count: desc.count },
        ))
    }

    fn destroy_query_set(&self, set: QuerySetHandle) {
        self.remove(ObjectKind::QuerySet, set.to_bits());
    }

    fn query_results(
        &self,
        set: QuerySetHandle,
        first_query: u32,
        out: &mut [u64],
    ) -> Result<(), HalError> {
        self.check(ObjectKind::QuerySet, set.to_bits(), "query set")?;
        let count = {
            let state = self.recorder.lock();
            let Some(object) = state.get(ObjectKind::QuerySet, set.to_bits()) else {
                return Err(HalError::invalid_handle("query set", set));
            };
            let Detail::QuerySet { count } = &object.detail else {
                unreachable!("a query set handle always carries query set detail");
            };
            *count
        };
        // The range check `Device::query_results` documents. It was impossible
        // before: `first_query` was ignored and the set's size was not even
        // stored, so the null backend accepted ranges `crcbl-vk` rejects.
        let end = u64::from(first_query) + out.len() as u64;
        if end > u64::from(count) {
            return Err(HalError::InvalidDescriptor(format!(
                "query range {first_query}..{end} exceeds the set's {count} queries"
            )));
        }
        // Zeros, as a device without timestamp support would report: the
        // profiler HUD degrades rather than breaking.
        out.fill(0);
        Ok(())
    }

    // --- synchronisation ---

    fn create_semaphore(&self, desc: &SemaphoreDesc<'_>) -> Result<SemaphoreHandle, HalError> {
        if matches!(desc.kind, SemaphoreKind::Timeline { .. })
            && !self.caps.features.contains(Features::TIMELINE_SEMAPHORE)
        {
            return Err(self.unsupported("timeline semaphores"));
        }
        let (timeline, value) = match desc.kind {
            SemaphoreKind::Timeline { initial_value } => (true, initial_value),
            SemaphoreKind::Binary => (false, 0),
        };
        Ok(self.insert(
            ObjectKind::Semaphore,
            desc.label,
            Detail::Semaphore { timeline, value },
        ))
    }

    fn destroy_semaphore(&self, semaphore: SemaphoreHandle) {
        self.remove(ObjectKind::Semaphore, semaphore.to_bits());
    }

    /// The value this timeline has reached, starting at the one it was created
    /// with.
    ///
    /// Both a host signal and a *submission's* signal move it. A submission
    /// moves it the instant it is recorded, because work that does not execute
    /// takes no time to complete — see this backend's `submit`, which is where
    /// that choice is argued.
    fn semaphore_value(&self, semaphore: SemaphoreHandle) -> Result<u64, HalError> {
        self.check(ObjectKind::Semaphore, semaphore.to_bits(), "semaphore")?;
        let state = self.recorder.lock();
        let Some(Detail::Semaphore { timeline, value }) = state
            .get(ObjectKind::Semaphore, semaphore.to_bits())
            .map(|object| &object.detail)
        else {
            // `check` above released the lock, so another thread could have
            // destroyed it in between. That is the same outcome as passing a
            // dead handle, and it is reported as one.
            return Err(HalError::invalid_handle("semaphore", semaphore));
        };
        if !*timeline {
            return Err(self.unsupported("a binary semaphore has no value to read"));
        }
        Ok(*value)
    }

    /// Signals the timeline from the host, and refuses a value that does not
    /// move it forwards.
    ///
    /// The one call on this backend whose *rule* is executed rather than
    /// recorded, and it has to be: the seam's guarantee is that a caller which
    /// signals backwards is told so on every backend, and a recorder that
    /// accepted it would be the one place the mistake is invisible.
    fn signal_semaphore(&self, semaphore: SemaphoreHandle, value: u64) -> Result<(), HalError> {
        self.check(ObjectKind::Semaphore, semaphore.to_bits(), "semaphore")?;
        let mut state = self.recorder.lock();
        let Some(Detail::Semaphore {
            timeline,
            value: held,
        }) = state
            .get_mut(ObjectKind::Semaphore, semaphore.to_bits())
            .map(|object| &mut object.detail)
        else {
            return Err(HalError::invalid_handle("semaphore", semaphore));
        };
        if !*timeline {
            return Err(self.unsupported("a binary semaphore has no value to signal"));
        }
        if value <= *held {
            return Err(timeline_goes_backwards(value, *held));
        }
        *held = value;
        Ok(())
    }

    /// Answers against the values the timelines have actually reached, and
    /// never blocks.
    ///
    /// `timeout_ns` is ignored because there is nothing to wait *for*: a
    /// submission's signals land the moment it is recorded, so every value that
    /// is ever going to arrive has already arrived by the time this is called.
    /// The answer is therefore immediate in both directions — `Ok(true)` once
    /// every wait's value has been reached, and `Ok(false)` — the seam's
    /// spelling of `vkWaitSemaphores`' `VK_TIMEOUT` — for a value nothing has
    /// signalled.
    ///
    /// It used to answer `Ok(true)` unconditionally, on the grounds that
    /// nothing is ever outstanding here. That is the one answer a caller cannot
    /// check its own sequencing against: a wait on a value no signal will ever
    /// produce — the mistake that deadlocks a real device — read as satisfied.
    fn wait_semaphores(&self, waits: &[SemaphoreWait], _timeout_ns: u64) -> Result<bool, HalError> {
        // Every `check` before the lock, never under it: `check` takes the
        // recorder itself, and this mutex is not reentrant. `signal_semaphore`
        // one method up is written in this order for the same reason.
        for wait in waits {
            self.check(ObjectKind::Semaphore, wait.semaphore.to_bits(), "semaphore")?;
        }
        let state = self.recorder.lock();
        let mut reached = true;
        for wait in waits {
            let Some(Detail::Semaphore { timeline, value }) = state
                .get(ObjectKind::Semaphore, wait.semaphore.to_bits())
                .map(|object| &object.detail)
            else {
                return Err(HalError::invalid_handle("semaphore", wait.semaphore));
            };
            // The refusal every real backend makes, and the one this backend
            // already makes in `signal_semaphore`: a binary semaphore carries no
            // value, so a CPU wait has nothing to compare against. Answering
            // `Ok(true)` said a wait no device will accept had been satisfied.
            if !*timeline {
                return Err(self.unsupported("a binary semaphore cannot be waited on from the CPU"));
            }
            // Not an early `return`: a wait list holding both an unreached
            // timeline and a binary semaphore has to report the refusal, and
            // returning the verdict here would decide the call on whichever
            // came first in the slice.
            if wait.value > *value {
                reached = false;
            }
        }
        Ok(reached)
    }

    /// Records the wait and returns at once — nothing here is ever outstanding.
    ///
    /// The one method that names no handle and can still fail, which is why the
    /// device-loss gate is spelled out here rather than reached through
    /// [`NullDevice::check_lost`]'s two funnels. `vkDeviceWaitIdle` reports
    /// `VK_ERROR_DEVICE_LOST` for the same reason: waiting for a dead device to
    /// finish is not something that can succeed.
    fn wait_idle(&self) -> Result<(), HalError> {
        self.check_lost()?;
        self.recorder.lock().events.push(Event::WaitedIdle);
        Ok(())
    }

    // --- commands ---

    fn create_command_encoder(&self, desc: &CommandEncoderDesc<'_>) -> Box<dyn CommandEncoder> {
        Box::new(NullEncoder {
            recorder: self.recorder.clone(),
            device_id: self.device_id,
            limits: self.caps.limits,
            label: desc.label.map(ToOwned::to_owned),
            commands: Vec::new(),
            scope: Scope::Outside,
            // There is no error path out of `create_command_encoder`, so a
            // queue that is not this device's is remembered and reported by
            // `finish` — exactly what `crcbl-vk` does when its command pool
            // cannot be created.
            failed: self.check_queue(desc.queue).err(),
        })
    }

    fn destroy_command_buffer(&self, buffer: CommandBufferHandle) {
        self.remove(ObjectKind::CommandBuffer, buffer.to_bits());
    }

    /// Records the submission and applies its signals at once.
    ///
    /// **A device that runs no work completes it instantly**, so the timeline
    /// values `submit.signals` names are reached before this returns — the same
    /// place a real queue reaches them, compressed to zero. The alternative,
    /// recording the signal and leaving the counter behind, would make every
    /// value a submission produces one that never arrives, which is the
    /// `SilentlyIgnored` verdict
    /// [`Capability::TimelineSemaphore`] exists to catch and which this backend
    /// claims not to be.
    ///
    /// The queue-side [`SubmitInfo::waits`] are recorded and not evaluated:
    /// [`Capability::TimelineWaitBeforeSignal`] says a submission may wait on a
    /// value nothing has signalled yet, so a wait here is not a rule to check.
    ///
    /// # Errors
    ///
    /// The handle checks, and [`HalError::InvalidDescriptor`] for a signal that
    /// does not move a timeline forwards — the rule
    /// [`Device::signal_semaphore`] already enforces, applied to the other way a
    /// timeline can be driven so that `submit` is not the one path that can move
    /// one backwards. Every signal is validated before any is applied, so a
    /// refused submission records no event and leaves every counter where it
    /// was.
    fn submit(&self, queue: QueueHandle, submit: &SubmitInfo<'_>) -> Result<(), HalError> {
        self.check_queue(queue)?;
        for buffer in submit.command_buffers {
            self.check(
                ObjectKind::CommandBuffer,
                buffer.to_bits(),
                "command buffer",
            )?;
        }
        for wait in submit.waits {
            self.check(ObjectKind::Semaphore, wait.semaphore.to_bits(), "semaphore")?;
        }
        for signal in submit.signals {
            self.check(
                ObjectKind::Semaphore,
                signal.semaphore.to_bits(),
                "semaphore",
            )?;
        }
        let mut state = self.recorder.lock();
        // Resolved and checked first, so a refused submission records nothing
        // and changes nothing — the order `reconfigure_swapchain` puts its own
        // failure in, for the same reason.
        let mut advanced: Vec<(u64, u64)> = Vec::new();
        for signal in submit.signals {
            let bits = signal.semaphore.to_bits();
            let Some(Detail::Semaphore {
                timeline: true,
                value: held,
            }) = state
                .get(ObjectKind::Semaphore, bits)
                .map(|object| &object.detail)
            else {
                // A binary semaphore — the swapchain's acquire/present pair is
                // where they come from — carries no value, so it is signalled
                // by being recorded and there is nothing to advance.
                continue;
            };
            // A second signal on the same semaphore in one batch measures
            // against the first, not against the counter both started from,
            // or an out-of-order pair would pass and land backwards anyway.
            let held = advanced
                .iter()
                .rev()
                .find(|(seen, _)| *seen == bits)
                .map_or(*held, |(_, pending)| *pending);
            if signal.value <= held {
                return Err(timeline_goes_backwards(signal.value, held));
            }
            advanced.push((bits, signal.value));
        }
        for (bits, value) in advanced {
            let Some(Detail::Semaphore { value: held, .. }) = state
                .get_mut(ObjectKind::Semaphore, bits)
                .map(|object| &mut object.detail)
            else {
                unreachable!("the pass above resolved these bits to a timeline semaphore");
            };
            *held = value;
        }
        state.events.push(Event::Submitted {
            queue,
            command_buffers: submit.command_buffers.to_vec(),
            waits: submit.waits.to_vec(),
            signals: submit.signals.to_vec(),
        });
        Ok(())
    }

    // --- presentation ---

    fn create_swapchain(&self, desc: &SwapchainDesc<'_>) -> Result<SwapchainHandle, SurfaceError> {
        self.check_instance_owned(ObjectKind::Surface, desc.surface.to_bits(), "surface")
            .map_err(SurfaceError::Hal)?;
        if desc.extent.0 == 0 || desc.extent.1 == 0 {
            return Err(SurfaceError::Hal(HalError::InvalidDescriptor(
                "swapchain extent must be non-zero".to_string(),
            )));
        }
        let ring = self.build_ring(desc)?;
        Ok(self.insert(ObjectKind::Swapchain, desc.label, ring))
    }

    fn reconfigure_swapchain(
        &self,
        swapchain: SwapchainHandle,
        desc: &SwapchainDesc<'_>,
    ) -> Result<(), SurfaceError> {
        // First, so a faulted call records nothing and changes nothing — the
        // property `GpuContext::set_pacing`'s rollback asserts on.
        if self.recorder.take_reconfigure_failure() {
            return Err(SurfaceError::Hal(HalError::OutOfDeviceMemory));
        }
        if desc.extent.0 == 0 || desc.extent.1 == 0 {
            return Err(SurfaceError::Hal(HalError::InvalidDescriptor(
                "swapchain extent must be non-zero".to_string(),
            )));
        }
        self.check(ObjectKind::Swapchain, swapchain.to_bits(), "swapchain")
            .map_err(SurfaceError::Hal)?;

        // Reissue the whole ring — images, views *and* semaphores — which is
        // what a real backend does, since `crcbl-vk` recreates the
        // `VkSwapchainKHR`. A caller that wrongly held one of those handles
        // across a resize therefore fails here, on the backend that needs no
        // GPU, rather than on the one that does.
        //
        // Built **before** anything old is destroyed. The other order looks
        // tidier and is wrong: `build_ring` can fail (an extent past
        // `max_image_2d`), and a failed reconfigure that had already destroyed
        // the old ring would leave the swapchain naming dead handles — a call
        // that returned `Err` having broken the object it was given.
        let fresh = self.build_ring(desc)?;

        let stale = {
            let mut state = self.recorder.lock();
            let Some(object) = state.get_mut(ObjectKind::Swapchain, swapchain.to_bits()) else {
                return Err(SurfaceError::Hal(HalError::invalid_handle(
                    "swapchain",
                    swapchain,
                )));
            };
            let previous = core::mem::replace(&mut object.detail, fresh);
            // The rebuild is what clears the out-of-date latch, so a caller
            // that handles the resize gets a working swapchain back and one
            // that ignores it keeps being told. Here rather than at the top of
            // the method: a reconfigure that failed rebuilt nothing.
            state.swapchain_out_of_date = false;
            state.events.push(Event::Reconfigured {
                swapchain,
                extent: desc.extent,
            });
            previous
        };

        let Detail::Swapchain {
            images,
            views,
            acquire_semaphores,
            present_semaphores,
            ..
        } = stale
        else {
            unreachable!("a swapchain handle always carries swapchain detail");
        };
        // Views before images: a view must not outlive what it views.
        for view in views {
            self.destroy_image_view(view);
        }
        for image in images {
            self.destroy_image(image);
        }
        for semaphore in acquire_semaphores
            .into_iter()
            .chain(present_semaphores)
            .flatten()
        {
            self.destroy_semaphore(semaphore);
        }
        Ok(())
    }

    fn destroy_swapchain(&self, swapchain: SwapchainHandle) {
        let owned = {
            let state = self.recorder.lock();
            match state
                .get(ObjectKind::Swapchain, swapchain.to_bits())
                .map(|object| &object.detail)
            {
                Some(Detail::Swapchain {
                    images,
                    views,
                    acquire_semaphores,
                    present_semaphores,
                    ..
                }) => Some((
                    images.clone(),
                    views.clone(),
                    acquire_semaphores.clone(),
                    present_semaphores.clone(),
                )),
                _ => None,
            }
        };
        if let Some((images, views, acquires, presents)) = owned {
            // Views before images: the seam says every view of an image must
            // already be destroyed when the image is.
            for view in views {
                self.destroy_image_view(view);
            }
            for image in images {
                self.destroy_image(image);
            }
            for semaphore in acquires.into_iter().chain(presents).flatten() {
                self.destroy_semaphore(semaphore);
            }
        }
        self.remove(ObjectKind::Swapchain, swapchain.to_bits());
    }

    fn acquire_next_frame(
        &self,
        swapchain: SwapchainHandle,
    ) -> Result<AcquiredFrame, SurfaceError> {
        self.check_current(swapchain)?;
        // Before the lock, like the `check` helpers above it and for the same
        // reason — the recorder's mutex is not reentrant, and the borrow of the
        // swapchain object below holds it until the frame is built. Reading it
        // here also spends the injection only on an acquire that got this far,
        // which is what leaves a refused one recording and consuming nothing.
        let suboptimal = self.recorder.take_suboptimal_acquire();
        let mut state = self.recorder.lock();
        let Some(object) = state.get_mut(ObjectKind::Swapchain, swapchain.to_bits()) else {
            return Err(SurfaceError::Hal(HalError::invalid_handle(
                "swapchain",
                swapchain,
            )));
        };
        let Detail::Swapchain {
            extent,
            images,
            views,
            acquire_semaphores,
            present_semaphores,
            next,
            acquired,
        } = &mut object.detail
        else {
            unreachable!("a swapchain handle always carries swapchain detail");
        };
        let index = *next;
        // The seam does not make an acquire exclusive — Vulkan lets a mailbox
        // ring hold several at once — so a second acquire overwrites rather
        // than being refused, exactly as every other backend's single slot
        // does. What the slot is for is the *present*, which needs to have been
        // given a frame at all.
        *acquired = Some(index);
        let slot = index as usize;
        // `.max(1)`, not `unwrap_or(1)`: `u32::try_from(0usize)` is `Ok(0)`, so
        // the fallback never fired for the one input it looked like it guarded
        // against, and an empty ring divided by zero.
        *next = (index + 1) % u32::try_from(images.len()).unwrap_or(u32::MAX).max(1);
        let frame = AcquiredFrame {
            image: images[slot],
            view: views[slot],
            // The extent the ring was actually built at, which is the
            // requested one unless `Recorder::clamp_acquired_extent_to` gave
            // this backend a platform opinion — the thing that makes
            // obligation 3's branch reachable at all.
            extent: *extent,
            index,
            acquire_semaphore: acquire_semaphores[slot],
            present_semaphore: present_semaphores[slot],
            suboptimal,
        };
        state.events.push(Event::Acquired { swapchain, index });
        Ok(frame)
    }

    fn present(&self, queue: QueueHandle, present: &PresentInfo<'_>) -> Result<(), SurfaceError> {
        self.check_queue(queue).map_err(SurfaceError::Hal)?;
        self.check_current(present.swapchain)?;
        for semaphore in present.waits {
            self.check(ObjectKind::Semaphore, semaphore.to_bits(), "semaphore")
                .map_err(SurfaceError::Hal)?;
        }
        let mut state = self.recorder.lock();
        // **A present needs a frame to present**, which this backend could not
        // say until it had somewhere to remember the acquire. The wording is
        // the one `crcbl-vk`, `crcbl-mtl` and `crcbl-dx12` already answer, so
        // one agnostic test holds every backend to the same sentence.
        let Some(Detail::Swapchain { acquired, .. }) = state
            .get_mut(ObjectKind::Swapchain, present.swapchain.to_bits())
            .map(|object| &mut object.detail)
        else {
            unreachable!("check_current resolved this swapchain a moment ago");
        };
        if acquired.take().is_none() {
            return Err(SurfaceError::Hal(HalError::InvalidDescriptor(
                "present without a matching acquire_next_frame".to_string(),
            )));
        }
        state.events.push(Event::Presented {
            swapchain: present.swapchain,
            present_id: present.present_id,
        });
        Ok(())
    }

    /// Records the request and returns at once, unless a timeout was injected.
    ///
    /// There is no display under this backend, so there is nothing a wait could
    /// observe and nothing that could make one late. On a device that does not
    /// advertise [`Features::PRESENT_FEEDBACK`] the seam requires exactly that
    /// answer anyway — an immediate `Ok`, never a refusal — so such a device
    /// needs no injection to be honest and is given none: it consumes nothing
    /// from [`Recorder::report_present_wait_timeouts`], leaving what was asked
    /// for owed to a device that can honour it. A device built with
    /// [`NullInstance::with_present_feedback`] claims the other half of the
    /// contract, and that is where an injected timeout comes out.
    ///
    /// The handle is still checked, because a caller waiting on a swapchain it
    /// already destroyed has a bug whether or not anyone was going to block —
    /// and so is the out-of-date latch, because a pacing wait is one of the
    /// three calls a resize makes fail. See [`check_current`](Self::check_current).
    fn wait_until_presented(
        &self,
        swapchain: SwapchainHandle,
        present_id: u64,
        _timeout: Duration,
    ) -> Result<(), SurfaceError> {
        self.check_current(swapchain)?;
        // After the checks and before the lock, exactly as `acquire_next_frame`
        // takes its own injection and for both of that call's reasons: the
        // recorder's mutex is not reentrant, and a wait the checks above
        // refused must spend nothing.
        let timed_out = self.caps.features.contains(Features::PRESENT_FEEDBACK)
            && self.recorder.take_present_wait_timeout();
        let mut state = self.recorder.lock();
        // Recorded either way. The wait was asked for and answered; which of
        // the two answers it got is the part the event has to carry.
        state.events.push(Event::PresentWaited {
            swapchain,
            present_id,
            timed_out,
        });
        if timed_out {
            Err(SurfaceError::Timeout)
        } else {
            Ok(())
        }
    }

    /// Always [`DisplayTiming::Unknown`], and the handle is checked first.
    ///
    /// There is no display under this backend to have a cadence, so this device
    /// never advertises [`Features::PRESENT_TIMING`] and the seam's answer for
    /// a device without it is the honest one here. The check is the same
    /// obligation-3 lookup every other method does: asking about a destroyed or
    /// foreign swapchain is a caller bug whether or not there was an answer to
    /// give.
    fn display_timing(&self, swapchain: SwapchainHandle) -> Result<DisplayTiming, SurfaceError> {
        self.check(ObjectKind::Swapchain, swapchain.to_bits(), "swapchain")
            .map_err(SurfaceError::Hal)?;
        Ok(DisplayTiming::Unknown)
    }
}

impl NullDevice {
    /// Builds a complete swapchain ring: one image, one view and — unless this
    /// device models an implicit acquire — one acquire and one present
    /// semaphore per ring slot.
    ///
    /// Shared by create and reconfigure so the four vectors can never end up
    /// with different lengths. They did once: reconfigure used to replace only
    /// the images and views, so reconfiguring from two images to three left
    /// two-element semaphore vectors and the third acquire indexed past the end
    /// of them. The lengths are an invariant, so one constructor establishes it.
    fn build_ring(&self, desc: &SwapchainDesc<'_>) -> Result<Detail, SurfaceError> {
        // `SwapchainDesc::format` must be one of `SurfaceCaps::formats`, and
        // this backend used to accept anything at all — including `D32Float`,
        // which no surface can present.
        if !SURFACE_FORMATS.contains(&desc.format) {
            return Err(SurfaceError::Hal(HalError::InvalidDescriptor(format!(
                "{:?} is not one of this surface's formats {SURFACE_FORMATS:?}",
                desc.format
            ))));
        }
        // Clamped to what `surface_caps` reports, not to a pair of literals
        // that happened to agree with it.
        let image_count = desc.image_count.clamp(RING_MIN_IMAGES, RING_MAX_IMAGES);
        // The platform's say over the extent, if a test has given this backend
        // one — see `Recorder::clamp_acquired_extent_to`. Applied here rather
        // than at acquire so the ring's *images* are the clamped size too: a
        // swapchain reporting one extent and holding images of another is a
        // fixture no window system produces, and a render area derived from
        // those images would disagree with the acquired extent for a reason
        // that is the fixture's rather than the caller's.
        let extent = self.recorder.clamped_extent().unwrap_or(desc.extent);
        let mut images = Vec::with_capacity(image_count as usize);
        let mut views = Vec::with_capacity(image_count as usize);
        let mut acquire_semaphores = Vec::with_capacity(image_count as usize);
        let mut present_semaphores = Vec::with_capacity(image_count as usize);
        for index in 0..image_count {
            let image = self
                .create_image(&ImageDesc {
                    label: Some("swapchain image"),
                    image_type: ImageType::D2,
                    extent: crate::Extent3d::d2(extent.0, extent.1),
                    format: desc.format,
                    mip_levels: 1,
                    samples: 1,
                    usage: ImageUsage::COLOR_ATTACHMENT | ImageUsage::PRESENT,
                })
                .map_err(SurfaceError::Hal)?;
            images.push(image);
            // The swapchain owns its images, so it owns their views — see
            // `crate::swapchain`. A caller never creates or destroys one.
            views.push(
                self.create_image_view(&ImageViewDesc {
                    label: Some("swapchain image view"),
                    image,
                    view_type: crate::ImageViewType::D2,
                    format: desc.format,
                    range: crate::ImageSubresourceRange::all(desc.format),
                })
                .map_err(SurfaceError::Hal)?,
            );
            if self.implicit_acquire {
                // The WebGPU shape: no semaphores at all, so the renderer's
                // wait/signal splice is a no-op rather than a branch.
                acquire_semaphores.push(None);
                present_semaphores.push(None);
            } else {
                let label = format!("swapchain acquire {index}");
                acquire_semaphores.push(Some(self.insert::<crate::Semaphore>(
                    ObjectKind::Semaphore,
                    Some(&label),
                    Detail::None,
                )));
                let label = format!("swapchain present {index}");
                present_semaphores.push(Some(self.insert::<crate::Semaphore>(
                    ObjectKind::Semaphore,
                    Some(&label),
                    Detail::None,
                )));
            }
        }
        Ok(Detail::Swapchain {
            extent,
            images,
            views,
            acquire_semaphores,
            present_semaphores,
            acquired: None,
            next: 0,
        })
    }

    /// Snapshots a bind-group layout, so validation can run without holding the
    /// recorder lock across the resource lookups it also needs.
    fn layout_of(&self, handle: BindGroupLayoutHandle) -> Result<LayoutRecord, HalError> {
        let state = self.recorder.lock();
        let Some(object) = state.get(ObjectKind::BindGroupLayout, handle.to_bits()) else {
            return Err(HalError::invalid_handle("bind group layout", handle));
        };
        let Detail::BindGroupLayout {
            entries,
            update_after_bind,
            variable_binding,
        } = &object.detail
        else {
            unreachable!("a layout handle always carries layout detail");
        };
        Ok(LayoutRecord {
            entries: entries.clone(),
            update_after_bind: *update_after_bind,
            variable_binding: *variable_binding,
        })
    }

    /// Checks every assignment against the layout it claims to fill.
    ///
    /// The three things a real backend checks and this one used not to: that
    /// the binding exists, that the array index is inside it, and that the
    /// resource is the right *kind*. Without them the null backend green-lit
    /// bind groups `crcbl-vk` rejects outright.
    fn check_entries_against(
        &self,
        layout: &LayoutRecord,
        entries: &[BindGroupEntry],
    ) -> Result<(), HalError> {
        for entry in entries {
            let Some(declared) = layout
                .entries
                .iter()
                .find(|slot| slot.binding == entry.binding)
            else {
                return Err(HalError::InvalidDescriptor(format!(
                    "bind group entry names binding {}, which the layout does not declare",
                    entry.binding
                )));
            };
            let ceiling = layout.binding_ceiling(entry.binding, &self.caps);
            if entry.array_index >= ceiling {
                return Err(HalError::InvalidDescriptor(format!(
                    "bind group entry writes index {} of binding {}, which holds {ceiling}",
                    entry.array_index, entry.binding
                )));
            }
            check_resource_kind(declared.kind, &entry.resource, entry.binding)?;
            self.check_binding(&entry.resource)?;
            self.check_shader_writable_memory(declared.kind, &entry.resource, entry.binding)?;
            self.check_binding_range(declared.kind, &entry.resource, entry.binding)?;
            self.check_binding_offset(declared.kind, &entry.resource, entry.binding)?;
        }
        Ok(())
    }

    /// Refuses a host-visible buffer filling a binding a shader can write.
    ///
    /// The seam's rule, stated on
    /// [`MemoryLocation`]: a buffer a shader writes is
    /// [`MemoryLocation::DeviceLocal`] and nothing else, because D3D12's upload
    /// and readback heaps admit no unordered access view. `crcbl-dx12` refuses
    /// it too, at the binding it builds the view for — but a violation that only
    /// that backend catches is one nobody sees until CI runs WARP, which has
    /// twice cost a device. The null backend is the reference implementation, so
    /// the class is refused here where every no-GPU test meets it.
    ///
    /// Read-only storage bindings are untouched: a host-visible buffer behind a
    /// `StructuredBuffer` is the engine's staged-table shape and legal on all
    /// four backends.
    ///
    /// The buffer's location is read from the record the seam already keeps,
    /// not inferred from whether it materialised bytes — that is a proxy, and
    /// the proxy is what the check would drift away from.
    fn check_shader_writable_memory(
        &self,
        kind: crate::BindingKind,
        resource: &crate::BindingResource,
        binding: u32,
    ) -> Result<(), HalError> {
        let (
            crate::BindingKind::StorageBuffer {
                read_only: false, ..
            },
            crate::BindingResource::Buffer { buffer, .. },
        ) = (kind, resource)
        else {
            return Ok(());
        };
        let state = self.recorder.lock();
        let Some(object) = state.get(ObjectKind::Buffer, buffer.to_bits()) else {
            return Err(HalError::invalid_handle("buffer", *buffer));
        };
        let Detail::Buffer { memory, .. } = &object.detail else {
            unreachable!("a buffer handle always carries buffer detail");
        };
        if matches!(memory, MemoryLocation::DeviceLocal) {
            return Ok(());
        }
        Err(HalError::InvalidDescriptor(format!(
            "binding {binding} is a writable storage buffer and was given a {memory:?} buffer; a \
             buffer a shader writes must be MemoryLocation::DeviceLocal, because D3D12's upload \
             and readback heaps refuse D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS at creation and \
             pin the resource to a state a shader cannot write from. Read-only storage bindings of \
             a host-visible buffer are unaffected"
        )))
    }

    /// Refuses a buffer range longer than the limit for the slot it fills.
    ///
    /// [`Limits::max_uniform_buffer_range`](crate::Limits::max_uniform_buffer_range)
    /// and
    /// [`Limits::max_storage_buffer_range`](crate::Limits::max_storage_buffer_range)
    /// are the two ceilings a bind group can exceed, and the one a caller is
    /// likeliest to walk into by accident: a uniform ceiling of 64 KiB is small
    /// enough that an ordinary table outgrows it, and the buffer itself was
    /// created without complaint because a buffer of that size is legal — it is
    /// binding *all of it* to a uniform slot that is not.
    ///
    /// [`BindingResource::WHOLE_BUFFER`](crate::BindingResource::WHOLE_BUFFER)
    /// is resolved against the buffer's own size before comparing, because that
    /// is what the backend does with it: a whole-buffer binding of a buffer over
    /// the ceiling is the same violation spelled without a number, and checking
    /// only explicit sizes would let the commonest spelling through.
    ///
    /// Vulkan states both as VUIDs on `VkDescriptorBufferInfo` rather than as
    /// errors, so a violation there is undefined behaviour caught by validation
    /// layers if they happen to be on; refusing here is what makes it a named
    /// error every no-GPU test meets.
    fn check_binding_range(
        &self,
        kind: crate::BindingKind,
        resource: &crate::BindingResource,
        binding: u32,
    ) -> Result<(), HalError> {
        let limits = &self.caps.limits;
        let (ceiling, what) = match kind {
            crate::BindingKind::UniformBuffer { .. } => {
                (limits.max_uniform_buffer_range, "max_uniform_buffer_range")
            }
            crate::BindingKind::StorageBuffer { .. } => {
                (limits.max_storage_buffer_range, "max_storage_buffer_range")
            }
            _ => return Ok(()),
        };
        let crate::BindingResource::Buffer {
            buffer,
            offset,
            size,
        } = resource
        else {
            return Ok(());
        };
        let state = self.recorder.lock();
        let Some(object) = state.get(ObjectKind::Buffer, buffer.to_bits()) else {
            return Err(HalError::invalid_handle("buffer", *buffer));
        };
        let Detail::Buffer { size: length, .. } = &object.detail else {
            unreachable!("a buffer handle always carries buffer detail");
        };
        let bound = if *size == crate::BindingResource::WHOLE_BUFFER {
            length.saturating_sub(*offset)
        } else {
            *size
        };
        if bound <= ceiling {
            return Ok(());
        }
        Err(HalError::InvalidDescriptor(format!(
            "binding {binding} is given {bound} bytes of a buffer, over this device's {what} of {ceiling}"
        )))
    }

    /// Refuses a buffer binding whose offset is not a multiple of the
    /// alignment its slot requires.
    ///
    /// [`crate::check_binding_offset_alignment`] is the rule; this resolves the
    /// offset out of the resource and hands it over. It needs no buffer record
    /// at all — the alignment turns on the *slot*, and the offset is in the
    /// descriptor — which is what makes it decidable here where every no-GPU
    /// test meets it. Before it existed, `crcbl-vk` and the two deferred
    /// backends each refused it and the reference implementation could not
    /// state the rule, so a misaligned offset was a bind group that this
    /// backend built and a driver later read from the wrong bytes.
    ///
    /// The bind-time half is [`crate::check_dynamic_offsets`], which
    /// `NullEncoder::bind_group` calls.
    fn check_binding_offset(
        &self,
        kind: crate::BindingKind,
        resource: &crate::BindingResource,
        binding: u32,
    ) -> Result<(), HalError> {
        let crate::BindingResource::Buffer { offset, .. } = resource else {
            return Ok(());
        };
        crate::check_binding_offset_alignment(&self.caps.limits, kind, binding, *offset)
    }

    fn check_binding(&self, resource: &crate::BindingResource) -> Result<(), HalError> {
        match resource {
            crate::BindingResource::Buffer { buffer, .. } => {
                self.check(ObjectKind::Buffer, buffer.to_bits(), "buffer")
            }
            crate::BindingResource::ImageView(view) => {
                self.check(ObjectKind::ImageView, view.to_bits(), "image view")
            }
            crate::BindingResource::Sampler(sampler) => {
                self.check(ObjectKind::Sampler, sampler.to_bits(), "sampler")
            }
        }
    }
}

/// A bind-group layout's declarations, copied out from under the lock.
#[derive(Debug)]
struct LayoutRecord {
    entries: Vec<crate::BindGroupLayoutEntry>,
    update_after_bind: bool,
    variable_binding: Option<u32>,
}

impl LayoutRecord {
    /// How many descriptors a binding actually holds.
    ///
    /// [`BindingFlags::VARIABLE_COUNT`](crate::BindingFlags::VARIABLE_COUNT)
    /// makes the declared `count` an upper bound, and
    /// [`BindGroupLayoutEntry::resolved_count`](crate::BindGroupLayoutEntry::resolved_count)
    /// is where the seam's `u32::MAX` becomes a number. Only the variable
    /// binding is resolved: every other binding holds exactly the length it
    /// declared, which is the bound a caller's `array_index` has to clear.
    fn binding_ceiling(&self, binding: u32, caps: &DeviceCaps) -> u32 {
        let Some(entry) = self.entries.iter().find(|slot| slot.binding == binding) else {
            return 0;
        };
        if self.variable_binding == Some(binding) {
            entry.resolved_count(&caps.limits)
        } else {
            entry.count
        }
    }
}

/// Whether a resource can fill a binding of that kind.
///
/// The same table `crcbl-vk`'s `check_resource_kind` uses, and for the same
/// reason: a mismatch must name the caller's binding number, not a descriptor
/// type in a driver message.
fn check_resource_kind(
    kind: crate::BindingKind,
    resource: &crate::BindingResource,
    binding: u32,
) -> Result<(), HalError> {
    use crate::{BindingKind as K, BindingResource as R};
    let ok = matches!(
        (kind, resource),
        (
            K::UniformBuffer { .. } | K::StorageBuffer { .. },
            R::Buffer { .. }
        ) | (
            K::SampledImage { .. } | K::StorageImage { .. },
            R::ImageView(_)
        ) | (K::Sampler { .. }, R::Sampler(_))
    );
    if ok {
        Ok(())
    } else {
        Err(HalError::InvalidDescriptor(format!(
            "binding {binding} is declared as {kind:?}, which cannot hold {resource:?}"
        )))
    }
}

/// Which pass, if any, is currently open on an encoder.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Scope {
    Outside,
    Render,
    Compute,
}

/// A no-op, recording [`CommandEncoder`].
#[derive(Debug)]
struct NullEncoder {
    recorder: Recorder,
    /// Owner id every handle a recorded command names must match.
    device_id: u64,
    /// This device's [`Limits`], copied at creation.
    ///
    /// The seam's two `min_*_buffer_offset_alignment` fields are the only thing
    /// read out of it, and they are what
    /// [`crate::check_dynamic_offsets`] measures a bind's offsets against — a
    /// rule that arrives at `bind_group` rather than at bind-group creation, so
    /// the device that knows the numbers is not in the room by then. Copied
    /// rather than reached through the recorder because [`Limits`] is `Copy`
    /// and an encoder outlives no device it was made by.
    limits: Limits,
    label: Option<String>,
    commands: Vec<Command>,
    scope: Scope,
    /// The first hard failure, reported by [`CommandEncoder::finish`]. Distinct
    /// from a [`ValidationError`], which is recorded and carried past.
    failed: Option<HalError>,
}

impl NullEncoder {
    /// Records `command` after checking it is legal in the current scope.
    fn record(&mut self, command: Command) {
        let name = command.name();
        match &command {
            Command::BeginRenderPass { .. } | Command::BeginComputePass { .. } => {
                if self.scope != Scope::Outside {
                    self.fail(ValidationError::NestedPass { command: name });
                }
                self.scope = match command {
                    Command::BeginComputePass { .. } => Scope::Compute,
                    _ => Scope::Render,
                };
            }
            Command::EndRenderPass => {
                if self.scope != Scope::Render {
                    self.fail(ValidationError::UnopenedPass { command: name });
                }
                self.scope = Scope::Outside;
            }
            Command::EndComputePass => {
                if self.scope != Scope::Compute {
                    self.fail(ValidationError::UnopenedPass { command: name });
                }
                self.scope = Scope::Outside;
            }
            _ => {}
        }
        self.commands.push(command);
    }

    fn fail(&self, error: ValidationError) {
        self.recorder.push_validation(error);
    }

    /// Requires an open render pass.
    fn need_render(&self, command: &'static str) {
        if self.scope != Scope::Render {
            self.fail(ValidationError::OutsidePass {
                command,
                expected: "render",
            });
        }
    }

    /// Requires an open compute pass.
    fn need_compute(&self, command: &'static str) {
        if self.scope != Scope::Compute {
            self.fail(ValidationError::OutsidePass {
                command,
                expected: "compute",
            });
        }
    }

    /// Requires some pass to be open — bindings are legal in either.
    fn need_any_pass(&self, command: &'static str) {
        if self.scope == Scope::Outside {
            self.fail(ValidationError::OutsidePass {
                command,
                expected: "render or compute",
            });
        }
    }

    /// Requires no pass to be open. Copies, barriers and query writes are
    /// forbidden inside dynamic rendering.
    fn need_outside(&self, command: &'static str) {
        if self.scope != Scope::Outside {
            self.fail(ValidationError::InsidePass { command });
        }
    }

    /// Checks a pass's [`PassTimestampWrites`], if it has any: the set must be
    /// this device's and live, the two indices must differ, and both must be
    /// queries the set actually holds.
    ///
    /// The seam has no free-standing timestamp call left to check, so this is
    /// where the graph's unit suite catches a mis-aimed timestamp without a GPU.
    fn need_timestamps(&self, command: &'static str, writes: Option<PassTimestampWrites>) {
        let Some(writes) = writes else { return };
        self.need_live(command, ObjectKind::QuerySet, writes.set.to_bits());
        if writes.beginning_of_pass == writes.end_of_pass {
            self.fail(ValidationError::CoincidentTimestamps {
                command,
                index: writes.beginning_of_pass,
            });
        }
        let state = self.recorder.lock();
        let Some(object) = state.get(ObjectKind::QuerySet, writes.set.to_bits()) else {
            // A dead or foreign handle, already reported by `need_live` above.
            return;
        };
        let Detail::QuerySet { count } = &object.detail else {
            unreachable!("a query set handle always carries query set detail");
        };
        let count = *count;
        for index in [writes.beginning_of_pass, writes.end_of_pass] {
            if index >= count {
                drop(state);
                self.fail(ValidationError::TimestampOutOfRange {
                    command,
                    index,
                    count,
                });
                return;
            }
        }
    }

    /// Requires an indirect draw's arguments to obey the seam's rules for
    /// stepping an array of argument structures — [`crate::indirect`].
    ///
    /// This backend resolves no driver object and can still answer all three
    /// rules, bounds included, because it recorded the buffer's size when it
    /// created it. That is the point of checking here: `crcbl-vk` needs a
    /// device to reach the same verdict, and this reaches it in a unit test.
    ///
    /// A refusal goes where [`report_indirect`](Self::report_indirect) sends
    /// it.
    fn need_indirect_arguments(
        &mut self,
        command: &'static str,
        draw: &DrawIndirect,
        indexed: bool,
    ) {
        let Some(length) = self.buffer_size(draw.args) else {
            // A dead or foreign handle, already reported by `need_live`. There
            // is no buffer to measure the arguments against.
            return;
        };
        self.report_indirect(
            command,
            plan_structures(draw, structure_bytes(indexed), length),
        );
    }

    /// [`need_indirect_arguments`](Self::need_indirect_arguments) for a **mesh**
    /// dispatch, whose argument structure is three words rather than a draw's
    /// four or five — [`plan_mesh_indirect`].
    ///
    /// Every other rule is the same one, because they are all rules about
    /// stepping an array of structures in a buffer rather than about what the
    /// structures say.
    fn need_mesh_indirect_arguments(&mut self, command: &'static str, draw: &DrawIndirect) {
        let Some(length) = self.buffer_size(draw.args) else {
            // A dead or foreign handle, already reported by `need_live`.
            return;
        };
        self.report_indirect(command, plan_mesh_indirect(draw, length));
    }

    /// [`need_indirect_arguments`](Self::need_indirect_arguments) for a
    /// count-limited draw, which is the same argument array plus the count word
    /// in a second buffer — [`plan_count_structures`].
    ///
    /// The count buffer is measured the same way and for the same reason: a
    /// count word hanging off the end of it is a draw count read from
    /// somebody else's memory, and no API reports it.
    fn need_indirect_count_arguments(
        &mut self,
        command: &'static str,
        draw: &DrawIndirectCount,
        indexed: bool,
    ) {
        let (Some(args_length), Some(count_length)) = (
            self.buffer_size(draw.args),
            self.buffer_size(draw.count_buffer),
        ) else {
            // A dead or foreign handle, already reported by `need_live`.
            return;
        };
        self.report_indirect(
            command,
            plan_count_structures(draw, structure_bytes(indexed), args_length, count_length),
        );
    }

    /// The size a live buffer of this device's was created with, or `None` for
    /// a handle that no longer resolves.
    ///
    /// **`size`, not `bytes.len()`**: only a mappable buffer keeps its
    /// contents, and an argument buffer is device-local everywhere it matters,
    /// so a length taken from `bytes` would be zero and would refuse every
    /// legitimate draw.
    fn buffer_size(&self, buffer: BufferHandle) -> Option<u64> {
        let state = self.recorder.lock();
        let object = state.get(ObjectKind::Buffer, buffer.to_bits())?;
        let Detail::Buffer { size, .. } = &object.detail else {
            unreachable!("a buffer handle always carries buffer detail");
        };
        Some(*size)
    }

    /// Records and remembers a refusal from [`crate::indirect`], and lets an
    /// accepted plan pass.
    ///
    /// A refusal goes two places. It is recorded, like every other violation,
    /// so a test sees the whole frame's worth; and it is remembered in
    /// [`failed`](Self::failed), because a recording method returns `()` and
    /// [`finish`](CommandEncoder::finish) is the first thing that can report
    /// it — the arrangement `create_command_encoder` already uses for a queue
    /// it cannot accept.
    fn report_indirect(
        &mut self,
        command: &'static str,
        planned: Result<Option<IndirectPlan>, HalError>,
    ) {
        let Err(error) = planned else {
            return;
        };
        self.report_refusal(error, |message| ValidationError::InvalidIndirectArguments {
            command,
            message,
        });
    }

    /// Requires a bind's dynamic offsets to obey the seam's rules for filling
    /// the dynamic-offset slots a layout declares —
    /// [`crate::check_dynamic_offsets`].
    ///
    /// This backend resolves no driver object and can still answer both rules,
    /// because it recorded the layout a bind group was created against and the
    /// slots that layout declares. That is the point of checking here:
    /// `crcbl-vk` needs a device and a `VkDescriptorSetLayout` to reach the
    /// same verdict, and this reaches it in a unit test.
    ///
    /// A refusal goes where [`report_indirect`](Self::report_indirect) sends
    /// one, and for the same reason.
    fn need_dynamic_offsets(
        &mut self,
        command: &'static str,
        group: BindGroupHandle,
        offsets: &[u32],
    ) {
        let Some(dynamic) = self.dynamic_slots(group) else {
            // A dead or foreign bind group, already reported by `need_live` —
            // or a layout destroyed since the group was built, which is legal
            // everywhere and leaves nothing to measure the offsets against.
            return;
        };
        let Err(error) = crate::check_dynamic_offsets(&self.limits, &dynamic, offsets) else {
            return;
        };
        self.report_refusal(error, |message| ValidationError::InvalidDynamicOffsets {
            command,
            message,
        });
    }

    /// The dynamic-offset slots of the layout a bind group was created
    /// against, sorted by binding number, or `None` if either handle no longer
    /// resolves.
    ///
    /// The sort is the seam's rule rather than tidiness:
    /// [`CommandEncoder::bind_group`] states that `dynamic_offsets` is
    /// positional and in binding order, so this order is what makes offset *i*
    /// the one belonging to slot *i*.
    fn dynamic_slots(&self, group: BindGroupHandle) -> Option<Vec<BindGroupLayoutEntry>> {
        let state = self.recorder.lock();
        let object = state.get(ObjectKind::BindGroup, group.to_bits())?;
        let Detail::BindGroup { layout, .. } = &object.detail else {
            unreachable!("a bind group handle always carries bind group detail");
        };
        let layout = state.get(ObjectKind::BindGroupLayout, layout.to_bits())?;
        let Detail::BindGroupLayout { entries, .. } = &layout.detail else {
            unreachable!("a bind group layout handle always carries layout detail");
        };
        let mut dynamic: Vec<BindGroupLayoutEntry> = entries
            .iter()
            .copied()
            .filter(|entry| {
                matches!(
                    entry.kind,
                    BindingKind::UniformBuffer { dynamic: true }
                        | BindingKind::StorageBuffer { dynamic: true, .. }
                )
            })
            .collect();
        dynamic.sort_by_key(|entry| entry.binding);
        Some(dynamic)
    }

    /// Records and remembers a refusal a unit-returning recording method
    /// cannot return.
    ///
    /// The two places above both need it, and `wrap` is the only part that
    /// differs: which [`ValidationError`] the refusal is recorded as. The
    /// message itself is the seam's own, unchanged, so the recorded violation
    /// and the [`HalError`] `finish` returns say the same thing.
    fn report_refusal(&mut self, error: HalError, wrap: impl FnOnce(String) -> ValidationError) {
        let message = match error {
            // The seam's checks document `InvalidDescriptor` as the only
            // refusal they have; anything else still crosses rather than being
            // dropped.
            HalError::InvalidDescriptor(message) => message,
            other => other.to_string(),
        };
        self.fail(wrap(message.clone()));
        if self.failed.is_none() {
            self.failed = Some(HalError::InvalidDescriptor(message));
        }
    }

    /// Requires a handle to still resolve *and* to belong to this device.
    fn need_live(&self, command: &'static str, kind: ObjectKind, bits: u64) {
        let state = self.recorder.lock();
        if state.is_owned_by(kind, bits, self.device_id) {
            return;
        }
        let error = if state.is_live(kind, bits) {
            ValidationError::ForeignHandle {
                command,
                kind,
                bits,
            }
        } else {
            ValidationError::DeadHandle {
                command,
                kind,
                bits,
            }
        };
        drop(state);
        self.fail(error);
    }
}

impl CommandEncoder for NullEncoder {
    fn begin_debug_label(&mut self, label: &str) {
        self.record(Command::BeginDebugLabel(label.to_string()));
    }

    fn end_debug_label(&mut self) {
        self.record(Command::EndDebugLabel);
    }

    fn insert_debug_marker(&mut self, label: &str) {
        self.record(Command::DebugMarker(label.to_string()));
    }

    fn pipeline_barrier(&mut self, barriers: &Barriers<'_>) {
        self.need_outside("Barrier");
        for barrier in barriers.buffers {
            self.need_live("Barrier", ObjectKind::Buffer, barrier.buffer.to_bits());
        }
        for barrier in barriers.images {
            self.need_live("Barrier", ObjectKind::Image, barrier.image.to_bits());
        }
        self.record(Command::Barrier {
            buffers: barriers.buffers.to_vec(),
            images: barriers.images.to_vec(),
            global: barriers.global,
        });
    }

    fn copy_buffer_to_buffer(&mut self, copy: &BufferCopy) {
        self.need_outside("CopyBufferToBuffer");
        self.need_live("CopyBufferToBuffer", ObjectKind::Buffer, copy.src.to_bits());
        self.need_live("CopyBufferToBuffer", ObjectKind::Buffer, copy.dst.to_bits());
        self.record(Command::CopyBufferToBuffer(*copy));
    }

    fn copy_buffer_to_image(&mut self, copy: &BufferImageCopy) {
        self.need_outside("CopyBufferToImage");
        self.need_live(
            "CopyBufferToImage",
            ObjectKind::Buffer,
            copy.buffer.to_bits(),
        );
        self.need_live("CopyBufferToImage", ObjectKind::Image, copy.image.to_bits());
        self.record(Command::CopyBufferToImage(*copy));
    }

    fn copy_image_to_buffer(&mut self, copy: &BufferImageCopy) {
        self.need_outside("CopyImageToBuffer");
        self.need_live("CopyImageToBuffer", ObjectKind::Image, copy.image.to_bits());
        self.need_live(
            "CopyImageToBuffer",
            ObjectKind::Buffer,
            copy.buffer.to_bits(),
        );
        self.record(Command::CopyImageToBuffer(*copy));
    }

    fn copy_image_to_image(&mut self, copy: &ImageCopy) {
        self.need_outside("CopyImageToImage");
        self.need_live("CopyImageToImage", ObjectKind::Image, copy.src.to_bits());
        self.need_live("CopyImageToImage", ObjectKind::Image, copy.dst.to_bits());
        self.record(Command::CopyImageToImage(*copy));
    }

    fn clear_buffer(&mut self, buffer: BufferHandle, offset: u64, size: u64) {
        self.need_outside("ClearBuffer");
        self.need_live("ClearBuffer", ObjectKind::Buffer, buffer.to_bits());
        self.record(Command::ClearBuffer {
            buffer,
            offset,
            size,
        });
    }

    fn begin_render_pass(&mut self, desc: &RenderPassDesc<'_>) {
        for attachment in desc.color_attachments {
            self.need_live(
                "BeginRenderPass",
                ObjectKind::ImageView,
                attachment.view.to_bits(),
            );
            if let Some(resolve) = attachment.resolve {
                self.need_live("BeginRenderPass", ObjectKind::ImageView, resolve.to_bits());
            }
        }
        if let Some(attachment) = desc.depth_stencil_attachment {
            self.need_live(
                "BeginRenderPass",
                ObjectKind::ImageView,
                attachment.view.to_bits(),
            );
        }
        self.need_timestamps("BeginRenderPass", desc.timestamp_writes);
        self.record(Command::BeginRenderPass {
            label: desc.label.map(ToOwned::to_owned),
            color_attachments: desc.color_attachments.to_vec(),
            depth_stencil_attachment: desc.depth_stencil_attachment,
            render_area: desc.render_area,
            timestamp_writes: desc.timestamp_writes,
        });
    }

    fn end_render_pass(&mut self) {
        self.record(Command::EndRenderPass);
    }

    fn set_viewport(&mut self, viewport: &Viewport) {
        self.need_render("SetViewport");
        self.record(Command::SetViewport(*viewport));
    }

    fn set_scissor(&mut self, rect: &Rect2d) {
        self.need_render("SetScissor");
        self.record(Command::SetScissor(*rect));
    }

    fn set_stencil_reference(&mut self, reference: u32) {
        self.need_render("SetStencilReference");
        self.record(Command::SetStencilReference(reference));
    }

    fn bind_graphics_pipeline(&mut self, pipeline: GraphicsPipelineHandle) {
        self.need_render("BindGraphicsPipeline");
        self.need_live(
            "BindGraphicsPipeline",
            ObjectKind::GraphicsPipeline,
            pipeline.to_bits(),
        );
        self.record(Command::BindGraphicsPipeline(pipeline));
    }

    fn bind_index_buffer(&mut self, buffer: BufferHandle, offset: u64, format: IndexFormat) {
        self.need_render("BindIndexBuffer");
        self.need_live("BindIndexBuffer", ObjectKind::Buffer, buffer.to_bits());
        self.record(Command::BindIndexBuffer {
            buffer,
            offset,
            format,
        });
    }

    fn bind_group(
        &mut self,
        slot: u32,
        group: BindGroupHandle,
        dynamic_offsets: &[u32],
        _layout: PipelineLayoutHandle,
    ) {
        self.need_any_pass("BindGroup");
        self.need_live("BindGroup", ObjectKind::BindGroup, group.to_bits());
        self.need_dynamic_offsets("BindGroup", group, dynamic_offsets);
        self.record(Command::BindGroup {
            slot,
            group,
            dynamic_offsets: dynamic_offsets.to_vec(),
        });
    }

    fn push_constants(
        &mut self,
        stages: ShaderStages,
        offset: u32,
        data: &[u8],
        _layout: PipelineLayoutHandle,
    ) {
        self.need_any_pass("PushConstants");
        self.record(Command::PushConstants {
            stages,
            offset,
            len: data.len(),
        });
    }

    fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>) {
        self.need_render("Draw");
        self.record(Command::Draw {
            vertices,
            instances,
        });
    }

    fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>) {
        self.need_render("DrawIndexed");
        self.record(Command::DrawIndexed {
            indices,
            base_vertex,
            instances,
        });
    }

    fn draw_indirect(&mut self, draw: &DrawIndirect) {
        self.need_render("DrawIndirect");
        self.need_live("DrawIndirect", ObjectKind::Buffer, draw.args.to_bits());
        self.need_indirect_arguments("DrawIndirect", draw, false);
        self.record(Command::DrawIndirect(*draw));
    }

    fn draw_indexed_indirect(&mut self, draw: &DrawIndirect) {
        self.need_render("DrawIndexedIndirect");
        self.need_live(
            "DrawIndexedIndirect",
            ObjectKind::Buffer,
            draw.args.to_bits(),
        );
        self.need_indirect_arguments("DrawIndexedIndirect", draw, true);
        self.record(Command::DrawIndexedIndirect(*draw));
    }

    fn draw_indirect_count(&mut self, draw: &DrawIndirectCount) {
        self.need_render("DrawIndirectCount");
        self.need_live("DrawIndirectCount", ObjectKind::Buffer, draw.args.to_bits());
        self.need_live(
            "DrawIndirectCount",
            ObjectKind::Buffer,
            draw.count_buffer.to_bits(),
        );
        self.need_indirect_count_arguments("DrawIndirectCount", draw, false);
        self.record(Command::DrawIndirectCount(*draw));
    }

    fn draw_indexed_indirect_count(&mut self, draw: &DrawIndirectCount) {
        self.need_render("DrawIndexedIndirectCount");
        self.need_live(
            "DrawIndexedIndirectCount",
            ObjectKind::Buffer,
            draw.args.to_bits(),
        );
        self.need_live(
            "DrawIndexedIndirectCount",
            ObjectKind::Buffer,
            draw.count_buffer.to_bits(),
        );
        self.need_indirect_count_arguments("DrawIndexedIndirectCount", draw, true);
        self.record(Command::DrawIndexedIndirectCount(*draw));
    }

    fn draw_mesh_tasks(&mut self, x: u32, y: u32, z: u32) {
        // A draw, so `need_render` rather than `need_compute` — the three
        // counts are workgroups, but they are workgroups of a stage that emits
        // fragments.
        self.need_render("DrawMeshTasks");
        self.record(Command::DrawMeshTasks { x, y, z });
    }

    fn draw_mesh_tasks_indirect(&mut self, draw: &DrawIndirect) {
        // A draw for `draw_mesh_tasks`' reason, and a live-buffer check for
        // `draw_indexed_indirect`'s: the argument buffer is the whole of what
        // this call names, so a dead handle here is a frame that reads its
        // group counts from nothing.
        self.need_render("DrawMeshTasksIndirect");
        self.need_live(
            "DrawMeshTasksIndirect",
            ObjectKind::Buffer,
            draw.args.to_bits(),
        );
        self.need_mesh_indirect_arguments("DrawMeshTasksIndirect", draw);
        self.record(Command::DrawMeshTasksIndirect(*draw));
    }

    fn begin_compute_pass(&mut self, desc: &ComputePassDesc<'_>) {
        self.need_timestamps("BeginComputePass", desc.timestamp_writes);
        self.record(Command::BeginComputePass {
            label: desc.label.map(ToOwned::to_owned),
            timestamp_writes: desc.timestamp_writes,
        });
    }

    fn end_compute_pass(&mut self) {
        self.record(Command::EndComputePass);
    }

    fn bind_compute_pipeline(&mut self, pipeline: ComputePipelineHandle) {
        self.need_compute("BindComputePipeline");
        self.need_live(
            "BindComputePipeline",
            ObjectKind::ComputePipeline,
            pipeline.to_bits(),
        );
        self.record(Command::BindComputePipeline(pipeline));
    }

    fn dispatch(&mut self, x: u32, y: u32, z: u32) {
        self.need_compute("Dispatch");
        self.record(Command::Dispatch { x, y, z });
    }

    fn dispatch_indirect(&mut self, args: BufferHandle, offset: u64) {
        self.need_compute("DispatchIndirect");
        self.need_live("DispatchIndirect", ObjectKind::Buffer, args.to_bits());
        self.record(Command::DispatchIndirect { args, offset });
    }

    fn reset_query_set(&mut self, set: QuerySetHandle, range: Range<u32>) {
        self.need_outside("ResetQuerySet");
        self.need_live("ResetQuerySet", ObjectKind::QuerySet, set.to_bits());
        self.record(Command::ResetQuerySet { set, range });
    }

    fn resolve_query_set(
        &mut self,
        set: QuerySetHandle,
        range: Range<u32>,
        dst: BufferHandle,
        dst_offset: u64,
    ) {
        self.need_outside("ResolveQuerySet");
        self.need_live("ResolveQuerySet", ObjectKind::QuerySet, set.to_bits());
        self.need_live("ResolveQuerySet", ObjectKind::Buffer, dst.to_bits());
        self.record(Command::ResolveQuerySet {
            set,
            range,
            dst,
            dst_offset,
        });
    }

    fn finish(self: Box<Self>) -> Result<CommandBufferHandle, HalError> {
        if let Some(error) = self.failed {
            return Err(error);
        }
        if self.scope != Scope::Outside {
            // Recorded *and* returned. The seam's `finish` doc names an
            // unclosed pass as an `Err` case and `crcbl-vk` returns one, so a
            // null backend that answered `Ok` let CI green-light a command
            // stream Vulkan refuses to end at all — `vkEndCommandBuffer` with
            // a `vkCmdBeginRendering` outstanding is itself illegal.
            self.fail(ValidationError::UnclosedPass);
            return Err(HalError::InvalidDescriptor(
                "finish with a pass still open".to_string(),
            ));
        }
        let mut state = self.recorder.lock();
        let command_buffer: CommandBufferHandle = state.insert_owned(
            ObjectKind::CommandBuffer,
            self.device_id,
            self.label.clone(),
            Detail::None,
        );
        for command in self.commands {
            state.events.push(Event::Command {
                command_buffer,
                command,
            });
        }
        state.events.push(Event::Finished {
            label: self.label,
            command_buffer,
        });
        Ok(command_buffer)
    }
}

#[cfg(test)]
mod tests;