Skip to content

Events

The DERControl scheduling engine: state machine, supersession, randomization.

py20305.events.processor

Top-level event processor orchestrating the DERControl lifecycle.

Called from poll callbacks after resource discovery. Processes DERControls through the event state machine: randomize, classify, upsert, supersede, activate, complete, and prune.

EventProcessor

Orchestrates DERControl event processing.

Wires together EventStore, RandomizationCache, supersession, response posting, DDERC tracking, timers, and control dispatch.

Source code in src/py20305/events/processor.py
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
class EventProcessor:
    """Orchestrates DERControl event processing.

    Wires together EventStore, RandomizationCache, supersession,
    response posting, DDERC tracking, timers, and control dispatch.
    """

    def __init__(
        self,
        http: Sep2Client,
        state: DiscoveredState,
        dispatcher: ControlDispatcher,
        shutdown: asyncio.Event,
        *,
        state_ready: asyncio.Event | None = None,
        group_lookup: Callable[[str], list[str] | None] | None = None,
        comms_loss: CommsLossState | None = None,
        timebase: ServerTimebase | None = None,
        audit: AuditEmitter | None = None,
        state_store: EventStateStore | None = None,
    ) -> None:
        # ``state_store`` shares the event state of each EndDevice with other
        # processes acting as the same client, so one can take a device over
        # from another (see py20305.events.shared_state). None keeps it here.
        #
        # ``group_lookup`` is an optional fan-out hook, unset by default.
        # Given a server-side program href, it returns the list of local
        # sub-device LFDIs that program should fan out to, or None to fall
        # back to 1-to-1 dispatch by server-side device href. Bookkeeping
        # (responses, supersession, mode tracking) stays in terms of the
        # server-side hrefs the server actually knows about; only the
        # connector-dispatch step is expanded.
        self._http = http
        self._state = state
        self._dispatcher = dispatcher
        self._shutdown = shutdown
        self._state_ready = state_ready
        self._group_lookup = group_lookup
        self._comms_loss = comms_loss or CommsLossState()
        # Server timebase for time-of-day-sensitive reads (classification,
        # timer firing, response timestamps). The default identity instance
        # behaves exactly like the local clock.
        self._timebase = timebase or ServerTimebase()
        # Lifecycle records for the audit trail. Disabled until the host
        # configures it, so every call below is a no-op by default.
        self._audit = audit if audit is not None else AuditEmitter()
        self._audit_failures = 0
        #: Events recorded as expired or skipped, by mRID, with their program.
        #: They are not stored, so this is what stops each poll recording them
        #: again. Kept while the program still serves them, not by age: both
        #: kinds can be past their end and still served, poll after poll.
        self._audit_unstored_seen: dict[bytes, str] = {}
        self._store = EventStore()
        self._state_store = state_store
        self._rand_cache = RandomizationCache(
            claim=self._claim_offsets if state_store is not None else None
        )
        self._response_tracker = ResponseTracker()
        if state_store is not None:
            self._response_tracker.on_sent = self._record_sent
        #: The snapshot last saved for each EndDevice, so an unchanged one is
        #: not written again.
        self._saved: dict[str, dict[str, Any]] = {}
        #: EndDevices handed to another process: their snapshots are not
        #: written from here any more.
        self._released: set[str] = set()
        #: EndDevices loaded by load_devices that resume_devices has not
        #: resumed yet. Their timers are left to resume_devices.
        self._awaiting_resume: set[str] = set()
        #: EndDevices taken over whose Response ledger is restored once
        #: discovery gives their LFDI.
        self._ledger_pending: set[str] = set()
        #: Loss-of-communications resume boundaries loaded with EndDevices
        #: taken over, by device href. They gate only those devices' events.
        self._imported_resume_after: dict[str, int] = {}
        #: Local epoch at which a cancelled event's delayed default-control
        #: fallback is due, by mRID, so a snapshot can carry it.
        self._fallback_due: dict[bytes, int] = {}
        #: Event work in progress: process_controls, activation and completion
        #: callbacks, take-over resumption and loss-of-communications entry.
        #: release_devices waits until none is running.
        self._busy = 0
        self._idle = asyncio.Event()
        self._idle.set()
        #: Each event's control as XML, with the object it was serialized from.
        self._control_xml: dict[bytes, tuple[Dercontrol1, str]] = {}
        self._dderc_tracker = DdercTracker()
        self._timer_mgr = EventTimerManager(shutdown)
        self._mode_tracker = ActiveModeTracker()
        self._closed = False
        # Schedule-notification relay (informational push to connectors).
        # Fire-on-change dedup keyed by (stream, mrid_hex) -> last content signature.
        self._relay_snapshots: dict[tuple[str, str], tuple[Any, ...]] = {}
        # Strong refs to in-flight fire-and-forget relay tasks.
        self._relay_tasks: set[asyncio.Task[None]] = set()
        # Strong refs to control dispatches still running past the activation
        # response ceiling. They are shielded from the ceiling's timeout so
        # the device still gets the control; this keeps them from being GC'd
        # mid-flight and gives shutdown something to cancel.
        self._dispatch_tasks: set[asyncio.Task[None]] = set()

    @property
    def closed(self) -> bool:
        """Whether this processor has been shut down."""
        return self._closed

    async def process_controls(self, program_href: str) -> None:
        """Process all DERControls for a given DERProgram.

        Called after polling discovers or refreshes DERControl data.
        """
        with self._working():
            try:
                await self._process_controls(program_href)
            finally:
                self._persist()

    @contextlib.contextmanager
    def _working(self) -> Iterator[None]:
        """Count one piece of event work as running, for :meth:`release_devices`."""
        self._busy += 1
        self._idle.clear()
        try:
            yield
        finally:
            self._busy -= 1
            if self._busy == 0:
                self._idle.set()

    async def _process_controls(self, program_href: str) -> None:
        """Process the DERControls of one DERProgram; see :meth:`process_controls`."""
        if self._closed:
            return

        derp_state = self._state.der_programs.get(program_href)
        if derp_state is None:
            return
        self._restore_pending_ledgers()

        # Relay the program's DefaultDERControl baseline (add/change only).
        self._relay_default_baseline(program_href, derp_state)

        # Server timebase (FSA-scoped): classification against server-epoch
        # eff_start/eff_end must follow the head-end's clock.
        now = int(self._timebase.now(self._fsa_scope(program_href)))
        self._prune_imported_boundaries(now)
        primacy = derp_state.primacy
        n_controls = len(derp_state.der_controls)
        logger.debug(
            "Processing %d controls for program %s (primacy=%d)",
            n_controls,
            program_href,
            primacy,
        )

        for derc in derp_state.der_controls:
            mrid = derc.m_rid.value
            mrid_short = mrid.hex()[:8]
            # Server status time for tie-breaking
            server_status_time = 0
            if derc.event_status is not None and derc.event_status.date_time is not None:
                server_status_time = derc.event_status.date_time.value

            # Check if already tracked
            existing = self._store.get(mrid)
            if existing is not None:
                # Update the derc reference (server may have updated fields)
                existing.derc = derc
                existing.server_status_time = server_status_time
                if derc.creation_time is not None:
                    existing.creation_time = derc.creation_time.value
                # Check server cancellation
                if self._is_server_cancelled(derc) and existing.state in (
                    EventState.SCHEDULED,
                    EventState.ACTIVE,
                ):
                    logger.debug(
                        "Server cancelled event %s (was %s)", mrid_short, existing.state.value
                    )
                    await self._handle_cancellation(existing)
                    if self._closed:
                        return
                else:
                    # Server refreshed the control's fields without a state
                    # change; relay only if the actionable content changed
                    # (fire-on-change dedup in _emit_relay).
                    self._relay_control_event(existing, "updated")
                    self._add_missing_windows(existing, now)
                continue

            # Each device draws its own randomization (IEEE 2030.5-2023
            # §10.2.3.2.2, §10.2.3.2.3). The event spans every device's window.
            devices = self._unique_devices(program_href)
            windows = self._draw_windows(derc, program_href, devices, now, late=True)
            eff_start = min(start for start, _ in windows.values())
            eff_end = max(end for _, end in windows.values())
            eff_duration = eff_end - eff_start

            # Comms-loss recovery: skip events at or before the resume boundary
            # (the window we opted out of during the outage). Only later
            # schedules resume. The boundary outlives the mode: skipped events
            # are not stored, so it must gate every poll until the window has
            # elapsed -- the client clears it only once it is in the past.
            if (
                self._comms_loss.resume_after_epoch is not None
                and eff_start <= self._comms_loss.resume_after_epoch
            ):
                self._audit_unstored(
                    derc, program_href, primacy, eff_start, eff_duration, "skipped"
                )
                logger.debug(
                    "Skipping event %s in opted-out window (start=%d <= resume_after=%d)",
                    mrid_short,
                    eff_start,
                    self._comms_loss.resume_after_epoch,
                )
                continue
            if self._gated_by_imported_boundary(program_href, eff_start):
                self._audit_unstored(
                    derc, program_href, primacy, eff_start, eff_duration, "skipped"
                )
                logger.debug(
                    "Skipping event %s: in the opted-out window of the devices taken over",
                    mrid_short,
                )
                continue

            if now > eff_end:
                # IEEE 2030.5 §10.2.2.3 rule j: EXPIRED is only for an event whose
                # end is already past *when first received*. If we already
                # responded to this event (e.g. ran it to COMPLETED and the store
                # then pruned it after its end), a later poll re-discovering it
                # must NOT re-post EXPIRED -- it would contradict the COMPLETED we
                # already sent. (Response posting is also gated on responseRequired
                # inside post_der_response.)
                if self._response_tracker.has_responded(mrid):
                    logger.debug(
                        "Skipping EXPIRED for already-handled event %s "
                        "(re-discovered %ds after end)",
                        mrid_short,
                        now - eff_end,
                    )
                    continue
                logger.debug(
                    "Event %s already expired when received (ended %ds ago)",
                    mrid_short,
                    now - eff_end,
                )
                self._audit_unstored(
                    derc, program_href, primacy, eff_start, eff_duration, "expired"
                )
                await self._post_response(derc, ResponseCode.EXPIRED, program_href)
                if self._closed:
                    return
                continue

            state = EventState.ACTIVE if now >= eff_start else EventState.SCHEDULED
            logger.info(
                "New event %s: state=%s start=T+%ds duration=%ds primacy=%d",
                mrid_short,
                state.value,
                eff_start - now,
                eff_duration,
                primacy,
            )

            # IEEE 10.2.2.3 rule e): use creationTime for tie-breaking
            creation_time = 0
            if derc.creation_time is not None:
                creation_time = derc.creation_time.value

            record = EventRecord(
                mrid=mrid,
                derc=derc,
                program_href=program_href,
                primacy=primacy,
                state=state,
                start=eff_start,
                duration=eff_duration,
                server_status_time=server_status_time,
                creation_time=creation_time,
                device_windows={d: windows[d] for d in devices},
            )

            # Check server cancellation before adding
            if self._is_server_cancelled(derc):
                record.state = EventState.CANCELLED
                self._store.upsert(record)
                logger.info("Event %s pre-cancelled by server", mrid_short)
                self._audit_transition(record, None, "cancelled")
                self._relay_control_event(record, "cancelled")
                await self._post_response(derc, ResponseCode.CANCELLED, program_href)
                if self._closed:
                    return
                continue

            self._store.upsert(record)
            # New event signals fresh state for affected devices — clear
            # stale DDERC tracker entries across ALL programs so initial
            # DDERC is re-evaluated (a device may belong to multiple programs).
            dev_hrefs = self._state.device_mapping.program_to_devices.get(program_href, [])
            affected_lfdis: set[bytes] = set()
            for dh in dev_hrefs:
                lfdi = self._get_device_lfdi(dh)
                if lfdi is not None:
                    affected_lfdis.add(lfdi)
            if affected_lfdis:
                self._dderc_tracker.clear_devices(affected_lfdis)

            if state == EventState.SCHEDULED:
                await self._handle_new_scheduled(record)
            else:
                await self._handle_late_discovery(record, derp_state)
            if self._closed:
                return

        # IEEE 2030.5-2023 §10.2.2.3 rule p): clients SHALL consider events
        # removed from the server before the end of their Effective Scheduled
        # Period as cancelled. The 2023 edition notes this differs from earlier
        # revisions, where currentStatus=2 was the only cancellation signal.
        #
        # Gated on der_controls_complete: a failed or unparseable DERControl
        # fetch leaves the list empty, and that is indistinguishable from a
        # server that removed every control. Reconciling against an incomplete
        # snapshot would cancel every live event on one transient error.
        if derp_state.der_controls_complete:
            served = {derc.m_rid.value for derc in derp_state.der_controls}
            # "before the end of their Effective Scheduled Period" is part of
            # the rule, not a detail: a server may drop an event once it is
            # over, and such an event completed rather than being cancelled.
            # The record can still be ACTIVE here because _on_completion blocks
            # on _state_ready for the length of a rediscovery, and a rediscovery
            # ends by refreshing the list and calling this method -- cancelling
            # would report status 6 for an event that ran its course and
            # suppress the status 3 the blocked completion still owes.
            removed = [
                record
                for record in self._store.all_active_states()
                if record.program_href == program_href
                and record.mrid not in served
                and now < record.end
            ]
            if removed and derp_state.der_controls_pages > 1:
                # A server that drops or adds a control between two page reads
                # shifts the later pages, and the read can miss a control the
                # server still serves. Cancellation is final, so the list is
                # read again now and only a control missing from both reads is
                # cancelled. A failed second read cancels nothing this pass.
                reread = await read_der_control_mrids(self._http, derp_state)
                if self._closed:
                    return
                removed = [] if reread is None else [r for r in removed if r.mrid not in reread]
            for record in removed:
                # Another task can end the event during an await in this loop.
                if record.state not in (EventState.SCHEDULED, EventState.ACTIVE):
                    continue
                # A refresh can also replace the program's list during an await
                # here or in the second read above. Cancel only a control that
                # the latest complete list still leaves out.
                if not self._absent_from_current_list(program_href, record.mrid):
                    continue
                logger.info(
                    "Event %s removed from program %s while %s -- cancelling (rule p)",
                    record.mrid.hex()[:8],
                    program_href,
                    record.state.value,
                )
                await self._handle_cancellation(record)
                if self._closed:
                    return

        # Run supersession across all non-terminal events
        await self._run_supersession()
        if self._closed:
            return

        # Prune expired
        expired = self._store.prune_expired(now)
        # Drop relay snapshots for events that left the store so the
        # fire-on-change cache doesn't grow without bound (both the control and
        # its doe projection, if any).
        for expired_mrid in expired:
            self._relay_snapshots.pop(("control", expired_mrid.hex()), None)
            self._relay_snapshots.pop(("doe", expired_mrid.hex()), None)
            self._fallback_due.pop(expired_mrid, None)
        for ended, device in self._rand_cache.prune(now):
            self._control_xml.pop(ended, None)
            if self._state_store is not None:
                try:
                    self._state_store.forget_offsets(ended.hex(), device)
                except Exception:
                    logger.warning("Could not forget the offsets of %s", ended.hex()[:8])
        self._forget_unstored_no_longer_served(program_href)
        self._response_tracker.prune(now)

        # Apply DDERC to devices that have no active events.
        # Per IEEE 2030.5 §10.10, the DefaultDERControl is the baseline
        # operating state and should be active whenever no event overrides it.
        await self._apply_initial_dderc(program_href)

    def _absent_from_current_list(self, program_href: str, mrid: bytes) -> bool:
        """Return True when the program's current complete DERControl list omits ``mrid``.

        False when the program is gone or its list is incomplete: neither
        shows that the server removed the control.
        """
        current = self._state.der_programs.get(program_href)
        if current is None or not current.der_controls_complete:
            return False
        return all(derc.m_rid.value != mrid for derc in current.der_controls)

    def _forget_unstored_no_longer_served(self, program_href: str) -> None:
        """Forget expired and skipped events the program no longer serves.

        Only on a complete fetch: an empty list from a failed one would forget
        every event, and the next poll would record them all again.
        """
        derp_state = self._state.der_programs.get(program_href)
        if derp_state is None or not derp_state.der_controls_complete:
            return
        served = {derc.m_rid.value for derc in derp_state.der_controls}
        for mrid, program in list(self._audit_unstored_seen.items()):
            if program == program_href and mrid not in served:
                del self._audit_unstored_seen[mrid]

    def cancel_program(self, program_href: str) -> None:
        """Cancel all events from a removed program (Gap 3: IEEE 8.8.3).

        Transitions all scheduled/active events from the given program to
        CANCELLED and cancels any pending timers.
        """
        cancelled_count = 0
        for record in self._store.all_active_states():
            if record.program_href == program_href:
                mrid_short = record.mrid.hex()[:8]
                logger.info("Cancelling event %s from removed program %s", mrid_short, program_href)
                from_state = record.state.value
                self._store.transition(record.mrid, EventState.CANCELLED)
                self._audit_transition(record, from_state, "cancelled")
                self._timer_mgr.cancel(record.mrid)
                # cancel_program is sync, but runs inside the event loop, so
                # _emit_relay's loop.create_task succeeds.
                self._relay_control_event(record, "cancelled")
                cancelled_count += 1
        # The program is gone -- drop its baseline relay slot so the cache stays
        # bounded by live program count.
        self._relay_snapshots.pop(("default_baseline", program_href), None)
        for mrid, program in list(self._audit_unstored_seen.items()):
            if program == program_href:
                del self._audit_unstored_seen[mrid]
        if cancelled_count:
            logger.info(
                "Cancelled %d event(s) from removed program %s", cancelled_count, program_href
            )

    async def release_cancelled_program(self, program_href: str) -> None:
        """Release the control that events cancelled by :meth:`cancel_program` still hold.

        Cancelling an event does not touch the device: the registration of the
        modes it set stays until they are released. For a program that was
        removed those modes would stay on every device for good, since no end
        of the event is left to release them. Each such event releases them as
        an ended event does: modes no default carries are disabled, and the
        default that now governs the device is applied. Call it after the
        program has left the discovered state, so its own default is not
        chosen. A device the event never registered on is untouched.
        """
        for record in self._store.by_state(EventState.CANCELLED):
            if record.program_href != program_href or record.opted_out:
                continue
            if not self._mode_tracker.devices_of(record.mrid):
                continue
            await self._apply_dderc_fallback(record)
            if self._closed:
                return

    async def shutdown(self) -> None:
        """Cancel all event timers + in-flight background tasks and mark closed."""
        self._closed = True
        await self._timer_mgr.cancel_all()
        # Cancel/await fire-and-forget relay tasks and any control dispatch
        # still running past the activation ceiling, so shutdown is clean
        # (no "Task was destroyed but it is pending" warnings).
        background = list(self._relay_tasks) + list(self._dispatch_tasks)
        for task in background:
            task.cancel()
        if background:
            await asyncio.gather(*background, return_exceptions=True)

    async def _handle_new_scheduled(self, record: EventRecord) -> None:
        """Post ack and schedule activation timer for a newly discovered scheduled event."""
        mrid_short = record.mrid.hex()[:8]
        logger.debug("Event %s: posting ACK, scheduling activation timer", mrid_short)
        await self._post_response(record.derc, ResponseCode.ACKNOWLEDGED, record.program_href)
        if self._closed:
            return
        self._schedule_activations(record)
        self._relay_control_event(record, "scheduled")
        self._audit_transition(record, None, "scheduled")

    def _draw_windows(
        self,
        derc: Dercontrol1,
        program_href: str,
        devices: Sequence[str],
        now: int,
        *,
        late: bool,
    ) -> dict[str, tuple[int, int]]:
        """Return each device's effective ``(start, end)`` for a DERControl.

        Each device draws its own start and duration offsets (IEEE 2030.5-2023
        §10.2.3.2.2, §10.2.3.2.3), keyed by event and device so the device
        keeps them across polls and, through a shared store, across
        processes. ``devices`` empty gives one window under the key
        ``NO_DEVICE``. Under a group lookup every device shares one draw: the
        lookup dispatches to the group's local devices together.

        §10.2.2.3 rule m.1: a successive event starts on each device at the
        predecessor's effective end on that device. Rule k, applied when
        ``late`` (an event first received here): a device whose effective
        start has passed while the specified end is still ahead starts at the
        current time plus the absolute value of its start offset, and keeps
        the specified end plus its duration offset.
        """
        mrid = derc.m_rid.value
        raw_start = derc.interval.start.value
        raw_duration = derc.interval.duration
        raw_end = raw_start + raw_duration
        predecessor = self._find_successive_predecessor(program_href, raw_start)
        shared = self._group_local_lfdis(program_href) is not None
        keys = [NO_DEVICE] if shared or not devices else list(devices)
        randomized_start = derc.randomize_start is not None and derc.randomize_start.value != 0
        drawn: dict[str, tuple[int, int]] = {}
        for key in keys:
            successive = predecessor.window(key)[1] - raw_start if predecessor is not None else None
            start_off, dur_off = self._rand_cache.get_offsets(
                derc, raw_start, raw_duration, device=key, start_offset=successive
            )
            if successive is not None and successive != start_off:
                logger.debug(
                    "Successive event %s on %s: adjusting start offset %d -> %d",
                    mrid.hex()[:8],
                    key or "its program",
                    start_off,
                    successive,
                )
                start_off = successive
                self._rand_cache.override_start_offset(
                    mrid, start_off, raw_start, raw_duration, device=key
                )
                self._share_adjusted_offsets(mrid, key, (start_off, dur_off))
            start = raw_start + start_off
            end = start + raw_duration + dur_off
            if late and predecessor is None and randomized_start and start < now < raw_end:
                end = raw_end + dur_off
                start = min(now + abs(start_off), end)
            drawn[key] = (start, end)
        if shared or not devices:
            return dict.fromkeys(devices, drawn[NO_DEVICE]) or drawn
        return drawn

    def _add_missing_windows(self, record: EventRecord, now: int) -> None:
        """Draw windows for devices mapped to a running or scheduled event after it arrived.

        A device whose window starts later gets its own activation timer. One
        whose window has already started is not dispatched here: a device
        that joins a running event is applied by :meth:`resume_devices`.
        """
        if record.state not in (EventState.SCHEDULED, EventState.ACTIVE):
            return
        missing = [
            d for d in self._unique_devices(record.program_href) if d not in record.device_windows
        ]
        if not missing:
            return
        windows = self._draw_windows(record.derc, record.program_href, missing, now, late=False)
        for device, (start, end) in windows.items():
            record.set_window(device, start, end)
        if record.opted_out:
            return
        later = [d for d in missing if windows[d][0] > now and d not in self._awaiting_resume]
        if later:
            self._schedule_activations(record, later)

    def _schedule_activations(
        self, record: EventRecord, devices: Iterable[str] | None = None
    ) -> None:
        """Schedule activation at each device's own window start.

        Devices that share a start share one timer. An event without device
        windows gets one timer at its start. ``devices`` None schedules every
        device not started yet.
        """
        now_fn = self._now_fn_for(record.program_href)
        if not record.device_windows:
            self._timer_mgr.schedule_activation(record, self._activate, now_fn=now_fn)
            return
        pending = (
            set(devices)
            if devices is not None
            else set(record.device_windows) - record.started_devices - record.ended_devices
        )
        groups: dict[int, set[str]] = {}
        for device in pending:
            if device in record.device_windows:
                groups.setdefault(record.device_windows[device][0], set()).add(device)
        for start, group in sorted(groups.items()):
            self._timer_mgr.schedule_at(
                record,
                start,
                partial(self._activate, devices=frozenset(group)),
                "activation",
                now_fn=now_fn,
            )

    def _schedule_completions(self, record: EventRecord, devices: set[str] | None) -> None:
        """Schedule completion at each started device's own window end.

        Devices that share an end share one timer. ``devices`` None, or an
        event without device windows, gets one timer at the event's end.
        """
        now_fn = self._now_fn_for(record.program_href)
        if devices is None or not record.device_windows:
            self._timer_mgr.schedule_completion(record, self._complete, now_fn=now_fn)
            return
        groups: dict[int, set[str]] = {}
        for device in devices:
            if device in record.device_windows and device not in record.ended_devices:
                groups.setdefault(record.device_windows[device][1], set()).add(device)
        for end, group in sorted(groups.items()):
            self._timer_mgr.schedule_at(
                record,
                end,
                partial(self._complete, devices=frozenset(group)),
                "completion",
                now_fn=now_fn,
            )

    def _due_devices(
        self, record: EventRecord, devices: Iterable[str] | None, now: int, *, first: bool
    ) -> set[str] | None:
        """Return the devices an activation starts the event on, or None for every device.

        None only for an event without device windows. ``devices`` None takes
        every device. The first activation also takes the program's devices
        that have no window yet, as the event's start applied to them before
        windows were drawn per device.
        """
        if not record.device_windows:
            return None
        due = set(record.device_windows) if devices is None else set(devices)
        if first:
            due |= {
                d
                for d in self._unique_devices(record.program_href)
                if d not in record.device_windows
            }
        return {
            d
            for d in due
            if d not in record.started_devices
            and d not in record.ended_devices
            and d not in self._released
        }

    async def _handle_late_discovery(self, record: EventRecord, derp_state: object) -> None:
        """Handle an event discovered after its start time (already active).

        Mirrors the ``_on_activation()`` flow: run supersession BEFORE posting
        ACTIVE so that SUPERSEDED responses go out first when multiple
        overlapping events are discovered late in the same poll cycle.
        """
        mrid_short = record.mrid.hex()[:8]
        if self._comms_loss.active:
            logger.info("Event %s: comms-loss active -- opting out (late discovery)", mrid_short)
            await self._opt_out_event(record, from_state=None)
            return
        # A device whose own window has already ended (its duration offset
        # ended it early) received the event after it expired there: it is
        # ignored on that device and answered EXPIRED (IEEE 2030.5-2023
        # §10.2.2.3 rule j), and the others go on.
        now = self._event_now(record)
        expired = {d for d, (_, end) in record.device_windows.items() if end <= now}
        record.ended_devices |= expired
        logger.info("Event %s: late discovery (already active), posting ACK", mrid_short)
        await self._post_response(
            record.derc,
            ResponseCode.ACKNOWLEDGED,
            record.program_href,
            exclude_devices=expired or None,
        )
        if expired:
            await self._post_response_for_devices(record.derc, ResponseCode.EXPIRED, expired)
        if self._closed:
            return

        # Devices whose own window has started run the event now; the others
        # start at their own start (IEEE 2030.5-2023 §10.2.3.2.2).
        started = [d for d, (start, end) in record.device_windows.items() if start <= now < end]
        due = self._due_devices(record, started, now, first=True)
        if due is not None:
            record.started_devices |= due

        # IEEE 10.2.2.3 rule l): SUPERSEDED before ACTIVE.
        await self._run_supersession()
        if self._closed:
            return

        if due is None:
            await self._apply_and_respond(record)
        elif due:
            await self._apply_and_respond(record, only=due)
        if self._closed:
            return
        self._relay_control_event(record, "active")
        self._audit_activation(record, from_state=None)

        self._schedule_completions(record, due)
        if record.device_windows:
            self._schedule_activations(record)

    async def _handle_cancellation(self, record: EventRecord) -> None:
        """Handle server cancellation of an event.

        IEEE 10.2.3.3: Cancellation of an active event applies randomization
        to the abbreviated duration. The wind-down period is
        max(abs(randomizeStart), abs(randomizeDuration)) seconds.
        """
        mrid_short = record.mrid.hex()[:8]
        was_active = record.state == EventState.ACTIVE
        logger.info("Event %s: cancelled (was %s)", mrid_short, record.state.value)
        from_state = record.state.value
        self._store.transition(record.mrid, EventState.CANCELLED)
        self._timer_mgr.cancel(record.mrid)
        self._relay_control_event(record, "cancelled")
        self._audit_transition(record, from_state, "cancelled")
        # A cancellation tells a device the event it was running has been called
        # off. A device that was told the event was rejected was never running it,
        # so it is not told again. An event cancelled while still SCHEDULED
        # never dispatched, so every device in the program still hears about it.
        # A device whose own window already ended was told COMPLETED instead.
        ended = set(record.ended_devices)
        await self._post_started_device_lifecycle(
            record, ResponseCode.CANCELLED, mrid_short, exclude=ended
        )
        if record.applied_devices or record.rejected_devices:
            # Devices still waiting for their own start acknowledged the event
            # and hear that it is cancelled.
            waiting = {
                d
                for d in record.device_windows
                if d not in record.started_devices and d not in ended
            } - record.superseded_devices
            if waiting:
                await self._post_response_for_devices(record.derc, ResponseCode.CANCELLED, waiting)

        if was_active:
            wind_down = self._cancellation_wind_down(record)
            if wind_down > 0:
                logger.info(
                    "Event %s: wind-down %ds before DDERC fallback",
                    mrid_short,
                    wind_down,
                )
                self._fallback_due[record.mrid] = int(time.time()) + wind_down
                self._timer_mgr.schedule_delayed_callback(
                    record, wind_down, self._wind_down, "wind-down"
                )
            else:
                await self._cancel_fallback(record)

    async def _wind_down(self, record: EventRecord) -> None:
        """Wind-down timer callback: fall back after a cancellation, then save the shared state.

        Counted as event work, so :meth:`release_devices` waits for its
        default-control writes before it saves and hands the devices over.
        """
        with self._working():
            # No longer due once it runs: a snapshot saved from here on must not
            # have the next process run the fallback again.
            self._fallback_due.pop(record.mrid, None)
            try:
                await self._cancel_fallback(record)
            finally:
                self._persist()

    async def _cancel_fallback(self, record: EventRecord) -> None:
        """Fall back to the default after a cancellation, on the devices still running it.

        Devices whose own window had not started, or had already ended (and
        fell back then), are left as they are.
        """
        waiting = {d for d in record.device_windows if d not in record.started_devices}
        await self._apply_dderc_fallback(record, exclude=(record.ended_devices | waiting) or None)

    @staticmethod
    def _cancellation_wind_down(record: EventRecord) -> int:
        """Compute wind-down duration for cancellation randomization.

        IEEE 10.2.3.3: abbreviated duration is the greater of
        abs(randomizeStart) and abs(randomizeDuration).
        """
        derc = record.derc
        rs = abs(derc.randomize_start.value) if derc.randomize_start is not None else 0
        rd = abs(derc.randomize_duration.value) if derc.randomize_duration is not None else 0
        return max(rs, rd)

    async def _activate(self, record: EventRecord, devices: frozenset[str] | None = None) -> None:
        """Activation timer callback: activate the event, then save the shared state."""
        with self._working():
            try:
                await self._on_activation(record, devices)
            finally:
                self._persist()

    async def _complete(self, record: EventRecord, devices: frozenset[str] | None = None) -> None:
        """Completion timer callback: complete the event, then save the shared state."""
        with self._working():
            try:
                await self._on_completion(record, devices)
            finally:
                self._persist()

    async def _on_activation(
        self, record: EventRecord, devices: Iterable[str] | None = None
    ) -> None:
        """Activation timer callback: start the event on ``devices``.

        Each device starts at its own window start (IEEE 2030.5-2023
        §10.2.3.2.2), so one event can have several activations. The first
        transitions the event from SCHEDULED to ACTIVE; a later one starts it
        on the devices named. ``devices`` None starts it on every device whose
        start has come, and acts only on a SCHEDULED event.

        If a rediscovery lock is configured, waits for any in-progress
        rediscovery to complete before reading state — this keeps timers
        firing on-time while ensuring the device mapping is consistent.
        """
        # Wait for state to be repopulated after _state.clear() during rediscovery
        if self._state_ready is not None and not self._state_ready.is_set():
            await self._state_ready.wait()

        now = self._timebase.now(self._fsa_scope(record.program_href))
        # Elapsed dispatch duration is measured on the monotonic clock: the
        # timebase can jump if a Time observation lands mid-dispatch, which
        # would corrupt (even negate) a timebase-vs-timebase subtraction.
        dispatch_started = time.monotonic()
        mrid_short = record.mrid.hex()[:8]
        first = record.state == EventState.SCHEDULED
        if not first and (devices is None or record.state != EventState.ACTIVE or record.opted_out):
            logger.debug("Event %s: activation skipped (state=%s)", mrid_short, record.state.value)
            return
        if first:
            delta = now - record.start
            logger.info(
                "Event %s: SCHEDULED -> ACTIVE (fired %.2fs %s intended start)",
                mrid_short,
                abs(delta),
                "after" if delta >= 0 else "before",
            )
            self._store.transition(record.mrid, EventState.ACTIVE)

            if self._comms_loss.active:
                logger.info(
                    "Event %s: comms-loss active -- opting out instead of applying", mrid_short
                )
                await self._opt_out_event(record, from_state=EventState.SCHEDULED.value)
                return

        due = self._due_devices(record, devices, int(now), first=first)
        if due is not None:
            if not due and not first:
                return
            record.started_devices |= due

        # IEEE 10.2.2.3 rule l): SUPERSEDED SHALL be POSTed at the Effective
        # Start Time of the superseding event.  Run supersession BEFORE
        # dispatching so the SUPERSEDED responses go out ahead of any ACTIVE.
        # Supersession stands whether or not this event's dispatch then
        # succeeds.
        await self._run_supersession()
        if self._closed:
            return

        if due is None:
            await self._apply_and_respond(record)
        elif due:
            await self._apply_and_respond(record, only=due)
        if self._closed:
            return
        if not first:
            self._schedule_completions(record, due)
            return

        # Absolute "after intended start" follows the server timebase; the
        # elapsed duration uses the monotonic anchor captured above and spans
        # the whole fleet -- individual devices responded as they finished.
        dispatch_done = self._timebase.now(self._fsa_scope(record.program_href))
        logger.info(
            "Event %s: all devices dispatched (%.2fs after intended start, %.2fs for the slowest)",
            mrid_short,
            dispatch_done - record.start,
            time.monotonic() - dispatch_started,
        )
        self._relay_control_event(record, "active")
        self._audit_activation(record, from_state=EventState.SCHEDULED.value)
        self._schedule_completions(record, due)

    async def _on_completion(
        self, record: EventRecord, devices: Iterable[str] | None = None
    ) -> None:
        """Completion timer callback: end the event on ``devices``.

        Each device ends at its own window end (IEEE 2030.5-2023
        §10.2.3.2.3). Ending it on some devices posts their COMPLETED and
        falls them back to the default; the event goes on for the others. The
        last devices to end transition it from ACTIVE to COMPLETED. ``devices``
        None ends it on every device that has not ended.

        Waits for any in-progress rediscovery before reading state.
        """
        # Wait for state to be repopulated after _state.clear() during rediscovery
        if self._state_ready is not None and not self._state_ready.is_set():
            await self._state_ready.wait()

        now = self._timebase.now(self._fsa_scope(record.program_href))
        mrid_short = record.mrid.hex()[:8]
        if record.state != EventState.ACTIVE:
            logger.debug("Event %s: completion skipped (state=%s)", mrid_short, record.state.value)
            return
        earlier = set(record.ended_devices)
        if devices is not None and record.device_windows:
            group = set(devices) - earlier - self._released
            record.ended_devices |= group
            if not set(record.device_windows) <= record.ended_devices:
                logger.info("Event %s: ended on %d device(s)", mrid_short, len(group))
                audience = (
                    record.applied_devices - record.superseded_devices - record.withdrawn_devices
                ) & group
                if audience:
                    await self._post_response_for_devices(
                        record.derc, ResponseCode.COMPLETED, audience
                    )
                await self._apply_dderc_fallback(record, only=group)
                return
        delta = now - record.end
        logger.info(
            "Event %s: ACTIVE -> COMPLETED (fired %.2fs %s intended end)",
            mrid_short,
            abs(delta),
            "after" if delta >= 0 else "before",
        )
        self._store.transition(record.mrid, EventState.COMPLETED)
        self._relay_control_event(record, "completed")
        self._audit_transition(record, EventState.ACTIVE.value, "completed")
        await self._post_started_device_lifecycle(
            record, ResponseCode.COMPLETED, mrid_short, exclude=earlier
        )
        await self._apply_dderc_fallback(record, exclude=earlier or None)

    async def _post_started_device_lifecycle(
        self,
        record: EventRecord,
        code: ResponseCode,
        mrid_short: str,
        *,
        exclude: set[str] | None = None,
    ) -> None:
        """Post a post-activation lifecycle code to the devices that started.

        Used for COMPLETED and CANCELLED: both say something about how an event
        the device was running ended, so neither applies to a device that was told
        the event was rejected.

        Stated positively rather than as "every program device except the
        superseded and rejected ones", because the
        program's device list is not stable across an event: a rediscovery can
        repopulate it under a different program href, or with different members.
        Subtracting from a list that has since changed produced two wrong answers
        -- a rejected device was told COMPLETED once its program mapping had gone
        (the list was empty, so the any-LFDI fallback fired and never consulted
        the exclusions), and a device added to the program mid-event would be told
        an event completed that it never ran.

        The fallback is kept for the one case it was meant for: an event that never
        dispatched at all, whose ACTIVE also went out against any available LFDI
        (see ``_apply_and_respond``), and an event cancelled while still SCHEDULED,
        which every device in the program needs to hear about. Without a dispatch
        there is nothing to have rejected, so there is no exclusion to honor.

        ``exclude`` names devices already told how the event ended on them,
        whose own window ended earlier.
        """
        dispatched = record.applied_devices or record.rejected_devices
        if not dispatched:
            await self._post_response(
                record.derc,
                code,
                record.program_href,
                exclude_devices=record.superseded_devices or None,
            )
            return

        audience = (
            record.applied_devices
            - record.superseded_devices
            - record.withdrawn_devices
            - (exclude or set())
        )
        if not audience:
            logger.info(
                "Event %s: no device was running it "
                "(%d rejected, %d superseded or withdrawn); posting no %s",
                mrid_short,
                len(record.rejected_devices),
                len(record.superseded_devices) + len(record.withdrawn_devices),
                code.name,
            )
            return
        await self._post_response_for_devices(record.derc, code, audience)

    async def release_withdrawn_devices(self, withdrawn: Iterable[tuple[str, str]]) -> None:
        """End the control running events hold on devices withdrawn from their programs.

        ``withdrawn`` holds ``(program_href, device_href)`` pairs the discovery
        refresh dropped from the device mapping. IEEE 2030.5-2023 §8.8.3 has a
        client act on the events of the function set assignments it is in, so a
        device no longer assigned to a program stops being governed by that
        program's events when the client learns of it. Each event the device
        was registered on releases its modes there, as at the end of the event:
        modes the device's remaining defaults do not carry are disabled, and the
        default that now governs the device is applied. The event keeps running
        on its other devices. The standard defines no response status for a
        withdrawal, so none is posted for the device.

        Under a group lookup a program's control reaches its whole group
        whichever server-side device was withdrawn, so nothing is released until
        the event ends.
        """
        by_program: dict[str, set[str]] = {}
        for program_href, dev_href in withdrawn:
            by_program.setdefault(program_href, set()).add(dev_href)
        if not by_program:
            return
        for record in self._store.by_state(EventState.ACTIVE):
            candidates = by_program.get(record.program_href)
            if not candidates or record.opted_out:
                continue
            # A device mapped to the program again is not withdrawn any more.
            mapped = set(self._unique_devices(record.program_href))
            running = (candidates & self._mode_tracker.devices_of(record.mrid)) - mapped
            if not running:
                continue
            if self._group_local_lfdis(record.program_href) is not None:
                logger.debug(
                    "Event %s: program %s uses a group lookup; its control on withdrawn "
                    "device(s) %s is released when the event ends",
                    record.mrid.hex()[:8],
                    record.program_href,
                    sorted(running),
                )
                continue
            logger.info(
                "Event %s: ending its control on %s, withdrawn from program %s",
                record.mrid.hex()[:8],
                ", ".join(sorted(running)),
                record.program_href,
            )
            record.withdrawn_devices |= running
            await self._apply_dderc_fallback(record, only=running)
            if self._closed:
                return

    async def _run_supersession(self) -> None:
        """Run supersession algorithm and apply transitions.

        IEEE 10.2.2.3 rule l): SUPERSEDED SHALL be POSTed at the Effective
        Start Time of the superseding event.  When the superseding event is
        still SCHEDULED and the superseded event is already ACTIVE, we defer
        all supersession bookkeeping until the superseding event activates
        (handled by ``_on_activation`` calling this method again).
        """
        events = self._store.all_active_states()
        if len(events) < 2:
            return

        device_map = self._build_program_device_map()
        results = compute_supersession(events, device_map)

        for result in results:
            superseded = self._store.get(result.superseded_mrid)
            if superseded is None:
                continue
            if superseded.state in (
                EventState.CANCELLED,
                EventState.SUPERSEDED,
                EventState.COMPLETED,
            ):
                continue

            superseding = self._store.get(result.superseding_mrid)
            if superseding is None:
                continue

            # Defer, per device, when the superseding event hasn't started on
            # the device yet and the superseded event is running there. It
            # runs normally until the higher-priority event starts on that
            # device, whose start can differ from the other devices' starts.
            affected = frozenset(
                d
                for d in result.affected_devices
                if not (self._started_on(superseded, d) and not self._started_on(superseding, d))
            )
            if not affected:
                continue

            # Post per-device SUPERSEDED responses for newly affected devices
            newly_superseded = affected - superseded.superseded_devices
            superseded.superseded_devices.update(affected)

            # A device that was told this event was rejected was never running it,
            # so a supersession notice would assert a lifecycle step it never
            # reached. Only the *response* is filtered: the bookkeeping set
            # above still records every affected device, because it drives dispatch
            # exclusion, the fully-superseded check below, and the DDERC fallback.
            #
            # Subtraction rather than the positive ``applied_devices`` test used for
            # COMPLETED/CANCELLED: an event still SCHEDULED has applied nothing yet
            # and can legitimately be superseded before it ever starts, so it must
            # still announce.
            announce = newly_superseded - superseded.rejected_devices
            if announce:
                await self._post_response_for_devices(
                    superseded.derc, ResponseCode.SUPERSEDED, announce
                )

            # Track per-mode supersession per device
            if result.affected_modes:
                for dev in affected:
                    existing = superseded.superseded_modes.get(dev, frozenset())
                    superseded.superseded_modes[dev] = existing | result.affected_modes
                    # The superseding event owns these modes now. Leaving them
                    # on the superseded event's registration would have the
                    # tracker read them as still covered when the superseding
                    # event ends, so nothing would release them until the
                    # superseded event ended too, or ever, when another event
                    # is running on the device then.
                    self._mode_tracker.release(dev, superseded.mrid, result.affected_modes)

            # If all devices for this program are superseded, fully supersede
            program_devices = device_map.get(superseded.program_href, set())
            fully = bool(program_devices) and superseded.superseded_devices >= program_devices
            if newly_superseded and not fully:
                # Not a transition: the event keeps running on its other
                # devices, so the record leaves its state where it was and
                # says which part was taken over.
                current = "opted_out" if superseded.opted_out else superseded.state.value
                self._audit_transition(
                    superseded,
                    current,
                    current,
                    partial(self._audit_supersession, superseded, result.superseding_mrid, True),
                )
            if fully:
                was_active = superseded.state == EventState.ACTIVE
                logger.info(
                    "Event %s: SUPERSEDED by %s (was %s)",
                    superseded.mrid.hex()[:8],
                    result.superseding_mrid.hex()[:8],
                    superseded.state.value,
                )
                from_state = superseded.state.value
                self._store.transition(superseded.mrid, EventState.SUPERSEDED)
                self._timer_mgr.cancel(superseded.mrid)
                self._relay_control_event(superseded, "superseded")
                self._audit_transition(
                    superseded,
                    from_state,
                    "superseded",
                    partial(self._audit_supersession, superseded, result.superseding_mrid, False),
                )

                # Per-device SUPERSEDED responses were already posted above
                # as each device was added to newly_superseded.
                if was_active:
                    await self._apply_dderc_fallback(superseded)

    @staticmethod
    def _started_on(record: EventRecord, device_href: str) -> bool:
        """Return whether ``record`` is running on ``device_href``."""
        return record.state == EventState.ACTIVE and record.runs_on(device_href)

    def _build_program_device_map(self) -> dict[str, set[str]]:
        """Build mapping from program_href to set of device hrefs."""
        result: dict[str, set[str]] = {}
        for href, devices in self._state.device_mapping.program_to_devices.items():
            result[href] = set(devices)
        return result

    async def _apply_and_respond(self, record: EventRecord, only: set[str] | None = None) -> None:
        """Dispatch the control, then report each device by its own outcome.

        Status 2 asserts the event started, so it is posted for a device only
        once that device's apply has returned successfully. A failure reports
        the matching rejection code instead and marks the device, which
        keeps it out of the COMPLETED response at the event's end.

        ``only`` limits the dispatch to those device hrefs, for devices taken
        over from another process while the event was running.
        """
        mrid_short = record.mrid.hex()[:8]

        async def respond(dev_href: str, failure: BaseException | None) -> None:
            if failure is None:
                record.applied_devices.add(dev_href)
                await self._post_response_for_devices(record.derc, ResponseCode.ACTIVE, {dev_href})
                return
            record.rejected_devices.add(dev_href)
            # Modes are registered for every target before dispatch, since the
            # outcome isn't known yet. Release this device's registration now that
            # it is: leaving it would have the tracker believe a control that was
            # never applied still owns those modes, so a later event releasing the
            # same mode would look "still covered" and skip its DDERC fallback.
            self._mode_tracker.unregister(dev_href, record.mrid)
            code = response_code_for_dispatch_error(failure)
            logger.info("Event %s: %s rejected -> %s", mrid_short, dev_href, code.name)
            await self._post_response_for_devices(record.derc, code, {dev_href})

        outcomes = await self._apply_control_to_devices(record, on_result=respond, only=only)
        if outcomes or only is not None:
            return
        # No dispatch targets -- the program has no device mapping, so nothing
        # could fail. Keep the existing any-LFDI ACTIVE announcement rather than
        # leaving the server with no notice that the event started.
        await self._post_response(
            record.derc,
            ResponseCode.ACTIVE,
            record.program_href,
            exclude_devices=record.superseded_devices or None,
        )

    async def _apply_control_to_devices(
        self,
        record: EventRecord,
        on_result: Callable[[str, BaseException | None], Awaitable[None]] | None = None,
        only: set[str] | None = None,
    ) -> dict[str, BaseException | None]:
        """Apply a DERControl to all devices in the program's group (parallel).

        Returns the per-device outcome keyed by device href: ``None`` where the
        control was applied, otherwise the failure. ``on_result`` is awaited for
        each device as soon as *that* device's dispatch settles, so a caller can
        post its response without waiting on the rest of the fleet.
        """
        devices = self._unique_devices(record.program_href)
        derp_state = self._state.der_programs.get(record.program_href)
        curves = derp_state.der_curves if derp_state else []
        mrid_short = record.mrid.hex()[:8]
        targets = [
            d for d in devices if d not in record.superseded_devices and (only is None or d in only)
        ]
        logger.debug("Event %s: applying control to %d device(s)", mrid_short, len(targets))
        if not targets:
            return {}

        # Track active modes per device for per-mode DDERC fallback
        active_modes = get_active_mode_names(record.derc.dercontrol_base)
        for dev_href in targets:
            self._mode_tracker.register(dev_href, record.mrid, active_modes)

        # A caller may supply a ``group_lookup`` that resolves one
        # server-side EndDevice href to several local sub-device LFDIs,
        # in which case dispatch is by LFDI. Unset by default.
        local_lfdis = self._group_local_lfdis(record.program_href)
        if local_lfdis is not None:
            return await self._dispatch_by_lfdi_group(
                record, local_lfdis, targets, curves, on_result
            )

        async def dispatch_and_report(dev_href: str) -> tuple[str, BaseException | None]:
            failure = await self._dispatch_one(
                mrid_short,
                dev_href,
                self._dispatcher.apply_control(dev_href, record.derc, curves),
                record=record,
            )
            if on_result is not None:
                await on_result(dev_href, failure)
            return dev_href, failure

        pairs = await asyncio.gather(*[dispatch_and_report(d) for d in targets])
        return dict(pairs)

    def _log_late_dispatch(
        self,
        mrid_short: str,
        label: str,
        task: asyncio.Task[None],
        record: EventRecord | None = None,
    ) -> None:
        """Consume and report a dispatch that finished after its rejection was sent.

        Retrieving the exception is the point: nothing awaits these tasks once
        the ceiling has fired, so a failure would sit unretrieved until GC and
        surface as a bare "Task exception was never retrieved". It also answers
        the question the rejection left open -- whether the control eventually
        landed on the device.
        """
        if task.cancelled():
            return
        exc = task.exception()
        if record is not None and self._audit.enabled:
            # The server was told this device rejected the event; this is the
            # record of whether the apply then reached it.
            try:
                self._audit.late_dispatch(
                    event_mrid=record.mrid,
                    lfdi=self._lfdi_or_href(label),
                    applied=exc is None,
                    at=self._timebase.now(self._fsa_scope(record.program_href)),
                    error=None if exc is None else str(exc),
                    error_type=None if exc is None else type(exc).__name__,
                )
            except Exception:
                logger.debug("Audit record for a late dispatch failed", exc_info=True)
        if exc is not None:
            logger.warning("Event %s: late dispatch to %s failed: %s", mrid_short, label, exc)
        else:
            logger.info(
                "Event %s: late dispatch to %s applied after its rejection was sent",
                mrid_short,
                label,
            )

    async def _dispatch_one(
        self,
        mrid_short: str,
        label: str,
        coro: Coroutine[Any, Any, None],
        *,
        record: EventRecord | None = None,
    ) -> BaseException | None:
        """Await one device's dispatch under the concurrency ceiling. Returns the failure.

        The ceiling bounds when this device's *response* goes out, not how long
        the control application gets. On expiry the apply is left running under
        the connector's own deadline -- shielded, so ``wait_for`` does not
        cancel it -- and a rejection is reported for the device now. A slow
        device therefore still receives the control; the client has simply
        stopped claiming the event started on it.
        """
        task = asyncio.ensure_future(coro)
        self._dispatch_tasks.add(task)
        task.add_done_callback(self._dispatch_tasks.discard)
        try:
            await asyncio.wait_for(asyncio.shield(task), timeout=ACTIVATION_DISPATCH_DEADLINE)
        except TimeoutError as exc:
            logger.warning(
                "Event %s: dispatch to %s still running after %.1fs; reporting a "
                "rejection now while the apply continues",
                mrid_short,
                label,
                ACTIVATION_DISPATCH_DEADLINE,
            )
            # Past the ceiling nothing awaits this task, so a later failure would
            # sit unretrieved until GC and surface with no context.
            task.add_done_callback(
                lambda finished: self._log_late_dispatch(mrid_short, label, finished, record)
            )
            return exc
        except Exception as exc:
            logger.warning("Event %s: dispatch to %s failed: %s", mrid_short, label, exc)
            return exc
        return None

    async def _dispatch_by_lfdi_group(
        self,
        record: EventRecord,
        local_lfdis: list[str],
        targets: list[str],
        curves: list[Any],
        on_result: Callable[[str, BaseException | None], Awaitable[None]] | None,
    ) -> dict[str, BaseException | None]:
        """Dispatch by local sub-device LFDI and collapse onto the server's hrefs.

        A group lookup resolves one server-side EndDevice to N local
        sub-devices, but the server only knows the aggregate -- there is no
        response channel for an individual sub-device. So the aggregate is
        reported rejected only when *every* sub-device failed; a partial failure
        still performed the event, and reporting it as unsupported would
        misstate a fleet that largely complied. This collapse also forces a
        barrier here: the aggregate outcome is not known until all N return.
        """
        mrid_short = record.mrid.hex()[:8]
        failures = await asyncio.gather(
            *[
                self._dispatch_one(
                    mrid_short,
                    lfdi,
                    self._dispatcher.apply_control_by_lfdi(lfdi, record.derc, curves),
                    record=record,
                )
                for lfdi in local_lfdis
            ]
        )
        for lfdi, failure in zip(local_lfdis, failures, strict=True):
            (record.applied_local if failure is None else record.rejected_local).add(lfdi)
        failed = [f for f in failures if f is not None]
        aggregate: BaseException | None = (
            failed[0] if failed and len(failed) == len(failures) else None
        )
        if not local_lfdis:
            # Every device in the group is a meter, so none can take the control.
            aggregate = DeviceNotConfiguredError(
                "no device in the group takes controls; every device is a meter"
            )
        if failed and aggregate is None:
            logger.info(
                "Event %s: %d/%d sub-devices failed; aggregate still reported ACTIVE",
                mrid_short,
                len(failed),
                len(failures),
            )
        if on_result is not None:
            for dev_href in targets:
                await on_result(dev_href, aggregate)
        return dict.fromkeys(targets, aggregate)

    def _fsa_scope(self, program_href: str) -> str | None:
        """Timebase scope for a program (IEEE 9.2.3): its discovering FSA."""
        ps = self._state.der_programs.get(program_href)
        return ps.discovered_from_fsa_href if ps else None

    def _now_fn_for(self, program_href: str) -> Callable[[], int]:
        """Clock for a program's timers: server timebase, FSA-scoped.

        The scope is bound at creation (a program's FSA parentage is stable
        for a record's lifetime) so the timer loop doesn't re-resolve state
        on every tick.
        """
        tb = self._timebase
        scope = self._fsa_scope(program_href)
        return lambda: int(tb.now(scope))

    def _group_local_lfdis(self, program_href: str) -> list[str] | None:
        """Return local sub-device LFDIs for ``program_href``, if grouped.

        Returns None when no ``group_lookup`` is configured or the callback
        finds no group for this program -- in which case the dispatcher
        dispatches 1-to-1 by server-side href, which is the default.

        A device the dispatcher says takes no controls, a meter, is left out of
        the group, so a site-wide control is not reported rejected because of
        the meters measuring it. A group of meters only is returned empty.
        """
        if self._group_lookup is None:
            return None
        local_lfdis = self._group_lookup(program_href)
        if not local_lfdis:
            return None
        # The ControlDispatcher protocol does not require ``takes_controls``, and
        # a dispatcher without it has every device take controls. Looked up on
        # the class, so an attribute an object creates on access is not taken
        # for the method.
        if getattr(type(self._dispatcher), "takes_controls", None) is None:
            return local_lfdis
        dispatcher: Any = self._dispatcher
        return [lfdi for lfdi in local_lfdis if dispatcher.takes_controls(lfdi)]

    # ------------------------------------------------------------------
    # Schedule-notification relay (informational push; not a control path)
    # ------------------------------------------------------------------

    def _affected_lfdis_for_program(
        self, program_href: str, exclude_hrefs: set[str] | None = None
    ) -> list[str]:
        """Resolve the hex LFDIs a program's events scope to.

        A supplied group lookup resolves the local sub-device LFDIs
        (`_group_local_lfdis`, already hex `str`); otherwise the program's
        EndDevice hrefs map to LFDIs via `_get_device_lfdi` (`bytes` -> `.hex()`),
        excluding ``exclude_hrefs`` (superseded devices) the same way
        ``_apply_control_to_devices`` does, so the relayed scope matches dispatch.
        """
        local = self._group_local_lfdis(program_href)
        if local is not None:
            return list(local)
        exclude = exclude_hrefs or set()
        out: list[str] = []
        for dev_href in self._state.device_mapping.program_to_devices.get(program_href, []):
            if dev_href in exclude:
                continue
            lfdi = self._get_device_lfdi(dev_href)
            if lfdi is not None:
                out.append(lfdi.hex())
        return out

    def _audit_activation(self, record: EventRecord, *, from_state: str | None) -> None:
        """Record an event going active, once its dispatch has settled.

        Emitted after the per-device outcomes are in, not at the state change,
        so the applied and rejected lists are final. They are the outcome each
        device's dispatch returned, which is what the server was told. Under a
        group lookup they list the local devices one by one, so a partial
        failure the server's single response hides is visible here.
        """

        def outcomes() -> dict[str, Any]:
            if record.applied_local or record.rejected_local:
                return {
                    "applied_lfdis": list(record.applied_local),
                    "rejected_lfdis": list(record.rejected_local),
                }
            return {
                "applied_lfdis": self._lfdis_for_hrefs(record.applied_devices),
                "rejected_lfdis": self._lfdis_for_hrefs(record.rejected_devices),
            }

        self._audit_transition(record, from_state, EventState.ACTIVE.value, outcomes)

    def _audit_supersession(
        self, record: EventRecord, superseded_by: bytes, part: bool
    ) -> dict[str, Any]:
        """A ``superseded`` record's details; for a partial one, what was taken over.

        In the same terms as the rest of the trail: under a group lookup the
        server's EndDevice is the program's local devices, so each of them is
        listed with the modes taken over on the EndDevice.
        """
        if not part:
            return {"superseded_by": superseded_by}
        local = self._group_local_lfdis(record.program_href)
        if local is None:
            return {
                "superseded_by": superseded_by,
                "superseded_lfdis": self._lfdis_for_hrefs(record.superseded_devices),
                "superseded_modes": {
                    self._lfdi_or_href(dev): _wire_mode_names(modes)
                    for dev, modes in record.superseded_modes.items()
                },
            }
        modes: set[str] = set()
        for taken in record.superseded_modes.values():
            modes |= taken
        return {
            "superseded_by": superseded_by,
            "superseded_lfdis": list(local),
            "superseded_modes": (
                {lfdi: _wire_mode_names(modes) for lfdi in local} if modes else {}
            ),
        }

    def _audit_transition(
        self,
        record: EventRecord,
        from_state: str | None,
        to_state: str,
        details: Callable[[], dict[str, Any]] | None = None,
    ) -> None:
        """Hand one lifecycle transition to the audit trail.

        Never raises: the trail must not be able to stop an event from being
        processed, so a failure building the record is logged and dropped.
        ``details`` is a callable for the same reason -- what it computes
        resolves devices, and it runs here, inside the guard, rather than on
        the caller's control path.
        """
        if not self._audit.enabled:
            return
        if record.opted_out and to_state != "opted_out":
            # An opted-out event keeps its stored state, so supersession and
            # classification see it unchanged. Its trail has left that state.
            from_state = "opted_out"
        try:
            # The control itself rides on an event's first record, for the
            # local history only: the history has to describe a control after
            # the server stops serving it.
            control = (
                self._control_summary(record)
                if from_state is None and self._audit.keeps_history
                else None
            )
            self._audit.event_transition(
                event_mrid=record.mrid,
                program_href=record.program_href,
                from_state=from_state,
                to_state=to_state,
                effective_start=record.start,
                effective_duration=record.duration,
                primacy=record.primacy,
                lfdis=self._affected_lfdis_for_program(record.program_href),
                at=self._timebase.now(self._fsa_scope(record.program_href)),
                control=control,
                **(details() if details is not None else {}),
            )
        except Exception:
            self._audit_failures += 1
            log = logger.warning if self._audit_failures == 1 else logger.debug
            log(
                "Audit record for event %s failed; further failures log at debug",
                record.mrid.hex()[:8],
                exc_info=True,
            )

    def attach_event_history(self, history: EventHistory | None) -> None:
        """Keep each response this processor posts, or fails to post, in ``history``."""
        self._response_tracker.observer = (
            None if history is None else partial(_record_response, history)
        )

    def _control_summary(self, record: EventRecord) -> dict[str, Any]:
        """The control's description, settings and timing, and its program's name."""
        program = self._state.der_programs.get(record.program_href)
        return {
            **serialize_der_control(record.derc),
            "description": record.derc.description,
            "program_description": program.program.description if program else None,
        }

    def _audit_unstored(
        self,
        derc: Dercontrol1,
        program_href: str,
        primacy: int,
        start: int,
        duration: int,
        to_state: str,
    ) -> None:
        """Record an event the store never holds: expired on arrival, or skipped
        in an opted-out window.

        Once per event. Neither is stored, so the next poll meets it again, and
        a trail that recorded it every poll would contradict the rule that a
        re-poll of an unchanged event records nothing.
        """
        if not self._audit.enabled:
            return
        mrid = derc.m_rid.value
        if mrid in self._audit_unstored_seen:
            return
        self._audit_unstored_seen[mrid] = program_href
        transient = EventRecord(
            mrid=mrid,
            derc=derc,
            program_href=program_href,
            primacy=primacy,
            state=EventState.CANCELLED,
            start=start,
            duration=duration,
            server_status_time=0,
        )
        self._audit_transition(transient, None, to_state)

    def _lfdi_or_href(self, dev_href: str) -> str:
        """A device as its hex LFDI, or its href when the LFDI is not known.

        The href is kept rather than dropping the device: an audit record that
        silently loses a device reads as the device never having been involved.
        """
        lfdi = self._get_device_lfdi(dev_href)
        return lfdi.hex() if lfdi is not None else dev_href

    def _lfdis_for_hrefs(self, hrefs: set[str]) -> list[str]:
        return [self._lfdi_or_href(h) for h in hrefs]

    def _relay_control_event(self, record: EventRecord, transition: str) -> None:
        """Relay a DERControl lifecycle change to affected connectors (stream=control)."""
        derc = record.derc
        current_status = derc.event_status.current_status if derc.event_status is not None else None
        randomization = (
            derc.randomize_start.value if derc.randomize_start is not None else None,
            derc.randomize_duration.value if derc.randomize_duration is not None else None,
        )
        notification = ScheduleNotification(
            stream="control",
            transition=transition,
            status=record.state.value,
            current_status=current_status,
            mrid=record.mrid.hex(),
            program_href=record.program_href,
            primacy=record.primacy,
            start=record.start,
            duration=record.duration,
            end=record.end,
            affected_lfdis=self._affected_lfdis_for_program(
                record.program_href, record.superseded_devices
            ),
            randomization=randomization,
            payload=serialize_der_control(derc),
        )
        # Lifecycle transitions are distinct events and always fire; the per-poll
        # "updated" refresh is content-deduped so an unchanged control doesn't re-relay.
        self._emit_relay(notification, dedup=(transition == "updated"))

        # `doe` projection: when this control carries CSIP-AUS envelope limits,
        # also emit a `doe` notification carrying only those limits, so an
        # optimizer can track operating envelopes without setpoint noise. Same
        # envelope/transition as `control`; deduped independently (keyed by
        # ("doe", mrid)) on the envelope alone -- a setpoint-only change updates
        # `control` but not `doe`.
        envelope = _extract_doe_envelope(derc.dercontrol_base)
        if envelope:
            doe = replace(notification, stream="doe", payload={"control_base": envelope})
            self._emit_relay(doe, dedup=(transition == "updated"))

    def _relay_default_baseline(self, program_href: str, derp_state: DerProgramState) -> None:
        """Relay a DefaultDERControl add/change (stream=default_baseline).

        Driven each `process_controls` pass; content-deduped so an unchanged
        baseline doesn't re-relay. First sighting -> ``default_added``, a content
        change -> ``default_updated``. A baseline has no EventStatus/interval, so
        status/timing fields are null.
        """
        dderc = derp_state.default_dercontrol
        if dderc is None:
            return
        mrid = dderc.m_rid.value.hex()
        # One baseline slot per program (not per mRID) so a DDERC mRID swap is a
        # "default_updated" and the cache stays bounded by program count.
        key = ("default_baseline", program_href)
        transition = "default_added" if key not in self._relay_snapshots else "default_updated"
        notification = ScheduleNotification(
            stream="default_baseline",
            transition=transition,
            status=None,
            current_status=None,
            mrid=mrid,
            program_href=program_href,
            primacy=derp_state.primacy,
            start=None,
            duration=None,
            end=None,
            affected_lfdis=self._affected_lfdis_for_program(program_href),
            randomization=(None, None),
            payload=serialize_default_der_control(dderc) or {},
        )
        self._emit_relay(notification, dedup=True, dedup_key=key)

    def _emit_relay(
        self,
        notification: ScheduleNotification,
        *,
        dedup: bool,
        dedup_key: tuple[str, str] | None = None,
    ) -> None:
        """Schedule the relay as a fire-and-forget task, applying fire-on-change.

        The content signature excludes ``transition`` so that the per-poll
        ``updated``/``default_updated`` path suppresses unchanged content while
        genuine lifecycle transitions (which the caller fires with ``dedup=False``)
        always go out.

        ``dedup_key`` overrides the snapshot key. Defaults to ``(stream, mrid)``
        (one slot per event). The baseline path passes ``(stream, program_href)``
        so a program keeps a single baseline slot regardless of mRID churn --
        bounding the cache to program count and turning a DDERC mRID swap into a
        ``default_updated`` rather than a fresh ``default_added`` + leaked slot.
        """
        # Actionable-content signature only: event identity, EventState,
        # effective interval, randomization, scope, and the DERControlBase.
        # Deliberately excludes transition, raw current_status, and the volatile
        # serialized fields (creation_time, event_status.date_time) that churn
        # each poll -- so an unchanged control isn't re-relayed as "updated".
        # ``mrid`` is included because the baseline key is program-scoped, so a
        # DDERC mRID swap must still register as a change.
        content_sig: tuple[Any, ...] = (
            notification.mrid,
            notification.status,
            notification.start,
            notification.duration,
            tuple(sorted(notification.affected_lfdis)),
            notification.randomization,
            json.dumps(notification.payload.get("control_base"), sort_keys=True, default=str),
        )
        key = dedup_key if dedup_key is not None else (notification.stream, notification.mrid)
        if dedup and self._relay_snapshots.get(key) == content_sig:
            return
        self._relay_snapshots[key] = content_sig
        try:
            loop = asyncio.get_running_loop()
        except RuntimeError:  # pragma: no cover - no running loop (unexpected sync path)
            return
        task = loop.create_task(
            self._dispatcher.relay_schedule_notification(
                list(notification.affected_lfdis), notification
            )
        )
        self._relay_tasks.add(task)
        task.add_done_callback(self._relay_tasks.discard)

    # ------------------------------------------------------------------
    # Shared event state: save, load, take over and release EndDevices
    # ------------------------------------------------------------------

    def _claim_offsets(self, mrid: bytes, device: str, offsets: tuple[int, int]) -> tuple[int, int]:
        """Return the shared offsets of ``mrid`` on ``device``, sharing ``offsets`` if none."""
        assert self._state_store is not None
        try:
            start, duration = self._state_store.claim_offsets(mrid.hex(), device, offsets)
        except Exception:
            logger.warning(
                "Could not share the randomization of %s; using this process's own",
                mrid.hex()[:8],
                exc_info=True,
            )
            return offsets
        return int(start), int(duration)

    def _record_sent(self, mrid: bytes, code: ResponseCode, lfdi: bytes, at: int) -> None:
        """Record one posted response in the shared event state."""
        assert self._state_store is not None
        self._state_store.record_response(lfdi.hex(), mrid.hex(), int(code), at)

    def _control_xml_of(self, record: EventRecord) -> str:
        """Return the record's DERControl as XML, serialized once per object."""
        from py20305.xml.serialization import to_xml

        cached = self._control_xml.get(record.mrid)
        if cached is not None and cached[0] is record.derc:
            return cached[1]
        xml = to_xml(record.derc).decode("utf-8")
        self._control_xml[record.mrid] = (record.derc, xml)
        return xml

    def _device_snapshot(self, dev_href: str, lfdi: bytes) -> dict[str, Any]:
        """Return the event state of one EndDevice in the shared snapshot format."""
        mapping = self._state.device_mapping.program_to_devices
        events: list[dict[str, Any]] = []
        for record in self._store.values():
            concerned = (
                dev_href in mapping.get(record.program_href, [])
                or dev_href in record.applied_devices
                or dev_href in record.rejected_devices
                or dev_href in record.superseded_devices
            )
            if not concerned:
                continue
            modes = record.superseded_modes.get(dev_href)
            events.append(
                {
                    "mrid": record.mrid.hex(),
                    "program_href": record.program_href,
                    "primacy": record.primacy,
                    "state": record.state.value,
                    "start": record.start,
                    "duration": record.duration,
                    "server_status_time": record.server_status_time,
                    "creation_time": record.creation_time,
                    "control": self._control_xml_of(record),
                    "window": list(record.window(dev_href)),
                    "started": dev_href in record.started_devices,
                    "ended": dev_href in record.ended_devices,
                    "applied": dev_href in record.applied_devices,
                    "rejected": dev_href in record.rejected_devices,
                    "superseded": dev_href in record.superseded_devices,
                    "withdrawn": dev_href in record.withdrawn_devices,
                    "superseded_modes": sorted(modes) if modes is not None else None,
                    "opted_out": record.opted_out,
                    "fallback_at": (
                        self._fallback_due.get(record.mrid)
                        if record.state == EventState.CANCELLED
                        and self._timer_mgr.has_pending(record.mrid)
                        else None
                    ),
                }
            )
        return {
            "version": SNAPSHOT_VERSION,
            "lfdi": lfdi.hex(),
            "events": events,
            "defaults": [
                {
                    "program_href": path,
                    "mrid": mrid.hex(),
                    "primacy": primacy,
                    "content": content.hex() if content is not None else None,
                    "modes": sorted(modes) if modes is not None else None,
                }
                for path, mrid, primacy, content, modes in self._dderc_tracker.entries_for(lfdi)
            ],
            "comms_loss": {
                "active": self._comms_loss.active,
                "resume_after": self._device_resume_after(dev_href),
            },
        }

    def _device_resume_after(self, dev_href: str) -> int | None:
        """Return the loss-of-communications resume boundary that applies to one device."""
        boundaries = [
            b
            for b in (
                self._comms_loss.resume_after_epoch,
                self._imported_resume_after.get(dev_href),
            )
            if b is not None
        ]
        return max(boundaries) if boundaries else None

    def _gated_by_imported_boundary(self, program_href: str, eff_start: int) -> bool:
        """Return whether a new event starts inside the opted-out window of its devices.

        True only when every device of the program was taken over with a
        resume boundary at or after ``eff_start``. A program that also serves
        devices without one runs the event on all of them.
        """
        if not self._imported_resume_after:
            return False
        devices = self._unique_devices(program_href)
        return bool(devices) and all(
            self._imported_resume_after.get(d, eff_start - 1) >= eff_start for d in devices
        )

    def _prune_imported_boundaries(self, now: int) -> None:
        """Drop imported resume boundaries that have passed."""
        for dev_href, boundary in list(self._imported_resume_after.items()):
            if now > boundary:
                del self._imported_resume_after[dev_href]

    def _restore_pending_ledgers(self) -> None:
        """Restore the Response ledger of taken-over devices discovery has found.

        Done before any control of theirs is processed, so a Response the
        previous process posted is not posted again, with or without a
        snapshot.
        """
        if not self._ledger_pending or self._state_store is None:
            return
        for dev_href in list(self._ledger_pending):
            edev = self._state.end_devices.get(dev_href)
            if edev is None:
                continue
            self._ledger_pending.discard(dev_href)
            self._restore_ledger(edev.lfdi)

    def _restore_ledger(self, lfdi: bytes) -> None:
        """Count the Responses recorded for ``lfdi`` in the shared state as sent."""
        assert self._state_store is not None
        for mrid_hex, status, at in self._state_store.responses(lfdi.hex()):
            self._response_tracker.restore(
                bytes.fromhex(mrid_hex), ResponseCode(status), lfdi, int(at)
            )

    def _share_adjusted_offsets(self, mrid: bytes, device: str, offsets: tuple[int, int]) -> None:
        """Replace a device's shared offsets with ones adjusted for a successive event."""
        if self._state_store is None:
            return
        try:
            self._state_store.forget_offsets(mrid.hex(), device)
            shared = self._state_store.claim_offsets(mrid.hex(), device, offsets)
        except Exception:
            logger.warning(
                "Could not share the adjusted timing of %s", mrid.hex()[:8], exc_info=True
            )
            return
        if tuple(shared) != offsets:
            logger.warning(
                "Event %s: another process stored a different timing while it was adjusted",
                mrid.hex()[:8],
            )

    def _persist(self, devices: Iterable[str] | None = None) -> set[str]:
        """Save the snapshot of each EndDevice this process acts for that changed.

        ``devices`` saves those devices, released ones included; None saves
        every device not released. A no-op without a shared store. A store
        that fails is logged and tried again at the next save; it never stops
        event processing. Returns the devices whose save failed.
        """
        failed: set[str] = set()
        if self._state_store is None:
            return failed
        if devices is None:
            hrefs = [h for h in self._state.end_devices if h not in self._released]
        else:
            hrefs = [h for h in devices if h in self._state.end_devices]
        for dev_href in hrefs:
            edev = self._state.end_devices[dev_href]
            try:
                snapshot = self._device_snapshot(dev_href, edev.lfdi)
                if self._saved.get(dev_href) == snapshot:
                    continue
                self._state_store.save_device(dev_href, snapshot)
            except Exception:
                logger.warning(
                    "Could not save the event state of %s; will retry", dev_href, exc_info=True
                )
                failed.add(dev_href)
                continue
            self._saved[dev_href] = snapshot
        return failed

    def load_devices(self, device_hrefs: Iterable[str]) -> int:
        """Load the saved event state of EndDevices taken over from another process.

        Merges each device's events into this processor: an event already held
        here gains the device's applied, rejected and superseded marks; an
        event not held here is created from the snapshot, with its saved
        timing, and its activation or completion timer is scheduled by
        :meth:`resume_devices`. Responses
        already posted for the devices are counted as sent, the DefaultDERControl
        last applied to each is remembered, and the loss-of-communications
        resume boundary is kept for those devices only. The Response ledger
        of a device without a snapshot is restored once discovery gives its
        LFDI. Returns how many snapshots were loaded.

        Call before the rediscovery that adds the devices, so the events are
        known when their controls are fetched, then :meth:`resume_devices`
        after it.
        """
        hrefs = list(device_hrefs)
        # This process acts for the devices again, with a store or without one.
        self._released.difference_update(hrefs)
        if self._state_store is None:
            return 0
        loaded = 0
        for dev_href in hrefs:
            self._saved.pop(dev_href, None)
            self._ledger_pending.add(dev_href)
            self._awaiting_resume.add(dev_href)
            snapshot = self._state_store.load_device(dev_href)
            if not snapshot or snapshot.get("version") != SNAPSHOT_VERSION:
                continue
            lfdi = bytes.fromhex(snapshot["lfdi"])
            for entry in snapshot.get("events", []):
                self._merge_event(dev_href, entry)
            for entry in snapshot.get("defaults", []):
                content = entry.get("content")
                # A snapshot from an older release has no modes. The default is
                # then written once more so its modes are recorded.
                modes = entry.get("modes")
                self._dderc_tracker.record_application(
                    lfdi,
                    entry["program_href"],
                    bytes.fromhex(entry["mrid"]),
                    entry["primacy"],
                    frozenset(modes) if modes is not None else None,
                    bytes.fromhex(content) if content else None,
                )
            resume_after = snapshot.get("comms_loss", {}).get("resume_after")
            if resume_after is not None:
                current = self._imported_resume_after.get(dev_href, 0)
                self._imported_resume_after[dev_href] = max(current, int(resume_after))
            self._restore_ledger(lfdi)
            loaded += 1
        return loaded

    def _merge_event(self, dev_href: str, entry: dict[str, Any]) -> None:
        """Merge one EndDevice's view of an event into this processor's record of it."""
        from py20305.xml.serialization import from_xml

        mrid = bytes.fromhex(entry["mrid"])
        record = self._store.get(mrid)
        window = entry.get("window") or [entry["start"], entry["start"] + entry["duration"]]
        start, end = int(window[0]), int(window[1])
        if record is None:
            derc = from_xml(entry["control"], Dercontrol1)
            record = EventRecord(
                mrid=mrid,
                derc=derc,
                program_href=entry["program_href"],
                primacy=entry["primacy"],
                state=EventState(entry["state"]),
                start=start,
                duration=end - start,
                server_status_time=entry["server_status_time"],
                creation_time=entry["creation_time"],
                opted_out=entry["opted_out"],
            )
            self._store.upsert(record)
            fallback_at = entry.get("fallback_at")
            if record.state == EventState.CANCELLED and fallback_at is not None:
                # Keep the delayed default-control fallback, and the guard its
                # timer gives, for the time it still had to wait.
                self._fallback_due[mrid] = int(fallback_at)
                self._timer_mgr.schedule_delayed_callback(
                    record,
                    max(0, int(fallback_at) - int(time.time())),
                    self._wind_down,
                    "wind-down",
                )
        else:
            incoming = EventState(entry["state"])
            if (
                record.state in (EventState.SUPERSEDED, EventState.COMPLETED)
                and incoming in (EventState.SCHEDULED, EventState.ACTIVE)
                and not entry["superseded"]
                and not entry.get("ended")
            ):
                # Superseded or completed here only on this process's devices:
                # the incoming device's own window is still open, so the event
                # keeps its timers and its completion for that device. The local
                # devices stay superseded, or are marked ended, so they are not
                # told again how the event ended on them.
                if record.state == EventState.COMPLETED:
                    local = (
                        set(record.device_windows)
                        | record.applied_devices
                        | record.rejected_devices
                    )
                    record.started_devices |= local
                    record.ended_devices |= local
                record.state = incoming
            if entry["opted_out"] and not record.opted_out:
                # Opted out on the incoming device only. The event goes on for
                # this process's devices; the incoming device gets no control
                # and no further lifecycle Response for it.
                record.rejected_devices.add(dev_href)
        # The device keeps the window, and so the offsets, it drew.
        record.set_window(dev_href, start, end)
        raw_start = record.derc.interval.start.value
        raw_duration = record.derc.interval.duration
        self._rand_cache.seed(mrid, dev_href, (start - raw_start, end - start - raw_duration), end)
        if entry.get("started"):
            record.started_devices.add(dev_href)
        if entry.get("ended"):
            record.ended_devices.add(dev_href)
        if entry["applied"]:
            record.applied_devices.add(dev_href)
        if entry["rejected"]:
            record.rejected_devices.add(dev_href)
        if entry["superseded"]:
            record.superseded_devices.add(dev_href)
        withdrawn = bool(entry.get("withdrawn"))
        if withdrawn:
            record.withdrawn_devices.add(dev_href)
        if entry.get("superseded_modes") is not None:
            held = record.superseded_modes.get(dev_href, frozenset())
            record.superseded_modes[dev_href] = held | frozenset(entry["superseded_modes"])
        running = record.state == EventState.ACTIVE and not record.opted_out
        if running and entry["applied"] and not entry["opted_out"] and not withdrawn:
            # Registered even when superseded on the device, as dispatch leaves
            # it: the tracker subtracts the modes other events cover. A device
            # withdrawn from the program had the event's modes released, so
            # they are not registered again.
            modes = get_active_mode_names(record.derc.dercontrol_base)
            self._mode_tracker.register(dev_href, mrid, modes)

    async def resume_devices(self, device_hrefs: Iterable[str]) -> None:
        """Apply running events to taken-over EndDevices that never received them.

        For a device the previous process stopped acting for in the middle of
        an activation, or one that joins a running event without a snapshot:
        the event is active, but the device was neither told it started nor
        told it was rejected. It gets the ACKNOWLEDGED Response unless one was
        posted for it, then the control and its ACTIVE Response. A device
        already marked applied or rejected gets nothing, so no control and no
        Response is sent twice. While in loss-of-communications mode the event
        is opted out instead, as on entering that mode.

        Not done for a program under a group lookup, whose dispatch goes to the
        group's local devices rather than to the EndDevices named here.

        Then schedules each taken-over device's own activation and completion
        at its window's start and end. They wait until now so an event does
        not activate before the devices it applies to are mapped. A device
        whose window has ended is not applied: on an active event it completes
        at once, with its Responses and fallback, and on a scheduled one it is
        left to expire.
        """
        with self._working():
            await self._resume_devices(set(device_hrefs))

    async def _resume_devices(self, taken: set[str]) -> None:
        """Resume taken-over devices; see :meth:`resume_devices`."""
        self._restore_pending_ledgers()
        self._awaiting_resume -= taken
        for record in self._store.values():
            if record.state not in (EventState.SCHEDULED, EventState.ACTIVE):
                continue
            if record.opted_out or self._closed:
                continue
            pending = self._time_taken_devices(record, taken)
            if not pending:
                continue
            if self._group_local_lfdis(record.program_href) is not None:
                logger.warning(
                    "Event %s: not applying to taken-over devices under a group lookup",
                    record.mrid.hex()[:8],
                )
                continue
            if self._comms_loss.active:
                await self._opt_out_event(record, from_state=EventState.ACTIVE.value)
                continue
            logger.info(
                "Event %s: applying to %d taken-over device(s)", record.mrid.hex()[:8], len(pending)
            )
            # A device that joins a running event is told it was received first,
            # as on late discovery. The tracker skips one already posted.
            await self._post_response_for_devices(record.derc, ResponseCode.ACKNOWLEDGED, pending)
            record.started_devices |= pending
            await self._apply_and_respond(record, only=pending)
            self._schedule_completions(record, pending)
        self._persist()

    def _time_taken_devices(self, record: EventRecord, taken: set[str]) -> set[str]:
        """Schedule taken-over devices' own timers. Return those to apply now.

        A device to apply now is in its window on a running event and was
        neither told the event started nor that it was rejected.
        """
        now = self._event_now(record)
        mapped = set(self._unique_devices(record.program_href))
        later: list[str] = []
        running: set[str] = set()
        apply_now: set[str] = set()
        for device in taken & (mapped | set(record.device_windows)):
            if device in record.ended_devices:
                continue
            start, end = record.window(device)
            # A device whose window started but that was neither applied nor
            # rejected was mid-activation when the previous process stopped.
            handled = device in (
                record.applied_devices | record.rejected_devices | record.superseded_devices
            )
            if handled:
                if record.state == EventState.ACTIVE:
                    record.started_devices.add(device)
                    running.add(device)
                continue
            if end <= now:
                if record.state == EventState.ACTIVE:
                    # Its window ended while no process acted for it: nothing is
                    # applied, and it completes at once.
                    running.add(device)
                else:
                    logger.info(
                        "Event %s: ended on %s while no process acted for it; not activated",
                        record.mrid.hex()[:8],
                        device,
                    )
                continue
            if start > now or record.state == EventState.SCHEDULED:
                later.append(device)
                continue
            apply_now.add(device)
        if later:
            self._schedule_activations(record, later)
        if running:
            self._schedule_completions(record, running)
        return apply_now

    def _event_now(self, record: EventRecord) -> int:
        """Return the server time on the clock of the event's program."""
        return int(self._timebase.now(self._fsa_scope(record.program_href)))

    async def release_devices(self, device_hrefs: Iterable[str]) -> None:
        """Stop acting for EndDevices another process will take over.

        New work leaves the devices out at once. Work already running for
        them (an activation, a control write, a Response) is allowed to finish
        first, so the snapshot saved next shows what reached the device and the
        server. Then their snapshots are saved, and their state forgotten: an
        event that concerns only released devices is forgotten here without a
        state change, a Response or a write to a device; its timers are
        cancelled and the taking-over process carries it on. An event that
        also concerns devices this process keeps loses only the released
        devices' marks. Call before the rediscovery that removes the devices,
        and not from a dispatcher or another event callback, which would wait
        for itself.

        Raises the store's error when a snapshot cannot be saved. The devices
        then stay with this process, their state kept, and the call can be
        made again.
        """
        released = set(device_hrefs)
        newly_released = released - self._released
        self._released |= released
        while True:
            if self._busy:
                await self._idle.wait()
                continue
            writes = [task for task in self._dispatch_tasks if not task.done()]
            if writes:
                await asyncio.gather(*writes, return_exceptions=True)
                continue
            break
        failed = self._persist(devices=released)
        if failed:
            self._released -= newly_released
            raise RuntimeError(
                f"could not save the event state of {', '.join(sorted(failed))}; "
                "the devices are still acted for here"
            )
        mapping = self._state.device_mapping.program_to_devices
        for dev_href in released:
            self._saved.pop(dev_href, None)
            self._ledger_pending.discard(dev_href)
            self._awaiting_resume.discard(dev_href)
            self._imported_resume_after.pop(dev_href, None)
            edev = self._state.end_devices.get(dev_href)
            if edev is not None:
                self._dderc_tracker.clear_devices({edev.lfdi})
        for record in self._store.values():
            devices = set(mapping.get(record.program_href, []))
            for dev_href in released:
                self._mode_tracker.unregister(dev_href, record.mrid)
            if devices and devices <= released:
                self._timer_mgr.cancel(record.mrid)
                self._store.remove(record.mrid)
                self._control_xml.pop(record.mrid, None)
                self._fallback_due.pop(record.mrid, None)
                continue
            record.applied_devices -= released
            record.rejected_devices -= released
            record.superseded_devices -= released
            record.withdrawn_devices -= released
            record.started_devices -= released
            record.ended_devices -= released
            for dev_href in released:
                record.superseded_modes.pop(dev_href, None)
                record.device_windows.pop(dev_href, None)

    async def enter_comms_loss(self) -> None:
        """Opt out of every active event and revert devices to the planning limit.

        Loss-of-communications entry: each active event is marked
        opted-out, its timers cancelled, and its devices reverted to DDERC (or
        cleared to the connector safe-default where no DDERC exists). No IEEE
        2030.5 responses are posted -- comms are down. The resume boundary is
        raised to the latest opted-out event end so recovery resumes only the
        schedule that follows it. Events stay in ACTIVE state (the ``opted_out``
        flag is the marker), so supersession and classification are unaffected.
        """
        with self._working():
            await self._enter_comms_loss()

    async def _enter_comms_loss(self) -> None:
        """Opt out of every active event; see :meth:`enter_comms_loss`."""
        active = [r for r in self._store.by_state(EventState.ACTIVE) if not r.opted_out]
        if not active:
            return
        boundary = self._comms_loss.resume_after_epoch or 0
        self._comms_loss.resume_after_epoch = max(boundary, max(r.end for r in active))
        # Flag all opted-out first so per-record reverts see no "other active"
        # event still covering a shared device.
        for record in active:
            record.opted_out = True
            self._timer_mgr.cancel(record.mrid)
            self._audit_transition(record, EventState.ACTIVE.value, "opted_out")
        for record in active:
            await self._apply_dderc_fallback(record, clear_if_no_dderc=True)
        self._persist()

    async def _opt_out_event(self, record: EventRecord, *, from_state: str | None) -> None:
        """Opt a single event out (comms-loss gate on activation/late discovery).

        Marks the event opted-out, raises the resume boundary to its end,
        cancels its timers, and reverts its devices to DDERC/clear. No response
        is posted.

        ``from_state`` is the state the audit record reports the event leaving:
        ``scheduled`` at activation, ``None`` for an event first seen already
        running.
        """
        record.opted_out = True
        self._audit_transition(record, from_state, "opted_out")
        boundary = self._comms_loss.resume_after_epoch or 0
        self._comms_loss.resume_after_epoch = max(boundary, record.end)
        self._timer_mgr.cancel(record.mrid)
        await self._apply_dderc_fallback(record, clear_if_no_dderc=True)

    async def _apply_dderc_fallback(
        self,
        record: EventRecord,
        *,
        clear_if_no_dderc: bool = False,
        only: Collection[str] | None = None,
        exclude: set[str] | None = None,
    ) -> None:
        """Apply per-mode DDERC fallback for modes released by the completing event.

        When an event completes/cancels/supersedes, unregister its modes from the
        tracker. Devices whose released modes are not covered by any other active
        event get DDERC applied. If no modes were tracked (empty DercontrolBase),
        fall back to checking whether other active events cover the device.

        The devices are the program's current devices and every device the
        event is still registered on. A device withdrawn from the program while
        the event ran is only in the second group, and it still holds the
        event's modes until they are released here.

        ``clear_if_no_dderc`` is the comms-loss opt-out failsafe: a device
        with no DDERC on any program is dispatched a connector clear instead of
        being left untouched. Opted-out events (``record.opted_out``) are ignored
        when deciding whether another active event still covers a device, so
        opting out every active event reverts the device to its planning limit.

        ``only`` limits the fallback to those devices: devices whose own window
        ended, or devices withdrawn from the program. The event keeps running on
        the others. ``exclude`` leaves out devices that fell back already.
        """
        candidates = dict.fromkeys(
            [
                *self._unique_devices(record.program_href),
                *sorted(self._mode_tracker.devices_of(record.mrid)),
            ]
        )
        all_devices = [
            d
            for d in candidates
            if (only is None or d in only) and (exclude is None or d not in exclude)
        ]
        # Asked in the vocabulary the supersession answered in. ``superseded_modes``
        # is recorded from the keys supersession compares, which leave out connect
        # and energize and do not reach extension elements, so measuring it against
        # every mode the event sets would read a device taken over whole as only
        # partly taken over -- for an event carrying nothing but CSIP-AUS limits,
        # always.
        owned = compared_mode_keys(record.derc.dercontrol_base)
        active_events = [r for r in self._store.by_state(EventState.ACTIVE) if not r.opted_out]
        # Devices with no DDERC anywhere: cleared to the connector safe-default
        # only in the comms-loss opt-out flow; the completion path leaves
        # them untouched as before.
        clear_targets: list[tuple[str, bytes]] = []

        # Unregister modes and compute per-device fallback needs
        needs_fallback: list[str] = []
        released_modes: dict[str, frozenset[str]] = {}
        for dev_href in all_devices:
            # Unregistered for every device, superseded ones included. Leaving
            # the registration would have the tracker believe this event still
            # owns those modes, so the event that took them over would release
            # nothing when it ends and they would stay on the device for good.
            released = self._mode_tracker.unregister(dev_href, record.mrid)
            released_modes[dev_href] = released
            # Dispatching is the separate question. A device another event took
            # over *entirely* is left to it: its activation is the write that
            # moves the device, and a fallback here would name this event as the
            # cause of a setpoint it no longer sets. Entirely, though -- a device
            # goes into ``superseded_devices`` when another event takes over any
            # one of this event's modes there, and the modes that event never
            # took are still this event's to release. Compared per mode.
            # ... and only while another event is actually running on the device.
            # Once the event that took it over has ended too, nothing is left to
            # bring the device back, so the last event to end releases it.
            if (
                dev_href in record.superseded_devices
                and record.superseded_modes.get(dev_href, frozenset()) >= owned
                and self._device_has_other_active(dev_href, record.mrid, active_events)
            ):
                continue
            if released:
                # Some modes were released and not covered by other events
                needs_fallback.append(dev_href)
            elif not self._device_has_other_active(dev_href, record.mrid, active_events):
                # No modes tracked (empty base) but no other active events either
                needs_fallback.append(dev_href)

        if not needs_fallback:
            return

        # Each device gets its default mode by mode (IEEE 2030.5-2023
        # §10.10.4.2.1): a mode comes from the default of the lowest-primacy
        # program that names it. The lowest-primacy default is always sent, as
        # one default always was; a default of another program is sent only
        # for the modes it supplies. Each target: device href, LFDI, program,
        # the default as sent, and the content digest of the program's whole
        # default.
        dderc_targets: list[tuple[str, bytes, DerProgramState, DefaultDercontrol, bytes]] = []
        # Modes the ended event set that the default does not carry. The
        # default only writes the modes it names, so these would stay in
        # effect on the device unless they are disabled here.
        withdraw_targets: list[tuple[str, frozenset[str]]] = []
        # Modes carried by the default of a device that falls back to one.
        default_modes: set[str] = set()
        for dev_href in needs_fallback:
            lfdi = self._get_device_lfdi(dev_href)
            if lfdi is None:
                continue
            selection = self._default_modes_by_program(dev_href)
            released = released_modes.get(dev_href, frozenset())
            if not selection:
                if clear_if_no_dderc:
                    clear_targets.append((dev_href, lfdi))
                elif released:
                    logger.debug(
                        "Event %s: no DDERC for device %s, disabling the modes it released",
                        record.mrid.hex()[:8],
                        dev_href,
                    )
                    withdraw_targets.append((dev_href, released))
                else:
                    logger.debug(
                        "Event %s: no DDERC for device %s, no revert action taken",
                        record.mrid.hex()[:8],
                        dev_href,
                    )
                continue
            written_on_device: set[str] = set()
            for rank, (program, supplied) in enumerate(selection):
                if rank > 0 and not supplied:
                    continue
                default = program.default_dercontrol
                assert default is not None  # guaranteed by _default_modes_by_program
                carried = get_active_mode_names(default.dercontrol_base)
                # A default is the baseline for the modes no event is controlling,
                # and this project does not let it override one. The default is
                # written whole, so where it names a mode an event that is still
                # running holds, applying it would take that mode from the event
                # that owns it. Withhold it there and disable what this event
                # released instead: the event still holding the device keeps what
                # is its, and its own end brings the default back for everything at
                # once. Recorded as a decision rather than quoted from the standard
                # -- see the note on `_modes_running_in`.
                # The default belongs to ``program.href``, which need not be the
                # ending event's program: under a group lookup it fans out to *that*
                # program's local devices, so that is what the write reaches.
                held = self._modes_running_in(
                    self._reach_of(program.href, [dev_href]), active_events
                )
                outranked = carried - supplied
                running = supplied & held
                if running:
                    logger.debug(
                        "Event %s: sending the default for %s without %s, which "
                        "another running event is controlling",
                        record.mrid.hex()[:8],
                        dev_href,
                        sorted(running),
                    )
                # Taken here rather than in the dispatch loop below, which is still
                # before any await: a refresh during dispatch can replace the
                # program's default, and recording the replacement would have the
                # next pass skip a default the device never received.
                taken = frozenset(outranked | running)
                effective = (
                    self._default_without(default, taken, settings=rank > 0)
                    if taken or rank > 0
                    else default
                )
                written = carried - taken
                written_on_device |= written
                # Nothing left to send only when the default had modes and every one
                # of them is being controlled. A default that names nothing still
                # goes out: it always did, and masking cannot have emptied it.
                emptied = bool(carried) and not written
                if not emptied and self._dderc_tracker.should_apply(
                    lfdi, program.href, program.primacy
                ):
                    dderc_targets.append(
                        (dev_href, lfdi, program, effective, _default_content(default))
                    )
            default_modes |= written_on_device
            uncovered = released - written_on_device
            if uncovered:
                withdraw_targets.append((dev_href, uncovered))

        # Dispatch DDERC in parallel, then update tracker for successes.
        # With a group lookup supplied, each server-side EDev resolves
        # to the program's local sub-device LFDIs; dispatch by LFDI then.
        # Cache the lookup per target so a mid-await groups rebuild can't
        # change the fan-out width between the build and attribution loops.
        if dderc_targets:
            plans: list[
                tuple[str, bytes, DerProgramState, list[str] | None, DefaultDercontrol, bytes]
            ] = [
                (
                    dev_href,
                    lfdi,
                    best_prog,
                    self._group_local_lfdis(best_prog.href),
                    effective,
                    content,
                )
                for dev_href, lfdi, best_prog, effective, content in dderc_targets
            ]
            # Both reasons land on the same DDERC write, and they read very
            # differently in an audit trail: "an event ended so the default came
            # back" versus "the upstream went away so we fell to the planning
            # limit". Distinguishing them here is what makes the recorded origin
            # answer why a setpoint moved.
            origin = (
                CommandOrigin.COMMS_LOSS if self._comms_loss.active else CommandOrigin.DDERC_REAPPLY
            )
            coros: list[Coroutine[Any, Any, None]] = []
            for dev_href, _, best_prog, local_lfdis, dderc, _content in plans:
                if local_lfdis is not None:
                    coros.extend(
                        self._dispatcher.apply_default_control_by_lfdi(
                            lfdi,
                            dderc,
                            best_prog.der_curves,
                            origin=origin,
                            cause_mrid=record.mrid,
                        )
                        for lfdi in local_lfdis
                    )
                else:
                    coros.append(
                        self._dispatcher.apply_default_control(
                            dev_href,
                            dderc,
                            best_prog.der_curves,
                            origin=origin,
                            cause_mrid=record.mrid,
                        )
                    )
            results = await asyncio.gather(*coros, return_exceptions=True)

            # The tracker is keyed by the server-side device LFDI (one entry
            # per dderc_target); collapse per-fan-out results down to one
            # success per target so the tracker isn't double-recorded.
            idx = 0
            for dev_href, lfdi, best_prog, local_lfdis, dderc, content in plans:
                n = len(local_lfdis) if local_lfdis is not None else 1
                target_results = results[idx : idx + n]
                idx += n
                failure = self._default_control_failure(target_results)
                if failure is not None:
                    logger.warning(
                        "Event %s: DDERC dispatch to %s failed: %s",
                        record.mrid.hex()[:8],
                        dev_href,
                        failure,
                    )
                else:
                    # The default's mRID, not the ended event's: the
                    # initial-default pass compares against it to skip a
                    # default that is already in place. Recorded for a default
                    # sent without some of its modes too, since that pass sends
                    # the same partial default to a device that still has a
                    # running event and would otherwise write it a second time.
                    # The event still running can bring the whole default back
                    # when it ends: this fallback checks primacy, not the mRID.
                    self._dderc_tracker.record_application(
                        lfdi,
                        best_prog.href,
                        dderc.m_rid.value,
                        best_prog.primacy,
                        get_active_mode_names(dderc.dercontrol_base),
                        content,
                    )

        if withdraw_targets:
            # Same fan-out as the DDERC path: by local LFDI when a group
            # lookup maps the server-side device to sub-devices, else by href.
            local_lfdis = self._group_local_lfdis(record.program_href)
            withdraw_coros: list[Coroutine[Any, Any, None]] = []
            if local_lfdis is not None:
                # A group lookup is keyed by program, so every server-side
                # device of the program stands for the same local devices. A
                # mode is disabled on them only when no server-side device
                # still needs it: none holds it from another event, and no
                # default restored above carries it. Sending each device's
                # released modes to every local device would disable a mode
                # that another event still controls there.
                still_needed = set(default_modes)
                for dev_href in all_devices:
                    still_needed |= self._mode_tracker.covered(dev_href, excluding=record.mrid)
                modes_for_program: frozenset[str] = (
                    frozenset().union(*(modes for _dev_href, modes in withdraw_targets))
                    - still_needed
                )
                if modes_for_program:
                    withdraw_coros.extend(
                        self._dispatcher.disable_modes_by_lfdi(
                            local, modes_for_program, cause_mrid=record.mrid
                        )
                        for local in dict.fromkeys(local_lfdis)
                    )
            else:
                withdraw_coros.extend(
                    self._dispatcher.disable_modes(dev_href, modes, cause_mrid=record.mrid)
                    for dev_href, modes in withdraw_targets
                )
            withdraw_results = await asyncio.gather(*withdraw_coros, return_exceptions=True)
            for failure in (r for r in withdraw_results if isinstance(r, Exception)):
                logger.warning(
                    "Event %s: disabling released modes failed: %s",
                    record.mrid.hex()[:8],
                    failure,
                )

        if clear_targets:
            # No DDERC to fall back to: clear the device to the connector
            # safe-default. Any fan-out is per-program (the same grouping
            # as the DDERC path above), so it is
            # built once -- not per target device, which would dispatch
            # duplicate clears to every local sub-device. Otherwise clear each
            # server-side device href directly.
            local_lfdis = self._group_local_lfdis(record.program_href)
            clear_coros: list[Coroutine[Any, Any, None]] = []
            if local_lfdis is not None:
                # dict.fromkeys: group_lookup and DeviceMapping.add don't dedup,
                # so guard against dispatching the same clear twice.
                clear_coros.extend(
                    self._dispatcher.clear_control_by_lfdi(local, cause_mrid=record.mrid)
                    for local in dict.fromkeys(local_lfdis)
                )
            else:
                clear_coros.extend(
                    self._dispatcher.clear_control(dev_href, cause_mrid=record.mrid)
                    for dev_href in dict.fromkeys(dev_href for dev_href, _lfdi in clear_targets)
                )
            clear_results = await asyncio.gather(*clear_coros, return_exceptions=True)
            for failure in (r for r in clear_results if isinstance(r, Exception)):
                logger.warning(
                    "Event %s: comms-loss clear dispatch failed: %s",
                    record.mrid.hex()[:8],
                    failure,
                )

    async def _apply_initial_dderc(self, program_href: str) -> None:
        """Apply the program's DefaultDERControl to each device, mode by mode.

        Called at the end of process_controls so a device is in its default
        operating state wherever no event overrides it. IEEE 2030.5-2023
        §10.10.4.2.1 reads per DERControl Mode: a mode with no active event in
        any program is managed by the default of the program with the lowest
        primacy that contains it. A device that has an active event therefore
        still takes the default's modes that no event controls there, and
        does not take the modes an event does control. Applies only if:
        - The program has a DefaultDERControl
        - No wind-down timers are pending (cancelled event with delayed fallback)
        - The DDERC hasn't already been applied (tracked by DdercTracker)
        - The default names a mode no active event controls on the device. A
          default that names no mode at all waits for the device's active
          events to end.
        """
        derp_state = self._state.der_programs.get(program_href)
        if derp_state is None or derp_state.default_dercontrol is None:
            logger.debug(
                "Initial DDERC skip %s: no DDERC (state=%s, dderc=%s)",
                program_href,
                derp_state is not None,
                derp_state.default_dercontrol is not None if derp_state else False,
            )
            return

        # Skip if any cancelled event from this program still has pending
        # timers (wind-down delay before DDERC fallback).
        cancelled = self._store.by_state(EventState.CANCELLED)
        if any(
            evt.program_href == program_href and self._timer_mgr.has_pending(evt.mrid)
            for evt in cancelled
        ):
            logger.debug("Initial DDERC skip %s: cancelled event with pending timer", program_href)
            return

        devices = self._unique_devices(program_href)
        if not devices:
            logger.debug("Initial DDERC skip %s: no devices in mapping", program_href)
            return

        # Devices that have an ACTIVE event in ANY program. Opted-out events
        # (comms-loss) don't control their devices -- the device was reverted to
        # DDERC -- so they're excluded here, consistent with
        # _apply_dderc_fallback's "other active" check. A device the event was
        # *rejected* on is the same situation and excluded for the same reason:
        # the control was refused, so nothing is holding that device, and without
        # this it would sit under no control at all for the event's whole duration
        # rather than under its default.
        active_events = [e for e in self._store.by_state(EventState.ACTIVE) if not e.opted_out]
        active_devices: set[str] = set()
        for evt in active_events:
            evt_devs = self._state.device_mapping.program_to_devices.get(evt.program_href, [])
            for d in evt_devs:
                if (
                    d not in evt.superseded_devices
                    and d not in evt.rejected_devices
                    and evt.runs_on(d)
                ):
                    active_devices.add(d)

        dderc_mrid = derp_state.default_dercontrol.m_rid.value
        dderc_content = _default_content(derp_state.default_dercontrol)
        carried = get_active_mode_names(derp_state.default_dercontrol.dercontrol_base)

        # Each target is sent the default without the modes that something
        # else governs on it (IEEE 2030.5-2023 §10.10.4.2.1): the modes a
        # running event holds where the write lands, and the modes the default
        # of a higher-priority program supplies. A device with neither gets the
        # whole default. Under a group lookup the write reaches the program's
        # local devices whichever server-side device it was decided for, so every
        # target resolves to the same reach and the same held modes.
        targets: list[tuple[str, bytes, DefaultDercontrol, frozenset[str]]] = []
        for dev_href in devices:
            lfdi = self._get_device_lfdi(dev_href)
            if lfdi is None:
                continue

            held = self._modes_running_in(self._reach_of(program_href, [dev_href]), active_events)
            selection = self._default_modes_by_program(dev_href)
            supplied = {p.href: modes for p, modes in selection}
            # The lowest-primacy default also carries the settings that are not
            # modes; a default beside it supplies only modes.
            lead = not selection or selection[0][0].href == program_href
            taken = (carried - supplied.get(program_href, carried)) | (carried & held)
            written = carried - taken
            if carried and not written:
                logger.debug(
                    "Initial DDERC skip %s: every mode it names is governed elsewhere on %s",
                    program_href,
                    dev_href,
                )
                continue

            if not self._dderc_tracker.should_apply_initial(
                lfdi, program_href, dderc_mrid, derp_state.primacy, written, dderc_content
            ):
                logger.debug(
                    "Initial DDERC skip %s: tracker blocked for %s (primacy=%d)",
                    program_href,
                    dev_href,
                    derp_state.primacy,
                )
                continue
            if not carried and dev_href in active_devices:
                logger.debug(
                    "Initial DDERC skip %s: %s has an active event and the default names no mode",
                    program_href,
                    dev_href,
                )
                continue
            if taken:
                logger.debug(
                    "Initial DDERC from %s sent to %s without %s, which something else governs",
                    program_href,
                    dev_href,
                    sorted(taken),
                )
            effective = (
                self._default_without(derp_state.default_dercontrol, taken, settings=not lead)
                if taken or not lead
                else derp_state.default_dercontrol
            )
            targets.append((dev_href, lfdi, effective, written))

        if not targets:
            logger.debug("Initial DDERC skip %s: no eligible devices", program_href)
            return

        logger.info(
            "Applying initial DDERC from %s to %d device(s)",
            program_href,
            len(targets),
        )
        curves = derp_state.der_curves
        # With a group lookup supplied, each server-side EDev resolves
        # to the program's local sub-device LFDIs.
        local_lfdis = self._group_local_lfdis(program_href)
        coros: list[Coroutine[Any, Any, None]] = []
        for dev_href, _, dderc, _written in targets:
            if local_lfdis is not None:
                coros.extend(
                    self._dispatcher.apply_default_control_by_lfdi(lfdi, dderc, curves)
                    for lfdi in local_lfdis
                )
            else:
                coros.append(self._dispatcher.apply_default_control(dev_href, dderc, curves))
        results = await asyncio.gather(*coros, return_exceptions=True)

        per_target_n = len(local_lfdis) if local_lfdis is not None else 1
        idx = 0
        for dev_href, lfdi, _, written in targets:
            target_results = results[idx : idx + per_target_n]
            idx += per_target_n
            failure = self._default_control_failure(target_results)
            if failure is not None:
                logger.warning("Initial DDERC dispatch to %s failed: %s", dev_href, failure)
            else:
                # Recorded with the modes it carried, so the next poll does not
                # write the same modes again but does write one that was freed
                # since. The end of a running event still brings the whole
                # default back: the fallback checks primacy, and the program is
                # the same.
                self._dderc_tracker.record_application(
                    lfdi, program_href, dderc_mrid, derp_state.primacy, written, dderc_content
                )

    def _default_modes_by_program(
        self, dev_href: str
    ) -> list[tuple[DerProgramState, frozenset[str]]]:
        """Return each program whose default applies to a device, with the modes it supplies.

        IEEE 2030.5-2023 §10.10.4.2.1: a mode no active control holds is managed
        by the default of the program with the lowest primacy that contains it.
        The programs come in that order, and each supplies the modes of its
        default that no program before it names. The first program is the one
        with the lowest primacy; programs of equal primacy rank in discovery
        order, so a mode two of them name has one source. Read from the programs
        as they stand, not from what was written before: the record of earlier
        writes is cleared when an event arrives and says nothing about
        precedence. Both the initial pass and the end-of-event fallback ask this,
        so the two cannot choose differently.
        """
        ranked: list[tuple[int, int, DerProgramState]] = []
        programs = self._state.device_mapping.device_to_programs.get(dev_href, [])
        for index, program_href in enumerate(dict.fromkeys(programs)):
            program = self._state.der_programs.get(program_href)
            if program is not None and program.default_dercontrol is not None:
                ranked.append((program.primacy, index, program))
        ranked.sort(key=lambda entry: entry[:2])
        claimed: set[str] = set()
        selection: list[tuple[DerProgramState, frozenset[str]]] = []
        for _primacy, _index, program in ranked:
            assert program.default_dercontrol is not None
            carried = get_active_mode_names(program.default_dercontrol.dercontrol_base)
            selection.append((program, frozenset(carried - claimed)))
            claimed |= carried
        return selection

    @staticmethod
    def _default_control_failure(results: Sequence[object]) -> Exception | None:
        """Return the first failure among one device's default-control writes, or None.

        A connector that implements none of the default's modes raises
        ``ModeNotSupportedError``. Retrying cannot change that, and a default
        has no response to reject, so it is not a failure to retry or warn about
        on every poll: the write is treated as done and logged at debug level.
        """
        for result in results:
            if isinstance(result, ModeNotSupportedError):
                logger.debug("Default control not applied: %s", result)
            elif isinstance(result, Exception):
                return result
        return None

    @staticmethod
    def _default_without(
        dderc: DefaultDercontrol, modes: frozenset[str], *, settings: bool = False
    ) -> DefaultDercontrol:
        """The default with ``modes`` taken out of it.

        ``settings`` also takes out the settings that are not modes (``setGradW``
        and the enter-service settings). A default sent beside one of lower
        primacy leaves those to it.

        A default is written whole, so the only way to let it set the modes no
        event is controlling without disturbing the ones an event is, is to
        send a copy that does not name them. Base modes are cleared by field
        name and the CSIP-AUS limits by element name, which is the pair
        :func:`get_active_mode_names` returns them in.
        """
        base = dderc.dercontrol_base
        cleared: dict[str, Any] = {name: None for name in modes if name in type(base).model_fields}
        kept = [
            element
            for element in (base.other_element or [])
            if doe_element_name(element) not in modes
        ]
        if len(kept) != len(base.other_element or []):
            cleared["other_element"] = kept
        update: dict[str, Any] = {"dercontrol_base": base.model_copy(update=cleared)}
        if settings:
            update.update({element.field: None for element in DEFAULT_CONTROL_ELEMENTS})
        return dderc.model_copy(update=update)

    def _reach_of(self, program_href: str, devices: Sequence[str]) -> frozenset[str]:
        """What a write made for ``devices`` of ``program_href`` actually touches.

        Under a group lookup a program's write goes to its group's local
        devices whichever of its server-side devices it was decided for, so the
        group is the reach and the server-side device it was decided for says
        nothing about where it lands. Without one the write goes to the device
        it names. The two are tagged apart because a local LFDI and a device
        href are both strings and nothing stops them colliding.
        """
        local_lfdis = self._group_local_lfdis(program_href)
        if local_lfdis is not None:
            return frozenset(f"lfdi:{lfdi}" for lfdi in local_lfdis)
        return frozenset(f"href:{device}" for device in devices)

    def _modes_running_in(
        self, reach: frozenset[str], active_events: list[EventRecord]
    ) -> frozenset[str]:
        """The modes running events hold on anything ``reach`` touches.

        Asked of every active event rather than of a device list, because a
        group lookup maps *programs* to local devices: another program can
        cover server-side devices this one never names and still resolve to the
        same local device, and its modes are as much at risk from a write that
        lands there.
        """
        held: set[str] = set()
        for record in active_events:
            devices = list(
                self._state.device_mapping.program_to_devices.get(record.program_href, [])
            )
            if not reach & self._reach_of(record.program_href, devices):
                continue
            # Its registrations on the devices this write touches, not on all
            # of the program's. Without a group lookup the write lands on one
            # device, and an event registered on that program's other devices
            # may not be registered on this one -- rejected there, or
            # superseded there before it started. Counting those would hold a
            # mode back on a device nothing is controlling it on, and the
            # device would sit under neither the event nor the default.
            # With a group lookup the registrations are keyed by server-side
            # device while the write lands on local ones, so there is no
            # per-device correspondence to make and all of them count.
            one = frozenset({record.mrid})
            grouped = self._group_local_lfdis(record.program_href) is not None
            for device in devices:
                if grouped or f"href:{device}" in reach:
                    held |= self._mode_tracker.covered_among(device, one)
        return frozenset(held)

    def _device_has_other_active(
        self, dev_href: str, exclude_mrid: bytes, active_events: list[EventRecord]
    ) -> bool:
        """Check if any active event (other than exclude_mrid) applies to dev_href.

        A device the event was rejected on is not under its control -- the same
        reasoning that excludes superseded devices and opted-out events. Counting
        it would withhold the DDERC fallback on the strength of a control that was
        never applied.
        """
        for evt in active_events:
            if evt.mrid == exclude_mrid:
                continue
            prog_devices = self._state.device_mapping.program_to_devices.get(evt.program_href, [])
            if (
                dev_href in prog_devices
                and dev_href not in evt.superseded_devices
                and dev_href not in evt.rejected_devices
                and evt.runs_on(dev_href)
            ):
                return True
        return False

    def _unique_devices(self, program_href: str) -> list[str]:
        """The program's devices, each once, in discovery order.

        Every caller of this treats the list as dispatch targets, and a device
        listed twice is written to twice -- which for a real connector means two
        writes to hardware. ``DeviceMapping.add`` no longer admits a repeated
        pair, so this guards the case it cannot: state populated by an embedding
        application rather than by discovery.

        dict.fromkeys rather than a set because order is discovery order, which
        the response fan-out reports in.
        """
        devices = self._state.device_mapping.program_to_devices.get(program_href, [])
        # A device handed to another process gets no new dispatch from here.
        return [d for d in dict.fromkeys(devices) if d not in self._released]

    def _get_device_lfdi(self, dev_href: str) -> bytes | None:
        """Look up LFDI for a device href."""
        edev_state = self._state.end_devices.get(dev_href)
        if edev_state is not None:
            return edev_state.lfdi
        return None

    async def _post_response(
        self,
        derc: object,
        code: ResponseCode,
        program_href: str | None = None,
        exclude_devices: set[str] | None = None,
    ) -> None:
        """Post a DER response for each device in the program.

        Multi-device conformance (AGG tests) requires one response per device.
        The ResponseTracker deduplicates on ``(mrid, code, lfdi)`` so each
        device gets exactly one response per code.

        Args:
            derc: The DERControl being responded to
            code: The response code
            program_href: The program href containing the control (used to find devices)
            exclude_devices: Device hrefs to skip (e.g. superseded devices)
        """
        if not isinstance(derc, Dercontrol1):
            return

        devices = (
            [
                d
                for d in self._state.device_mapping.program_to_devices.get(program_href, [])
                if d not in self._released
            ]
            if program_href
            else []
        )

        if not devices:
            # No program mapping — fall back to any available LFDI.
            if exclude_devices:
                # The fallback guesses a device. With an exclusion set in play we
                # cannot check the guess against it (the mapping that would
                # resolve href -> LFDI is the thing that is missing), and posting
                # a lifecycle code to a device that was superseded or rejected
                # misreports the event. Silence is the safer error here.
                logger.warning(
                    "No device mapping for %s and %d device(s) excluded; skipping the "
                    "any-LFDI %s fallback rather than risk posting to an excluded device",
                    program_href,
                    len(exclude_devices),
                    code.name,
                )
                return
            lfdi = self._get_any_lfdi()
            if lfdi is None:
                logger.warning("No device LFDI available for response posting")
                return
            await post_der_response(
                self._http,
                derc,
                code,
                lfdi,
                self._response_tracker,
                now_ts=int(self._timebase.now()),
                supported_modes2=await self._supported_modes2(lfdi),
            )
            return

        for dev_href in devices:
            if exclude_devices and dev_href in exclude_devices:
                continue
            lfdi = self._get_device_lfdi(dev_href)
            if lfdi is not None:
                await post_der_response(
                    self._http,
                    derc,
                    code,
                    lfdi,
                    self._response_tracker,
                    now_ts=int(self._timebase.now()),
                    supported_modes2=await self._supported_modes2(lfdi),
                )

    async def _post_response_for_devices(
        self, derc: object, code: ResponseCode, device_hrefs: frozenset[str] | set[str]
    ) -> None:
        """Post a DER response for specific devices only."""
        if not isinstance(derc, Dercontrol1):
            return
        for dev_href in device_hrefs:
            lfdi = self._get_device_lfdi(dev_href)
            if lfdi is not None:
                await post_der_response(
                    self._http,
                    derc,
                    code,
                    lfdi,
                    self._response_tracker,
                    now_ts=int(self._timebase.now()),
                    supported_modes2=await self._supported_modes2(lfdi),
                )

    async def _supported_modes2(self, lfdi: bytes) -> int | None:
        """Return the DERControlType2 bits the device with ``lfdi`` can apply, if known.

        None when the server profile does not take ``modesResponded2``, since the
        response does not carry it.
        """
        profile = getattr(self._http, "profile", None)
        if profile is not None and not profile.sends_modes_responded2:
            return None
        supported = getattr(self._dispatcher, "supported_modes2", None)
        if supported is None:
            return None
        result = await supported(lfdi.hex())
        return result if isinstance(result, int) else None

    def _get_any_lfdi(self) -> bytes | None:
        """Get any available device LFDI for response posting."""
        for edev in self._state.end_devices.values():
            return edev.lfdi
        return None

    def _find_successive_predecessor(self, program_href: str, raw_start: int) -> EventRecord | None:
        """Find an event in the same program whose raw end equals raw_start.

        Used for IEEE 10.2.2.3 rule m) successive events detection.
        """
        for record in self._store.all_active_states():
            if record.program_href != program_href:
                continue
            # Check if raw end of predecessor matches raw start of this event
            raw_end = record.derc.interval.start.value + record.derc.interval.duration
            if raw_end == raw_start:
                return record
        return None

    @staticmethod
    def _is_server_cancelled(derc: object) -> bool:
        if not isinstance(derc, Dercontrol1):
            return False
        return derc.event_status is not None and derc.event_status.current_status == 2
