openadr 0.7.0

OpenADR 3.1 in Rust: VTN server, VEN runtime, typed client and an open conformance suite
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
//! The checks.
//!
//! Each one is a normative sentence turned into a request and an assertion. They are listed here
//! rather than discovered, in the order they run, so that adding one is a visible edit and the
//! report is stable between runs.
//!
//! Ordering is not arbitrary: the discovery checks come first because a VTN that fails them will
//! fail everything else for the same reason, and a report that says so at the top saves reading the
//! rest.

use serde_json::{Value, json};

use super::{Check, Needs, Outcome, RUN_PREFIX, Runner, Severity};
use crate::client::{Client, ClientError, Query, RawResponse, Role};

/// How many times a request that never reached the VTN is retried.
///
/// A conformance suite runs across a network at somebody else's server, and a refused connection or
/// a reset is not evidence about the specification. Reporting one as non-conformance produces a
/// false accusation, which is worse than no measurement: the whole value of the report is that a
/// failing line can be taken to the implementer.
///
/// Only *transport* failures are retried. A `500` is an answer, and answers are never retried —
/// re-running a check that writes would leave a second object behind and could turn a real failure
/// into an intermittent one.
const TRANSPORT_ATTEMPTS: usize = 3;

/// One request, retried while it fails to arrive at all.
async fn attempt<R: Role>(
    client: &Client<R>,
    method: &str,
    path: &str,
    query: &Query,
    body: Option<&Value>,
    headers: &[(String, String)],
) -> Result<RawResponse, Outcome> {
    let mut last = None;
    for n in 0..TRANSPORT_ATTEMPTS {
        match client.exchange(method, path, query, body, headers).await {
            Ok(response) => return Ok(response),
            Err(e @ ClientError::Transport(_)) => {
                last = Some(e);
                // Short and growing: the case this exists for is a listener that is a moment from
                // ready, not a server that is down.
                tokio::time::sleep(std::time::Duration::from_millis(50 << n)).await;
            }
            Err(other) => return Err(transport(other)),
        }
    }
    Err(transport(last.expect("the loop ran at least once")))
}

/// The same, decoded as JSON, for a check that only cares about the body.
async fn fetch<R: Role>(client: &Client<R>, path: &str, query: &Query) -> Result<Value, Outcome> {
    let response = attempt(client, "GET", path, query, None, &[]).await?;
    if !response.status.is_success() {
        return Err(Outcome::Failed(format!(
            "GET /{path} answered {}: {}",
            response.status,
            String::from_utf8_lossy(&response.body)
        )));
    }
    response
        .json()
        .ok_or_else(|| Outcome::Failed(format!("GET /{path} returned no JSON body")))
}