closed property
closed: bool

Whether this processor has been shut down.

process_controls async
process_controls(program_href: str) -> None

Process all DERControls for a given DERProgram.

Called after polling discovers or refreshes DERControl data.

Source code in src/py20305/events/processor.py
async def process_controls(self, program_href: str) -> None:
    """Process all DERControls for a given DERProgram.

    Called after polling discovers or refreshes DERControl data.
    """
    with self._working():
        try:
            await self._process_controls(program_href)
        finally:
            self._persist()
cancel_program
cancel_program(program_href: str) -> None

Cancel all events from a removed program (Gap 3: IEEE 8.8.3).

Transitions all scheduled/active events from the given program to CANCELLED and cancels any pending timers.

Source code in src/py20305/events/processor.py
def cancel_program(self, program_href: str) -> None:
    """Cancel all events from a removed program (Gap 3: IEEE 8.8.3).

    Transitions all scheduled/active events from the given program to
    CANCELLED and cancels any pending timers.
    """
    cancelled_count = 0
    for record in self._store.all_active_states():
        if record.program_href == program_href:
            mrid_short = record.mrid.hex()[:8]
            logger.info("Cancelling event %s from removed program %s", mrid_short, program_href)
            from_state = record.state.value
            self._store.transition(record.mrid, EventState.CANCELLED)
            self._audit_transition(record, from_state, "cancelled")
            self._timer_mgr.cancel(record.mrid)
            # cancel_program is sync, but runs inside the event loop, so
            # _emit_relay's loop.create_task succeeds.
            self._relay_control_event(record, "cancelled")
            cancelled_count += 1
    # The program is gone -- drop its baseline relay slot so the cache stays
    # bounded by live program count.
    self._relay_snapshots.pop(("default_baseline", program_href), None)
    for mrid, program in list(self._audit_unstored_seen.items()):
        if program == program_href:
            del self._audit_unstored_seen[mrid]
    if cancelled_count:
        logger.info(
            "Cancelled %d event(s) from removed program %s", cancelled_count, program_href
        )
release_cancelled_program async
release_cancelled_program(program_href: str) -> None

Release the control that events cancelled by :meth:cancel_program still hold.

Cancelling an event does not touch the device: the registration of the modes it set stays until they are released. For a program that was removed those modes would stay on every device for good, since no end of the event is left to release them. Each such event releases them as an ended event does: modes no default carries are disabled, and the default that now governs the device is applied. Call it after the program has left the discovered state, so its own default is not chosen. A device the event never registered on is untouched.

Source code in src/py20305/events/processor.py
async def release_cancelled_program(self, program_href: str) -> None:
    """Release the control that events cancelled by :meth:`cancel_program` still hold.

    Cancelling an event does not touch the device: the registration of the
    modes it set stays until they are released. For a program that was
    removed those modes would stay on every device for good, since no end
    of the event is left to release them. Each such event releases them as
    an ended event does: modes no default carries are disabled, and the
    default that now governs the device is applied. Call it after the
    program has left the discovered state, so its own default is not
    chosen. A device the event never registered on is untouched.
    """
    for record in self._store.by_state(EventState.CANCELLED):
        if record.program_href != program_href or record.opted_out:
            continue
        if not self._mode_tracker.devices_of(record.mrid):
            continue
        await self._apply_dderc_fallback(record)
        if self._closed:
            return