/// Every check, in the order they run.
pub fn checks() -> &'static [Check] {
    &[
        // -- discovery -----------------------------------------------------
        Check {
            id: "auth-server-unauthenticated",
            clause: "[API /auth/server]",
            title: "GET /auth/server answers without credentials and names a token URL",
            severity: Severity::Required,
            needs: Needs::Nothing,
        },
        Check {
            id: "notifiers-webhook-key",
            clause: "[Def §Notifications]",
            title: "GET /notifiers carries the WEBHOOK binding key",
            severity: Severity::Required,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "unauthenticated-write-refused",
            clause: "[API securitySchemes]",
            title: "a write with no credentials is refused",
            severity: Severity::Required,
            needs: Needs::Nothing,
        },
        // -- object lifecycle ----------------------------------------------
        Check {
            id: "create-stamps-metadata",
            clause: "[API objectMetadata]",
            title: "POST answers 201 and the VTN stamps id, timestamps and objectType",
            severity: Severity::Required,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "create-ignores-client-metadata",
            clause: "[Def §Response Codes and Errors]",
            title: "id and createdDateTime in a request body are ignored, not honoured",
            severity: Severity::Required,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "update-moves-modification-time",
            clause: "[API objectMetadata]",
            title: "PUT advances modificationDateTime and leaves createdDateTime alone",
            severity: Severity::Required,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "missing-object-is-404-problem",
            clause: "[Def §Response Codes and Errors]",
            title: "a missing object answers 404 with a problem body",
            severity: Severity::Required,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "malformed-body-is-400-problem",
            clause: "[Def §Response Codes and Errors]",
            title: "a malformed request body answers 400 with a problem body",
            severity: Severity::Required,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "program-name-is-unique",
            clause: "[Def §Object names]",
            title: "a second programme with the same programName is refused",
            severity: Severity::Required,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "event-needs-a-programme",
            clause: "[API eventRequest]",
            title: "an event naming a programme that does not exist is refused",
            severity: Severity::Required,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "programme-delete-leaves-no-orphan",
            clause: "[API eventRequest.programID]",
            title: "no event is left naming a programme that no longer exists",
            severity: Severity::Required,
            needs: Needs::BusinessLogic,
        },
        // -- collections ---------------------------------------------------
        Check {
            id: "limit-is-capped-at-fifty",
            clause: "[API skip/limit]",
            title: "limit above 50 is refused rather than silently honoured",
            severity: Severity::Required,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "pagination-is-complete-and-ordered",
            clause: "[Def §Response Filtering]",
            title: "skip and limit walk the collection once, with no gap or repeat",
            severity: Severity::Required,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "filters-are-additive",
            clause: "[Def §Response Filtering]",
            title: "two filters narrow together rather than either one winning",
            severity: Severity::Required,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "targets-accept-both-forms",
            clause: "[extension] both forms occur in the field",
            title: "?targets=a&targets=b and ?targets=a,b mean the same thing",
            severity: Severity::Extension,
            needs: Needs::BusinessLogic,
        },
        // -- time semantics ------------------------------------------------
        Check {
            id: "forever-duration-round-trips",
            clause: "[UG §7.3]",
            title: "a P9999Y duration survives a write and a read unchanged",
            severity: Severity::Required,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "now-sentinel-round-trips",
            clause: "[UG §7.3]",
            title: "a 0001-01-01 start survives a write and a read as a start, not as a date",
            severity: Severity::Required,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "interval-payloads-round-trip",
            clause: "[API eventRequest]",
            title: "an event's intervals and payloads come back exactly as written",
            severity: Severity::Required,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "decimal-prices-are-exact",
            clause: "[API values]",
            title: "a price of 0.1 comes back as 0.1",
            severity: Severity::Required,
            needs: Needs::BusinessLogic,
        },
        // -- object privacy ------------------------------------------------
        Check {
            id: "ven-cannot-write-programmes",
            clause: "[API securitySchemes]",
            title: "a VEN cannot create a programme",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "ven-cannot-grant-itself-targets",
            clause: "[Def §BL created object privacy]",
            title: "targets in a VEN-written ven body are not honoured",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "untargeted-objects-are-visible",
            clause: "[Def §Object Privacy]",
            title: "an untargeted programme is readable by a VEN",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "ungranted-targets-are-invisible",
            clause: "[Def §Object Privacy]",
            title: "a VEN cannot read an event targeted at a group it was not granted",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "granted-targets-are-visible",
            clause: "[Def §Object Privacy]",
            title: "a VEN reads an event targeted at a group it was granted, by naming it",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "target-hiding-on-reads",
            clause: "[Def §Object Privacy]",
            title: "a granted VEN sees only its own target on the object, never the full set",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "hidden-object-is-404-not-403",
            clause: "[Def §Object Privacy]",
            title: "reading a targeted object by id answers 404 rather than confirming it exists",
            severity: Severity::Recommended,
            needs: Needs::BothRoles,
        },
        Check {
            id: "ven-reads-only-its-own-vens",
            clause: "[Def §VEN created object privacy]",
            title: "GET /vens returns only the VEN objects whose clientID is the caller's",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "ven-cannot-grant-a-resource-targets",
            clause: "[API resourceRequest]",
            title: "a VEN cannot write targets onto a resource it creates",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "ven-reads-only-its-own-reports",
            clause: "[Def §Object Privacy]",
            title: "a VEN reads only the reports it filed",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "ven-reads-only-its-own-resources",
            clause: "[Def §Object Privacy]",
            title: "a VEN reads only the resources belonging to it",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "ven-reads-only-its-own-subscriptions",
            clause: "[Def §VEN created object privacy]",
            title: "GET /subscriptions returns only the caller's, tokens included",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "ven-cannot-change-a-foreign-ven",
            clause: "[Def §VEN created object privacy]",
            title: "a VEN can neither replace nor delete another client's VEN object",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "ven-cannot-change-a-foreign-resource",
            clause: "[Def §Object Privacy]",
            title: "a VEN can neither replace nor delete a resource under another client's VEN",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "ven-cannot-change-a-foreign-subscription",
            clause: "[Def §VEN created object privacy]",
            title: "a VEN can neither replace nor delete another client's subscription",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "foreign-write-is-404-not-403",
            clause: "[Def §Object Privacy]",
            title: "a refused write to another client's object answers 404, not 403",
            severity: Severity::Recommended,
            needs: Needs::BothRoles,
        },
        // -- reports -------------------------------------------------------
        Check {
            id: "report-round-trips",
            clause: "[API reportRequest]",
            title: "a report a VEN files comes back with its resources, intervals and values intact",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "report-is-stamped-not-claimed",
            clause: "[Def §VEN created object privacy]",
            title: "the VTN stamps a report's clientID from the credential, not from the body",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "report-filters-by-event",
            clause: "[API /reports ?eventID]",
            title: "GET /reports?eventID= returns that event's reports and no others",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "report-needs-an-event",
            clause: "[API reportRequest.eventID]",
            title: "a report naming an event that does not exist is refused",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        // -- the MQTT notifier binding -------------------------------------
        Check {
            id: "mqtt-binding-shape",
            clause: "[Notifiers §7.2]",
            title: "the MQTT binding names URIS, a serialization and an authentication method",
            severity: Severity::Required,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "mqtt-collection-topics-are-business-logic-only",
            clause: "[Notifiers §9.3]",
            title: "a VEN cannot obtain a collection-wide topic name",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "mqtt-ven-scoped-topics",
            clause: "[Notifiers §8.2]",
            title: "a VEN obtains its own topics, and they carry UPDATE and DELETE",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        Check {
            id: "mqtt-foreign-ven-topics-refused",
            clause: "[Notifiers §9.2]",
            title: "a VEN cannot obtain another VEN's topic names",
            severity: Severity::Required,
            needs: Needs::BothRoles,
        },
        // -- extensions ----------------------------------------------------
        Check {
            id: "active-excludes-transpired-events",
            clause: "[API /events ?active]",
            title: "?active=true drops events whose intervals have all elapsed",
            severity: Severity::Required,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "etag-and-conditional-read",
            clause: "[extension] RFC 9110 §8.8",
            title: "GET carries an ETag and a matching If-None-Match answers 304",
            severity: Severity::Extension,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "problem-uses-the-rfc-9457-media-type",
            clause: "[extension] RFC 9457 §3",
            title: "an error body is served as application/problem+json",
            severity: Severity::Extension,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "problem-carries-a-traceable-instance",
            clause: "[extension] RFC 9457 §3.1.5",
            title: "an error's problem.instance matches the response's request id header",
            severity: Severity::Extension,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "program-name-lookup",
            clause: "[extension] not in openadr3.yaml",
            title: "GET /programs?programName= finds one programme without paging",
            severity: Severity::Extension,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "unauthorized-names-the-scheme",
            clause: "RFC 9110 §11.6.1",
            title: "a 401 carries WWW-Authenticate, so a client knows what to present",
            severity: Severity::Required,
            needs: Needs::Nothing,
        },
        Check {
            id: "token-response-is-not-stored",
            clause: "RFC 6749 §5.1",
            title: "the token endpoint answers Cache-Control: no-store",
            severity: Severity::Required,
            needs: Needs::Nothing,
        },
        Check {
            id: "foreign-media-type-is-refused",
            clause: "[API createProgram requestBody] RFC 9110 §15.5.16",
            title: "a body labelled with a media type the endpoint does not declare answers 415",
            severity: Severity::Recommended,
            needs: Needs::BusinessLogic,
        },
        Check {
            id: "reads-declare-a-caching-policy",
            clause: "[extension] RFC 9111 §5.2.2",
            title: "a read says how it may be cached, because its body depends on who asked",
            severity: Severity::Extension,
            needs: Needs::BusinessLogic,
        },
    ]
}

/// Dispatch one check by id.
///
/// A `match` rather than a table of function pointers, so that a check listed above and never
/// implemented fails to compile — which is the same reason the storage conformance suite writes its
/// list out by hand.
pub(super) async fn run_one(run: &Runner, check: &Check) -> Outcome {
    match check.id {
        "auth-server-unauthenticated" => auth_server_unauthenticated(run).await,
        "notifiers-webhook-key" => notifiers_webhook_key(run).await,
        "unauthenticated-write-refused" => unauthenticated_write_refused(run).await,
        "create-stamps-metadata" => create_stamps_metadata(run).await,
        "create-ignores-client-metadata" => create_ignores_client_metadata(run).await,
        "update-moves-modification-time" => update_moves_modification_time(run).await,
        "missing-object-is-404-problem" => missing_object_is_404_problem(run).await,
        "malformed-body-is-400-problem" => malformed_body_is_400_problem(run).await,
        "program-name-is-unique" => program_name_is_unique(run).await,
        "event-needs-a-programme" => event_needs_a_programme(run).await,
        "programme-delete-leaves-no-orphan" => programme_delete_leaves_no_orphan(run).await,
        "limit-is-capped-at-fifty" => limit_is_capped_at_fifty(run).await,
        "pagination-is-complete-and-ordered" => pagination_is_complete_and_ordered(run).await,
        "filters-are-additive" => filters_are_additive(run).await,
        "targets-accept-both-forms" => targets_accept_both_forms(run).await,
        "forever-duration-round-trips" => forever_duration_round_trips(run).await,
        "now-sentinel-round-trips" => now_sentinel_round_trips(run).await,
        "interval-payloads-round-trip" => interval_payloads_round_trip(run).await,
        "decimal-prices-are-exact" => decimal_prices_are_exact(run).await,
        "ven-cannot-write-programmes" => ven_cannot_write_programmes(run).await,
        "ven-cannot-grant-itself-targets" => ven_cannot_grant_itself_targets(run).await,
        "untargeted-objects-are-visible" => untargeted_objects_are_visible(run).await,
        "ungranted-targets-are-invisible" => ungranted_targets_are_invisible(run).await,
        "granted-targets-are-visible" => granted_targets_are_visible(run).await,
        "target-hiding-on-reads" => target_hiding_on_reads(run).await,
        "hidden-object-is-404-not-403" => hidden_object_is_404_not_403(run).await,
        "ven-reads-only-its-own-vens" => ven_reads_only_its_own_vens(run).await,
        "ven-cannot-grant-a-resource-targets" => ven_cannot_grant_a_resource_targets(run).await,
        "ven-reads-only-its-own-reports" => ven_reads_only_its_own_reports(run).await,
        "ven-reads-only-its-own-resources" => ven_reads_only_its_own_resources(run).await,
        "ven-reads-only-its-own-subscriptions" => ven_reads_only_its_own_subscriptions(run).await,
        "ven-cannot-change-a-foreign-ven" => ven_cannot_change_a_foreign_ven(run).await,
        "ven-cannot-change-a-foreign-resource" => ven_cannot_change_a_foreign_resource(run).await,
        "ven-cannot-change-a-foreign-subscription" => {
            ven_cannot_change_a_foreign_subscription(run).await
        }
        "foreign-write-is-404-not-403" => foreign_write_is_404_not_403(run).await,
        "report-round-trips" => report_round_trips(run).await,
        "report-is-stamped-not-claimed" => report_is_stamped_not_claimed(run).await,
        "report-filters-by-event" => report_filters_by_event(run).await,
        "report-needs-an-event" => report_needs_an_event(run).await,
        "mqtt-binding-shape" => mqtt_binding_shape(run).await,
        "mqtt-collection-topics-are-business-logic-only" => {
            mqtt_collection_topics_are_business_logic_only(run).await
        }
        "mqtt-ven-scoped-topics" => mqtt_ven_scoped_topics(run).await,
        "mqtt-foreign-ven-topics-refused" => mqtt_foreign_ven_topics_refused(run).await,
        "active-excludes-transpired-events" => active_excludes_transpired_events(run).await,
        "etag-and-conditional-read" => etag_and_conditional_read(run).await,
        "problem-uses-the-rfc-9457-media-type" => problem_uses_the_rfc_9457_media_type(run).await,
        "problem-carries-a-traceable-instance" => problem_carries_a_traceable_instance(run).await,
        "program-name-lookup" => program_name_lookup(run).await,
        "unauthorized-names-the-scheme" => unauthorized_names_the_scheme(run).await,
        "token-response-is-not-stored" => token_response_is_not_stored(run).await,
        "foreign-media-type-is-refused" => foreign_media_type_is_refused(run).await,
        "reads-declare-a-caching-policy" => reads_declare_a_caching_policy(run).await,
        other => Outcome::Skipped(format!("{other} is listed but not implemented")),
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// A name unique to this run, so two suites against one VTN do not collide.
fn unique(kind: &str) -> String {
    use std::sync::atomic::{AtomicU32, Ordering};
    static SEQ: AtomicU32 = AtomicU32::new(0);
    let n = SEQ.fetch_add(1, Ordering::Relaxed);
    let stamp = crate::model::Timestamp::now().as_second();
    format!("{RUN_PREFIX}{kind}-{stamp}-{n}")
}

/// `Ok` if the condition holds, a failure naming what was expected otherwise.
fn expect(condition: bool, message: impl Into<String>) -> Result<(), Outcome> {
    if condition {
        Ok(())
    } else {
        Err(Outcome::Failed(message.into()))
    }
}

/// Turn a fallible async body into an `Outcome`.
///
/// The bodies use `?` to stop at the first thing that went wrong, which is what makes a check read
/// like a description of the behaviour rather than like a decision tree.
macro_rules! check {
    ($body:block) => {
        match async move { $body }.await {
            Ok(()) => Outcome::Passed,
            Err(outcome) => outcome,
        }
    };
}

/// Create a programme as business logic, tracking it for cleanup.
async fn make_program(run: &Runner, body: Value) -> Result<Value, Outcome> {
    let response = attempt(
        run.business_logic(),
        "POST",
        "programs",
        &Query::new(),
        Some(&body),
        &[],
    )
    .await?;
    if response.status.as_u16() != 201 {
        return Err(Outcome::Failed(format!(
            "POST /programs answered {} (expected 201): {}",
            response.status,
            String::from_utf8_lossy(&response.body)
        )));
    }
    let created = response
        .json()
        .ok_or_else(|| Outcome::Failed("POST /programs returned no JSON body".into()))?;
    if let Some(id) = created["id"].as_str() {
        run.track("programs", id);
    }
    Ok(created)
}

/// Create an event as business logic, tracking it for cleanup.
async fn make_event(run: &Runner, body: Value) -> Result<Value, Outcome> {
    let response = attempt(
        run.business_logic(),
        "POST",
        "events",
        &Query::new(),
        Some(&body),
        &[],
    )
    .await?;
    if response.status.as_u16() != 201 {
        return Err(Outcome::Failed(format!(
            "POST /events answered {} (expected 201): {}",
            response.status,
            String::from_utf8_lossy(&response.body)
        )));
    }
    let created = response
        .json()
        .ok_or_else(|| Outcome::Failed("POST /events returned no JSON body".into()))?;
    if let Some(id) = created["id"].as_str() {
        run.track("events", id);
    }
    Ok(created)
}

/// A minimal event body for a programme.
fn event_body(program_id: &str, targets: &[&str]) -> Value {
    json!({
        "programID": program_id,
        "eventName": unique("event"),
        "targets": targets,
        "intervalPeriod": { "start": "2026-02-11T12:00:00Z", "duration": "PT15M" },
        "intervals": [
            { "id": 0, "payloads": [{ "type": "IMPORT_CAPACITY_LIMIT", "values": [60] }] }
        ]
    })
}

/// File a report as the VEN, tracking it for cleanup.
///
/// The suite had no such helper, and consequently never wrote a report at all — which made
/// `ven-reads-only-its-own-reports` a check that passed against an empty collection, and left the
/// object carrying customer meter data with the least coverage of any in the API.
async fn make_report(run: &Runner, body: Value) -> Result<Value, Outcome> {
    let response = attempt(
        run.virtual_end_node(),
        "POST",
        "reports",
        &Query::new(),
        Some(&body),
        &[],
    )
    .await?;
    if response.status.as_u16() != 201 {
        return Err(Outcome::Failed(format!(
            "POST /reports as a VEN answered {} (expected 201): {}",
            response.status,
            String::from_utf8_lossy(&response.body)
        )));
    }
    let created = response
        .json()
        .ok_or_else(|| Outcome::Failed("POST /reports returned no JSON body".into()))?;
    if let Some(id) = created["id"].as_str() {
        run.track("reports", id);
    }
    Ok(created)
}

/// A programme, an event under it, and the event's id — the scaffolding every report check needs.
async fn seed_event(run: &Runner) -> Result<String, Outcome> {
    let program = make_program(run, json!({ "programName": unique("program") })).await?;
    let program_id = program["id"]
        .as_str()
        .ok_or_else(|| Outcome::Failed("a created programme carries no id".into()))?;
    let event = make_event(run, event_body(program_id, &[])).await?;
    event["id"]
        .as_str()
        .map(str::to_string)
        .ok_or_else(|| Outcome::Failed("a created event carries no id".into()))
}

/// A report body against an event, with one resource and one interval carrying a decimal.
fn report_body(event_id: &str, resource: &str, value: f64) -> Value {
    json!({
        "eventID": event_id,
        "clientName": unique("client"),
        "reportName": unique("report"),
        "payloadDescriptors": [
            { "objectType": "REPORT_PAYLOAD_DESCRIPTOR", "payloadType": "USAGE",
              "readingType": "DIRECT_READ", "units": "KWH" }
        ],
        "resources": [{
            "resourceName": resource,
            "intervalPeriod": { "start": "2026-02-11T12:00:00Z", "duration": "PT15M" },
            "intervals": [
                { "id": 0, "payloads": [{ "type": "USAGE", "values": [value] }] }
            ]
        }]
    })
}

/// What a request that failed to complete means for the check, with the reason — all of it.
///
/// `reqwest`'s own `Display` is "error sending request for url (…)" and puts the thing that
/// actually happened — connection refused, TLS handshake failed, DNS — in the source chain. A
/// conformance report that stops at the first line tells the reader nothing they can act on.
fn transport(e: crate::client::ClientError) -> Outcome {
    let mut message = e.to_string();
    let mut source = std::error::Error::source(&e);
    while let Some(cause) = source {
        message.push_str(": ");
        message.push_str(&cause.to_string());
        source = cause.source();
    }
    // A request that never arrived is not evidence about the specification: reporting it as a
    // failure accuses the VTN of something a slow start or a reset connection did. It is a skip,
    // and a run in which every required check skipped is reported as "not measured".
    if matches!(e, crate::client::ClientError::Transport(_)) {
        Outcome::Skipped(format!("the VTN could not be reached: {message}"))
    } else {
        Outcome::Failed(format!("the request could not be made: {message}"))
    }
}

/// Grant the configured VEN a target, returning the VEN object's id.
///
/// Business logic writes the grant, because only business logic may. If no VEN object exists for
/// the configured `clientID` this creates one, which is also what a VTN's enrollment flow does.
/// Somebody else's VEN object, so an ownership check has something to *fail* to see.
///
/// A check that asserts "no foreign object appears" and never creates a foreign object asserts that
/// an empty list is empty, which is the shape D-092 named and which running this suite against a
/// VTN that reads every credential as business logic found in two more checks.
async fn foreign_ven(run: &Runner) -> Result<String, Outcome> {
    let response = attempt(
        run.business_logic(),
        "POST",
        "vens",
        &Query::new(),
        Some(&json!({
            "objectType": "BL_VEN_REQUEST",
            // Unique per call: this VTN, and the specification's own model, allow one VEN object
            // per `clientID`, so two checks each wanting "somebody else's VEN" need two
            // somebody-elses.
            "clientID": unique("another-client"),
            "venName": unique("other-ven"),
        })),
        &[],
    )
    .await?;
    if response.status.as_u16() != 201 {
        return Err(Outcome::Failed(format!(
            "could not create a second VEN object to test ownership against: {} {}",
            response.status,
            String::from_utf8_lossy(&response.body)
        )));
    }
    let id = response
        .json()
        .and_then(|v| v["id"].as_str().map(str::to_string))
        .ok_or_else(|| Outcome::Failed("the second VEN object has no id".into()))?;
    run.track("vens", &id);
    Ok(id)
}

async fn grant_target(run: &Runner, target: &str) -> Result<String, Outcome> {
    let client_id = run
        .target
        .ven_client_id
        .as_deref()
        .expect("the precondition check guarantees a clientID");
    let bl = run.business_logic();

    // An existing VEN object for this client, if there is one. `?venName=` cannot find it — the
    // name is not known — so this reads the collection business logic can see in full.
    let existing = fetch(bl, "vens", &Query::new().limit(50)).await?;
    let found = existing
        .as_array()
        .and_then(|vens| {
            vens.iter()
                .find(|v| v["clientID"].as_str() == Some(client_id))
        })
        .cloned();

    let body = json!({
        "objectType": "BL_VEN_REQUEST",
        "clientID": client_id,
        "venName": found
            .as_ref()
            .and_then(|v| v["venName"].as_str())
            .map(str::to_string)
            .unwrap_or_else(|| unique("ven")),
        "targets": [target],
    });

    let (method, path, expected) = match found.as_ref().and_then(|v| v["id"].as_str()) {
        Some(id) => ("PUT", format!("vens/{id}"), 200),
        None => ("POST", "vens".to_string(), 201),
    };
    let response = attempt(bl, method, &path, &Query::new(), Some(&body), &[]).await?;
    if response.status.as_u16() != expected {
        return Err(Outcome::Failed(format!(
            "{method} /{path} answered {} (expected {expected}) while granting a target: {}",
            response.status,
            String::from_utf8_lossy(&response.body)
        )));
    }
    let id = response
        .json()
        .and_then(|v| v["id"].as_str().map(str::to_string))
        .ok_or_else(|| Outcome::Failed("the VEN object has no id".into()))?;
    if method == "POST" {
        run.track("vens", &id);
    }
    Ok(id)
}

// ---------------------------------------------------------------------------
// Discovery
// ---------------------------------------------------------------------------

async fn auth_server_unauthenticated(run: &Runner) -> Outcome {
    check!({
        let client = run.anonymous().map_err(transport)?;
        let response = attempt(&client, "GET", "auth/server", &Query::new(), None, &[]).await?;
        expect(
            response.status.is_success(),
            format!(
                "GET /auth/server answered {} without credentials; the endpoint is how a client \
                 discovers where to get them, so it cannot require one",
                response.status
            ),
        )?;
        let body = response
            .json()
            .ok_or_else(|| Outcome::Failed("GET /auth/server returned no JSON".into()))?;
        expect(
            body["tokenURL"].as_str().is_some_and(|u| !u.is_empty()),
            format!("GET /auth/server returned no tokenURL: {body}"),
        )
    })
}

async fn notifiers_webhook_key(run: &Runner) -> Outcome {
    check!({
        let response = attempt(
            run.business_logic(),
            "GET",
            "notifiers",
            &Query::new(),
            None,
            &[],
        )
        .await?;
        expect(
            response.status.is_success(),
            format!("GET /notifiers answered {}", response.status),
        )?;
        let body = response
            .json()
            .ok_or_else(|| Outcome::Failed("GET /notifiers returned no JSON".into()))?;
        expect(
            body.get("WEBHOOK").is_some(),
            format!(
                "GET /notifiers has no WEBHOOK key; it must be present so a client can tell \
                 whether webhooks are available: {body}"
            ),
        )
    })
}

async fn unauthenticated_write_refused(run: &Runner) -> Outcome {
    check!({
        let client = run.anonymous().map_err(transport)?;
        let response = attempt(
            &client,
            "POST",
            "programs",
            &Query::new(),
            Some(&json!({ "programName": unique("should-not-exist") })),
            &[],
        )
        .await?;
        expect(
            matches!(response.status.as_u16(), 401 | 403),
            format!(
                "an unauthenticated POST /programs answered {} (expected 401 or 403)",
                response.status
            ),
        )
    })
}

// ---------------------------------------------------------------------------
// Object lifecycle
// ---------------------------------------------------------------------------

async fn create_stamps_metadata(run: &Runner) -> Outcome {
    check!({
        let name = unique("program");
        let created = make_program(run, json!({ "programName": name })).await?;
        for field in [
            "id",
            "createdDateTime",
            "modificationDateTime",
            "objectType",
        ] {
            expect(
                created.get(field).is_some(),
                format!("the created programme has no {field}: {created}"),
            )?;
        }
        expect(
            created["objectType"] == "PROGRAM",
            format!("objectType is {} (expected PROGRAM)", created["objectType"]),
        )?;
        expect(
            created["createdDateTime"]
                .as_str()
                .is_some_and(|t| t.parse::<crate::model::Timestamp>().is_ok()),
            format!(
                "createdDateTime is not RFC 3339: {}",
                created["createdDateTime"]
            ),
        )
    })
}

async fn create_ignores_client_metadata(run: &Runner) -> Outcome {
    check!({
        let created = make_program(
            run,
            json!({
                "programName": unique("program"),
                "id": "client-chosen-id",
                "createdDateTime": "1999-01-01T00:00:00Z",
                "objectType": "PROGRAM",
            }),
        )
        .await?;
        expect(
            created["id"] != "client-chosen-id",
            "the VTN honoured an id supplied by the client; ids are the VTN's to assign"
                .to_string(),
        )?;
        expect(
            created["createdDateTime"] != "1999-01-01T00:00:00Z",
            "the VTN honoured a createdDateTime supplied by the client".to_string(),
        )
    })
}

async fn update_moves_modification_time(run: &Runner) -> Outcome {
    check!({
        let created = make_program(run, json!({ "programName": unique("program") })).await?;
        let id = created["id"].as_str().unwrap_or_default();

        let updated = attempt(
            run.business_logic(),
            "PUT",
            &format!("programs/{id}"),
            &Query::new(),
            Some(&json!({
                "programName": created["programName"],
                "programDescriptions": [{ "URL": "https://example.com/tariff" }],
            })),
            &[],
        )
        .await?;
        expect(
            updated.status.is_success(),
            format!("PUT /programs/{id} answered {}", updated.status),
        )?;
        let updated = updated
            .json()
            .ok_or_else(|| Outcome::Failed("PUT returned no JSON".into()))?;

        expect(
            updated["createdDateTime"] == created["createdDateTime"],
            "PUT changed createdDateTime; it records when the object was created".to_string(),
        )?;
        expect(
            updated["modificationDateTime"] != created["modificationDateTime"],
            "PUT left modificationDateTime unchanged after a real change; a client polling on it \
             would never see the update"
                .to_string(),
        )
    })
}

async fn missing_object_is_404_problem(run: &Runner) -> Outcome {
    check!({
        let response = attempt(
            run.business_logic(),
            "GET",
            "programs/oadr-conformance-no-such-program",
            &Query::new(),
            None,
            &[],
        )
        .await?;
        expect(
            response.status.as_u16() == 404,
            format!(
                "a missing programme answered {} (expected 404)",
                response.status
            ),
        )?;
        let problem = response
            .problem()
            .ok_or_else(|| Outcome::Failed("the 404 carried no problem body".into()))?;
        expect(
            problem.status == Some(404),
            format!(
                "the problem body's status is {:?} (expected 404)",
                problem.status
            ),
        )?;
        expect(
            problem.title.is_some(),
            "the problem body has no title".to_string(),
        )
    })
}

async fn malformed_body_is_400_problem(run: &Runner) -> Outcome {
    check!({
        // A programme with no `programName`, which the schema requires.
        let response = attempt(
            run.business_logic(),
            "POST",
            "programs",
            &Query::new(),
            Some(&json!({ "notAField": true })),
            &[],
        )
        .await?;
        expect(
            response.status.as_u16() == 400,
            format!(
                "a body missing the required programName answered {} (expected 400)",
                response.status
            ),
        )?;
        expect(
            response.problem().is_some(),
            "the 400 carried no problem body".to_string(),
        )
    })
}

async fn program_name_is_unique(run: &Runner) -> Outcome {
    check!({
        let name = unique("program");
        make_program(run, json!({ "programName": name.clone() })).await?;

        let second = attempt(
            run.business_logic(),
            "POST",
            "programs",
            &Query::new(),
            Some(&json!({ "programName": name })),
            &[],
        )
        .await?;
        if second.status.as_u16() == 201
            && let Some(id) = second
                .json()
                .and_then(|v| v["id"].as_str().map(str::to_string))
        {
            run.track("programs", id);
        }
        expect(
            second.status.as_u16() == 409,
            format!(
                "a duplicate programName answered {} (expected 409); the name must be unique to a \
                 VTN instance",
                second.status
            ),
        )
    })
}

async fn event_needs_a_programme(run: &Runner) -> Outcome {
    check!({
        let response = attempt(
            run.business_logic(),
            "POST",
            "events",
            &Query::new(),
            Some(&event_body("oadr-conformance-no-such-program", &[])),
            &[],
        )
        .await?;
        if response.status.as_u16() == 201
            && let Some(id) = response
                .json()
                .and_then(|v| v["id"].as_str().map(str::to_string))
        {
            run.track("events", id);
        }
        expect(
            matches!(response.status.as_u16(), 400 | 404 | 409),
            format!(
                "an event naming a programme that does not exist answered {} (expected 400, 404 \
                 or 409); a dangling programID leaves an event no VEN can resolve",
                response.status
            ),
        )
    })
}

/// Deleting a programme must not leave its events pointing at nothing.
///
/// The specification says what a `DELETE /programs/{id}` returns and nothing about what becomes of
/// the events that name it, so *cascade* and *refuse while dependents exist* are both defensible
/// and implementations do both. What no reading permits is the third outcome: the delete succeeds
/// and the events survive, each naming a `programID` that now resolves to nothing.
///
/// This check used to assert the cascade — this implementation's choice — as though the
/// specification required it, and reported a peer that refuses instead as non-conformant. That is
/// the failure mode requiring a citation is supposed to prevent, and it took running the suite
/// against somebody else to notice.
async fn programme_delete_leaves_no_orphan(run: &Runner) -> Outcome {
    check!({
        let program = make_program(run, json!({ "programName": unique("program") })).await?;
        let program_id = program["id"].as_str().unwrap_or_default().to_string();
        let event = make_event(run, event_body(&program_id, &[])).await?;
        let event_id = event["id"].as_str().unwrap_or_default().to_string();

        let deleted = attempt(
            run.business_logic(),
            "DELETE",
            &format!("programs/{program_id}"),
            &Query::new(),
            None,
            &[],
        )
        .await?;

        let program_gone = attempt(
            run.business_logic(),
            "GET",
            &format!("programs/{program_id}"),
            &Query::new(),
            None,
            &[],
        )
        .await?
        .status
        .as_u16()
            == 404;
        let event_gone = attempt(
            run.business_logic(),
            "GET",
            &format!("events/{event_id}"),
            &Query::new(),
            None,
            &[],
        )
        .await?
        .status
        .as_u16()
            == 404;

        if deleted.status.is_success() {
            expect(
                program_gone,
                format!(
                    "DELETE answered {} and the programme is still there",
                    deleted.status
                ),
            )?;
            return expect(
                event_gone,
                "the programme was deleted and its event survived, naming a programID that now \
                 resolves to nothing. Either take the events with it or refuse the delete"
                    .to_string(),
            );
        }

        // Refusing is the other defensible answer — as long as nothing was half-done.
        expect(
            !program_gone && !event_gone,
            format!(
                "DELETE answered {} but something was removed anyway; a refused delete must leave \
                 the programme and its events exactly as they were",
                deleted.status
            ),
        )
    })
}

// ---------------------------------------------------------------------------
// Collections
// ---------------------------------------------------------------------------

async fn limit_is_capped_at_fifty(run: &Runner) -> Outcome {
    check!({
        let response = attempt(
            run.business_logic(),
            "GET",
            "programs",
            &Query::new().param("limit", "500"),
            None,
            &[],
        )
        .await?;
        expect(
            response.status.as_u16() == 400,
            format!(
                "?limit=500 answered {} (expected 400); the schema's maximum is 50, and silently \
                 clamping it leaves a client unable to tell a short page from the end",
                response.status
            ),
        )
    })
}

async fn pagination_is_complete_and_ordered(run: &Runner) -> Outcome {
    check!({
        // Five programmes of our own, then walked two at a time.
        let mut mine: Vec<String> = Vec::new();
        for _ in 0..5 {
            let created = make_program(run, json!({ "programName": unique("page") })).await?;
            mine.push(created["id"].as_str().unwrap_or_default().to_string());
        }

        let mut seen: Vec<String> = Vec::new();
        for skip in (0..200).step_by(2) {
            let page = fetch(
                run.business_logic(),
                "programs",
                &Query::new()
                    .param("skip", skip.to_string())
                    .param("limit", "2"),
            )
            .await?;
            let items = page.as_array().cloned().unwrap_or_default();
            let count = items.len();
            for item in items {
                if let Some(id) = item["id"].as_str() {
                    seen.push(id.to_string());
                }
            }
            if count < 2 {
                break;
            }
        }

        let mut unique_seen = seen.clone();
        unique_seen.sort();
        unique_seen.dedup();
        expect(
            unique_seen.len() == seen.len(),
            format!(
                "walking the collection returned {} records of which only {} were distinct; pages \
                 overlap, which means the order is not stable",
                seen.len(),
                unique_seen.len()
            ),
        )?;
        let missing: Vec<&String> = mine.iter().filter(|id| !seen.contains(id)).collect();
        expect(
            missing.is_empty(),
            format!(
                "{} programme(s) this run created were never returned by any page: {missing:?}",
                missing.len()
            ),
        )
    })
}

async fn filters_are_additive(run: &Runner) -> Outcome {
    check!({
        let a = make_program(run, json!({ "programName": unique("filter-a") })).await?;
        let b = make_program(run, json!({ "programName": unique("filter-b") })).await?;
        let a_id = a["id"].as_str().unwrap_or_default().to_string();
        let b_id = b["id"].as_str().unwrap_or_default().to_string();

        make_event(run, event_body(&a_id, &[])).await?;
        let wanted = make_event(run, event_body(&b_id, &[])).await?;
        let wanted_id = wanted["id"].as_str().unwrap_or_default().to_string();

        let filtered = fetch(
            run.business_logic(),
            "events",
            &Query::new().param("programID", &b_id),
        )
        .await?;
        let ids: Vec<&str> = filtered
            .as_array()
            .map(|items| items.iter().filter_map(|i| i["id"].as_str()).collect())
            .unwrap_or_default();

        expect(
            ids.contains(&wanted_id.as_str()),
            format!("?programID={b_id} did not return the event in that programme"),
        )?;
        expect(
            filtered
                .as_array()
                .is_some_and(|items| items.iter().all(|i| i["programID"] == b_id.as_str())),
            format!(
                "?programID={b_id} returned events from another programme; a filter that is \
                     ignored is worse than one that is refused"
            ),
        )
    })
}

async fn targets_accept_both_forms(run: &Runner) -> Outcome {
    check!({
        // Two events with different targets, so the two forms have something to *disagree* about.
        // Comparing two unfiltered reads to each other compares an empty list with an empty list
        // against a fresh VTN, which agrees with itself whatever the VTN does with `?targets=` —
        // including ignoring it (D-092's shape).
        let x = format!("{RUN_PREFIX}form-x");
        let y = format!("{RUN_PREFIX}form-y");
        let program = make_program(run, json!({ "programName": unique("program") })).await?;
        let program_id = program["id"].as_str().unwrap_or_default().to_string();
        let event_x = make_event(run, event_body(&program_id, &[&x])).await?;
        let event_y = make_event(run, event_body(&program_id, &[&y])).await?;
        let id_x = event_x["id"].as_str().unwrap_or_default().to_string();
        let id_y = event_y["id"].as_str().unwrap_or_default().to_string();

        let ids = |page: &Value| -> Vec<String> {
            let mut out: Vec<String> = page
                .as_array()
                .map(|items| {
                    items
                        .iter()
                        .filter_map(|i| i["id"].as_str().map(str::to_string))
                        .collect()
                })
                .unwrap_or_default();
            out.sort();
            out
        };

        let repeated = fetch(
            run.business_logic(),
            "events",
            &Query::new().param("targets", &x).param("targets", &y),
        )
        .await?;
        let comma = fetch(
            run.business_logic(),
            "events",
            &Query::new().param("targets", format!("{x},{y}")),
        )
        .await?;

        // Both forms find both events…
        for (form, page) in [("a&targets=b", &repeated), ("a,b", &comma)] {
            let found = ids(page);
            expect(
                found.contains(&id_x) && found.contains(&id_y),
                format!("?targets={form} did not return both targeted events; it found {found:?}"),
            )?;
        }
        // …and they find the same ones.
        expect(
            ids(&repeated) == ids(&comma),
            format!(
                "?targets=a&targets=b and ?targets=a,b returned different results ({:?} against \
                 {:?}); both forms occur in the field",
                ids(&repeated),
                ids(&comma)
            ),
        )?;

        // And the filter is a filter. Without this the check passes against a VTN that ignores
        // `?targets=` altogether, because both forms then agree on the whole collection.
        let narrowed = fetch(
            run.business_logic(),
            "events",
            &Query::new().param("targets", &x),
        )
        .await?;
        let found = ids(&narrowed);
        expect(
            found.contains(&id_x) && !found.contains(&id_y),
            format!(
                "?targets={x} returned {found:?}; a filter that is accepted and ignored is worse \
                 than one that is refused"
            ),
        )
    })
}

// ---------------------------------------------------------------------------
// Time semantics
// ---------------------------------------------------------------------------

async fn forever_duration_round_trips(run: &Runner) -> Outcome {
    check!({
        let program = make_program(run, json!({ "programName": unique("program") })).await?;
        let program_id = program["id"].as_str().unwrap_or_default().to_string();

        let mut body = event_body(&program_id, &[]);
        body["intervalPeriod"]["duration"] = json!("P9999Y");
        let created = make_event(run, body).await?;

        expect(
            created["intervalPeriod"]["duration"] == "P9999Y",
            format!(
                "expected the P9999Y infinity sentinel on the wire, received {}; readers that \
                 recognise only the canonical spelling can treat this as a finite interval",
                created["intervalPeriod"]["duration"]
            ),
        )
    })
}

async fn now_sentinel_round_trips(run: &Runner) -> Outcome {
    check!({
        let program = make_program(run, json!({ "programName": unique("program") })).await?;
        let program_id = program["id"].as_str().unwrap_or_default().to_string();

        let mut body = event_body(&program_id, &[]);
        body["intervalPeriod"]["start"] = json!("0001-01-01T00:00:00Z");
        let created = make_event(run, body).await?;

        let start = created["intervalPeriod"]["start"].as_str().unwrap_or("");
        expect(
            start.starts_with("0001-01-01"),
            format!(
                "a 0001-01-01 start came back as {start:?}; the value means \"now\" to the \
                 reader, and resolving it at write time fixes it to the writer's clock instead"
            ),
        )
    })
}

async fn interval_payloads_round_trip(run: &Runner) -> Outcome {
    check!({
        let program = make_program(run, json!({ "programName": unique("program") })).await?;
        let program_id = program["id"].as_str().unwrap_or_default().to_string();

        let mut body = event_body(&program_id, &[]);
        body["intervals"] = json!([
            { "id": 0, "payloads": [{ "type": "IMPORT_CAPACITY_LIMIT", "values": [60] }] },
            { "id": 1,
              "intervalPeriod": { "duration": "PT30M" },
              "payloads": [{ "type": "IMPORT_CAPACITY_LIMIT", "values": [40] }] },
        ]);
        let created = make_event(run, body.clone()).await?;

        expect(
            created["intervals"] == body["intervals"],
            format!(
                "the intervals came back changed.\\n  sent: {}\\n  got:  {}",
                body["intervals"], created["intervals"]
            ),
        )
    })
}

async fn decimal_prices_are_exact(run: &Runner) -> Outcome {
    check!({
        let program = make_program(run, json!({ "programName": unique("program") })).await?;
        let program_id = program["id"].as_str().unwrap_or_default().to_string();

        let mut body = event_body(&program_id, &[]);
        body["intervals"] = json!([
            { "id": 0, "payloads": [{ "type": "PRICE", "values": [0.1, 0.2, 20.25] }] }
        ]);
        let created = make_event(run, body).await?;

        let values = &created["intervals"][0]["payloads"][0]["values"];
        let rendered = values.to_string();
        expect(
            rendered == "[0.1,0.2,20.25]",
            format!(
                "a price of 0.1 came back as {rendered}; money held as a binary float does not \
                 survive a round trip, and these are settled amounts"
            ),
        )
    })
}

// ---------------------------------------------------------------------------
// Object privacy
// ---------------------------------------------------------------------------

async fn ven_cannot_write_programmes(run: &Runner) -> Outcome {
    check!({
        let response = attempt(
            run.virtual_end_node(),
            "POST",
            "programs",
            &Query::new(),
            Some(&json!({ "programName": unique("ven-should-not-create") })),
            &[],
        )
        .await?;
        if response.status.as_u16() == 201
            && let Some(id) = response
                .json()
                .and_then(|v| v["id"].as_str().map(str::to_string))
        {
            run.track("programs", id);
        }
        expect(
            matches!(response.status.as_u16(), 401 | 403),
            format!(
                "a VEN created a programme ({}); write_programs is business logic's",
                response.status
            ),
        )
    })
}

async fn ven_cannot_grant_itself_targets(run: &Runner) -> Outcome {
    check!({
        let stolen = format!("{RUN_PREFIX}stolen-target");
        let response = attempt(
            run.virtual_end_node(),
            "POST",
            "vens",
            &Query::new(),
            Some(&json!({
                "objectType": "VEN_VEN_REQUEST",
                "venName": unique("ven"),
                "targets": [stolen],
            })),
            &[],
        )
        .await?;

        // Either refusing the body or ignoring the field is conformant; honouring it is not.
        let Some(created) = response.json().filter(|_| response.status.as_u16() == 201) else {
            return Ok(());
        };
        if let Some(id) = created["id"].as_str() {
            run.track("vens", id);
        }
        let targets = created["targets"].as_array().cloned().unwrap_or_default();
        expect(
            !targets.iter().any(|t| t == &json!(stolen)),
            format!(
                "a VEN granted itself the target {stolen:?}; only business logic may write \
                 targets, because a VEN that can grant itself one can read any event aimed at it"
            ),
        )
    })
}

async fn untargeted_objects_are_visible(run: &Runner) -> Outcome {
    check!({
        let name = unique("public");
        let created = make_program(run, json!({ "programName": name.clone() })).await?;
        let id = created["id"].as_str().unwrap_or_default().to_string();

        let visible = fetch(run.virtual_end_node(), "programs", &Query::new().limit(50)).await?;
        let found = visible
            .as_array()
            .is_some_and(|items| items.iter().any(|p| p["id"] == id.as_str()));
        expect(
            found,
            format!(
                "a VEN could not see the untargeted programme {name:?}; an object with no targets \
                 is not gated by targeting"
            ),
        )
    })
}

async fn ungranted_targets_are_invisible(run: &Runner) -> Outcome {
    check!({
        let program = make_program(run, json!({ "programName": unique("program") })).await?;
        let program_id = program["id"].as_str().unwrap_or_default().to_string();
        let secret = format!("{RUN_PREFIX}not-granted");
        let event = make_event(run, event_body(&program_id, &[&secret])).await?;
        let event_id = event["id"].as_str().unwrap_or_default().to_string();

        let listed = fetch(run.virtual_end_node(), "events", &Query::new().limit(50)).await?;
        expect(
            !listed
                .as_array()
                .is_some_and(|items| items.iter().any(|e| e["id"] == event_id.as_str())),
            "a VEN listing events with no targets saw an event targeted at a group it was not \
             granted; naming no targets must hide every targeted object"
                .to_string(),
        )?;

        let asked = fetch(
            run.virtual_end_node(),
            "events",
            &Query::new().param("targets", &secret),
        )
        .await?;
        expect(
            !asked
                .as_array()
                .is_some_and(|items| items.iter().any(|e| e["id"] == event_id.as_str())),
            format!(
                "a VEN read an event targeted at {secret:?} merely by asking for it; the target \
                 must be granted through the VEN object first, or guessing a group name is enough \
                 to read a competitor's dispatch"
            ),
        )
    })
}

async fn granted_targets_are_visible(run: &Runner) -> Outcome {
    check!({
        let target = format!("{RUN_PREFIX}granted");
        grant_target(run, &target).await?;

        let program = make_program(run, json!({ "programName": unique("program") })).await?;
        let program_id = program["id"].as_str().unwrap_or_default().to_string();
        let event = make_event(run, event_body(&program_id, &[&target])).await?;
        let event_id = event["id"].as_str().unwrap_or_default().to_string();

        let visible = fetch(
            run.virtual_end_node(),
            "events",
            &Query::new().param("targets", &target),
        )
        .await?;
        expect(
            visible
                .as_array()
                .is_some_and(|items| items.iter().any(|e| e["id"] == event_id.as_str())),
            format!(
                "a VEN granted {target:?} could not read an event targeted at it; the grant is \
                 written on the VEN object and the request named the target"
            ),
        )
    })
}

async fn target_hiding_on_reads(run: &Runner) -> Outcome {
    check!({
        let mine = format!("{RUN_PREFIX}mine");
        let theirs = format!("{RUN_PREFIX}theirs");
        grant_target(run, &mine).await?;

        let program = make_program(run, json!({ "programName": unique("program") })).await?;
        let program_id = program["id"].as_str().unwrap_or_default().to_string();
        let event = make_event(run, event_body(&program_id, &[&mine, &theirs])).await?;
        let event_id = event["id"].as_str().unwrap_or_default().to_string();

        let visible = fetch(
            run.virtual_end_node(),
            "events",
            &Query::new().param("targets", &mine),
        )
        .await?;
        let seen = visible
            .as_array()
            .and_then(|items| items.iter().find(|e| e["id"] == event_id.as_str()))
            .cloned()
            .ok_or_else(|| {
                Outcome::Failed(format!(
                    "the VEN could not read the event it was granted {mine:?} for"
                ))
            })?;

        let targets = seen["targets"].as_array().cloned().unwrap_or_default();
        expect(
            !targets.iter().any(|t| t == &json!(theirs)),
            format!(
                "the response carried {theirs:?}, a target this VEN was not granted. The full \
                 target list on an event is a competitor's dispatch schedule, and target hiding \
                 exists to conceal it: {targets:?}"
            ),
        )
    })
}

async fn hidden_object_is_404_not_403(run: &Runner) -> Outcome {
    check!({
        let program = make_program(run, json!({ "programName": unique("program") })).await?;
        let program_id = program["id"].as_str().unwrap_or_default().to_string();
        let secret = format!("{RUN_PREFIX}hidden");
        let event = make_event(run, event_body(&program_id, &[&secret])).await?;
        let event_id = event["id"].as_str().unwrap_or_default().to_string();

        let response = attempt(
            run.virtual_end_node(),
            "GET",
            &format!("events/{event_id}"),
            &Query::new(),
            None,
            &[],
        )
        .await?;
        expect(
            response.status.as_u16() != 200,
            "a VEN read an event by id that it was not granted a target for".to_string(),
        )?;
        expect(
            response.status.as_u16() == 404,
            format!(
                "reading a hidden event by id answered {} (expected 404); a 403 confirms the \
                 object exists, which is what targeting conceals",
                response.status
            ),
        )
    })
}

async fn ven_reads_only_its_own_vens(run: &Runner) -> Outcome {
    check!({
        let client_id = run
            .target
            .ven_client_id
            .as_deref()
            .expect("the precondition guarantees a clientID");

        // A VEN object belonging to somebody else.
        let other = format!("{RUN_PREFIX}other-client");
        let created = attempt(
            run.business_logic(),
            "POST",
            "vens",
            &Query::new(),
            Some(&json!({
                "objectType": "BL_VEN_REQUEST",
                "clientID": other,
                "venName": unique("other-ven"),
            })),
            &[],
        )
        .await?;
        if created.status.as_u16() != 201 {
            return Err(Outcome::Failed(format!(
                "could not create a second VEN object to test against: {}",
                created.status
            )));
        }
        if let Some(id) = created
            .json()
            .and_then(|v| v["id"].as_str().map(str::to_string))
        {
            run.track("vens", id);
        }

        let visible = fetch(run.virtual_end_node(), "vens", &Query::new().limit(50)).await?;
        let foreign: Vec<String> = visible
            .as_array()
            .map(|items| {
                items
                    .iter()
                    .filter(|v| v["clientID"].as_str().is_some_and(|c| c != client_id))
                    .filter_map(|v| v["id"].as_str().map(str::to_string))
                    .collect()
            })
            .unwrap_or_default();
        expect(
            foreign.is_empty(),
            format!(
                "a VEN read {} VEN object(s) belonging to another client: {foreign:?}",
                foreign.len()
            ),
        )
    })
}

async fn ven_reads_only_its_own_subscriptions(run: &Runner) -> Outcome {
    check!({
        // A subscription belonging to somebody else. Business logic's own will do: what the VEN
        // must not see is any `clientID` but its own, and the body carries a `bearerToken`.
        //
        // A VTN with no webhook transport refuses to create one at all, and there the check has
        // nothing to observe — which is a skip, not a pass.
        let program = make_program(run, json!({ "programName": unique("program") })).await?;
        let program_id = program["id"].as_str().unwrap_or_default().to_string();
        let planted = attempt(
            run.business_logic(),
            "POST",
            "subscriptions",
            &Query::new(),
            Some(&json!({
                "clientName": unique("other-subscriber"),
                "programID": program_id,
                "objectOperations": [{
                    "objects": ["EVENT"],
                    "operations": ["CREATE"],
                    "callbackUrl": "https://subscriber.invalid/hook",
                    "bearerToken": "a-secret-nobody-else-may-read",
                }],
            })),
            &[],
        )
        .await?;
        match planted.status.as_u16() {
            201 => {
                if let Some(id) = planted
                    .json()
                    .and_then(|v| v["id"].as_str().map(str::to_string))
                {
                    run.track("subscriptions", &id);
                }
            }
            _ => {
                return Err(Outcome::Skipped(format!(
                    "this VTN would not create a subscription ({}), so there is no foreign one to \
                     be hidden from",
                    planted.status
                )));
            }
        }

        let listed = attempt(
            run.virtual_end_node(),
            "GET",
            "subscriptions",
            &Query::new().limit(50),
            None,
            &[],
        )
        .await?;
        if !listed.status.is_success() {
            return Err(Outcome::Failed(format!(
                "GET /subscriptions as a VEN answered {}",
                listed.status
            )));
        }
        let Some(items) = listed.json().and_then(|v| v.as_array().cloned()) else {
            return Err(Outcome::Failed(
                "GET /subscriptions did not return an array".into(),
            ));
        };
        let client_id = run
            .target
            .ven_client_id
            .as_deref()
            .expect("the precondition guarantees a clientID");
        let foreign: Vec<&Value> = items
            .iter()
            .filter(|s| s["clientID"].as_str().is_some_and(|c| c != client_id))
            .collect();
        expect(
            foreign.is_empty(),
            format!(
                "a VEN read {} subscription(s) belonging to another client. A subscription carries \
                 a callbackUrl and a bearerToken, so this hands over another subscriber's \
                 credentials",
                foreign.len()
            ),
        )
    })
}

/// What a VEN's replace and delete of somebody else's object answered.
struct ForeignWrite {
    put: u16,
    delete: u16,
}

/// Send a valid `PUT` and then a `DELETE` for `collection/id` as the VEN, and prove the object
/// survived both by reading it back through business logic.
///
/// `id` is always one this run created a moment ago through business logic and tracked for cleanup
/// (spec 002, SR-004): against a VTN that is broken in exactly the way these checks look for, the
/// `DELETE` succeeds, and the only object it may then destroy is one the suite planted.
///
/// The `PUT` body is valid on purpose. A VTN that validates a body before it authorizes the caller
/// would refuse an invalid one with `400`, and a privacy check that passes on a schema error is a
/// privacy check that measured the schema. The `DELETE` has no body and carries the weight.
async fn foreign_write_refused(
    run: &Runner,
    collection: &str,
    id: &str,
    put_body: Value,
    name_field: &str,
) -> Result<ForeignWrite, Outcome> {
    let path = format!("{collection}/{id}");
    let bl = run.business_logic();
    let before = fetch(bl, &path, &Query::new()).await?;
    let ven = run.virtual_end_node();

    let put = attempt(ven, "PUT", &path, &Query::new(), Some(&put_body), &[]).await?;
    let delete = attempt(ven, "DELETE", &path, &Query::new(), None, &[]).await?;
    for (method, status) in [("PUT", put.status), ("DELETE", delete.status)] {
        if status.is_success() {
            return Err(Outcome::Failed(format!(
                "{method} /{path} as a VEN that does not own it answered {status}: one client \
                 changed another's object"
            )));
        }
    }

    // A refusal is not enough on its own: a VTN that answers 404 and deletes anyway is still a VTN
    // where one client erased another's object (SR-002).
    let after = attempt(bl, "GET", &path, &Query::new(), None, &[]).await?;
    if after.status.as_u16() != 200 {
        return Err(Outcome::Failed(format!(
            "the VTN refused the VEN's writes, but /{path} answers {} to business logic afterwards",
            after.status
        )));
    }
    let after = after.json().unwrap_or(Value::Null);
    expect(
        after[name_field] == before[name_field],
        format!(
            "the VTN refused the VEN's PUT, but {name_field} on /{path} changed from {} to {}",
            before[name_field], after[name_field]
        ),
    )?;
    Ok(ForeignWrite {
        put: put.status.as_u16(),
        delete: delete.status.as_u16(),
    })
}

/// A resource under a VEN this client does not own, planted through business logic.
async fn foreign_resource(run: &Runner) -> Result<(String, String), Outcome> {
    let other_ven = foreign_ven(run).await?;
    let planted = attempt(
        run.business_logic(),
        "POST",
        "resources",
        &Query::new(),
        Some(&json!({
            "objectType": "BL_RESOURCE_REQUEST",
            "resourceName": unique("other-resource"),
            "venID": other_ven,
        })),
        &[],
    )
    .await?;
    let id = (planted.status.as_u16() == 201)
        .then(|| planted.json())
        .flatten()
        .and_then(|v| v["id"].as_str().map(str::to_string))
        .ok_or_else(|| {
            Outcome::Failed(format!(
                "could not create a resource under another VEN to test against: {} {}",
                planted.status,
                String::from_utf8_lossy(&planted.body)
            ))
        })?;
    run.track("resources", &id);
    Ok((id, other_ven))
}

/// A VEN can neither replace nor delete another client's VEN object.
///
/// The read half — `ven-reads-only-its-own-vens` — says what a VEN can *see*. This is what it can
/// *do*, and it is the half a VTN that authorizes by role rather than by owner gets wrong while the
/// read half passes: in October 2026 a peer shipped exactly that, a VEN able to delete another
/// user's VEN, as a security advisory.
async fn ven_cannot_change_a_foreign_ven(run: &Runner) -> Outcome {
    check!({
        let id = foreign_ven(run).await?;
        foreign_write_refused(
            run,
            "vens",
            &id,
            json!({ "objectType": "VEN_VEN_REQUEST", "venName": unique("taken-over") }),
            "venName",
        )
        .await
        .map(drop)
    })
}

/// A VEN can neither replace nor delete a resource under another client's VEN.
async fn ven_cannot_change_a_foreign_resource(run: &Runner) -> Outcome {
    check!({
        let (id, other_ven) = foreign_resource(run).await?;
        foreign_write_refused(
            run,
            "resources",
            &id,
            json!({
                "objectType": "VEN_RESOURCE_REQUEST",
                "resourceName": unique("taken-over"),
                "venID": other_ven,
            }),
            "resourceName",
        )
        .await
        .map(drop)
    })
}

/// A VEN can neither replace nor delete another client's subscription.
///
/// A subscription carries a `callbackUrl` and a `bearerToken`. A VEN that can replace one can
/// redirect another subscriber's notifications to itself; one that can delete it can silence them.
async fn ven_cannot_change_a_foreign_subscription(run: &Runner) -> Outcome {
    check!({
        let program = make_program(run, json!({ "programName": unique("program") })).await?;
        let program_id = program["id"].as_str().unwrap_or_default().to_string();
        let body = |name: String, hook: &str| {
            json!({
                "clientName": name,
                "programID": program_id,
                "objectOperations": [{
                    "objects": ["EVENT"],
                    "operations": ["CREATE"],
                    "callbackUrl": hook,
                }],
            })
        };
        let planted = attempt(
            run.business_logic(),
            "POST",
            "subscriptions",
            &Query::new(),
            Some(&body(
                unique("other-subscriber"),
                "https://subscriber.invalid/hook",
            )),
            &[],
        )
        .await?;
        let Some(id) = (planted.status.as_u16() == 201)
            .then(|| planted.json())
            .flatten()
            .and_then(|v| v["id"].as_str().map(str::to_string))
        else {
            return Err(Outcome::Skipped(format!(
                "this VTN would not create a subscription ({}), so there is no foreign one to \
                 protect",
                planted.status
            )));
        };
        run.track("subscriptions", &id);
        foreign_write_refused(
            run,
            "subscriptions",
            &id,
            body(unique("taken-over"), "https://attacker.invalid/hook"),
            "clientName",
        )
        .await
        .map(drop)
    })
}

/// A refused write to another client's object answers `404`, not `403`.
///
/// The write-side twin of `hidden-object-is-404-not-403`. A `403` tells the VEN the id exists, so
/// writes become a way to enumerate other clients' objects one guess at a time. Recommended rather
/// than required: the specification says a VEN cannot access the object, and does not say which
/// status a refused write carries.
async fn foreign_write_is_404_not_403(run: &Runner) -> Outcome {
    check!({
        let id = foreign_ven(run).await?;
        let statuses = foreign_write_refused(
            run,
            "vens",
            &id,
            json!({ "objectType": "VEN_VEN_REQUEST", "venName": unique("probe") }),
            "venName",
        )
        .await?;
        expect(
            statuses.put == 404 && statuses.delete == 404,
            format!(
                "a refused PUT answered {} and a refused DELETE {}; anything but 404 confirms to \
                 the VEN that another client's object has that id",
                statuses.put, statuses.delete
            ),
        )
    })
}

/// A VEN cannot write targets onto a resource it creates.
///
/// The other half of the discriminator claim. `VEN_VEN_REQUEST` has no `targets` field and neither
/// does `VEN_RESOURCE_REQUEST` `[API resourceRequest]`, and 3.1.0 extended target-based access
/// control to resources precisely so that a resource could carry a grant `[CL 3.1.0 issue 321]`. A
/// VEN that can write one has granted itself the right to read every event aimed at it — through
/// the collection an implementation added *after* it had got `vens` right, which is the one place
/// the rule is most likely to have been left behind.
async fn ven_cannot_grant_a_resource_targets(run: &Runner) -> Outcome {
    check!({
        // The VEN's own VEN object, which is what a resource has to hang off.
        let mine = fetch(run.virtual_end_node(), "vens", &Query::new().limit(50)).await?;
        let Some(ven_id) = mine
            .as_array()
            .and_then(|v| v.first())
            .and_then(|v| v["id"].as_str())
            .map(str::to_string)
        else {
            return Err(Outcome::Skipped(
                "this VEN credential owns no ven object, so it has nothing to hang a resource on"
                    .into(),
            ));
        };

        let stolen = format!("{RUN_PREFIX}stolen-target");
        let response = attempt(
            run.virtual_end_node(),
            "POST",
            "resources",
            &Query::new(),
            Some(&json!({
                "objectType": "VEN_RESOURCE_REQUEST",
                "resourceName": unique("res"),
                "venID": ven_id,
                "targets": [stolen],
            })),
            &[],
        )
        .await?;

        // Either refusing the body or ignoring the field is conformant; honouring it is not.
        let Some(created) = response.json().filter(|_| response.status.as_u16() == 201) else {
            return Ok(());
        };
        if let Some(id) = created["id"].as_str() {
            run.track("resources", id);
        }
        let targets = created["targets"].as_array().cloned().unwrap_or_default();
        expect(
            !targets.iter().any(|t| t == &json!(stolen)),
            format!(
                "a VEN granted its own resource the target {stolen:?}. Targets on a resource are a \
                 grant, so this is a VEN awarding itself the right to read every event aimed at \
                 that group"
            ),
        )
    })
}

/// A VEN reads only the reports it filed.
///
/// The most sensitive owned type and the one a suite is least likely to name: a report is a
/// customer's meter data. `report` carries no `targets` at all, so an implementation that reaches
/// for the targeting rule here admits *everyone* — the same shape as the subscription leak this
/// suite was extended to catch, where one backend let any VEN read every subscription in the VTN.
async fn ven_reads_only_its_own_reports(run: &Runner) -> Outcome {
    check!({
        // Seed one first. This check used to read a collection nothing in the suite ever wrote to,
        // so against a fresh VTN it asserted that an empty list contained no foreign reports —
        // which is true of every implementation, conformant or not (rule 18).
        let event_id = seed_event(run).await?;
        let filed = make_report(run, report_body(&event_id, &unique("resource"), 1.0)).await?;

        let listed = attempt(
            run.virtual_end_node(),
            "GET",
            "reports",
            &Query::new().limit(50),
            None,
            &[],
        )
        .await?;
        if !listed.status.is_success() {
            return Err(Outcome::Failed(format!(
                "GET /reports as a VEN answered {}",
                listed.status
            )));
        }
        let Some(items) = listed.json().and_then(|v| v.as_array().cloned()) else {
            return Err(Outcome::Failed(
                "GET /reports did not return an array".into(),
            ));
        };
        let client_id = run
            .target
            .ven_client_id
            .as_deref()
            .expect("the precondition guarantees a clientID");
        expect(
            items.iter().any(|r| r["id"] == filed["id"]),
            "a VEN could not read back the report it had just filed, so this check has nothing to \
             be right about"
                .to_string(),
        )?;
        let foreign: Vec<&Value> = items
            .iter()
            .filter(|r| r["clientID"].as_str().is_some_and(|c| c != client_id))
            .collect();
        expect(
            foreign.is_empty(),
            format!(
                "a VEN read {} report(s) filed by another client. A report is a customer's meter \
                 data, and it carries no targets — so target-based filtering admits everyone here",
                foreign.len()
            ),
        )
    })
}

/// A report a VEN files comes back with everything it carried.
///
/// Reports are the object with the least coverage anywhere — in this suite, and in the two
/// implementations it has been pointed at. They are also the only object carrying a customer's
/// meter data, and the only one whose contents a settlement process reads back months later. A
/// round trip that loses an interval id, rounds a decimal or drops a `payloadDescriptor` is a
/// billing dispute, and none of the three fails loudly at the time.
async fn report_round_trips(run: &Runner) -> Outcome {
    check!({
        let event_id = seed_event(run).await?;
        let resource = unique("resource");
        let filed = make_report(run, report_body(&event_id, &resource, 12.34)).await?;
        let id = filed["id"]
            .as_str()
            .ok_or_else(|| Outcome::Failed("a created report carries no id".into()))?;

        let read = fetch(
            run.business_logic(),
            &format!("reports/{id}"),
            &Query::new(),
        )
        .await?;
        expect(
            read["eventID"].as_str() == Some(event_id.as_str()),
            format!("the report came back naming eventID {:?}", read["eventID"]),
        )?;
        expect(
            read["objectType"].as_str() == Some("REPORT"),
            format!(
                "the report's objectType is {:?}, not REPORT",
                read["objectType"]
            ),
        )?;

        let resources = read["resources"].as_array().cloned().unwrap_or_default();
        expect(
            resources.len() == 1,
            format!(
                "the report came back with {} resource(s), not 1",
                resources.len()
            ),
        )?;
        expect(
            resources[0]["resourceName"].as_str() == Some(resource.as_str()),
            format!(
                "the resource came back as {:?} rather than {resource:?}",
                resources[0]["resourceName"]
            ),
        )?;

        let intervals = resources[0]["intervals"]
            .as_array()
            .cloned()
            .unwrap_or_default();
        expect(
            intervals.len() == 1,
            format!(
                "the resource came back with {} interval(s), not 1",
                intervals.len()
            ),
        )?;
        expect(
            intervals[0]["id"].as_i64() == Some(0),
            format!(
                "the interval id came back as {:?}; a report quotes the *event's* interval ids so \
                 the VTN can correlate them [UG §7.5], and losing them makes the data unusable",
                intervals[0]["id"]
            ),
        )?;

        let values = intervals[0]["payloads"][0]["values"]
            .as_array()
            .cloned()
            .unwrap_or_default();
        expect(
            values.len() == 1,
            format!(
                "the payload came back with {} value(s), not 1",
                values.len()
            ),
        )?;
        expect(
            values[0].as_f64() == Some(12.34),
            format!(
                "12.34 kWh came back as {:?}. A meter reading that does not survive a round trip \
                 is a settlement discrepancy nobody notices until the bill",
                values[0]
            ),
        )?;

        // The descriptor is what says what the number means. A VTN that drops it returns a series
        // of bare numbers whose unit is a guess.
        let descriptors = read["payloadDescriptors"]
            .as_array()
            .cloned()
            .unwrap_or_default();
        expect(
            descriptors
                .iter()
                .any(|d| d["payloadType"].as_str() == Some("USAGE")),
            "the report's payloadDescriptors did not survive the round trip; without one the \
             values have no unit and no readingType"
                .to_string(),
        )
    })
}

/// The VTN stamps a report's `clientID`; a body cannot claim one.
///
/// `[Def §VEN created object privacy]` puts the identity on the credential, and every ownership
/// decision downstream reads that field. A VTN that copies it out of the body lets one VEN file a
/// report *as* another — which hides the reading from its author and shows it to a competitor, and
/// does both silently.
async fn report_is_stamped_not_claimed(run: &Runner) -> Outcome {
    check!({
        let event_id = seed_event(run).await?;
        let mine = run
            .target
            .ven_client_id
            .as_deref()
            .expect("the precondition guarantees a clientID");

        let mut body = report_body(&event_id, &unique("resource"), 1.0);
        body["clientID"] = json!(format!("{RUN_PREFIX}somebody-else"));
        let filed = make_report(run, body).await?;

        // Some VTNs omit `clientID` from the response entirely, which is a defensible reading of a
        // field the schema does not list. What none of them may do is echo the claim.
        match filed["clientID"].as_str() {
            None => Ok(()),
            Some(stamped) => expect(
                stamped == mine,
                format!(
                    "the report came back owned by {stamped:?}; the body claimed a clientID and \
                     the VTN believed it, so a VEN can file a report as another VEN"
                ),
            ),
        }
    })
}

/// `GET /reports?eventID=` narrows to that event.
///
/// The filter a settlement process actually uses: reports accumulate without bound, and reading
/// them back per event is the only query that stays bounded. A filter that is parsed and ignored
/// returns every report in the VTN and the caller cannot tell — the same shape as D-045.
async fn report_filters_by_event(run: &Runner) -> Outcome {
    check!({
        let wanted = seed_event(run).await?;
        let other = seed_event(run).await?;
        make_report(run, report_body(&wanted, &unique("resource"), 1.0)).await?;
        make_report(run, report_body(&other, &unique("resource"), 2.0)).await?;

        let listed = fetch(
            run.business_logic(),
            "reports",
            &Query::new().param("eventID", &wanted).limit(50),
        )
        .await?;
        let items = listed.as_array().cloned().unwrap_or_default();
        expect(
            !items.is_empty(),
            "?eventID= returned nothing for an event that has a report".to_string(),
        )?;
        let strays: Vec<&Value> = items
            .iter()
            .filter(|r| r["eventID"].as_str() != Some(wanted.as_str()))
            .collect();
        expect(
            strays.is_empty(),
            format!(
                "?eventID={wanted} returned {} report(s) belonging to other events, so the filter \
                 was accepted and not applied",
                strays.len()
            ),
        )
    })
}

/// A report has to name an event that exists.
///
/// `eventID` is required and is a reference `[API reportRequest]`. A report pointing at nothing
/// cannot be correlated with the intervals it reports on, which is the only thing that makes the
/// numbers mean anything. As with `event-needs-a-programme`, the specification does not pick a
/// status, so any refusal counts.
async fn report_needs_an_event(run: &Runner) -> Outcome {
    check!({
        let response = attempt(
            run.virtual_end_node(),
            "POST",
            "reports",
            &Query::new(),
            Some(&report_body(
                "oadr-conformance-no-such-event",
                &unique("resource"),
                1.0,
            )),
            &[],
        )
        .await?;
        if response.status.as_u16() == 201
            && let Some(id) = response
                .json()
                .and_then(|v| v["id"].as_str().map(str::to_string))
        {
            run.track("reports", id);
        }
        expect(
            matches!(response.status.as_u16(), 400 | 404 | 409),
            format!(
                "a report naming an event that does not exist answered {} (expected 400, 404 or \
                 409); a dangling eventID leaves meter data nothing can be correlated with",
                response.status
            ),
        )
    })
}

/// A VEN reads only the resources belonging to it.
///
/// The other half of the grant, and the half a suite is most likely to leave out. A `resource`
/// carries the targets business logic granted it `[Def §Object Privacy, CL 3.1.0 issue 321]`, so
/// reading another VEN's resources is reading which programmes a competitor was enrolled in — and
/// `/resources` only became a first-class collection in 3.1.0 `[CL 3.1.0 issue 306]`, which is
/// exactly the sort of endpoint an implementation adds without carrying the ownership rule across.
async fn ven_reads_only_its_own_resources(run: &Runner) -> Outcome {
    check!({
        // A resource under a VEN this client does not own. Without it the assertion below is
        // "nothing foreign appeared" against a collection that holds nothing foreign.
        let other_ven = foreign_ven(run).await?;
        let planted = attempt(
            run.business_logic(),
            "POST",
            "resources",
            &Query::new(),
            Some(&json!({
                "objectType": "BL_RESOURCE_REQUEST",
                "resourceName": unique("other-resource"),
                "venID": other_ven,
            })),
            &[],
        )
        .await?;
        if planted.status.as_u16() != 201 {
            return Err(Outcome::Failed(format!(
                "could not create a resource under another VEN to test against: {} {}",
                planted.status,
                String::from_utf8_lossy(&planted.body)
            )));
        }
        if let Some(id) = planted
            .json()
            .and_then(|v| v["id"].as_str().map(str::to_string))
        {
            run.track("resources", &id);
        }

        let listed = attempt(
            run.virtual_end_node(),
            "GET",
            "resources",
            &Query::new().limit(50),
            None,
            &[],
        )
        .await?;
        if !listed.status.is_success() {
            return Err(Outcome::Failed(format!(
                "GET /resources as a VEN answered {}",
                listed.status
            )));
        }
        let Some(items) = listed.json().and_then(|v| v.as_array().cloned()) else {
            return Err(Outcome::Failed(
                "GET /resources did not return an array".into(),
            ));
        };

        // Which VENs the caller owns. A resource names its VEN, and 3.1.1 dropped `clientID` from
        // the resource body as redundant with it, so ownership is established through the VEN
        // rather than read off the resource.
        let mine = fetch(run.virtual_end_node(), "vens", &Query::new().limit(50)).await?;
        let mine: Vec<String> = mine
            .as_array()
            .map(|v| {
                v.iter()
                    .filter_map(|ven| ven["id"].as_str().map(str::to_string))
                    .collect()
            })
            .unwrap_or_default();

        let foreign: Vec<&Value> = items
            .iter()
            .filter(|r| {
                r["venID"]
                    .as_str()
                    .is_some_and(|ven| !mine.iter().any(|m| m == ven))
            })
            .collect();
        expect(
            foreign.is_empty(),
            format!(
                "a VEN read {} resource(s) under a VEN it does not own. A resource carries the \
                 targets business logic granted it, so this is another operator's programme \
                 enrolment",
                foreign.len()
            ),
        )
    })
}

/// `?active=true` drops events whose intervals have all elapsed.
///
/// New in 3.1.0 `[CL 3.1.0 issue 234]`, and the parameter a poller uses on every cycle: "ignore
/// events that have transpired" `[API /events ?active]`. It is not "events happening right now" —
/// an event scheduled for next week has not transpired, so filtering it out would hide the
/// day-ahead schedule from every client that asked to skip yesterday's.
async fn active_excludes_transpired_events(run: &Runner) -> Outcome {
    check!({
        let program = make_program(run, json!({ "programName": unique("active") })).await?;
        let program_id = program["id"].as_str().unwrap_or_default().to_string();

        let mut past = event_body(&program_id, &[]);
        past["intervalPeriod"] = json!({ "start": "2020-01-01T00:00:00Z", "duration": "PT15M" });
        let past = make_event(run, past).await?;
        let past_id = past["id"].as_str().unwrap_or_default().to_string();

        let mut future = event_body(&program_id, &[]);
        future["intervalPeriod"] = json!({ "start": "2099-01-01T00:00:00Z", "duration": "PT15M" });
        let future = make_event(run, future).await?;
        let future_id = future["id"].as_str().unwrap_or_default().to_string();

        let ids = |v: &Value| -> Vec<String> {
            v.as_array()
                .map(|items| {
                    items
                        .iter()
                        .filter_map(|e| e["id"].as_str().map(str::to_string))
                        .collect()
                })
                .unwrap_or_default()
        };

        let unfiltered = fetch(
            run.business_logic(),
            "events",
            &Query::new().param("programID", &program_id).limit(50),
        )
        .await?;
        let unfiltered = ids(&unfiltered);
        expect(
            unfiltered.contains(&past_id) && unfiltered.contains(&future_id),
            "without ?active both events should be listed; the filter cannot be measured otherwise",
        )?;

        let filtered = fetch(
            run.business_logic(),
            "events",
            &Query::new()
                .param("programID", &program_id)
                .active(true)
                .limit(50),
        )
        .await?;
        let filtered = ids(&filtered);
        expect(
            !filtered.contains(&past_id),
            "?active=true listed an event whose only interval ended in 2020",
        )?;
        expect(
            filtered.contains(&future_id),
            "?active=true dropped an event scheduled for 2099. \"Active\" is \"has not \
             transpired\", so a future event stays: dropping it hides the day-ahead schedule from \
             every client that asked to skip yesterday's",
        )
    })
}

// ---------------------------------------------------------------------------
// The MQTT notifier binding
// ---------------------------------------------------------------------------

/// The MQTT binding from `GET /notifiers`, or a skip when this VTN offers none.
///
/// A runtime skip rather than a precondition: whether a VTN has a broker is something only the VTN
/// can say, and it says it here. MQTT is **optional** — "A VTN **MAY** support notifications via
/// MQTT" `[Notifiers §7.2]` — so its absence is not a failure and must not be reported as one.
async fn mqtt_binding(run: &Runner) -> Result<Value, Outcome> {
    let notifiers = fetch(run.business_logic(), "notifiers", &Query::new()).await?;
    notifiers
        .get("MQTT")
        .filter(|v| !v.is_null())
        .cloned()
        .ok_or_else(|| {
            Outcome::Skipped("this VTN offers no MQTT notifier binding, which is optional".into())
        })
}

async fn mqtt_binding_shape(run: &Runner) -> Outcome {
    check!({
        let mqtt = mqtt_binding(run).await?;
        expect(
            mqtt["URIS"].as_array().is_some_and(|u| !u.is_empty()),
            format!("the MQTT binding names no URIS: {mqtt}"),
        )?;
        expect(
            mqtt["serialization"].as_str() == Some("JSON"),
            format!(
                "serialization is {} (expected JSON, the only format the binding defines)",
                mqtt["serialization"]
            ),
        )?;
        let method = mqtt["authentication"]["method"].as_str();
        expect(
            matches!(
                method,
                Some("ANONYMOUS" | "OAUTH2_BEARER_TOKEN" | "CERTIFICATE")
            ),
            format!(
                "authentication.method is {method:?}; the binding defines ANONYMOUS, \
                 OAUTH2_BEARER_TOKEN and CERTIFICATE, and a client cannot connect without \
                 recognising one"
            ),
        )
    })
}

async fn mqtt_collection_topics_are_business_logic_only(run: &Runner) -> Outcome {
    check!({
        mqtt_binding(run).await?;
        for path in [
            "notifiers/mqtt/topics/events",
            "notifiers/mqtt/topics/reports",
            "notifiers/mqtt/topics/vens",
        ] {
            let response = attempt(
                run.virtual_end_node(),
                "GET",
                path,
                &Query::new(),
                None,
                &[],
            )
            .await?;
            expect(
                !response.status.is_success(),
                format!(
                    "a VEN obtained {path}. Subscribing to a collection-wide topic yields every \
                     object of that type with its full target set, which is every other VEN's \
                     dispatch schedule"
                ),
            )?;
        }
        Ok(())
    })
}

async fn mqtt_ven_scoped_topics(run: &Runner) -> Outcome {
    check!({
        mqtt_binding(run).await?;
        let ven_id = grant_target(run, &format!("{RUN_PREFIX}mqtt")).await?;

        let response = attempt(
            run.virtual_end_node(),
            "GET",
            &format!("notifiers/mqtt/topics/vens/{ven_id}/events"),
            &Query::new(),
            None,
            &[],
        )
        .await?;
        expect(
            response.status.is_success(),
            format!(
                "a VEN could not obtain its own event topics ({}); the VEN-scoped endpoints are \
                 what 3.1 added for exactly this client",
                response.status
            ),
        )?;
        let body = response
            .json()
            .ok_or_else(|| Outcome::Failed("the topic response carried no JSON".into()))?;
        for operation in ["UPDATE", "DELETE"] {
            expect(
                body["topics"][operation]
                    .as_str()
                    .is_some_and(|t| !t.is_empty()),
                format!("the topic set has no {operation} entry: {body}"),
            )?;
        }
        Ok(())
    })
}

async fn mqtt_foreign_ven_topics_refused(run: &Runner) -> Outcome {
    check!({
        mqtt_binding(run).await?;

        // Somebody else's VEN object, through the one helper that makes them.
        let other_id = foreign_ven(run).await?;

        let response = attempt(
            run.virtual_end_node(),
            "GET",
            &format!("notifiers/mqtt/topics/vens/{other_id}/events"),
            &Query::new(),
            None,
            &[],
        )
        .await?;
        expect(
            !response.status.is_success(),
            format!(
                "a VEN obtained another VEN's topic names ({}); those topics carry the other \
                 VEN's dispatch",
                response.status
            ),
        )
    })
}

// ---------------------------------------------------------------------------
// Extensions
// ---------------------------------------------------------------------------

async fn etag_and_conditional_read(run: &Runner) -> Outcome {
    check!({
        let first = attempt(
            run.business_logic(),
            "GET",
            "programs",
            &Query::new().limit(1),
            None,
            &[],
        )
        .await?;
        let Some(etag) = first.header("etag").map(str::to_string) else {
            return Err(Outcome::Failed(
                "GET /programs carried no ETag; every deployment surveyed polls, so a repeat read \
                 costs the whole collection again"
                    .into(),
            ));
        };

        let second = attempt(
            run.business_logic(),
            "GET",
            "programs",
            &Query::new().limit(1),
            None,
            &[("if-none-match".to_string(), etag)],
        )
        .await?;
        expect(
            second.status.as_u16() == 304,
            format!(
                "a matching If-None-Match answered {} (expected 304)",
                second.status
            ),
        )?;
        expect(
            second.body.is_empty(),
            "the 304 carried a body; RFC 9110 says it must not".to_string(),
        )
    })
}

/// An error body is served as `application/problem+json`.
///
/// An **extension**, deliberately, and the severity is the whole point of the check. RFC 9457 §3
/// defines that media type for exactly this body, and the Zalando guidelines the specification
/// borrows the shape from say the same. `openadr3.yaml` nonetheless declares every error response as
/// `application/json`, so a VTN that sends the plain type is conformant and a report that called it
/// a failure would be filing this project's opinion as a requirement — the mistake D-075 exists to
/// remember.
///
/// It is still worth *measuring*: a client built from the document's own schema may refuse a media
/// type the document does not mention, and a matrix that says which peers send which is the only
/// place that disagreement becomes visible before it is a support ticket.
async fn problem_uses_the_rfc_9457_media_type(run: &Runner) -> Outcome {
    check!({
        let response = attempt(
            run.business_logic(),
            "GET",
            "programs/oadr-conformance-no-such-program",
            &Query::new(),
            None,
            &[],
        )
        .await?;
        expect(
            response.status.as_u16() == 404,
            format!("a missing programme answered {}", response.status),
        )?;
        expect(
            response.is_problem_json(),
            format!(
                "the error body is {:?} rather than application/problem+json. Both are defensible \
                 — the OpenAPI document says application/json and RFC 9457 says otherwise — so this \
                 is information, not non-conformance",
                response.header("content-type").unwrap_or("(absent)")
            ),
        )
    })
}

async fn problem_carries_a_traceable_instance(run: &Runner) -> Outcome {
    check!({
        let response = attempt(
            run.business_logic(),
            "GET",
            "programs/oadr-conformance-no-such-program",
            &Query::new(),
            None,
            &[],
        )
        .await?;
        let problem = response
            .problem()
            .ok_or_else(|| Outcome::Failed("the error carried no problem body".into()))?;
        let Some(instance) = problem.instance else {
            return Err(Outcome::Failed(
                "problem.instance is absent; without it an error a client quotes cannot be found \
                 in the VTN's log"
                    .into(),
            ));
        };
        let Some(header) = response.header("x-request-id") else {
            return Err(Outcome::Failed(
                "the response carried no x-request-id to correlate problem.instance with".into(),
            ));
        };
        expect(
            instance == header,
            format!(
                "problem.instance is {instance:?} and x-request-id is {header:?}; the field is \
                 only worth having if the two are the same string"
            ),
        )
    })
}

async fn program_name_lookup(run: &Runner) -> Outcome {
    check!({
        let name = unique("lookup");
        let created = make_program(run, json!({ "programName": name.clone() })).await?;
        let id = created["id"].as_str().unwrap_or_default().to_string();

        let found = fetch(
            run.business_logic(),
            "programs",
            &Query::new().param("programName", &name),
        )
        .await?;
        let items = found.as_array().cloned().unwrap_or_default();
        expect(
            items.len() == 1 && items[0]["id"] == id.as_str(),
            format!(
                "?programName={name} returned {} programme(s); finding one tariff among hundreds \
                 otherwise means paging the whole collection",
                items.len()
            ),
        )
    })
}

// ---------------------------------------------------------------------------
// HTTP contract
// ---------------------------------------------------------------------------

/// A `401` says how to authenticate.
///
/// RFC 9110 §11.6.1: a `401` **MUST** carry `WWW-Authenticate`. Without it a client that has just
/// been refused cannot tell a missing token from a wrong realm from an unsupported scheme, and the
/// OpenADR enrolment flow — discover the VTN, discover the token endpoint, present a bearer token —
/// is exactly the flow that walks into this.
async fn unauthorized_names_the_scheme(run: &Runner) -> Outcome {
    check!({
        let client = run.anonymous().map_err(transport)?;
        let response = attempt(&client, "GET", "programs", &Query::new(), None, &[]).await?;
        if response.status.as_u16() != 401 {
            // A VTN that serves anonymous readers, or that answers 403 instead, is not wrong —
            // there is simply no 401 to inspect. Reporting that as a pass would be counting an
            // absence of evidence as evidence.
            return Err(Outcome::Skipped(format!(
                "an unauthenticated GET /programs answered {} rather than 401, so there is no \
                 challenge to inspect",
                response.status
            )));
        }
        expect(
            response.header("www-authenticate").is_some(),
            "the 401 carried no WWW-Authenticate header".to_string(),
        )
    })
}

/// A response carrying an access token is never stored.
///
/// RFC 6749 §5.1, a **MUST**, and the one HTTP header on the token endpoint whose absence is
/// invisible until a proxy hands one client another client's token.
///
/// The check does not need a working credential: the header is a property of the endpoint, so a
/// deliberately wrong secret exercises it without a valid one existing. A VTN that delegates token
/// issuance has no endpoint to check and the result is a skip.
async fn token_response_is_not_stored(run: &Runner) -> Outcome {
    check!({
        let client = run.anonymous().map_err(transport)?;
        let response = attempt(
            &client,
            "POST",
            "auth/token",
            &Query::new(),
            None,
            &[
                (
                    "content-type".to_string(),
                    "application/x-www-form-urlencoded".to_string(),
                ),
                // reqwest sends no body without one; the credentials are deliberately absent, and
                // the endpoint's answer to that is still an answer from the endpoint.
                ("content-length".to_string(), "0".to_string()),
            ],
        )
        .await?;
        if matches!(response.status.as_u16(), 404 | 405 | 501) {
            return Err(Outcome::Skipped(format!(
                "POST /auth/token answered {}, so this VTN does not run its own token endpoint",
                response.status
            )));
        }
        let value = response
            .header("cache-control")
            .unwrap_or_default()
            .to_ascii_lowercase();
        expect(
            value.split(',').any(|d| d.trim() == "no-store"),
            format!(
                "the token endpoint answered Cache-Control: {:?}; RFC 6749 §5.1 requires no-store \
                 on any response that may carry a token",
                response.header("cache-control").unwrap_or("<absent>")
            ),
        )
    })
}

/// A body labelled with a media type the endpoint does not declare is refused.
///
/// `openadr3.yaml` declares one request media type for every write: `application/json`. A VTN that
/// parses `text/plain` as JSON has accepted something the contract does not describe, and the cost
/// falls on the client: a misconfigured serialiser is reported as a syntax error in JSON it never
/// sent. RFC 9110 §15.5.16 names the status for it.
///
/// **Recommended** rather than **Required**: the OpenADR documents say nothing about media-type
/// negotiation, so a lenient VTN is interoperable rather than wrong.
async fn foreign_media_type_is_refused(run: &Runner) -> Outcome {
    check!({
        let name = unique("media-type");
        let response = attempt(
            run.business_logic(),
            "POST",
            "programs",
            &Query::new(),
            Some(&json!({ "programName": name.clone() })),
            &[("content-type".to_string(), "text/plain".to_string())],
        )
        .await?;
        // Whatever the VTN decided, it may have created the programme; track it either way so the
        // run leaves nothing behind.
        if response.status.as_u16() == 201
            && let Some(id) = response
                .json()
                .and_then(|b| b["id"].as_str().map(str::to_string))
        {
            run.track("programs", id);
        }
        expect(
            response.status.as_u16() == 415,
            format!(
                "a text/plain body answered {} (expected 415); the document declares \
                 application/json and nothing else",
                response.status
            ),
        )
    })
}

/// A read says how it may be cached.
///
/// Object privacy makes the body a function of the *reader*: two VENs asking for the same URL are
/// entitled to different targets on the same event. A response that says nothing about caching is
/// one an intermediary is free to key by URL alone.
///
/// An **extension**: no OpenADR document requires it, and this is the report saying whether a peer
/// happens to be safe behind a shared cache.
async fn reads_declare_a_caching_policy(run: &Runner) -> Outcome {
    check!({
        let response = attempt(
            run.business_logic(),
            "GET",
            "programs",
            &Query::new().limit(1),
            None,
            &[],
        )
        .await?;
        let directives = response
            .header("cache-control")
            .unwrap_or_default()
            .to_ascii_lowercase();
        let varies_on_credentials = response
            .headers
            .get_all("vary")
            .iter()
            .filter_map(|v| v.to_str().ok())
            .any(|v| {
                v.split(',')
                    .any(|f| f.trim().eq_ignore_ascii_case("authorization"))
            });
        expect(
            directives.contains("private")
                || directives.contains("no-store")
                || varies_on_credentials,
            format!(
                "GET /programs answered Cache-Control: {:?} and no Vary on authorization, so a \
                 shared cache may key this body by URL alone — and object privacy means the body \
                 depends on who asked",
                response.header("cache-control").unwrap_or("<absent>")
            ),
        )
    })
}