shutdown async
shutdown() -> None

Cancel all event timers + in-flight background tasks and mark closed.

Source code in src/py20305/events/processor.py
async def shutdown(self) -> None:
    """Cancel all event timers + in-flight background tasks and mark closed."""
    self._closed = True
    await self._timer_mgr.cancel_all()
    # Cancel/await fire-and-forget relay tasks and any control dispatch
    # still running past the activation ceiling, so shutdown is clean
    # (no "Task was destroyed but it is pending" warnings).
    background = list(self._relay_tasks) + list(self._dispatch_tasks)
    for task in background:
        task.cancel()
    if background:
        await asyncio.gather(*background, return_exceptions=True)
release_withdrawn_devices async
release_withdrawn_devices(withdrawn: Iterable[tuple[str, str]]) -> None

End the control running events hold on devices withdrawn from their programs.

withdrawn holds (program_href, device_href) pairs the discovery refresh dropped from the device mapping. IEEE 2030.5-2023 §8.8.3 has a client act on the events of the function set assignments it is in, so a device no longer assigned to a program stops being governed by that program's events when the client learns of it. Each event the device was registered on releases its modes there, as at the end of the event: modes the device's remaining defaults do not carry are disabled, and the default that now governs the device is applied. The event keeps running on its other devices. The standard defines no response status for a withdrawal, so none is posted for the device.

Under a group lookup a program's control reaches its whole group whichever server-side device was withdrawn, so nothing is released until the event ends.

Source code in src/py20305/events/processor.py
async def release_withdrawn_devices(self, withdrawn: Iterable[tuple[str, str]]) -> None:
    """End the control running events hold on devices withdrawn from their programs.

    ``withdrawn`` holds ``(program_href, device_href)`` pairs the discovery
    refresh dropped from the device mapping. IEEE 2030.5-2023 §8.8.3 has a
    client act on the events of the function set assignments it is in, so a
    device no longer assigned to a program stops being governed by that
    program's events when the client learns of it. Each event the device
    was registered on releases its modes there, as at the end of the event:
    modes the device's remaining defaults do not carry are disabled, and the
    default that now governs the device is applied. The event keeps running
    on its other devices. The standard defines no response status for a
    withdrawal, so none is posted for the device.

    Under a group lookup a program's control reaches its whole group
    whichever server-side device was withdrawn, so nothing is released until
    the event ends.
    """
    by_program: dict[str, set[str]] = {}
    for program_href, dev_href in withdrawn:
        by_program.setdefault(program_href, set()).add(dev_href)
    if not by_program:
        return
    for record in self._store.by_state(EventState.ACTIVE):
        candidates = by_program.get(record.program_href)
        if not candidates or record.opted_out:
            continue
        # A device mapped to the program again is not withdrawn any more.
        mapped = set(self._unique_devices(record.program_href))
        running = (candidates & self._mode_tracker.devices_of(record.mrid)) - mapped
        if not running:
            continue
        if self._group_local_lfdis(record.program_href) is not None:
            logger.debug(
                "Event %s: program %s uses a group lookup; its control on withdrawn "
                "device(s) %s is released when the event ends",
                record.mrid.hex()[:8],
                record.program_href,
                sorted(running),
            )
            continue
        logger.info(
            "Event %s: ending its control on %s, withdrawn from program %s",
            record.mrid.hex()[:8],
            ", ".join(sorted(running)),
            record.program_href,
        )
        record.withdrawn_devices |= running
        await self._apply_dderc_fallback(record, only=running)
        if self._closed:
            return
attach_event_history
attach_event_history(history: EventHistory | None) -> None

Keep each response this processor posts, or fails to post, in history.

Source code in src/py20305/events/processor.py
def attach_event_history(self, history: EventHistory | None) -> None:
    """Keep each response this processor posts, or fails to post, in ``history``."""
    self._response_tracker.observer = (
        None if history is None else partial(_record_response, history)
    )
load_devices
load_devices(device_hrefs: Iterable[str]) -> int

Load the saved event state of EndDevices taken over from another process.

Merges each device's events into this processor: an event already held here gains the device's applied, rejected and superseded marks; an event not held here is created from the snapshot, with its saved timing, and its activation or completion timer is scheduled by :meth:resume_devices. Responses already posted for the devices are counted as sent, the DefaultDERControl last applied to each is remembered, and the loss-of-communications resume boundary is kept for those devices only. The Response ledger of a device without a snapshot is restored once discovery gives its LFDI. Returns how many snapshots were loaded.

Call before the rediscovery that adds the devices, so the events are known when their controls are fetched, then :meth:resume_devices after it.

Source code in src/py20305/events/processor.py
def load_devices(self, device_hrefs: Iterable[str]) -> int:
    """Load the saved event state of EndDevices taken over from another process.

    Merges each device's events into this processor: an event already held
    here gains the device's applied, rejected and superseded marks; an
    event not held here is created from the snapshot, with its saved
    timing, and its activation or completion timer is scheduled by
    :meth:`resume_devices`. Responses
    already posted for the devices are counted as sent, the DefaultDERControl
    last applied to each is remembered, and the loss-of-communications
    resume boundary is kept for those devices only. The Response ledger
    of a device without a snapshot is restored once discovery gives its
    LFDI. Returns how many snapshots were loaded.

    Call before the rediscovery that adds the devices, so the events are
    known when their controls are fetched, then :meth:`resume_devices`
    after it.
    """
    hrefs = list(device_hrefs)
    # This process acts for the devices again, with a store or without one.
    self._released.difference_update(hrefs)
    if self._state_store is None:
        return 0
    loaded = 0
    for dev_href in hrefs:
        self._saved.pop(dev_href, None)
        self._ledger_pending.add(dev_href)
        self._awaiting_resume.add(dev_href)
        snapshot = self._state_store.load_device(dev_href)
        if not snapshot or snapshot.get("version") != SNAPSHOT_VERSION:
            continue
        lfdi = bytes.fromhex(snapshot["lfdi"])
        for entry in snapshot.get("events", []):
            self._merge_event(dev_href, entry)
        for entry in snapshot.get("defaults", []):
            content = entry.get("content")
            # A snapshot from an older release has no modes. The default is
            # then written once more so its modes are recorded.
            modes = entry.get("modes")
            self._dderc_tracker.record_application(
                lfdi,
                entry["program_href"],
                bytes.fromhex(entry["mrid"]),
                entry["primacy"],
                frozenset(modes) if modes is not None else None,
                bytes.fromhex(content) if content else None,
            )
        resume_after = snapshot.get("comms_loss", {}).get("resume_after")
        if resume_after is not None:
            current = self._imported_resume_after.get(dev_href, 0)
            self._imported_resume_after[dev_href] = max(current, int(resume_after))
        self._restore_ledger(lfdi)
        loaded += 1
    return loaded
resume_devices async
resume_devices(device_hrefs: Iterable[str]) -> None

Apply running events to taken-over EndDevices that never received them.

For a device the previous process stopped acting for in the middle of an activation, or one that joins a running event without a snapshot: the event is active, but the device was neither told it started nor told it was rejected. It gets the ACKNOWLEDGED Response unless one was posted for it, then the control and its ACTIVE Response. A device already marked applied or rejected gets nothing, so no control and no Response is sent twice. While in loss-of-communications mode the event is opted out instead, as on entering that mode.

Not done for a program under a group lookup, whose dispatch goes to the group's local devices rather than to the EndDevices named here.

Then schedules each taken-over device's own activation and completion at its window's start and end. They wait until now so an event does not activate before the devices it applies to are mapped. A device whose window has ended is not applied: on an active event it completes at once, with its Responses and fallback, and on a scheduled one it is left to expire.

Source code in src/py20305/events/processor.py
async def resume_devices(self, device_hrefs: Iterable[str]) -> None:
    """Apply running events to taken-over EndDevices that never received them.

    For a device the previous process stopped acting for in the middle of
    an activation, or one that joins a running event without a snapshot:
    the event is active, but the device was neither told it started nor
    told it was rejected. It gets the ACKNOWLEDGED Response unless one was
    posted for it, then the control and its ACTIVE Response. A device
    already marked applied or rejected gets nothing, so no control and no
    Response is sent twice. While in loss-of-communications mode the event
    is opted out instead, as on entering that mode.

    Not done for a program under a group lookup, whose dispatch goes to the
    group's local devices rather than to the EndDevices named here.

    Then schedules each taken-over device's own activation and completion
    at its window's start and end. They wait until now so an event does
    not activate before the devices it applies to are mapped. A device
    whose window has ended is not applied: on an active event it completes
    at once, with its Responses and fallback, and on a scheduled one it is
    left to expire.
    """
    with self._working():
        await self._resume_devices(set(device_hrefs))
release_devices async
release_devices(device_hrefs: Iterable[str]) -> None

Stop acting for EndDevices another process will take over.

New work leaves the devices out at once. Work already running for them (an activation, a control write, a Response) is allowed to finish first, so the snapshot saved next shows what reached the device and the server. Then their snapshots are saved, and their state forgotten: an event that concerns only released devices is forgotten here without a state change, a Response or a write to a device; its timers are cancelled and the taking-over process carries it on. An event that also concerns devices this process keeps loses only the released devices' marks. Call before the rediscovery that removes the devices, and not from a dispatcher or another event callback, which would wait for itself.

Raises the store's error when a snapshot cannot be saved. The devices then stay with this process, their state kept, and the call can be made again.

Source code in src/py20305/events/processor.py
async def release_devices(self, device_hrefs: Iterable[str]) -> None:
    """Stop acting for EndDevices another process will take over.

    New work leaves the devices out at once. Work already running for
    them (an activation, a control write, a Response) is allowed to finish
    first, so the snapshot saved next shows what reached the device and the
    server. Then their snapshots are saved, and their state forgotten: an
    event that concerns only released devices is forgotten here without a
    state change, a Response or a write to a device; its timers are
    cancelled and the taking-over process carries it on. An event that
    also concerns devices this process keeps loses only the released
    devices' marks. Call before the rediscovery that removes the devices,
    and not from a dispatcher or another event callback, which would wait
    for itself.

    Raises the store's error when a snapshot cannot be saved. The devices
    then stay with this process, their state kept, and the call can be
    made again.
    """
    released = set(device_hrefs)
    newly_released = released - self._released
    self._released |= released
    while True:
        if self._busy:
            await self._idle.wait()
            continue
        writes = [task for task in self._dispatch_tasks if not task.done()]
        if writes:
            await asyncio.gather(*writes, return_exceptions=True)
            continue
        break
    failed = self._persist(devices=released)
    if failed:
        self._released -= newly_released
        raise RuntimeError(
            f"could not save the event state of {', '.join(sorted(failed))}; "
            "the devices are still acted for here"
        )
    mapping = self._state.device_mapping.program_to_devices
    for dev_href in released:
        self._saved.pop(dev_href, None)
        self._ledger_pending.discard(dev_href)
        self._awaiting_resume.discard(dev_href)
        self._imported_resume_after.pop(dev_href, None)
        edev = self._state.end_devices.get(dev_href)
        if edev is not None:
            self._dderc_tracker.clear_devices({edev.lfdi})
    for record in self._store.values():
        devices = set(mapping.get(record.program_href, []))
        for dev_href in released:
            self._mode_tracker.unregister(dev_href, record.mrid)
        if devices and devices <= released:
            self._timer_mgr.cancel(record.mrid)
            self._store.remove(record.mrid)
            self._control_xml.pop(record.mrid, None)
            self._fallback_due.pop(record.mrid, None)
            continue
        record.applied_devices -= released
        record.rejected_devices -= released
        record.superseded_devices -= released
        record.withdrawn_devices -= released
        record.started_devices -= released
        record.ended_devices -= released
        for dev_href in released:
            record.superseded_modes.pop(dev_href, None)
            record.device_windows.pop(dev_href, None)
enter_comms_loss async
enter_comms_loss() -> None

Opt out of every active event and revert devices to the planning limit.

Loss-of-communications entry: each active event is marked opted-out, its timers cancelled, and its devices reverted to DDERC (or cleared to the connector safe-default where no DDERC exists). No IEEE 2030.5 responses are posted -- comms are down. The resume boundary is raised to the latest opted-out event end so recovery resumes only the schedule that follows it. Events stay in ACTIVE state (the opted_out flag is the marker), so supersession and classification are unaffected.

Source code in src/py20305/events/processor.py
async def enter_comms_loss(self) -> None:
    """Opt out of every active event and revert devices to the planning limit.

    Loss-of-communications entry: each active event is marked
    opted-out, its timers cancelled, and its devices reverted to DDERC (or
    cleared to the connector safe-default where no DDERC exists). No IEEE
    2030.5 responses are posted -- comms are down. The resume boundary is
    raised to the latest opted-out event end so recovery resumes only the
    schedule that follows it. Events stay in ACTIVE state (the ``opted_out``
    flag is the marker), so supersession and classification are unaffected.
    """
    with self._working():
        await self._enter_comms_loss()

py20305.events.state_machine

Event state machine: EventState enum, EventRecord, and EventStore.

EventRecord dataclass

Single event tracked in the store, keyed by mRID.

Source code in src/py20305/events/state_machine.py
@dataclass
class EventRecord:
    """Single event tracked in the store, keyed by mRID."""

    mrid: bytes
    derc: Dercontrol1
    program_href: str
    primacy: int
    state: EventState
    start: int  # effective (post-randomization) epoch seconds
    duration: int  # effective (post-randomization) seconds
    server_status_time: int  # EventStatus.dateTime (legacy, kept for compat)
    creation_time: int = 0  # Event.creationTime for IEEE tie-breaking
    superseded_devices: set[str] = field(default_factory=set)
    superseded_modes: dict[str, frozenset[str]] = field(default_factory=dict)
    #: Devices whose control dispatch failed at activation, so they were sent a
    #: rejection (251/252/253) instead of ACTIVE. They never ran the event, so they
    #: are excluded from the COMPLETED response at its end.
    rejected_devices: set[str] = field(default_factory=set)
    #: Devices that were told the event started -- their dispatch returned
    #: successfully. COMPLETED is posted to exactly this set, rather than to the
    #: program's current device list minus the rejected ones: the device list can
    #: change under a mid-event rediscovery, and a device that was never told
    #: ACTIVE must not be told the event completed. Empty alongside an empty
    #: ``rejected_devices`` means dispatch never had a target at all, which is the
    #: one case where the any-LFDI fallback still announces the lifecycle.
    applied_devices: set[str] = field(default_factory=set)
    #: Devices withdrawn from the program while the event ran. The control the
    #: event held on them was ended at the withdrawal, so they are not told the
    #: event completed or was cancelled: those say the event ran its course on a
    #: device the program no longer reaches.
    withdrawn_devices: set[str] = field(default_factory=set)
    #: Under a group lookup, each local device's dispatch outcome by its LFDI,
    #: for the audit trail. The two sets above are in the server's terms: one
    #: EndDevice stands for several local devices, its response reports them as
    #: one, and a partial failure there still reads as applied. Empty without a
    #: group lookup, where the sets above already name each device.
    applied_local: set[str] = field(default_factory=set)
    rejected_local: set[str] = field(default_factory=set)
    #: Set when the event was opted out during loss-of-communications mode: its
    #: control is not applied (or is reverted to DDERC) and no response is
    #: posted. Stays set until the record is pruned (recovery clears only the
    #: shared CommsLossState, not this flag) so the event never resumes and stays
    #: excluded from "other active" DDERC checks. The state stays SCHEDULED/ACTIVE
    #: so supersession/classification are unaffected.
    opted_out: bool = False
    #: Each EndDevice's effective window, ``device href -> (start, end)``.
    #: IEEE 2030.5-2023 §10.2.3.2.2 and §10.2.3.2.3 have each device draw its
    #: own start and duration randomization, so devices of one event start and
    #: end at different moments. ``start`` and ``duration`` above then span
    #: every window. Empty for an event whose program has no device mapping:
    #: it runs on ``start`` and ``end``.
    device_windows: dict[str, tuple[int, int]] = field(default_factory=dict)
    #: Devices whose window has started here (the control was dispatched or
    #: the device was found superseded at its start).
    started_devices: set[str] = field(default_factory=set)
    #: Devices whose window has ended here (COMPLETED and fallback handled).
    ended_devices: set[str] = field(default_factory=set)

    @property
    def end(self) -> int:
        return self.start + self.duration

    def window(self, device_href: str) -> tuple[int, int]:
        """Return the effective ``(start, end)`` of the event on one device."""
        return self.device_windows.get(device_href, (self.start, self.end))

    def set_window(self, device_href: str, start: int, end: int) -> None:
        """Record one device's window and widen ``start``/``duration`` to cover every window."""
        self.device_windows[device_href] = (start, end)
        first = min(s for s, _ in self.device_windows.values())
        last = max(e for _, e in self.device_windows.values())
        self.start = first
        self.duration = last - first

    def runs_on(self, device_href: str) -> bool:
        """Return whether the event is in its window on ``device_href`` here.

        False before the device's own start and after its own end. A device
        without a window of its own follows the event's state.
        """
        if device_href in self.ended_devices:
            return False
        return device_href not in self.device_windows or device_href in self.started_devices
window
window(device_href: str) -> tuple[int, int]

Return the effective (start, end) of the event on one device.

Source code in src/py20305/events/state_machine.py
def window(self, device_href: str) -> tuple[int, int]:
    """Return the effective ``(start, end)`` of the event on one device."""
    return self.device_windows.get(device_href, (self.start, self.end))
set_window
set_window(device_href: str, start: int, end: int) -> None

Record one device's window and widen start/duration to cover every window.

Source code in src/py20305/events/state_machine.py
def set_window(self, device_href: str, start: int, end: int) -> None:
    """Record one device's window and widen ``start``/``duration`` to cover every window."""
    self.device_windows[device_href] = (start, end)
    first = min(s for s, _ in self.device_windows.values())
    last = max(e for _, e in self.device_windows.values())
    self.start = first
    self.duration = last - first
runs_on
runs_on(device_href: str) -> bool

Return whether the event is in its window on device_href here.

False before the device's own start and after its own end. A device without a window of its own follows the event's state.

Source code in src/py20305/events/state_machine.py
def runs_on(self, device_href: str) -> bool:
    """Return whether the event is in its window on ``device_href`` here.

    False before the device's own start and after its own end. A device
    without a window of its own follows the event's state.
    """
    if device_href in self.ended_devices:
        return False
    return device_href not in self.device_windows or device_href in self.started_devices

EventStore

Single-dict event store keyed by mRID.

Replaces the original's 4+ separate dicts, eliminating move-related races.

Source code in src/py20305/events/state_machine.py
class EventStore:
    """Single-dict event store keyed by mRID.

    Replaces the original's 4+ separate dicts, eliminating move-related races.
    """

    def __init__(self) -> None:
        self._events: dict[bytes, EventRecord] = {}

    def upsert(self, record: EventRecord) -> EventRecord:
        """Insert or update an event record. Returns the stored record."""
        self._events[record.mrid] = record
        return record

    def get(self, mrid: bytes) -> EventRecord | None:
        return self._events.get(mrid)

    def remove(self, mrid: bytes) -> None:
        """Forget an event without a state change. An unknown mRID is not an error."""
        self._events.pop(mrid, None)

    def values(self) -> list[EventRecord]:
        """Return every stored event, whatever its state."""
        return list(self._events.values())

    def by_state(self, state: EventState) -> list[EventRecord]:
        return [r for r in self._events.values() if r.state == state]

    def transition(self, mrid: bytes, new_state: EventState) -> EventRecord:
        """Transition an event to a new state. Raises KeyError if not found."""
        record = self._events[mrid]
        record.state = new_state
        return record

    def all_active_states(self) -> list[EventRecord]:
        """Return events that are scheduled or active (for supersession)."""
        return [
            r for r in self._events.values() if r.state in (EventState.SCHEDULED, EventState.ACTIVE)
        ]

    def prune_expired(self, now: int, grace: int = 60) -> list[bytes]:
        """Remove events whose end time + grace period has passed.

        The grace window keeps a just-ended event in the store long enough that
        an immediate re-poll still recognises it as already-handled rather than
        re-classifying it as a new (expired) event. Returns list of pruned mRIDs.
        """
        expired: list[bytes] = []
        for mrid, record in list(self._events.items()):
            if record.end + grace < now:
                expired.append(mrid)
                del self._events[mrid]
        return expired

    def __len__(self) -> int:
        return len(self._events)

    def __contains__(self, mrid: bytes) -> bool:
        return mrid in self._events
upsert
upsert(record: EventRecord) -> EventRecord

Insert or update an event record. Returns the stored record.

Source code in src/py20305/events/state_machine.py
def upsert(self, record: EventRecord) -> EventRecord:
    """Insert or update an event record. Returns the stored record."""
    self._events[record.mrid] = record
    return record
remove
remove(mrid: bytes) -> None

Forget an event without a state change. An unknown mRID is not an error.

Source code in src/py20305/events/state_machine.py
def remove(self, mrid: bytes) -> None:
    """Forget an event without a state change. An unknown mRID is not an error."""
    self._events.pop(mrid, None)
values
values() -> list[EventRecord]

Return every stored event, whatever its state.

Source code in src/py20305/events/state_machine.py
def values(self) -> list[EventRecord]:
    """Return every stored event, whatever its state."""
    return list(self._events.values())
transition
transition(mrid: bytes, new_state: EventState) -> EventRecord

Transition an event to a new state. Raises KeyError if not found.

Source code in src/py20305/events/state_machine.py
def transition(self, mrid: bytes, new_state: EventState) -> EventRecord:
    """Transition an event to a new state. Raises KeyError if not found."""
    record = self._events[mrid]
    record.state = new_state
    return record
all_active_states
all_active_states() -> list[EventRecord]

Return events that are scheduled or active (for supersession).

Source code in src/py20305/events/state_machine.py
def all_active_states(self) -> list[EventRecord]:
    """Return events that are scheduled or active (for supersession)."""
    return [
        r for r in self._events.values() if r.state in (EventState.SCHEDULED, EventState.ACTIVE)
    ]
prune_expired
prune_expired(now: int, grace: int = 60) -> list[bytes]

Remove events whose end time + grace period has passed.

The grace window keeps a just-ended event in the store long enough that an immediate re-poll still recognises it as already-handled rather than re-classifying it as a new (expired) event. Returns list of pruned mRIDs.

Source code in src/py20305/events/state_machine.py
def prune_expired(self, now: int, grace: int = 60) -> list[bytes]:
    """Remove events whose end time + grace period has passed.

    The grace window keeps a just-ended event in the store long enough that
    an immediate re-poll still recognises it as already-handled rather than
    re-classifying it as a new (expired) event. Returns list of pruned mRIDs.
    """
    expired: list[bytes] = []
    for mrid, record in list(self._events.items()):
        if record.end + grace < now:
            expired.append(mrid)
            del self._events[mrid]
    return expired

py20305.events.supersession

Pure-function supersession algorithm for DERControl events.

Compares the pairs of active/scheduled events whose programs reach a common device. If two events have overlapping time ranges and identical DERControlBase parameters (excluding opModConnect/opModEnergize), the lower-primacy event supersedes the higher-primacy one. Same primacy: newer creationTime wins (IEEE 10.2.2.3 rule e), with server_status_time as fallback.

Fixes from original: - Returns ALL superseded pairs (original only returned the last pair) - Status=4 is handled per-event, not by clearing all results

SupersessionResult dataclass

One supersession relationship: superseding event beats superseded event.

Source code in src/py20305/events/supersession.py
@dataclass(frozen=True)
class SupersessionResult:
    """One supersession relationship: superseding event beats superseded event."""

    superseded_mrid: bytes
    superseding_mrid: bytes
    affected_devices: frozenset[str]
    superseded_program_href: str = ""
    superseding_program_href: str = ""
    affected_modes: frozenset[str] = frozenset()

compared_mode_keys

compared_mode_keys(base: DercontrolBase) -> frozenset[str]

Return the modes supersession compares, as it compares them.

DERControlBase field names, leaving out connect and energize, plus the CSIP-AUS envelope limits by element name (opModExpLimW, opModImpLimW, opModGenLimW, opModLoadLimW). The limits are extension elements carried in other_element, not fields, and they are modes of the DERControlBase: CSIP-AUS v1.1a section 5.2.4.1 has DERControls follow the event rules of IEEE 2030.5, and IEEE 2030.5-2023 section 10.2.2.3 rule q (rule t in IEEE 2030.5-2018 section 10.2.3.3) supersedes overlapping events mode by mode. An event with none of those elements has no CSIP-AUS modes to compare, so servers that do not use them see no change.

Narrower than :func:~py20305.events.modes_bitmask.get_active_mode_names, which also names connect and energize. Anything deciding what a supersession covered has to ask in this vocabulary: superseded_modes is recorded from it, so comparing it against the wider set says a device was only partly taken over whenever an event carries a mode this cannot see.

Source code in src/py20305/events/supersession.py
def compared_mode_keys(base: DercontrolBase) -> frozenset[str]:
    """Return the modes supersession compares, as it compares them.

    ``DERControlBase`` field names, leaving out connect and energize, plus the
    CSIP-AUS envelope limits by element name (``opModExpLimW``, ``opModImpLimW``,
    ``opModGenLimW``, ``opModLoadLimW``). The limits are extension elements
    carried in ``other_element``, not fields, and they are modes of the
    DERControlBase: CSIP-AUS v1.1a section 5.2.4.1 has DERControls follow the
    event rules of IEEE 2030.5, and IEEE 2030.5-2023 section 10.2.2.3 rule q
    (rule t in IEEE 2030.5-2018 section 10.2.3.3) supersedes overlapping events
    mode by mode. An event with none of those elements has no CSIP-AUS modes to
    compare, so servers that do not use them see no change.

    Narrower than :func:`~py20305.events.modes_bitmask.get_active_mode_names`,
    which also names connect and energize.
    Anything deciding what a supersession covered has to ask in this
    vocabulary: ``superseded_modes`` is recorded from it, so comparing it
    against the wider set says a device was only partly taken over whenever an
    event carries a mode this cannot see.
    """
    keys: set[str] = set(doe_limits(base))
    for name in DercontrolBase.model_fields:
        if name in _EXCLUDED_FIELDS:
            continue
        if name.startswith(("dercontrol_base_", "other_element", "any_attributes")):
            continue
        val = getattr(base, name, None)
        if val is not None:
            keys.add(name)
    return frozenset(keys)

compute_supersession

compute_supersession(events: list[EventRecord], program_to_devices: dict[str, set[str]]) -> list[SupersessionResult]

Compute all supersession pairs among the given events.

Only events whose programs reach a common device can supersede one another. Each event is compared with the later events of the programs it shares a device with, in the order of events, so each such pair is compared once and the results, and their order, are those of comparing every pair. Each event's compared modes are worked out once.

Parameters:

Name Type Description Default
events list[EventRecord]

List of active/scheduled EventRecords to compare.

required
program_to_devices dict[str, set[str]]

Mapping from program_href to set of device hrefs belonging to that program's FSA group.

required

Returns:

Type Description
list[SupersessionResult]

List of SupersessionResult for each superseded pair.

Source code in src/py20305/events/supersession.py
def compute_supersession(
    events: list[EventRecord],
    program_to_devices: dict[str, set[str]],
) -> list[SupersessionResult]:
    """Compute all supersession pairs among the given events.

    Only events whose programs reach a common device can supersede one
    another. Each event is compared with the later events of the programs it
    shares a device with, in the order of *events*, so each such pair is
    compared once and the results, and their order, are those of comparing
    every pair. Each event's compared modes are worked out once.

    Args:
        events: List of active/scheduled EventRecords to compare.
        program_to_devices: Mapping from program_href to set of device hrefs
            belonging to that program's FSA group.

    Returns:
        List of SupersessionResult for each superseded pair.
    """
    programs_on: dict[str, set[str]] = {}
    for program, devices in program_to_devices.items():
        for device in devices:
            programs_on.setdefault(device, set()).add(program)
    sharing: dict[str, set[str]] = {}

    def programs_sharing(program: str) -> set[str]:
        """The programs that reach a device *program* reaches, itself included."""
        if program not in sharing:
            reach: set[str] = set()
            for device in program_to_devices.get(program, ()):
                reach |= programs_on[device]
            sharing[program] = reach
        return sharing[program]

    indices_of: dict[str, list[int]] = {}
    for index, event in enumerate(events):
        indices_of.setdefault(event.program_href, []).append(index)

    modes: dict[int, frozenset[str]] = {}

    def modes_of(index: int) -> frozenset[str]:
        if index not in modes:
            modes[index] = compared_mode_keys(events[index].derc.dercontrol_base)
        return modes[index]

    results: list[SupersessionResult] = []
    checked: set[tuple[bytes, bytes]] = set()

    for i, a in enumerate(events):
        later: list[int] = []
        for program in programs_sharing(a.program_href):
            indices = indices_of.get(program, [])
            later.extend(indices[bisect.bisect_right(indices, i) :])
        later.sort()
        for j in later:
            b = events[j]
            pair_key = (min(a.mrid, b.mrid), max(a.mrid, b.mrid))
            if pair_key in checked:
                continue
            checked.add(pair_key)

            if not _time_overlaps(a, b):
                continue

            # Per-mode supersession: intersecting modes supersede independently.
            # Exact match (including both-empty) or non-empty overlap triggers supersession.
            params_a = modes_of(i)
            params_b = modes_of(j)
            overlap = params_a & params_b
            if params_a != params_b and not overlap:
                continue

            # Determine winner: lower primacy number wins;
            # same primacy: newer creationTime wins (IEEE 10.2.2.3 rule e)
            if a.primacy < b.primacy:
                winner, loser = a, b
            elif b.primacy < a.primacy:
                winner, loser = b, a
            else:
                # Use creation_time (preferred per IEEE), fall back to
                # server_status_time for events that lack creationTime.
                a_time = a.creation_time or a.server_status_time
                b_time = b.creation_time or b.server_status_time
                if a_time >= b_time:
                    winner, loser = a, b
                else:
                    winner, loser = b, a

            # Affected devices: those both programs reach on which the two
            # events overlap. Each device has its own randomized window (IEEE
            # 2030.5-2023 §10.2.3.2), so two events can overlap on one device
            # and not on another.
            devs_winner = program_to_devices.get(winner.program_href, set())
            devs_loser = program_to_devices.get(loser.program_href, set())
            affected = frozenset(
                d
                for d in devs_winner & devs_loser
                if _windows_overlap(winner.window(d), loser.window(d))
            )

            if affected:
                results.append(
                    SupersessionResult(
                        superseded_mrid=loser.mrid,
                        superseding_mrid=winner.mrid,
                        affected_devices=affected,
                        superseded_program_href=loser.program_href,
                        superseding_program_href=winner.program_href,
                        affected_modes=overlap,
                    )
                )

    return results

py20305.events.randomization

Per-device randomization of event start time and duration, drawn once and reused.

IEEE 2030.5-2023 §10.2.3.2.2: "The device SHALL randomly select a number in seconds from zero to the randomizeStart specified for this event." §10.2.3.2.3: "Devices SHALL randomly select a number in seconds from zero to the randomizeDuration value." The purpose (§10.2.3.1) is to keep a large group of devices from acting at the same moment, and §10.2.3.3 has a proxy for devices that do not speak IEEE 2030.5 apply a distribution of values across them. So a client acting for several EndDevices draws one offset per (event, device), not one per event.

RandomizationCache

Cache randomized offsets per (mRID, device) so a device keeps one timing per event.

Offsets are drawn at random once per event and device, and reused on subsequent calls. Each device draws its own (IEEE 2030.5-2023 §10.2.3.2.2 and §10.2.3.2.3), so the devices of one event spread out. The cache is prunable to avoid unbounded memory growth.

claim shares the offsets beyond this process: it is called with the mRID, the device and the offsets just drawn, and returns the offsets to use, which are the first ever stored for that event and device (see :meth:~py20305.events.shared_state.EventStateStore.claim_offsets). None keeps them in this cache only.

draw returns a random offset in [0, bound] for a positive bound; None uses :func:random.randint. Tests inject it to make the draws known.

Source code in src/py20305/events/randomization.py
class RandomizationCache:
    """Cache randomized offsets per (mRID, device) so a device keeps one timing per event.

    Offsets are drawn at random once per event and device, and reused on
    subsequent calls. Each device draws its own (IEEE 2030.5-2023 §10.2.3.2.2
    and §10.2.3.2.3), so the devices of one event spread out. The cache is
    prunable to avoid unbounded memory growth.

    ``claim`` shares the offsets beyond this process: it is called with the
    mRID, the device and the offsets just drawn, and returns the offsets to
    use, which are the first ever stored for that event and device (see
    :meth:`~py20305.events.shared_state.EventStateStore.claim_offsets`). None
    keeps them in this cache only.

    ``draw`` returns a random offset in ``[0, bound]`` for a positive bound;
    None uses :func:`random.randint`. Tests inject it to make the draws known.
    """

    def __init__(
        self,
        claim: OffsetClaim | None = None,
        draw: Callable[[int], int] | None = None,
    ) -> None:
        self._cache: dict[tuple[bytes, str], tuple[int, int]] = {}
        self._expiry: dict[tuple[bytes, str], int] = {}
        self._claim = claim
        self._draw = draw if draw is not None else (lambda bound: random.randint(0, bound))

    def get_offsets(
        self,
        event: RandomizableEvent,
        start: int,
        duration: int,
        *,
        device: str = NO_DEVICE,
        start_offset: int | None = None,
    ) -> tuple[int, int]:
        """Return (start_offset, duration_offset) of ``event`` on ``device``.

        Works for any ``RandomizableEvent`` (DERControl, TimeTariffInterval, ...)
        since it only reads the base ``m_rid`` / ``randomize_start`` /
        ``randomize_duration`` fields. Offsets are cached per mRID and device.
        Range is [0, abs(value)] with sign preserved from the randomization
        field. Zero randomization fields produce zero offsets.

        ``start_offset``, when given, replaces the drawn start offset of an
        event not cached yet for the device, before the offsets are claimed:
        a successive event's start follows its predecessor's end on that
        device (§10.2.2.3 rule m.1).
        """
        key = (event.m_rid.value, device)
        if key in self._cache:
            return self._cache[key]

        if start_offset is None:
            start_offset = self._offset(event.randomize_start)
        dur_offset = self._offset(event.randomize_duration)
        if self._claim is not None:
            start_offset, dur_offset = self._claim(key[0], device, (start_offset, dur_offset))

        self._cache[key] = (start_offset, dur_offset)
        # Track expiry based on effective end time
        self._expiry[key] = start + start_offset + duration + dur_offset
        return (start_offset, dur_offset)

    def prune(self, now: int, grace: int = 10) -> list[tuple[bytes, str]]:
        """Remove entries for events that have ended. Return their ``(mrid, device)`` keys."""
        expired = [key for key, end in self._expiry.items() if end + grace < now]
        for key in expired:
            del self._cache[key]
            del self._expiry[key]
        return expired

    def seed(self, mrid: bytes, device: str, offsets: tuple[int, int], end: int) -> None:
        """Use ``offsets`` for ``mrid`` on ``device``, loaded with their timing already drawn."""
        self._cache[(mrid, device)] = offsets
        self._expiry[(mrid, device)] = end

    def _offset(self, value: OneHourRangeType | None) -> int:
        """Draw an offset from a randomization field. Returns 0 for None or 0."""
        if value is None or value.value == 0:
            return 0
        raw = value.value
        sign = 1 if raw > 0 else -1
        return sign * self._draw(abs(raw))

    def override_start_offset(
        self,
        mrid: bytes,
        new_start_offset: int,
        raw_start: int,
        raw_duration: int,
        *,
        device: str = NO_DEVICE,
    ) -> None:
        """Override the cached start offset of an event on one device.

        Used by IEEE 10.2.2.3 rule m) to prevent randomization gaps
        between successive events: the earlier event's effective end time
        becomes the later event's effective start time.
        """
        key = (mrid, device)
        if key not in self._cache:
            return
        _, dur_offset = self._cache[key]
        self._cache[key] = (new_start_offset, dur_offset)
        self._expiry[key] = raw_start + new_start_offset + raw_duration + dur_offset

    def __len__(self) -> int:
        return len(self._cache)
get_offsets
get_offsets(event: RandomizableEvent, start: int, duration: int, *, device: str = NO_DEVICE, start_offset: int | None = None) -> tuple[int, int]

Return (start_offset, duration_offset) of event on device.

Works for any RandomizableEvent (DERControl, TimeTariffInterval, ...) since it only reads the base m_rid / randomize_start / randomize_duration fields. Offsets are cached per mRID and device. Range is [0, abs(value)] with sign preserved from the randomization field. Zero randomization fields produce zero offsets.

start_offset, when given, replaces the drawn start offset of an event not cached yet for the device, before the offsets are claimed: a successive event's start follows its predecessor's end on that device (§10.2.2.3 rule m.1).

Source code in src/py20305/events/randomization.py
def get_offsets(
    self,
    event: RandomizableEvent,
    start: int,
    duration: int,
    *,
    device: str = NO_DEVICE,
    start_offset: int | None = None,
) -> tuple[int, int]:
    """Return (start_offset, duration_offset) of ``event`` on ``device``.

    Works for any ``RandomizableEvent`` (DERControl, TimeTariffInterval, ...)
    since it only reads the base ``m_rid`` / ``randomize_start`` /
    ``randomize_duration`` fields. Offsets are cached per mRID and device.
    Range is [0, abs(value)] with sign preserved from the randomization
    field. Zero randomization fields produce zero offsets.

    ``start_offset``, when given, replaces the drawn start offset of an
    event not cached yet for the device, before the offsets are claimed:
    a successive event's start follows its predecessor's end on that
    device (§10.2.2.3 rule m.1).
    """
    key = (event.m_rid.value, device)
    if key in self._cache:
        return self._cache[key]

    if start_offset is None:
        start_offset = self._offset(event.randomize_start)
    dur_offset = self._offset(event.randomize_duration)
    if self._claim is not None:
        start_offset, dur_offset = self._claim(key[0], device, (start_offset, dur_offset))

    self._cache[key] = (start_offset, dur_offset)
    # Track expiry based on effective end time
    self._expiry[key] = start + start_offset + duration + dur_offset
    return (start_offset, dur_offset)
prune
prune(now: int, grace: int = 10) -> list[tuple[bytes, str]]

Remove entries for events that have ended. Return their (mrid, device) keys.

Source code in src/py20305/events/randomization.py
def prune(self, now: int, grace: int = 10) -> list[tuple[bytes, str]]:
    """Remove entries for events that have ended. Return their ``(mrid, device)`` keys."""
    expired = [key for key, end in self._expiry.items() if end + grace < now]
    for key in expired:
        del self._cache[key]
        del self._expiry[key]
    return expired
seed
seed(mrid: bytes, device: str, offsets: tuple[int, int], end: int) -> None

Use offsets for mrid on device, loaded with their timing already drawn.

Source code in src/py20305/events/randomization.py
def seed(self, mrid: bytes, device: str, offsets: tuple[int, int], end: int) -> None:
    """Use ``offsets`` for ``mrid`` on ``device``, loaded with their timing already drawn."""
    self._cache[(mrid, device)] = offsets
    self._expiry[(mrid, device)] = end
override_start_offset
override_start_offset(mrid: bytes, new_start_offset: int, raw_start: int, raw_duration: int, *, device: str = NO_DEVICE) -> None

Override the cached start offset of an event on one device.

Used by IEEE 10.2.2.3 rule m) to prevent randomization gaps between successive events: the earlier event's effective end time becomes the later event's effective start time.

Source code in src/py20305/events/randomization.py
def override_start_offset(
    self,
    mrid: bytes,
    new_start_offset: int,
    raw_start: int,
    raw_duration: int,
    *,
    device: str = NO_DEVICE,
) -> None:
    """Override the cached start offset of an event on one device.

    Used by IEEE 10.2.2.3 rule m) to prevent randomization gaps
    between successive events: the earlier event's effective end time
    becomes the later event's effective start time.
    """
    key = (mrid, device)
    if key not in self._cache:
        return
    _, dur_offset = self._cache[key]
    self._cache[key] = (new_start_offset, dur_offset)
    self._expiry[key] = raw_start + new_start_offset + raw_duration + dur_offset

py20305.events.shared_state

Event state that a client process shares so another process can take over its devices.

A host application that runs several client processes as one client moves EndDevices from a process that stops to one that carries on. The process that takes a device over needs what the first process knew about it, or it repeats or drops work the server and the device have already seen:

  • the events the device is under, with their state, their randomized start and duration, whether the control was applied to the device or rejected, and whether a higher-priority event superseded it there;
  • the Responses already posted for the device, so none is posted twice;
  • which DefaultDERControl was last applied to the device, so it is not written again;
  • the loss-of-communications state: whether events were opted out, and the boundary before which recovered events are not resumed.

The event processor writes this to an :class:EventStateStore as it works, one snapshot per EndDevice, and records each Response as it is posted. A process taking devices over loads their snapshots (see :meth:CsipClient.take_over_devices).

The store also holds the randomization offsets of each event on each EndDevice, drawn from its randomizeStart and randomizeDuration. Each device draws its own (IEEE 2030.5-2023 §10.2.3.2.2 and §10.2.3.2.3), and a device moved between processes keeps the offsets it drew.

No store is the default: the processor keeps all of this in memory only, as before. :class:MemoryEventStateStore keeps it in a dict, for tests and for several clients in one process.

EventStateStore

Bases: Protocol

Shared event state, by EndDevice, plus the randomization offsets of each event.

The processor calls these methods from its event loop and does not await them, so each must return quickly. Values are JSON types, so a store can write them to a database as they are. mRIDs and LFDIs are hex strings.

Concurrency expectations:

  • One EndDevice is acted for by one process at a time, so its snapshot has one writer. The host moves a device by releasing it in one process before taking it over in another.
  • claim_offsets is compare-and-set per event and device: the first offsets stored for that pair win, and every later call returns them. It must be atomic across processes.
  • record_response only appends.
Source code in src/py20305/events/shared_state.py
@runtime_checkable
class EventStateStore(Protocol):
    """Shared event state, by EndDevice, plus the randomization offsets of each event.

    The processor calls these methods from its event loop and does not await
    them, so each must return quickly. Values are JSON types, so a store can
    write them to a database as they are. mRIDs and LFDIs are hex strings.

    Concurrency expectations:

    - One EndDevice is acted for by one process at a time, so its snapshot has
      one writer. The host moves a device by releasing it in one process
      before taking it over in another.
    - ``claim_offsets`` is compare-and-set per event and device: the first
      offsets stored for that pair win, and every later call returns them. It
      must be atomic across processes.
    - ``record_response`` only appends.
    """

    def load_device(self, device_href: str) -> dict[str, Any] | None:
        """Return the last snapshot saved for the EndDevice at ``device_href``, or None."""
        ...

    def save_device(self, device_href: str, snapshot: dict[str, Any]) -> None:
        """Replace the snapshot of the EndDevice at ``device_href``."""
        ...

    def record_response(self, lfdi: str, mrid: str, status: int, at: int) -> None:
        """Record that a Response with ``status`` for event ``mrid`` was posted for ``lfdi``."""
        ...

    def responses(self, lfdi: str) -> list[tuple[str, int, int]]:
        """Return ``(mrid, status, at)`` for each Response recorded for ``lfdi``."""
        ...

    def claim_offsets(self, mrid: str, device: str, offsets: tuple[int, int]) -> tuple[int, int]:
        """Return the stored ``(start, duration)`` offsets of event ``mrid`` on ``device``.

        Stores ``offsets`` first when that event and device have none.
        ``device`` is the EndDevice href, or the empty string for an event
        whose program has no device mapping.
        """
        ...

    def forget_offsets(self, mrid: str, device: str) -> None:
        """Drop the offsets of event ``mrid`` on ``device``, which have ended."""
        ...
load_device
load_device(device_href: str) -> dict[str, Any] | None

Return the last snapshot saved for the EndDevice at device_href, or None.

Source code in src/py20305/events/shared_state.py
def load_device(self, device_href: str) -> dict[str, Any] | None:
    """Return the last snapshot saved for the EndDevice at ``device_href``, or None."""
    ...
save_device
save_device(device_href: str, snapshot: dict[str, Any]) -> None

Replace the snapshot of the EndDevice at device_href.

Source code in src/py20305/events/shared_state.py
def save_device(self, device_href: str, snapshot: dict[str, Any]) -> None:
    """Replace the snapshot of the EndDevice at ``device_href``."""
    ...
record_response
record_response(lfdi: str, mrid: str, status: int, at: int) -> None

Record that a Response with status for event mrid was posted for lfdi.

Source code in src/py20305/events/shared_state.py
def record_response(self, lfdi: str, mrid: str, status: int, at: int) -> None:
    """Record that a Response with ``status`` for event ``mrid`` was posted for ``lfdi``."""
    ...
responses
responses(lfdi: str) -> list[tuple[str, int, int]]

Return (mrid, status, at) for each Response recorded for lfdi.

Source code in src/py20305/events/shared_state.py
def responses(self, lfdi: str) -> list[tuple[str, int, int]]:
    """Return ``(mrid, status, at)`` for each Response recorded for ``lfdi``."""
    ...
claim_offsets
claim_offsets(mrid: str, device: str, offsets: tuple[int, int]) -> tuple[int, int]

Return the stored (start, duration) offsets of event mrid on device.

Stores offsets first when that event and device have none. device is the EndDevice href, or the empty string for an event whose program has no device mapping.

Source code in src/py20305/events/shared_state.py
def claim_offsets(self, mrid: str, device: str, offsets: tuple[int, int]) -> tuple[int, int]:
    """Return the stored ``(start, duration)`` offsets of event ``mrid`` on ``device``.

    Stores ``offsets`` first when that event and device have none.
    ``device`` is the EndDevice href, or the empty string for an event
    whose program has no device mapping.
    """
    ...
forget_offsets
forget_offsets(mrid: str, device: str) -> None

Drop the offsets of event mrid on device, which have ended.

Source code in src/py20305/events/shared_state.py
def forget_offsets(self, mrid: str, device: str) -> None:
    """Drop the offsets of event ``mrid`` on ``device``, which have ended."""
    ...

MemoryEventStateStore

Shared event state in dicts, in this process.

Responses older than response_max_age seconds, counted back from the newest recorded for the same LFDI, are dropped as new ones arrive. The processor keeps a Response in memory for two hours for the same purpose.

Source code in src/py20305/events/shared_state.py
class MemoryEventStateStore:
    """Shared event state in dicts, in this process.

    Responses older than ``response_max_age`` seconds, counted back from the
    newest recorded for the same LFDI, are dropped as new ones arrive. The
    processor keeps a Response in memory for two hours for the same purpose.
    """

    def __init__(self, *, response_max_age: int = 7200) -> None:
        self._devices: dict[str, dict[str, Any]] = {}
        self._responses: dict[str, list[tuple[str, int, int]]] = {}
        self._offsets: dict[tuple[str, str], tuple[int, int]] = {}
        self._response_max_age = response_max_age

    def load_device(self, device_href: str) -> dict[str, Any] | None:
        """Return the last snapshot saved for ``device_href``, or None."""
        return self._devices.get(device_href)

    def save_device(self, device_href: str, snapshot: dict[str, Any]) -> None:
        """Replace the snapshot of ``device_href``."""
        self._devices[device_href] = snapshot

    def record_response(self, lfdi: str, mrid: str, status: int, at: int) -> None:
        """Record one posted Response and drop the ones too old to matter."""
        kept = self._responses.setdefault(lfdi, [])
        kept.append((mrid, status, at))
        cutoff = at - self._response_max_age
        kept[:] = [entry for entry in kept if entry[2] >= cutoff]

    def responses(self, lfdi: str) -> list[tuple[str, int, int]]:
        """Return the Responses recorded for ``lfdi``."""
        return list(self._responses.get(lfdi, []))

    def claim_offsets(self, mrid: str, device: str, offsets: tuple[int, int]) -> tuple[int, int]:
        """Return the stored offsets of ``mrid`` on ``device``, storing ``offsets`` if none."""
        return self._offsets.setdefault((mrid, device), offsets)

    def forget_offsets(self, mrid: str, device: str) -> None:
        """Drop the offsets of ``mrid`` on ``device``."""
        self._offsets.pop((mrid, device), None)
load_device
load_device(device_href: str) -> dict[str, Any] | None

Return the last snapshot saved for device_href, or None.

Source code in src/py20305/events/shared_state.py
def load_device(self, device_href: str) -> dict[str, Any] | None:
    """Return the last snapshot saved for ``device_href``, or None."""
    return self._devices.get(device_href)
save_device
save_device(device_href: str, snapshot: dict[str, Any]) -> None

Replace the snapshot of device_href.

Source code in src/py20305/events/shared_state.py
def save_device(self, device_href: str, snapshot: dict[str, Any]) -> None:
    """Replace the snapshot of ``device_href``."""
    self._devices[device_href] = snapshot
record_response
record_response(lfdi: str, mrid: str, status: int, at: int) -> None

Record one posted Response and drop the ones too old to matter.

Source code in src/py20305/events/shared_state.py
def record_response(self, lfdi: str, mrid: str, status: int, at: int) -> None:
    """Record one posted Response and drop the ones too old to matter."""
    kept = self._responses.setdefault(lfdi, [])
    kept.append((mrid, status, at))
    cutoff = at - self._response_max_age
    kept[:] = [entry for entry in kept if entry[2] >= cutoff]
responses
responses(lfdi: str) -> list[tuple[str, int, int]]

Return the Responses recorded for lfdi.

Source code in src/py20305/events/shared_state.py
def responses(self, lfdi: str) -> list[tuple[str, int, int]]:
    """Return the Responses recorded for ``lfdi``."""
    return list(self._responses.get(lfdi, []))
claim_offsets
claim_offsets(mrid: str, device: str, offsets: tuple[int, int]) -> tuple[int, int]

Return the stored offsets of mrid on device, storing offsets if none.

Source code in src/py20305/events/shared_state.py
def claim_offsets(self, mrid: str, device: str, offsets: tuple[int, int]) -> tuple[int, int]:
    """Return the stored offsets of ``mrid`` on ``device``, storing ``offsets`` if none."""
    return self._offsets.setdefault((mrid, device), offsets)
forget_offsets
forget_offsets(mrid: str, device: str) -> None

Drop the offsets of mrid on device.

Source code in src/py20305/events/shared_state.py
def forget_offsets(self, mrid: str, device: str) -> None:
    """Drop the offsets of ``mrid`` on ``device``."""
    self._offsets.pop((mrid, device), None)

py20305.events.response

DER response building and posting to the IEEE 2030.5 server.

ResponseCode

Bases: IntEnum

IEEE 2030.5 response status codes for the DER function set.

The values follow IEEE 2030.5-2023 Table 31. IEEE 2030.5-2018 Table 27 assigns the same values to 1 to 14 and 252 to 254, and reserves 15 (RESUMED) and 251 (NOT_SUPPORTED); see :meth:~py20305.server_profile.ServerProfile.wire_response_code.

Source code in src/py20305/events/response.py
class ResponseCode(enum.IntEnum):
    """IEEE 2030.5 response status codes for the DER function set.

    The values follow IEEE 2030.5-2023 Table 31. IEEE 2030.5-2018 Table 27
    assigns the same values to 1 to 14 and 252 to 254, and reserves 15
    (``RESUMED``) and 251 (``NOT_SUPPORTED``); see
    :meth:`~py20305.server_profile.ServerProfile.wire_response_code`.
    """

    ACKNOWLEDGED = 1
    ACTIVE = 2
    COMPLETED = 3
    OPT_OUT = 4
    OPT_IN = 5
    CANCELLED = 6
    SUPERSEDED = 7
    PARTIAL_OPT_OUT = 8
    PARTIAL_OPT_IN = 9
    COMPLETE_NO_PARTICIPATION = 10
    SUPERSEDED_ALTERNATE_SERVER = 13
    SUPERSEDED_ALTERNATE_PROGRAM = 14
    RESUMED = 15
    NOT_SUPPORTED = 251
    NOT_APPLICABLE = 252
    INVALID = 253
    EXPIRED = 254

ResponseTracker

Deduplicates DER response posts and provides expiry-based pruning.

Dedup key is (mrid, code, lfdi) so that the same event can produce separate responses for different devices (required by multi-device AGG conformance tests).

Source code in src/py20305/events/response.py
class ResponseTracker:
    """Deduplicates DER response posts and provides expiry-based pruning.

    Dedup key is ``(mrid, code, lfdi)`` so that the same event can produce
    separate responses for different devices (required by multi-device AGG
    conformance tests).
    """

    def __init__(self) -> None:
        self._sent: dict[tuple[bytes, ResponseCode, bytes], int] = {}
        #: Keys claimed by a POST that has not returned, each mapped to a future
        #: resolved with whether that POST landed. Held apart from ``_sent`` so
        #: an age prune cannot evict a response still in flight.
        self._in_flight: dict[tuple[bytes, ResponseCode, bytes], asyncio.Future[bool]] = {}
        #: Told about each response once its POST has returned or failed, as
        #: ``(mrid, code, lfdi, at, error)``, with ``error`` None on success.
        #: The operations history listens here; None when nothing does.
        self.observer: Callable[[bytes, ResponseCode, bytes, int, str | None], None] | None = None
        #: Told about each response as it is marked sent, as ``(mrid, code,
        #: lfdi, at)``. The shared event state records it here. Not told about
        #: responses loaded with :meth:`restore`.
        self.on_sent: Callable[[bytes, ResponseCode, bytes, int], None] | None = None

    def notify(
        self, mrid: bytes, code: ResponseCode, lfdi: bytes, at: int, error: str | None = None
    ) -> None:
        """Tell the observer how one POST ended. Never raises."""
        if self.observer is None:
            return
        try:
            self.observer(mrid, code, lfdi, at, error)
        except Exception:
            logger.debug("Response observer failed for mrid=%s", mrid.hex()[:8], exc_info=True)

    def already_sent(self, mrid: bytes, code: ResponseCode, lfdi: bytes) -> bool:
        """True if this response was sent, or is being sent right now.

        In-flight posts count, so a concurrent caller does not send a second
        copy. :meth:`has_responded` answers the narrower question -- whether
        anything has actually reached the server for this event -- and the two
        therefore disagree for the duration of a POST.
        """
        key = (mrid, code, lfdi)
        return key in self._sent or key in self._in_flight

    async def reserve(self, mrid: bytes, code: ResponseCode, lfdi: bytes) -> bool:
        """Claim this key, waiting out anyone already posting it.

        Returns True when the caller must post, False when the response is
        already the server's. A caller that arrives while another is posting
        waits for that POST's outcome rather than being turned away: the DER
        status-2 path runs once per state transition and has no retry driver,
        so giving up on the strength of someone else's attempt would let a
        failed POST mean the response is never sent at all.

        The check and the claim have no await between them, so the claim itself
        is atomic on one event loop.
        """
        key = (mrid, code, lfdi)
        while True:
            if key in self._sent:
                return False
            in_flight = self._in_flight.get(key)
            if in_flight is None:
                self._in_flight[key] = asyncio.get_running_loop().create_future()
                return True
            # Someone else holds it. Their outcome decides ours: if their POST
            # landed there is nothing to do, and if it did not, this caller
            # goes back around and claims the key itself.
            if await asyncio.shield(in_flight):
                return False

    def release(self, mrid: bytes, code: ResponseCode, lfdi: bytes) -> None:
        """Give up a claim whose POST never landed, so a waiter can take it."""
        in_flight = self._in_flight.pop((mrid, code, lfdi), None)
        if in_flight is not None and not in_flight.done():
            in_flight.set_result(False)

    def has_responded(self, mrid: bytes) -> bool:
        """True if any response (any code, any device) was already sent for *mrid*.

        Used to suppress a spurious EXPIRED on an event we already handled (e.g.
        ran to COMPLETED) that the event store pruned and a later poll
        re-discovered -- IEEE 2030.5 §10.2.2.3 rule j scopes EXPIRED to events
        already past their end *when first received*.
        """
        return any(sent_mrid == mrid for sent_mrid, _code, _lfdi in self._sent)

    def mark_sent(self, mrid: bytes, code: ResponseCode, lfdi: bytes, now: int) -> None:
        key = (mrid, code, lfdi)
        self._sent[key] = now
        in_flight = self._in_flight.pop(key, None)
        if in_flight is not None and not in_flight.done():
            in_flight.set_result(True)
        if self.on_sent is not None:
            try:
                self.on_sent(mrid, code, lfdi, now)
            except Exception:
                logger.warning(
                    "Could not record the response for mrid=%s in the shared event state",
                    mrid.hex()[:8],
                    exc_info=True,
                )

    def restore(self, mrid: bytes, code: ResponseCode, lfdi: bytes, at: int) -> None:
        """Count a response another process posted as sent, without telling ``on_sent``."""
        self._sent.setdefault((mrid, code, lfdi), at)

    def sent_for(self, lfdi: bytes) -> list[tuple[bytes, ResponseCode, int]]:
        """Return ``(mrid, code, at)`` for each response sent for ``lfdi``."""
        return [(m, c, at) for (m, c, who), at in self._sent.items() if who == lfdi]

    def prune(self, now: int, max_age: int = 7200) -> None:
        """Remove entries older than max_age seconds."""
        expired = [k for k, ts in self._sent.items() if now - ts > max_age]
        for k in expired:
            del self._sent[k]

    def retain_mrids(self, live_mrids: set[bytes]) -> None:
        """Drop dedup entries whose event mRID is not in *live_mrids*.

        Liveness-scoped eviction (vs :meth:`prune`'s age-based one) suits callers
        that re-scan a known set of events each cycle and must never re-post for a
        still-present event: an age prune could drop a long-lived event's entry
        and cause a duplicate post, whereas this only forgets events that are gone.
        """
        stale = [key for key in self._sent if key[0] not in live_mrids]
        for key in stale:
            del self._sent[key]

    def __len__(self) -> int:
        return len(self._sent)
notify
notify(mrid: bytes, code: ResponseCode, lfdi: bytes, at: int, error: str | None = None) -> None

Tell the observer how one POST ended. Never raises.

Source code in src/py20305/events/response.py
def notify(
    self, mrid: bytes, code: ResponseCode, lfdi: bytes, at: int, error: str | None = None
) -> None:
    """Tell the observer how one POST ended. Never raises."""
    if self.observer is None:
        return
    try:
        self.observer(mrid, code, lfdi, at, error)
    except Exception:
        logger.debug("Response observer failed for mrid=%s", mrid.hex()[:8], exc_info=True)
already_sent
already_sent(mrid: bytes, code: ResponseCode, lfdi: bytes) -> bool

True if this response was sent, or is being sent right now.

In-flight posts count, so a concurrent caller does not send a second copy. :meth:has_responded answers the narrower question -- whether anything has actually reached the server for this event -- and the two therefore disagree for the duration of a POST.

Source code in src/py20305/events/response.py
def already_sent(self, mrid: bytes, code: ResponseCode, lfdi: bytes) -> bool:
    """True if this response was sent, or is being sent right now.

    In-flight posts count, so a concurrent caller does not send a second
    copy. :meth:`has_responded` answers the narrower question -- whether
    anything has actually reached the server for this event -- and the two
    therefore disagree for the duration of a POST.
    """
    key = (mrid, code, lfdi)
    return key in self._sent or key in self._in_flight
reserve async
reserve(mrid: bytes, code: ResponseCode, lfdi: bytes) -> bool

Claim this key, waiting out anyone already posting it.

Returns True when the caller must post, False when the response is already the server's. A caller that arrives while another is posting waits for that POST's outcome rather than being turned away: the DER status-2 path runs once per state transition and has no retry driver, so giving up on the strength of someone else's attempt would let a failed POST mean the response is never sent at all.

The check and the claim have no await between them, so the claim itself is atomic on one event loop.

Source code in src/py20305/events/response.py
async def reserve(self, mrid: bytes, code: ResponseCode, lfdi: bytes) -> bool:
    """Claim this key, waiting out anyone already posting it.

    Returns True when the caller must post, False when the response is
    already the server's. A caller that arrives while another is posting
    waits for that POST's outcome rather than being turned away: the DER
    status-2 path runs once per state transition and has no retry driver,
    so giving up on the strength of someone else's attempt would let a
    failed POST mean the response is never sent at all.

    The check and the claim have no await between them, so the claim itself
    is atomic on one event loop.
    """
    key = (mrid, code, lfdi)
    while True:
        if key in self._sent:
            return False
        in_flight = self._in_flight.get(key)
        if in_flight is None:
            self._in_flight[key] = asyncio.get_running_loop().create_future()
            return True
        # Someone else holds it. Their outcome decides ours: if their POST
        # landed there is nothing to do, and if it did not, this caller
        # goes back around and claims the key itself.
        if await asyncio.shield(in_flight):
            return False
release
release(mrid: bytes, code: ResponseCode, lfdi: bytes) -> None

Give up a claim whose POST never landed, so a waiter can take it.

Source code in src/py20305/events/response.py
def release(self, mrid: bytes, code: ResponseCode, lfdi: bytes) -> None:
    """Give up a claim whose POST never landed, so a waiter can take it."""
    in_flight = self._in_flight.pop((mrid, code, lfdi), None)
    if in_flight is not None and not in_flight.done():
        in_flight.set_result(False)
has_responded
has_responded(mrid: bytes) -> bool

True if any response (any code, any device) was already sent for mrid.

Used to suppress a spurious EXPIRED on an event we already handled (e.g. ran to COMPLETED) that the event store pruned and a later poll re-discovered -- IEEE 2030.5 §10.2.2.3 rule j scopes EXPIRED to events already past their end when first received.

Source code in src/py20305/events/response.py
def has_responded(self, mrid: bytes) -> bool:
    """True if any response (any code, any device) was already sent for *mrid*.

    Used to suppress a spurious EXPIRED on an event we already handled (e.g.
    ran to COMPLETED) that the event store pruned and a later poll
    re-discovered -- IEEE 2030.5 §10.2.2.3 rule j scopes EXPIRED to events
    already past their end *when first received*.
    """
    return any(sent_mrid == mrid for sent_mrid, _code, _lfdi in self._sent)
restore
restore(mrid: bytes, code: ResponseCode, lfdi: bytes, at: int) -> None

Count a response another process posted as sent, without telling on_sent.

Source code in src/py20305/events/response.py
def restore(self, mrid: bytes, code: ResponseCode, lfdi: bytes, at: int) -> None:
    """Count a response another process posted as sent, without telling ``on_sent``."""
    self._sent.setdefault((mrid, code, lfdi), at)
sent_for
sent_for(lfdi: bytes) -> list[tuple[bytes, ResponseCode, int]]

Return (mrid, code, at) for each response sent for lfdi.

Source code in src/py20305/events/response.py
def sent_for(self, lfdi: bytes) -> list[tuple[bytes, ResponseCode, int]]:
    """Return ``(mrid, code, at)`` for each response sent for ``lfdi``."""
    return [(m, c, at) for (m, c, who), at in self._sent.items() if who == lfdi]
prune
prune(now: int, max_age: int = 7200) -> None

Remove entries older than max_age seconds.

Source code in src/py20305/events/response.py
def prune(self, now: int, max_age: int = 7200) -> None:
    """Remove entries older than max_age seconds."""
    expired = [k for k, ts in self._sent.items() if now - ts > max_age]
    for k in expired:
        del self._sent[k]
retain_mrids
retain_mrids(live_mrids: set[bytes]) -> None

Drop dedup entries whose event mRID is not in live_mrids.

Liveness-scoped eviction (vs :meth:prune's age-based one) suits callers that re-scan a known set of events each cycle and must never re-post for a still-present event: an age prune could drop a long-lived event's entry and cause a duplicate post, whereas this only forgets events that are gone.

Source code in src/py20305/events/response.py
def retain_mrids(self, live_mrids: set[bytes]) -> None:
    """Drop dedup entries whose event mRID is not in *live_mrids*.

    Liveness-scoped eviction (vs :meth:`prune`'s age-based one) suits callers
    that re-scan a known set of events each cycle and must never re-post for a
    still-present event: an age prune could drop a long-lived event's entry
    and cause a duplicate post, whereas this only forgets events that are gone.
    """
    stale = [key for key in self._sent if key[0] not in live_mrids]
    for key in stale:
        del self._sent[key]

response_required_allows

response_required_allows(response_required: bytes | None, code: ResponseCode) -> bool

Whether the event's responseRequired bitfield requests a code response.

IEEE 2030.5 §8.10.3.1: a client SHALL only POST a response when the corresponding bit is set. None/empty/0x00 all mean "no bits set" -> no response requested.

Source code in src/py20305/events/response.py
def response_required_allows(response_required: bytes | None, code: ResponseCode) -> bool:
    """Whether the event's responseRequired bitfield requests a *code* response.

    IEEE 2030.5 §8.10.3.1: a client SHALL only POST a response when the
    corresponding bit is set. ``None``/empty/``0x00`` all mean "no bits set" ->
    no response requested.
    """
    flags = int.from_bytes(response_required or b"\x00", "big")
    return bool(flags & _required_bit_for(code))

response_code_for_dispatch_error

response_code_for_dispatch_error(exc: BaseException) -> ResponseCode

Map an unsuccessful control dispatch onto the code to report.

An unclassified failure falls through to NOT_SUPPORTED: the client lacks a precise reason, but the control still was not applied, and reporting ACTIVE for it would assert something that did not happen. The in-process connector path does not raise the typed control errors, so its failures land here until those connectors are migrated.

Note the fall-through is deliberately a capability limit, never status 4: an opt-out has to be an explicit OptOutError, so no unrecognized error can be misreported to the head-end as a customer decision.

Source code in src/py20305/events/response.py
def response_code_for_dispatch_error(exc: BaseException) -> ResponseCode:
    """Map an unsuccessful control dispatch onto the code to report.

    An unclassified failure falls through to ``NOT_SUPPORTED``: the client
    lacks a precise reason, but the control still was not applied,
    and reporting ACTIVE for it would assert something that did not happen. The
    in-process connector path does not raise the typed control errors, so its
    failures land here until those connectors are migrated.

    Note the fall-through is deliberately a capability limit, never status 4: an
    opt-out has to be an explicit ``OptOutError``, so no unrecognized error can
    be misreported to the head-end as a customer decision.
    """
    for exc_type, code in _DISPATCH_ERROR_CODES:
        if isinstance(exc, exc_type):
            return code
    return ResponseCode.NOT_SUPPORTED

translate_code_for_revision

translate_code_for_revision(code: ResponseCode, *, profile: ServerProfile) -> ResponseCode

Map code onto the response status table of the server's edition.

The table is the profile's (:meth:ServerProfile.wire_response_code).

Source code in src/py20305/events/response.py
def translate_code_for_revision(code: ResponseCode, *, profile: ServerProfile) -> ResponseCode:
    """Map *code* onto the response status table of the server's edition.

    The table is the profile's (:meth:`ServerProfile.wire_response_code`).
    """
    return ResponseCode(profile.wire_response_code(code.value))

post_der_response async

post_der_response(http: Sep2Client, derc: Dercontrol1, code: ResponseCode, lfdi: bytes, tracker: ResponseTracker, *, now_ts: int | None = None, supported_modes2: int | None = None) -> None

Post a DERControlResponse to the server.

Uses replyTo from the DERControl. If replyTo is absent the response is skipped (the server failed to provide a destination, per IEEE 2030.5 Section 8.10.3.1).

now_ts sets createdDateTime (and the tracker stamp); the event processor passes server-timebase time so the server sees its own clock. Defaults to the local clock.

supported_modes2 is the DERControlType2 bitmap of the controls the device supports. modesResponded2 reports only the additional modes the control sets that the device supports, so a device never claims a mode it cannot apply; None means unknown, and none is reported.

Source code in src/py20305/events/response.py
async def post_der_response(
    http: Sep2Client,
    derc: Dercontrol1,
    code: ResponseCode,
    lfdi: bytes,
    tracker: ResponseTracker,
    *,
    now_ts: int | None = None,
    supported_modes2: int | None = None,
) -> None:
    """Post a DERControlResponse to the server.

    Uses replyTo from the DERControl.  If replyTo is absent the response is
    skipped (the server failed to provide a destination, per IEEE 2030.5
    Section 8.10.3.1).

    ``now_ts`` sets ``createdDateTime`` (and the tracker stamp); the event
    processor passes server-timebase time so the server sees its own clock.
    Defaults to the local clock.

    ``supported_modes2`` is the DERControlType2 bitmap of the controls the device
    supports. ``modesResponded2`` reports only the additional modes the control
    sets that the device supports, so a device never claims a mode it cannot
    apply; None means unknown, and none is reported.
    """
    mrid = derc.m_rid.value
    # Resolve before gating and dedup so both act on the value that actually
    # goes on the wire: under 2018 two codes collapse onto one, and the server
    # must not receive it twice.
    code = _resolve_wire_code(derc, code, profile=http.profile, mrid=mrid)
    if not response_required_allows(derc.response_required, code):
        logger.debug(
            "responseRequired=%s does not request %s; skipping response mrid=%s",
            (derc.response_required or b"\x00").hex(),
            code.name,
            mrid.hex()[:8],
        )
        return

    path = derc.reply_to
    if not path:
        logger.warning(
            "No replyTo on control mrid=%s; skipping %s response", mrid.hex()[:8], code.name
        )
        return

    # Reserved rather than checked: the per-device fan-out posts concurrently,
    # and a check that the POST separates from its mark lets two responses out
    # for one (mrid, code, lfdi).
    if not await tracker.reserve(mrid, code, lfdi):
        logger.debug("Skipping duplicate response mrid=%s code=%s", mrid.hex(), code.name)
        return

    # Everything from here sits inside the release: a raise while building the
    # response would otherwise leak the claim, and nothing prunes it.
    sent = False
    try:
        now_ts = now_ts if now_ts is not None else int(time.time())
        # modesResponded was added in IEEE 2030.5-2023; the profile says whether this
        # server takes it. modesResponded2 carries only the additional modes the
        # control sets that the device supports and the profile permits.
        profile = http.profile
        modes = (
            build_modes_responded(derc.dercontrol_base) if profile.sends_modes_responded else None
        )
        modes2 = (
            build_modes_responded2(derc.dercontrol_base, profile.mask_modes2(supported_modes2 or 0))
            if profile.sends_modes_responded2
            else None
        )
        response = DercontrolResponse(
            end_device_lfdi=lfdi,
            status=code.value,
            subject=MRidtype(value=mrid),
            created_date_time=TimeType(value=now_ts),
            modes_responded=modes,
            modes_responded2=modes2,
        )
        await http.post(path, response)
        tracker.mark_sent(mrid, code, lfdi, now_ts)
        sent = True
        tracker.notify(mrid, code, lfdi, now_ts)
        logger.info(
            "Response posted: mrid=%s lfdi=%s %s -> %s",
            mrid.hex()[:8],
            lfdi.hex()[:8].upper(),
            code.name,
            path,
        )
    except Exception as exc:
        logger.warning(
            "Failed to post response mrid=%s code=%s", mrid.hex()[:8], code.name, exc_info=True
        )
        tracker.notify(
            mrid, code, lfdi, int(time.time()) if now_ts is None else now_ts, error=str(exc)
        )
    finally:
        # In `finally`, not in the `except`: cancellation raises
        # CancelledError, which is not an Exception, and `_in_flight` is never
        # pruned -- so a claim released only on Exception would survive a
        # shutdown and silence this response for the life of the process.
        # Cancellation still propagates; only the claim is given back.
        if not sent:
            tracker.release(mrid, code, lfdi)

post_price_response async

post_price_response(http: Sep2Client, interval: TimeTariffInterval1, code: ResponseCode, lfdi: bytes, tracker: ResponseTracker, *, now_ts: int | None = None) -> None

Post a PriceResponse for a consumed TimeTariffInterval.

IEEE 2030.5 Price function set: when a TimeTariffInterval's responseRequired bitfield requests it, the price-responsive client acknowledges receipt. Reuses the DER response machinery -- the responseRequired bit gating (:func:response_required_allows) and the per-(mrid, code, lfdi) dedup tracker -- but builds a PriceResponse (no DER modesResponded).

now_ts sets createdDateTime (and the tracker stamp); the tariff processor passes FSA-scoped server-timebase time so the server sees its own clock (Response.createdDateTime is relative to the event's Time server). Defaults to the local clock.

Source code in src/py20305/events/response.py
async def post_price_response(
    http: Sep2Client,
    interval: TimeTariffInterval1,
    code: ResponseCode,
    lfdi: bytes,
    tracker: ResponseTracker,
    *,
    now_ts: int | None = None,
) -> None:
    """Post a PriceResponse for a consumed TimeTariffInterval.

    IEEE 2030.5 Price function set: when a TimeTariffInterval's responseRequired
    bitfield requests it, the price-responsive client acknowledges receipt.
    Reuses the DER response machinery -- the responseRequired bit gating
    (:func:`response_required_allows`) and the per-(mrid, code, lfdi) dedup
    tracker -- but builds a ``PriceResponse`` (no DER modesResponded).

    ``now_ts`` sets ``createdDateTime`` (and the tracker stamp); the tariff
    processor passes FSA-scoped server-timebase time so the server sees its own
    clock (Response.createdDateTime is relative to the event's Time server).
    Defaults to the local clock.
    """
    mrid = interval.m_rid.value
    if not response_required_allows(interval.response_required, code):
        logger.debug(
            "responseRequired=%s does not request %s; skipping price response mrid=%s",
            (interval.response_required or b"\x00").hex(),
            code.name,
            mrid.hex()[:8],
        )
        return

    path = interval.reply_to
    if not path:
        logger.warning(
            "No replyTo on tariff interval mrid=%s; skipping %s response",
            mrid.hex()[:8],
            code.name,
        )
        return

    if not await tracker.reserve(mrid, code, lfdi):
        logger.debug("Skipping duplicate price response mrid=%s code=%s", mrid.hex(), code.name)
        return

    sent = False
    try:
        now_ts = now_ts if now_ts is not None else int(time.time())
        response = PriceResponse(
            end_device_lfdi=lfdi,
            status=code.value,
            subject=MRidtype(value=mrid),
            created_date_time=TimeType(value=now_ts),
        )
        await http.post(path, response)
        tracker.mark_sent(mrid, code, lfdi, now_ts)
        sent = True
        logger.info(
            "Price response posted: mrid=%s lfdi=%s %s -> %s",
            mrid.hex()[:8],
            lfdi.hex()[:8].upper(),
            code.name,
            path,
        )
    except Exception:
        logger.warning(
            "Failed to post price response mrid=%s code=%s",
            mrid.hex()[:8],
            code.name,
            exc_info=True,
        )
    finally:
        # Same reason as the DER path: cancellation is not an Exception, and a
        # leaked claim is permanent.
        if not sent:
            tracker.release(mrid, code, lfdi)

py20305.events.dispatch

Control dispatcher protocol for applying DER controls to devices.

NullDispatcher is the no-op default; ConnectorDispatcher is the implementation backed by real connectors.

ControlDispatcher

Bases: Protocol

Interface for applying DER controls to devices.

Source code in src/py20305/events/dispatch.py
class ControlDispatcher(Protocol):
    """Interface for applying DER controls to devices."""

    async def apply_control(
        self,
        device_href: str,
        derc: Dercontrol1,
        curves: list[Dercurve1],
    ) -> None:
        """Apply a DERControl's settings to a device."""
        ...

    async def apply_default_control(
        self,
        device_href: str,
        dderc: DefaultDercontrol,
        curves: list[Dercurve1],
        *,
        origin: str = CommandOrigin.DDERC_REAPPLY,
        cause_mrid: bytes | None = None,
    ) -> None:
        """Apply default DER control (DDERC fallback) to a device.

        ``origin`` says why the default is being applied -- an event ending and
        an upstream outage land on the same write and read very differently in
        an audit trail. ``cause_mrid`` names the event whose end brought the
        default back, or ``None`` when no single event did.
        """
        ...

    async def clear_control(
        self,
        device_href: str,
        *,
        cause_mrid: bytes | None = None,
    ) -> None:
        """Clear active control from a device.

        ``cause_mrid`` names the event whose opt-out led to the clear.
        """
        ...

    async def apply_control_by_lfdi(
        self,
        lfdi: str,
        derc: Dercontrol1,
        curves: list[Dercurve1],
    ) -> None:
        """Apply a DERControl directly to a device identified by LFDI.

        Used when a caller supplies a group lookup, so a single
        server-side EndDevice href resolves to several locally-managed
        sub-device LFDIs.
        """
        ...

    async def apply_default_control_by_lfdi(
        self,
        lfdi: str,
        dderc: DefaultDercontrol,
        curves: list[Dercurve1],
        *,
        origin: str = CommandOrigin.DDERC_REAPPLY,
        cause_mrid: bytes | None = None,
    ) -> None:
        """Apply DDERC directly to a device identified by LFDI."""
        ...

    async def clear_control_by_lfdi(
        self,
        lfdi: str,
        *,
        cause_mrid: bytes | None = None,
    ) -> None:
        """Clear active control from a device identified by LFDI.

        The by-LFDI counterpart of ``clear_control``, used by the comms-loss
        safe-default when a server-side EndDevice href resolves to several
        locally-managed sub-device LFDIs.
        """
        ...

    async def disable_modes(
        self,
        device_href: str,
        modes: frozenset[str],
        *,
        cause_mrid: bytes | None = None,
    ) -> None:
        """Disable the named modes on a device at the end of an event.

        ``modes`` are the names the event processor tracks (DERControlBase
        field names and CSIP-AUS limit element names); ``cause_mrid`` names
        the event that ended.
        """
        ...

    async def disable_modes_by_lfdi(
        self,
        lfdi: str,
        modes: frozenset[str],
        *,
        cause_mrid: bytes | None = None,
    ) -> None:
        """The by-LFDI counterpart of ``disable_modes``."""
        ...

    async def relay_schedule_notification(
        self,
        lfdis: list[str],
        notification: ScheduleNotification,
    ) -> None:
        """Relay a schedule notification to each connector owning an affected LFDI.

        Informational push (see ScheduleNotification). Resolves connectors,
        de-duplicates connector instances (one connector may own several LFDIs),
        and isolates per-connector errors so a throwing connector can't affect
        event processing or the others. Callers start one relay per
        notification without waiting for earlier ones, so an implementation
        should deliver a stream's notifications to each connector in call order.
        """
        ...
apply_control async
apply_control(device_href: str, derc: Dercontrol1, curves: list[Dercurve1]) -> None

Apply a DERControl's settings to a device.

Source code in src/py20305/events/dispatch.py
async def apply_control(
    self,
    device_href: str,
    derc: Dercontrol1,
    curves: list[Dercurve1],
) -> None:
    """Apply a DERControl's settings to a device."""
    ...
apply_default_control async
apply_default_control(device_href: str, dderc: DefaultDercontrol, curves: list[Dercurve1], *, origin: str = CommandOrigin.DDERC_REAPPLY, cause_mrid: bytes | None = None) -> None

Apply default DER control (DDERC fallback) to a device.

origin says why the default is being applied -- an event ending and an upstream outage land on the same write and read very differently in an audit trail. cause_mrid names the event whose end brought the default back, or None when no single event did.

Source code in src/py20305/events/dispatch.py
async def apply_default_control(
    self,
    device_href: str,
    dderc: DefaultDercontrol,
    curves: list[Dercurve1],
    *,
    origin: str = CommandOrigin.DDERC_REAPPLY,
    cause_mrid: bytes | None = None,
) -> None:
    """Apply default DER control (DDERC fallback) to a device.

    ``origin`` says why the default is being applied -- an event ending and
    an upstream outage land on the same write and read very differently in
    an audit trail. ``cause_mrid`` names the event whose end brought the
    default back, or ``None`` when no single event did.
    """
    ...
clear_control async
clear_control(device_href: str, *, cause_mrid: bytes | None = None) -> None

Clear active control from a device.

cause_mrid names the event whose opt-out led to the clear.

Source code in src/py20305/events/dispatch.py
async def clear_control(
    self,
    device_href: str,
    *,
    cause_mrid: bytes | None = None,
) -> None:
    """Clear active control from a device.

    ``cause_mrid`` names the event whose opt-out led to the clear.
    """
    ...
apply_control_by_lfdi async
apply_control_by_lfdi(lfdi: str, derc: Dercontrol1, curves: list[Dercurve1]) -> None

Apply a DERControl directly to a device identified by LFDI.

Used when a caller supplies a group lookup, so a single server-side EndDevice href resolves to several locally-managed sub-device LFDIs.

Source code in src/py20305/events/dispatch.py
async def apply_control_by_lfdi(
    self,
    lfdi: str,
    derc: Dercontrol1,
    curves: list[Dercurve1],
) -> None:
    """Apply a DERControl directly to a device identified by LFDI.

    Used when a caller supplies a group lookup, so a single
    server-side EndDevice href resolves to several locally-managed
    sub-device LFDIs.
    """
    ...
apply_default_control_by_lfdi async
apply_default_control_by_lfdi(lfdi: str, dderc: DefaultDercontrol, curves: list[Dercurve1], *, origin: str = CommandOrigin.DDERC_REAPPLY, cause_mrid: bytes | None = None) -> None

Apply DDERC directly to a device identified by LFDI.

Source code in src/py20305/events/dispatch.py
async def apply_default_control_by_lfdi(
    self,
    lfdi: str,
    dderc: DefaultDercontrol,
    curves: list[Dercurve1],
    *,
    origin: str = CommandOrigin.DDERC_REAPPLY,
    cause_mrid: bytes | None = None,
) -> None:
    """Apply DDERC directly to a device identified by LFDI."""
    ...
clear_control_by_lfdi async
clear_control_by_lfdi(lfdi: str, *, cause_mrid: bytes | None = None) -> None

Clear active control from a device identified by LFDI.

The by-LFDI counterpart of clear_control, used by the comms-loss safe-default when a server-side EndDevice href resolves to several locally-managed sub-device LFDIs.

Source code in src/py20305/events/dispatch.py
async def clear_control_by_lfdi(
    self,
    lfdi: str,
    *,
    cause_mrid: bytes | None = None,
) -> None:
    """Clear active control from a device identified by LFDI.

    The by-LFDI counterpart of ``clear_control``, used by the comms-loss
    safe-default when a server-side EndDevice href resolves to several
    locally-managed sub-device LFDIs.
    """
    ...
disable_modes async
disable_modes(device_href: str, modes: frozenset[str], *, cause_mrid: bytes | None = None) -> None

Disable the named modes on a device at the end of an event.

modes are the names the event processor tracks (DERControlBase field names and CSIP-AUS limit element names); cause_mrid names the event that ended.

Source code in src/py20305/events/dispatch.py
async def disable_modes(
    self,
    device_href: str,
    modes: frozenset[str],
    *,
    cause_mrid: bytes | None = None,
) -> None:
    """Disable the named modes on a device at the end of an event.

    ``modes`` are the names the event processor tracks (DERControlBase
    field names and CSIP-AUS limit element names); ``cause_mrid`` names
    the event that ended.
    """
    ...
disable_modes_by_lfdi async
disable_modes_by_lfdi(lfdi: str, modes: frozenset[str], *, cause_mrid: bytes | None = None) -> None

The by-LFDI counterpart of disable_modes.

Source code in src/py20305/events/dispatch.py
async def disable_modes_by_lfdi(
    self,
    lfdi: str,
    modes: frozenset[str],
    *,
    cause_mrid: bytes | None = None,
) -> None:
    """The by-LFDI counterpart of ``disable_modes``."""
    ...
relay_schedule_notification async
relay_schedule_notification(lfdis: list[str], notification: ScheduleNotification) -> None

Relay a schedule notification to each connector owning an affected LFDI.

Informational push (see ScheduleNotification). Resolves connectors, de-duplicates connector instances (one connector may own several LFDIs), and isolates per-connector errors so a throwing connector can't affect event processing or the others. Callers start one relay per notification without waiting for earlier ones, so an implementation should deliver a stream's notifications to each connector in call order.

Source code in src/py20305/events/dispatch.py
async def relay_schedule_notification(
    self,
    lfdis: list[str],
    notification: ScheduleNotification,
) -> None:
    """Relay a schedule notification to each connector owning an affected LFDI.

    Informational push (see ScheduleNotification). Resolves connectors,
    de-duplicates connector instances (one connector may own several LFDIs),
    and isolates per-connector errors so a throwing connector can't affect
    event processing or the others. Callers start one relay per
    notification without waiting for earlier ones, so an implementation
    should deliver a stream's notifications to each connector in call order.
    """
    ...

NullDispatcher

Dispatcher that accepts every control and does nothing with it.

Source code in src/py20305/events/dispatch.py
class NullDispatcher:
    """Dispatcher that accepts every control and does nothing with it."""

    async def apply_control(
        self,
        device_href: str,
        derc: Dercontrol1,
        curves: list[Dercurve1],
    ) -> None:
        pass

    async def apply_default_control(
        self,
        device_href: str,
        dderc: DefaultDercontrol,
        curves: list[Dercurve1],
        *,
        origin: str = CommandOrigin.DDERC_REAPPLY,
        cause_mrid: bytes | None = None,
    ) -> None:
        pass

    async def clear_control(
        self,
        device_href: str,
        *,
        cause_mrid: bytes | None = None,
    ) -> None:
        pass

    async def apply_control_by_lfdi(
        self,
        lfdi: str,
        derc: Dercontrol1,
        curves: list[Dercurve1],
    ) -> None:
        pass

    async def apply_default_control_by_lfdi(
        self,
        lfdi: str,
        dderc: DefaultDercontrol,
        curves: list[Dercurve1],
        *,
        origin: str = CommandOrigin.DDERC_REAPPLY,
        cause_mrid: bytes | None = None,
    ) -> None:
        pass

    async def clear_control_by_lfdi(
        self,
        lfdi: str,
        *,
        cause_mrid: bytes | None = None,
    ) -> None:
        pass

    async def disable_modes(
        self,
        device_href: str,
        modes: frozenset[str],
        *,
        cause_mrid: bytes | None = None,
    ) -> None:
        pass

    async def disable_modes_by_lfdi(
        self,
        lfdi: str,
        modes: frozenset[str],
        *,
        cause_mrid: bytes | None = None,
    ) -> None:
        pass

    async def relay_schedule_notification(
        self,
        lfdis: list[str],
        notification: ScheduleNotification,
    ) -> None:
        pass