File: scheduler.py

package info (click to toggle)
dask.distributed 2022.12.1%2Bds.1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 10,164 kB
  • sloc: python: 81,938; javascript: 1,549; makefile: 228; sh: 100
file content (8168 lines) | stat: -rw-r--r-- 292,785 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
from __future__ import annotations

import asyncio
import contextlib
import dataclasses
import heapq
import inspect
import itertools
import json
import logging
import math
import operator
import os
import pickle
import random
import sys
import uuid
import warnings
import weakref
from collections import defaultdict, deque
from collections.abc import (
    Callable,
    Collection,
    Container,
    Hashable,
    Iterable,
    Iterator,
    Mapping,
    Sequence,
    Set,
)
from contextlib import suppress
from functools import partial
from numbers import Number
from typing import TYPE_CHECKING, Any, ClassVar, Literal, NamedTuple, cast, overload

import psutil
from sortedcontainers import SortedDict, SortedSet
from tlz import (
    first,
    groupby,
    merge,
    merge_sorted,
    merge_with,
    partition,
    pluck,
    second,
    valmap,
)
from tornado.ioloop import IOLoop

import dask
from dask.highlevelgraph import HighLevelGraph
from dask.utils import (
    format_bytes,
    format_time,
    key_split,
    parse_bytes,
    parse_timedelta,
    tmpfile,
)
from dask.widgets import get_template

from distributed import cluster_dump, preloading, profile
from distributed import versions as version_module
from distributed._stories import scheduler_story
from distributed.active_memory_manager import ActiveMemoryManagerExtension, RetireWorker
from distributed.batched import BatchedSend
from distributed.collections import HeapSet
from distributed.comm import (
    Comm,
    CommClosedError,
    get_address_host,
    normalize_address,
    resolve_address,
    unparse_host_port,
)
from distributed.comm.addressing import addresses_from_user_args
from distributed.compatibility import PeriodicCallback
from distributed.core import Status, clean_exception, rpc, send_recv
from distributed.diagnostics.memory_sampler import MemorySamplerExtension
from distributed.diagnostics.plugin import SchedulerPlugin, _get_plugin_name
from distributed.event import EventExtension
from distributed.http import get_handlers
from distributed.lock import LockExtension
from distributed.metrics import monotonic, time
from distributed.multi_lock import MultiLockExtension
from distributed.node import ServerNode
from distributed.proctitle import setproctitle
from distributed.protocol.pickle import dumps, loads
from distributed.protocol.serialize import Serialized, serialize
from distributed.publish import PublishExtension
from distributed.pubsub import PubSubSchedulerExtension
from distributed.queues import QueueExtension
from distributed.recreate_tasks import ReplayTaskScheduler
from distributed.security import Security
from distributed.semaphore import SemaphoreExtension
from distributed.shuffle import ShuffleSchedulerExtension
from distributed.stealing import WorkStealing
from distributed.utils import (
    All,
    TimeoutError,
    empty_context,
    get_fileno_limit,
    key_split_group,
    log_errors,
    no_default,
    recursive_to_dict,
    validate_key,
)
from distributed.utils_comm import (
    gather_from_workers,
    retry_operation,
    scatter_to_workers,
)
from distributed.utils_perf import disable_gc_diagnosis, enable_gc_diagnosis
from distributed.variable import VariableExtension

if TYPE_CHECKING:
    # TODO import from typing (requires Python >=3.10)
    from typing_extensions import TypeAlias

    # TODO move out of TYPE_CHECKING (requires Python >=3.10)
    # Not to be confused with distributed.worker_state_machine.TaskStateState
    TaskStateState: TypeAlias = Literal[
        "released",
        "waiting",
        "no-worker",
        "queued",
        "processing",
        "memory",
        "erred",
        "forgotten",
    ]

    # TODO remove quotes (requires Python >=3.9)
    # {task key -> finish state}
    # Not to be confused with distributed.worker_state_machine.Recs
    Recs: TypeAlias = "dict[str, TaskStateState]"
    # {client or worker address: [{op: <key>, ...}, ...]}
    Msgs: TypeAlias = "dict[str, list[dict[str, Any]]]"
    # (recommendations, client messages, worker messages)
    RecsMsgs: TypeAlias = "tuple[Recs, Msgs, Msgs]"
else:
    TaskStateState = str
    Recs = dict
    Msgs = dict
    RecsMsgs = tuple

ALL_TASK_STATES: set[TaskStateState] = {
    "released",
    "waiting",
    "no-worker",
    "queued",
    "processing",
    "memory",
    "erred",
    "forgotten",
}

logger = logging.getLogger(__name__)
LOG_PDB = dask.config.get("distributed.admin.pdb-on-err")
DEFAULT_DATA_SIZE = parse_bytes(
    dask.config.get("distributed.scheduler.default-data-size")
)
STIMULUS_ID_UNSET = "<stimulus_id unset>"

DEFAULT_EXTENSIONS = {
    "locks": LockExtension,
    "multi_locks": MultiLockExtension,
    "publish": PublishExtension,
    "replay-tasks": ReplayTaskScheduler,
    "queues": QueueExtension,
    "variables": VariableExtension,
    "pubsub": PubSubSchedulerExtension,
    "semaphores": SemaphoreExtension,
    "events": EventExtension,
    "amm": ActiveMemoryManagerExtension,
    "memory_sampler": MemorySamplerExtension,
    "shuffle": ShuffleSchedulerExtension,
    "stealing": WorkStealing,
}


class ClientState:
    """A simple object holding information about a client."""

    #: A unique identifier for this client. This is generally an opaque
    #: string generated by the client itself.
    client_key: str

    #: Cached hash of :attr:`~ClientState.client_key`
    _hash: int

    #: A set of tasks this client wants to be kept in memory, so that it can download
    #: its result when desired. This is the reverse mapping of
    #: :class:`TaskState.who_wants`. Tasks are typically removed from this set when the
    #: corresponding object in the client's space (for example a ``Future`` or a Dask
    #: collection) gets garbage-collected.
    wants_what: set[TaskState]

    #: The last time we received a heartbeat from this client, in local scheduler time.
    last_seen: float

    #: Output of :func:`distributed.versions.get_versions` on the client
    versions: dict[str, Any]

    __slots__ = tuple(__annotations__)

    def __init__(self, client: str, *, versions: dict[str, Any] | None = None):
        self.client_key = client
        self._hash = hash(client)
        self.wants_what = set()
        self.last_seen = time()
        self.versions = versions or {}

    def __hash__(self) -> int:
        return self._hash

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, ClientState):
            return False
        return self.client_key == other.client_key

    def __repr__(self) -> str:
        return f"<Client {self.client_key!r}>"

    def __str__(self) -> str:
        return self.client_key

    def _to_dict_no_nest(self, *, exclude: Container[str] = ()) -> dict:
        """Dictionary representation for debugging purposes.
        Not type stable and not intended for roundtrips.

        See also
        --------
        Client.dump_cluster_state
        distributed.utils.recursive_to_dict
        TaskState._to_dict
        """
        return recursive_to_dict(
            self,
            exclude=set(exclude) | {"versions"},  # type: ignore
            members=True,
        )


class MemoryState:
    """Memory readings on a worker or on the whole cluster.

    See :doc:`worker-memory`.

    Attributes / properties:

    managed
        Sum of the output of sizeof() for all dask keys held by the worker in memory,
        plus number of bytes spilled to disk

    managed_in_memory
        Sum of the output of sizeof() for the dask keys held in RAM. Note that this may
        be inaccurate, which may cause inaccurate unmanaged memory (see below).

    managed_spilled
        Number of bytes  for the dask keys spilled to the hard drive.
        Note that this is the size on disk; size in memory may be different due to
        compression and inaccuracies in sizeof(). In other words, given the same keys,
        'managed' will change depending if the keys are in memory or spilled.

    process
        Total RSS memory measured by the OS on the worker process.
        This is always exactly equal to managed_in_memory + unmanaged.

    unmanaged
        process - managed_in_memory. This is the sum of

        - Python interpreter and modules
        - global variables
        - memory temporarily allocated by the dask tasks that are currently running
        - memory fragmentation
        - memory leaks
        - memory not yet garbage collected
        - memory not yet free()'d by the Python memory manager to the OS

    unmanaged_old
        Minimum of the 'unmanaged' measures over the last
        ``distributed.memory.recent-to-old-time`` seconds

    unmanaged_recent
        unmanaged - unmanaged_old; in other words process memory that has been recently
        allocated but is not accounted for by dask; hopefully it's mostly a temporary
        spike.

    optimistic
        managed_in_memory + unmanaged_old; in other words the memory held long-term by
        the process under the hopeful assumption that all unmanaged_recent memory is a
        temporary spike

    .. note::
        There is an intentional misalignment in terminology between this class (which is
        meant for internal / programmatic use) and the memory readings on the GUI (which
        is aimed at the general public:

        ================= =====================
        MemoryState       GUI
        ================= =====================
        managed           n/a
        managed_in_memory managed
        managed_spilled   spilled
        process           process (RSS); memory
        unmanaged         n/a
        unmanaged_old     unmanaged (old)
        unmanaged_recent  unmanaged (recent)
        optimistic        n/a
        ================= =====================
    """

    process: int
    unmanaged_old: int
    managed_in_memory: int
    managed_spilled: int

    __slots__ = tuple(__annotations__)

    def __init__(
        self,
        *,
        process: int,
        unmanaged_old: int,
        managed_in_memory: int,
        managed_spilled: int,
    ):
        # Some data arrives with the heartbeat, some other arrives in realtime as the
        # tasks progress. Also, sizeof() is not guaranteed to return correct results.
        # This can cause glitches where a partial measure is larger than the whole, so
        # we need to force all numbers to add up exactly by definition.
        self.process = process
        self.managed_in_memory = min(self.process, managed_in_memory)
        self.managed_spilled = managed_spilled
        # Subtractions between unsigned ints guaranteed by construction to be >= 0
        self.unmanaged_old = min(unmanaged_old, process - self.managed_in_memory)

    @staticmethod
    def sum(*infos: MemoryState) -> MemoryState:
        process = 0
        unmanaged_old = 0
        managed_in_memory = 0
        managed_spilled = 0
        for ms in infos:
            process += ms.process
            unmanaged_old += ms.unmanaged_old
            managed_spilled += ms.managed_spilled
            managed_in_memory += ms.managed_in_memory
        return MemoryState(
            process=process,
            unmanaged_old=unmanaged_old,
            managed_in_memory=managed_in_memory,
            managed_spilled=managed_spilled,
        )

    @property
    def managed(self) -> int:
        return self.managed_in_memory + self.managed_spilled

    @property
    def unmanaged(self) -> int:
        # This is never negative thanks to __init__
        return self.process - self.managed_in_memory

    @property
    def unmanaged_recent(self) -> int:
        # This is never negative thanks to __init__
        return self.process - self.managed_in_memory - self.unmanaged_old

    @property
    def optimistic(self) -> int:
        return self.managed_in_memory + self.unmanaged_old

    def __repr__(self) -> str:
        return (
            f"Process memory (RSS)  : {format_bytes(self.process)}\n"
            f"  - managed by Dask   : {format_bytes(self.managed_in_memory)}\n"
            f"  - unmanaged (old)   : {format_bytes(self.unmanaged_old)}\n"
            f"  - unmanaged (recent): {format_bytes(self.unmanaged_recent)}\n"
            f"Spilled to disk       : {format_bytes(self.managed_spilled)}\n"
        )

    def _to_dict(self, *, exclude: Container[str] = ()) -> dict:
        """Dictionary representation for debugging purposes.
        Not type stable and not intended for roundtrips.

        See also
        --------
        Client.dump_cluster_state
        distributed.utils.recursive_to_dict
        """
        return recursive_to_dict(self, exclude=exclude, members=True)


class WorkerState:
    """A simple object holding information about a worker.

    Not to be confused with :class:`distributed.worker_state_machine.WorkerState`.
    """

    #: This worker's unique key. This can be its connected address
    #: (such as ``"tcp://127.0.0.1:8891"``) or an alias (such as ``"alice"``).
    address: str

    pid: int
    name: Hashable

    #: The number of CPU threads made available on this worker
    nthreads: int

    #: Memory available to the worker, in bytes
    memory_limit: int

    local_directory: str
    services: dict[str, int]

    #: Output of :meth:`distributed.versions.get_versions` on the worker
    versions: dict[str, Any]

    #: Address of the associated :class:`~distributed.nanny.Nanny`, if present
    nanny: str

    #: Read-only worker status, synced one way from the remote Worker object
    status: Status

    #: Cached hash of :attr:`~WorkerState.address`
    _hash: int

    #: The total memory size, in bytes, used by the tasks this worker holds in memory
    #: (i.e. the tasks in this worker's :attr:`~WorkerState.has_what`).
    nbytes: int

    #: Worker memory unknown to the worker, in bytes, which has been there for more than
    #: 30 seconds. See :class:`MemoryState`.
    _memory_unmanaged_old: int

    #: History of the last 30 seconds' worth of unmanaged memory. Used to differentiate
    #: between "old" and "new" unmanaged memory.
    #: Format: ``[(timestamp, bytes), (timestamp, bytes), ...]``
    _memory_unmanaged_history: deque[tuple[float, int]]

    metrics: dict[str, Any]

    #: The last time we received a heartbeat from this worker, in local scheduler time.
    last_seen: float

    time_delay: float
    bandwidth: float

    #: A set of all TaskStates on this worker that are actors. This only includes those
    #: actors whose state actually lives on this worker, not actors to which this worker
    #: has a reference.
    actors: set[TaskState]

    #: Underlying data of :meth:`WorkerState.has_what`
    _has_what: dict[TaskState, None]

    #: A set of tasks that have been submitted to this worker. Multiple tasks may be
    # submitted to a worker in advance and the worker will run them eventually,
    # depending on its execution resources (but see :doc:`work-stealing`).
    #:
    #: All the tasks here are in the "processing" state.
    #: This attribute is kept in sync with :attr:`TaskState.processing_on`.
    processing: set[TaskState]

    #: Running tasks that invoked :func:`distributed.secede`
    long_running: set[TaskState]

    #: A dictionary of tasks that are currently being run on this worker.
    #: Each task state is associated with the duration in seconds which the task has
    #: been running.
    executing: dict[TaskState, float]

    #: The available resources on this worker, e.g. ``{"GPU": 2}``.
    #: These are abstract quantities that constrain certain tasks from running at the
    #: same time on this worker.
    resources: dict[str, float]

    #: The sum of each resource used by all tasks allocated to this worker.
    #: The numbers in this dictionary can only be less or equal than those in this
    #: worker's :attr:`~WorkerState.resources`.
    used_resources: dict[str, float]

    #: Arbitrary additional metadata to be added to :meth:`~WorkerState.identity`
    extra: dict[str, Any]

    # The unique server ID this WorkerState is referencing
    server_id: str

    # Reference to scheduler task_groups
    scheduler_ref: weakref.ref[SchedulerState] | None
    task_prefix_count: defaultdict[str, int]
    _network_occ: float
    _occupancy_cache: float | None

    #: Keys that may need to be fetched to this worker, and the number of tasks that need them.
    #: All tasks are currently in `memory` on a worker other than this one.
    #: Much like `processing`, this does not exactly reflect worker state:
    #: keys here may be queued to fetch, in flight, or already in memory
    #: on the worker.
    needs_what: dict[TaskState, int]

    __slots__ = tuple(__annotations__)

    def __init__(
        self,
        *,
        address: str,
        status: Status,
        pid: int,
        name: object,
        nthreads: int = 0,
        memory_limit: int,
        local_directory: str,
        nanny: str,
        server_id: str,
        services: dict[str, int] | None = None,
        versions: dict[str, Any] | None = None,
        extra: dict[str, Any] | None = None,
        scheduler: SchedulerState | None = None,
    ):
        self.server_id = server_id
        self.address = address
        self.pid = pid
        self.name = name
        self.nthreads = nthreads
        self.memory_limit = memory_limit
        self.local_directory = local_directory
        self.services = services or {}
        self.versions = versions or {}
        self.nanny = nanny
        self.status = status
        self._hash = hash(self.server_id)
        self.nbytes = 0
        self._memory_unmanaged_old = 0
        self._memory_unmanaged_history = deque()
        self.metrics = {}
        self.last_seen = 0
        self.time_delay = 0
        self.bandwidth = parse_bytes(dask.config.get("distributed.scheduler.bandwidth"))
        self.actors = set()
        self._has_what = {}
        self.processing = set()
        self.long_running = set()
        self.executing = {}
        self.resources = {}
        self.used_resources = {}
        self.extra = extra or {}
        self.scheduler_ref = weakref.ref(scheduler) if scheduler else None
        self.task_prefix_count = defaultdict(int)
        self.needs_what = {}
        self._network_occ = 0
        self._occupancy_cache = None

    def __hash__(self) -> int:
        return self._hash

    def __eq__(self, other: object) -> bool:
        return isinstance(other, WorkerState) and other.server_id == self.server_id

    @property
    def has_what(self) -> Set[TaskState]:
        """An insertion-sorted set-like of tasks which currently reside on this worker.
        All the tasks here are in the "memory" state.
        This is the reverse mapping of :attr:`TaskState.who_has`.

        This is a read-only public accessor. The data is implemented as a dict without
        values, because rebalance() relies on dicts being insertion-sorted.
        """
        return self._has_what.keys()

    @property
    def host(self) -> str:
        return get_address_host(self.address)

    @property
    def memory(self) -> MemoryState:
        """Polished memory metrics for the worker.

        **Design note on managed memory**

        There are two measures available for managed memory:

        - ``self.nbytes``
        - ``self.metrics["managed_bytes"]``

        At rest, the two numbers must be identical. However, ``self.nbytes`` is
        immediately updated through the batched comms as soon as each task lands in
        memory on the worker; ``self.metrics["managed_bytes"]`` instead is updated by
        the heartbeat, which can lag several seconds behind.

        Below we are mixing likely newer managed memory info from ``self.nbytes`` with
        process and spilled memory from the heartbeat. This is deliberate, so that
        managed memory total is updated more frequently.

        Managed memory directly and immediately contributes to optimistic memory, which
        is in turn used in Active Memory Manager heuristics (at the moment of writing;
        more uses will likely be added in the future). So it's important to have it
        up to date; much more than it is for process memory.

        Having up-to-date managed memory info as soon as the scheduler learns about
        task completion also substantially simplifies unit tests.

        The flip side of this design is that it may cause some noise in the
        unmanaged_recent measure. e.g.:

        1. Delete 100MB of managed data
        2. The updated managed memory reaches the scheduler faster than the
           updated process memory
        3. There's a blip where the scheduler thinks that there's a sudden 100MB
           increase in unmanaged_recent, since process memory hasn't changed but managed
           memory has decreased by 100MB
        4. When the heartbeat arrives, process memory goes down and so does the
           unmanaged_recent.

        This is OK - one of the main reasons for the unmanaged_recent / unmanaged_old
        split is exactly to concentrate all the noise in unmanaged_recent and exclude it
        from optimistic memory, which is used for heuristics.

        Something that is less OK, but also less frequent, is that the sudden deletion
        of spilled keys will cause a negative blip of managed_in_memory:

        1. Delete 100MB of spilled data
        2. The updated managed memory *total* reaches the scheduler faster than the
           updated spilled portion
        3. This causes managed_in_memory to temporarily plummet and be replaced by
           unmanaged_recent, while managed_spilled remains unaltered
        4. When the heartbeat arrives, managed_in_memory goes back up, unmanaged_recent
           goes back down, and managed_spilled goes down by 100MB as it should have to
           begin with.

        https://github.com/dask/distributed/issues/6002 will let us solve this.
        """
        return MemoryState(
            process=self.metrics["memory"],
            managed_in_memory=max(
                0, self.nbytes - self.metrics["spilled_bytes"]["memory"]
            ),
            managed_spilled=self.metrics["spilled_bytes"]["disk"],
            unmanaged_old=self._memory_unmanaged_old,
        )

    def clean(self) -> WorkerState:
        """Return a version of this object that is appropriate for serialization"""
        ws = WorkerState(
            address=self.address,
            status=self.status,
            pid=self.pid,
            name=self.name,
            nthreads=self.nthreads,
            memory_limit=self.memory_limit,
            local_directory=self.local_directory,
            services=self.services,
            nanny=self.nanny,
            extra=self.extra,
            server_id=self.server_id,
        )
        ws._occupancy_cache = self.occupancy

        ws.executing = {
            ts.key: duration for ts, duration in self.executing.items()  # type: ignore
        }
        return ws

    def __repr__(self) -> str:
        name = f", name: {self.name}" if self.name != self.address else ""
        return (
            f"<WorkerState {self.address!r}{name}, "
            f"status: {self.status.name}, "
            f"memory: {len(self.has_what)}, "
            f"processing: {len(self.processing)}>"
        )

    def _repr_html_(self) -> str:
        return get_template("worker_state.html.j2").render(
            address=self.address,
            name=self.name,
            status=self.status.name,
            has_what=self.has_what,
            processing=self.processing,
        )

    def identity(self) -> dict[str, Any]:
        return {
            "type": "Worker",
            "id": self.name,
            "host": self.host,
            "resources": self.resources,
            "local_directory": self.local_directory,
            "name": self.name,
            "nthreads": self.nthreads,
            "memory_limit": self.memory_limit,
            "last_seen": self.last_seen,
            "services": self.services,
            "metrics": self.metrics,
            "status": self.status.name,
            "nanny": self.nanny,
            **self.extra,
        }

    def _to_dict_no_nest(self, *, exclude: Container[str] = ()) -> dict[str, Any]:
        """Dictionary representation for debugging purposes.
        Not type stable and not intended for roundtrips.

        See also
        --------
        Client.dump_cluster_state
        distributed.utils.recursive_to_dict
        TaskState._to_dict
        """
        return recursive_to_dict(
            self,
            exclude=set(exclude) | {"versions"},  # type: ignore
            members=True,
        )

    @property
    def scheduler(self) -> SchedulerState:
        assert self.scheduler_ref
        s = self.scheduler_ref()
        assert s
        return s

    def add_to_processing(self, ts: TaskState) -> None:
        """Assign a task to this worker for compute."""
        if self.scheduler.validate:
            assert ts not in self.processing

        tp = ts.prefix
        self.task_prefix_count[tp.name] += 1
        self.scheduler._task_prefix_count_global[tp.name] += 1
        self.processing.add(ts)
        for dts in ts.dependencies:
            if self not in dts.who_has:
                self._inc_needs_replica(dts)

    def add_to_long_running(self, ts: TaskState) -> None:
        if self.scheduler.validate:
            assert ts in self.processing
            assert ts not in self.long_running

        self._remove_from_task_prefix_count(ts)
        # Cannot remove from processing since we're using this for things like
        # idleness detection. Idle workers are typically targeted for
        # downscaling but we should not downscale workers with long running
        # tasks
        self.long_running.add(ts)

    def remove_from_processing(self, ts: TaskState) -> None:
        """Remove a task from a workers processing"""
        if self.scheduler.validate:
            assert ts in self.processing

        if ts in self.long_running:
            self.long_running.discard(ts)
        else:
            self._remove_from_task_prefix_count(ts)
        self.processing.remove(ts)
        for dts in ts.dependencies:
            if dts in self.needs_what:
                self._dec_needs_replica(dts)

    def _remove_from_task_prefix_count(self, ts: TaskState) -> None:
        count = self.task_prefix_count[ts.prefix.name] - 1
        if count:
            self.task_prefix_count[ts.prefix.name] = count
        else:
            del self.task_prefix_count[ts.prefix.name]

        count = self.scheduler._task_prefix_count_global[ts.prefix.name] - 1
        if count:
            self.scheduler._task_prefix_count_global[ts.prefix.name] = count
        else:
            del self.scheduler._task_prefix_count_global[ts.prefix.name]

    def remove_replica(self, ts: TaskState) -> None:
        """The worker no longer has a task in memory"""
        if self.scheduler.validate:
            assert self in ts.who_has
            assert ts in self.has_what
            assert ts not in self.needs_what

        self.nbytes -= ts.get_nbytes()
        del self._has_what[ts]
        ts.who_has.remove(self)

    def _inc_needs_replica(self, ts: TaskState) -> None:
        """Assign a task fetch to this worker and update network occupancies"""
        if self.scheduler.validate:
            assert self not in ts.who_has
            assert ts not in self.has_what
        if ts not in self.needs_what:
            self.needs_what[ts] = 1
            nbytes = ts.get_nbytes()
            self._network_occ += nbytes
            self.scheduler._network_occ_global += nbytes
        else:
            self.needs_what[ts] += 1

    def _dec_needs_replica(self, ts: TaskState) -> None:
        if self.scheduler.validate:
            assert ts in self.needs_what

        self.needs_what[ts] -= 1
        if self.needs_what[ts] == 0:
            del self.needs_what[ts]
            nbytes = ts.get_nbytes()
            self._network_occ -= nbytes
            self.scheduler._network_occ_global -= nbytes

    def add_replica(self, ts: TaskState) -> None:
        """The worker acquired a replica of task"""
        if self.scheduler.validate:
            assert self not in ts.who_has
            assert ts not in self.has_what

        nbytes = ts.get_nbytes()
        if ts in self.needs_what:
            del self.needs_what[ts]
            self._network_occ -= nbytes
            self.scheduler._network_occ_global -= nbytes
        ts.who_has.add(self)
        self.nbytes += nbytes
        self._has_what[ts] = None

    @property
    def occupancy(self) -> float:
        return self._occupancy_cache or self.scheduler._calc_occupancy(
            self.task_prefix_count, self._network_occ
        )


@dataclasses.dataclass
class ErredTask:
    """Lightweight representation of an erred task without any dependency information
    or runspec.

    See also
    --------
    TaskState
    """

    key: Hashable
    timestamp: float
    erred_on: set[str]
    exception_text: str
    traceback_text: str


class Computation:
    """Collection tracking a single compute or persist call

    See also
    --------
    TaskPrefix
    TaskGroup
    TaskState
    """

    start: float
    groups: set[TaskGroup]
    code: SortedSet
    id: uuid.UUID

    __slots__ = tuple(__annotations__)

    def __init__(self):
        self.start = time()
        self.groups = set()
        self.code = SortedSet()
        self.id = uuid.uuid4()

    @property
    def stop(self) -> float:
        if self.groups:
            return max(tg.stop for tg in self.groups)
        else:
            return -1

    @property
    def states(self) -> dict[TaskStateState, int]:
        return merge_with(sum, (tg.states for tg in self.groups))

    def __repr__(self) -> str:
        return (
            f"<Computation {self.id}: "
            + "Tasks: "
            + ", ".join(
                "%s: %d" % (k, v) for (k, v) in sorted(self.states.items()) if v
            )
            + ">"
        )

    def _repr_html_(self) -> str:
        return get_template("computation.html.j2").render(
            id=self.id,
            start=self.start,
            stop=self.stop,
            groups=self.groups,
            states=self.states,
            code=self.code,
        )


class TaskPrefix:
    """Collection tracking all tasks within a group

    Keys often have a structure like ``("x-123", 0)``
    A group takes the first section, like ``"x"``

    See Also
    --------
    TaskGroup
    """

    #: The name of a group of tasks.
    #: For a task like ``("x-123", 0)`` this is the text ``"x"``
    name: str

    #: An exponentially weighted moving average duration of all tasks with this prefix
    duration_average: float

    #: Numbers of times a task was marked as suspicious with this prefix
    suspicious: int

    #: Store timings for each prefix-action
    all_durations: defaultdict[str, float]

    #: This measures the maximum recorded live execution time and can be used to
    #: detect outliers
    max_exec_time: float

    #: Task groups associated to this prefix
    groups: list[TaskGroup]

    #: Accumulate count of number of tasks in each state
    state_counts: defaultdict[str, int]

    __slots__ = tuple(__annotations__)

    def __init__(self, name: str):
        self.name = name
        self.groups = []
        self.all_durations = defaultdict(float)
        self.state_counts = defaultdict(int)
        task_durations = dask.config.get("distributed.scheduler.default-task-durations")
        if self.name in task_durations:
            self.duration_average = parse_timedelta(task_durations[self.name])
        else:
            self.duration_average = -1
        self.max_exec_time = -1
        self.suspicious = 0

    def add_exec_time(self, duration: float) -> None:
        self.max_exec_time = max(duration, self.max_exec_time)
        if duration > 2 * self.duration_average:
            self.duration_average = -1

    def add_duration(self, action: str, start: float, stop: float) -> None:
        duration = stop - start
        self.all_durations[action] += duration
        if action == "compute":
            old = self.duration_average
            if old < 0:
                self.duration_average = duration
            else:
                self.duration_average = 0.5 * duration + 0.5 * old

    @property
    def states(self) -> dict[str, int]:
        """The number of tasks in each state,
        like ``{"memory": 10, "processing": 3, "released": 4, ...}``
        """
        return merge_with(sum, [tg.states for tg in self.groups])

    @property
    def active(self) -> list[TaskGroup]:
        return [
            tg
            for tg in self.groups
            if any(k != "forgotten" and v != 0 for k, v in tg.states.items())
        ]

    @property
    def active_states(self) -> dict[str, int]:
        return merge_with(sum, [tg.states for tg in self.active])

    def __repr__(self) -> str:
        return (
            "<"
            + self.name
            + ": "
            + ", ".join(
                "%s: %d" % (k, v) for (k, v) in sorted(self.states.items()) if v
            )
            + ">"
        )

    @property
    def nbytes_total(self) -> int:
        return sum(tg.nbytes_total for tg in self.groups)

    def __len__(self) -> int:
        return sum(map(len, self.groups))

    @property
    def duration(self) -> float:
        return sum(tg.duration for tg in self.groups)

    @property
    def types(self) -> set[str]:
        return {typ for tg in self.groups for typ in tg.types}


class TaskGroup:
    """Collection tracking all tasks within a group

    Keys often have a structure like ``("x-123", 0)``
    A group takes the first section, like ``"x-123"``

    See also
    --------
    TaskPrefix
    """

    #: The name of a group of tasks.
    #: For a task like ``("x-123", 0)`` this is the text ``"x-123"``
    name: str

    #: The number of tasks in each state,
    #: like ``{"memory": 10, "processing": 3, "released": 4, ...}``
    states: dict[TaskStateState, int]

    #: The other TaskGroups on which this one depends
    dependencies: set[TaskGroup]

    #: The total number of bytes that this task group has produced
    nbytes_total: int

    #: The total amount of time spent on all tasks in this TaskGroup
    duration: float

    #: The result types of this TaskGroup
    types: set[str]

    #: The worker most recently assigned a task from this group, or None when the group
    #: is not identified to be root-like by `SchedulerState.decide_worker`.
    last_worker: WorkerState | None

    #: If `last_worker` is not None, the number of times that worker should be assigned
    #: subsequent tasks until a new worker is chosen.
    last_worker_tasks_left: int

    prefix: TaskPrefix | None
    start: float
    stop: float
    all_durations: defaultdict[str, float]

    __slots__ = tuple(__annotations__)

    def __init__(self, name: str):
        self.name = name
        self.prefix = None
        self.states = dict.fromkeys(ALL_TASK_STATES, 0)
        self.dependencies = set()
        self.nbytes_total = 0
        self.duration = 0
        self.types = set()
        self.start = 0.0
        self.stop = 0.0
        self.all_durations = defaultdict(float)
        self.last_worker = None
        self.last_worker_tasks_left = 0

    def add_duration(self, action: str, start: float, stop: float) -> None:
        duration = stop - start
        self.all_durations[action] += duration
        if action == "compute":
            if self.stop < stop:
                self.stop = stop
            self.start = self.start or start
        self.duration += duration
        assert self.prefix is not None
        self.prefix.add_duration(action, start, stop)

    def add(self, other: TaskState) -> None:
        self.states[other.state] += 1
        other.group = self

    def __repr__(self) -> str:
        return (
            "<"
            + (self.name or "no-group")
            + ": "
            + ", ".join(
                "%s: %d" % (k, v) for (k, v) in sorted(self.states.items()) if v
            )
            + ">"
        )

    def __len__(self) -> int:
        return sum(self.states.values())

    def _to_dict_no_nest(self, *, exclude: Container[str] = ()) -> dict[str, Any]:
        """Dictionary representation for debugging purposes.
        Not type stable and not intended for roundtrips.

        See also
        --------
        Client.dump_cluster_state
        distributed.utils.recursive_to_dict
        TaskState._to_dict
        """
        return recursive_to_dict(self, exclude=exclude, members=True)


class TaskState:
    """A simple object holding information about a task.

    Not to be confused with :class:`distributed.worker_state_machine.TaskState`, which
    holds similar information on the Worker side.
    """

    #: The key is the unique identifier of a task, generally formed from the name of the
    #: function, followed by a hash of the function and arguments, like
    #: ``'inc-ab31c010444977004d656610d2d421ec'``.
    key: str

    #: The broad class of tasks to which this task belongs like "inc" or "read_csv"
    prefix: TaskPrefix

    #: A specification of how to run the task.  The type and meaning of this value is
    #: opaque to the scheduler, as it is only interpreted by the worker to which the
    #: task is sent for executing.
    #:
    #: As a special case, this attribute may also be ``None``, in which case the task is
    #: "pure data" (such as, for example, a piece of data loaded in the scheduler using
    #: :meth:`Client.scatter`).  A "pure data" task cannot be computed again if its
    #: value is lost.
    run_spec: object

    #: The priority provides each task with a relative ranking which is used to break
    #: ties when many tasks are being considered for execution.
    #:
    #: This ranking is generally a 2-item tuple.  The first (and dominant) item
    #: corresponds to when it was submitted.  Generally, earlier tasks take precedence.
    #: The second item is determined by the client, and is a way to prioritize tasks
    #: within a large graph that may be important, such as if they are on the critical
    #: path, or good to run in order to release many dependencies.  This is explained
    #: further in :doc:`Scheduling Policy <scheduling-policies>`.
    priority: tuple[int, ...]

    # Attribute underlying the state property
    _state: TaskStateState

    #: The set of tasks this task depends on for proper execution. Only tasks still
    #: alive are listed in this set. If, for whatever reason, this task also depends on
    #: a forgotten task, the :attr:`has_lost_dependencies` flag is set.
    #:
    #: A task can only be executed once all its dependencies have already been
    #: successfully executed and have their result stored on at least one worker. This
    #: is tracked by progressively draining the :attr:`waiting_on` set.
    dependencies: set[TaskState]

    #: The set of tasks which depend on this task.  Only tasks still alive are listed in
    #: this set. This is the reverse mapping of :attr:`dependencies`.
    dependents: set[TaskState]

    #: Whether any of the dependencies of this task has been forgotten. For memory
    #: consumption reasons, forgotten tasks are not kept in memory even though they may
    #: have dependent tasks.  When a task is forgotten, therefore, each of its
    #: dependents has their :attr:`has_lost_dependencies` attribute set to ``True``.
    #:
    #: If :attr:`has_lost_dependencies` is true, this task cannot go into the
    #: "processing" state anymore.
    has_lost_dependencies: bool

    #: The set of tasks this task is waiting on *before* it can be executed. This is
    #: always a subset of :attr:`dependencies`.  Each time one of the dependencies has
    #: finished processing, it is removed from the :attr:`waiting_on` set.
    #:
    #: Once :attr:`waiting_on` becomes empty, this task can move from the "waiting"
    #: state to the "processing" state (unless one of the dependencies errored out, in
    #: which case this task is instead marked "erred").
    waiting_on: set[TaskState]

    #: The set of tasks which need this task to remain alive.  This is always a subset
    #: of :attr:`dependents`.  Each time one of the dependents has finished processing,
    #: it is removed from the :attr:`waiters` set.
    #:
    #: Once both :attr:`waiters` and :attr:`who_wants` become empty, this task can be
    #: released (if it has a non-empty :attr:`run_spec`) or forgotten (otherwise) by the
    #: scheduler, and by any workers in :attr:`who_has`.
    #:
    #: .. note::
    #:    Counter-intuitively, :attr:`waiting_on` and :attr:`waiters` are not reverse
    #:    mappings of each other.
    waiters: set[TaskState]

    #: The set of clients who want the result of this task to remain alive.
    #: This is the reverse mapping of :attr:`ClientState.wants_what`.
    #:
    #: When a client submits a graph to the scheduler it also specifies which output
    #: tasks it desires, such that their results are not released from memory.
    #:
    #: Once a task has finished executing (i.e. moves into the "memory" or "erred"
    #: state), the clients in :attr:`who_wants` are notified.
    #:
    #: Once both :attr:`waiters` and :attr:`who_wants` become empty, this task can be
    #: released (if it has a non-empty :attr:`run_spec`) or forgotten (otherwise) by the
    #: scheduler, and by any workers in :attr:`who_has`.
    who_wants: set[ClientState]

    #: The set of workers who have this task's result in memory. It is non-empty iff the
    #: task is in the "memory" state.  There can be more than one worker in this set if,
    #: for example, :meth:`Client.scatter` or :meth:`Client.replicate` was used.
    #:
    #: This is the reverse mapping of :attr:`WorkerState.has_what`.
    who_has: set[WorkerState]

    #: If this task is in the "processing" state, which worker is currently processing
    #: it. This attribute is kept in sync with :attr:`WorkerState.processing`.
    processing_on: WorkerState | None

    #: The number of times this task can automatically be retried in case of failure.
    #: If a task fails executing (the worker returns with an error), its :attr:`retries`
    #: attribute is checked. If it is equal to 0, the task is marked "erred". If it is
    #: greater than 0, the :attr:`retries` attribute is decremented and execution is
    #: attempted again.
    retries: int

    #: The number of bytes, as determined by ``sizeof``, of the result of a finished
    #: task. This number is used for diagnostics and to help prioritize work.
    #: Set to -1 for unfinished tasks.
    nbytes: int

    #: The type of the object as a string. Only present for tasks that have been
    #: computed.
    type: str

    #: If this task failed executing, the exception object is stored here.
    exception: Serialized | None

    #: If this task failed executing, the traceback object is stored here.
    traceback: Serialized | None

    #: string representation of exception
    exception_text: str

    #: string representation of traceback
    traceback_text: str

    #: If this task or one of its dependencies failed executing, the failed task is
    #: stored here (possibly itself).
    exception_blame: TaskState | None

    #: Worker addresses on which errors appeared, causing this task to be in an error
    #: state.
    erred_on: set[str]

    #: The number of times this task has been involved in a worker death.
    #:
    #: Some tasks may cause workers to die (such as calling ``os._exit(0)``). When a
    #: worker dies, all of the tasks on that worker are reassigned to others. This
    #: combination of behaviors can cause a bad task to catastrophically destroy all
    #: workers on the cluster, one after another. Whenever a worker dies, we mark each
    #: task currently processing on that worker (as recorded by
    #: :attr:`WorkerState.processing`) as suspicious. If a task is involved in three
    #: deaths (or some other fixed constant) then we mark the task as ``erred``.
    suspicious: int

    #: A set of hostnames where this task can be run (or ``None`` if empty). Usually
    #: this is empty unless the task has been specifically restricted to only run on
    #: certain hosts. A hostname may correspond to one or several connected workers.
    host_restrictions: set[str]

    #: A set of complete worker addresses where this can be run (or ``None`` if empty).
    #: Usually this is empty unless the task has been specifically restricted to only
    #: run on certain workers.
    #: Note this is tracking worker addresses, not worker states, since the specific
    #: workers may not be connected at this time.
    worker_restrictions: set[str]

    #: Resources required by this task, such as ``{'gpu': 1}`` or ``{'memory': 1e9}``
    #: These are user-defined names and are matched against the : contents of each
    #: :attr:`WorkerState.resources` dictionary.
    resource_restrictions: dict[str, float]

    #: False
    #:     Each of :attr:`host_restrictions`, :attr:`worker_restrictions` and
    #:     :attr:`resource_restrictions` is a hard constraint: if no worker is available
    #:     satisfying those restrictions, the task cannot go into the "processing" state
    #:     and will instead go into the "no-worker" state.
    #: True
    #:     The above restrictions are mere preferences: if no worker is available
    #:     satisfying those restrictions, the task can still go into the
    #:     "processing" state and be sent for execution to another connected worker.
    loose_restrictions: bool

    #: Whether this task is an Actor
    actor: bool

    #: The group of tasks to which this one belongs
    group: TaskGroup

    #: Same as of group.name
    group_key: str

    #: Metadata related to task
    metadata: dict[str, Any]

    #: Task annotations
    annotations: dict[str, Any]

    #: Cached hash of :attr:`~TaskState.client_key`
    _hash: int

    # Support for weakrefs to a class with __slots__
    __weakref__: Any = None
    __slots__ = tuple(__annotations__)

    # Instances not part of slots since class variable
    _instances: ClassVar[weakref.WeakSet[TaskState]] = weakref.WeakSet()

    def __init__(self, key: str, run_spec: object, state: TaskStateState):
        self.key = key
        self._hash = hash(key)
        self.run_spec = run_spec
        self._state = state
        self.exception = None
        self.exception_blame = None
        self.traceback = None
        self.exception_text = ""
        self.traceback_text = ""
        self.suspicious = 0
        self.retries = 0
        self.nbytes = -1
        self.priority = None  # type: ignore
        self.who_wants = set()
        self.dependencies = set()
        self.dependents = set()
        self.waiting_on = set()
        self.waiters = set()
        self.who_has = set()
        self.processing_on = None
        self.has_lost_dependencies = False
        self.host_restrictions = None  # type: ignore
        self.worker_restrictions = None  # type: ignore
        self.resource_restrictions = {}
        self.loose_restrictions = False
        self.actor = False
        self.prefix = None  # type: ignore
        self.type = None  # type: ignore
        self.group_key = key_split_group(key)
        self.group = None  # type: ignore
        self.metadata = {}
        self.annotations = {}
        self.erred_on = set()
        TaskState._instances.add(self)

    def __hash__(self) -> int:
        return self._hash

    def __eq__(self, other: object) -> bool:
        return isinstance(other, TaskState) and self.key == other.key

    @property
    def state(self) -> TaskStateState:
        """This task's current state.  Valid states are ``released``, ``waiting``,
        ``no-worker``, ``processing``, ``memory``, ``erred`` and ``forgotten``.  If it
        is ``forgotten``, the task isn't stored in the ``tasks`` dictionary anymore and
        will probably disappear soon from memory.
        """
        return self._state

    @state.setter
    def state(self, value: TaskStateState) -> None:
        self.group.states[self._state] -= 1
        self.group.states[value] += 1
        self._state = value
        self.prefix.state_counts[value] += 1

    def add_dependency(self, other: TaskState) -> None:
        """Add another task as a dependency of this task"""
        self.dependencies.add(other)
        self.group.dependencies.add(other.group)
        other.dependents.add(self)

    def get_nbytes(self) -> int:
        return self.nbytes if self.nbytes >= 0 else DEFAULT_DATA_SIZE

    def set_nbytes(self, nbytes: int) -> None:
        diff = nbytes
        old_nbytes = self.nbytes
        if old_nbytes >= 0:
            diff -= old_nbytes
        self.group.nbytes_total += diff
        for ws in self.who_has:
            ws.nbytes += diff
        self.nbytes = nbytes

    def __repr__(self) -> str:
        return f"<TaskState {self.key!r} {self._state}>"

    def _repr_html_(self) -> str:
        return get_template("task_state.html.j2").render(
            state=self.state,
            nbytes=self.nbytes,
            key=self.key,
        )

    def validate(self) -> None:
        try:
            for cs in self.who_wants:
                assert isinstance(cs, ClientState), (repr(cs), self.who_wants)
            for ws in self.who_has:
                assert isinstance(ws, WorkerState), (repr(ws), self.who_has)
            for ts in self.dependencies:
                assert isinstance(ts, TaskState), (repr(ts), self.dependencies)
            for ts in self.dependents:
                assert isinstance(ts, TaskState), (repr(ts), self.dependents)
            validate_task_state(self)
        except Exception as e:
            logger.exception(e)
            if LOG_PDB:
                import pdb

                pdb.set_trace()

    def get_nbytes_deps(self) -> int:
        return sum(ts.get_nbytes() for ts in self.dependencies)

    def _to_dict_no_nest(self, *, exclude: Container[str] = ()) -> dict[str, Any]:
        """Dictionary representation for debugging purposes.
        Not type stable and not intended for roundtrips.

        See also
        --------
        Client.dump_cluster_state
        distributed.utils.recursive_to_dict

        Notes
        -----
        This class uses ``_to_dict_no_nest`` instead of ``_to_dict``.
        When a task references another task, or when a WorkerState.tasks contains tasks,
        this method is not executed for the inner task, even if the inner task was never
        seen before; you get a repr instead. All tasks should neatly appear under
        Scheduler.tasks. This also prevents a RecursionError during particularly heavy
        loads, which have been observed to happen whenever there's an acyclic dependency
        chain of ~200+ tasks.
        """
        return recursive_to_dict(self, exclude=exclude, members=True)


class Transition(NamedTuple):
    """An entry in :attr:`SchedulerState.transition_log`"""

    key: str
    start: TaskStateState
    finish: TaskStateState
    recommendations: Recs
    stimulus_id: str
    timestamp: float


class SchedulerState:
    """Underlying task state of dynamic scheduler

    Tracks the current state of workers, data, and computations.

    Handles transitions between different task states. Notifies the
    Scheduler of changes by messaging passing through Queues, which the
    Scheduler listens to responds accordingly.

    All events are handled quickly, in linear time with respect to their
    input (which is often of constant size) and generally within a
    millisecond.

    Users typically do not interact with ``Transitions`` directly. Instead
    users interact with the ``Client``, which in turn engages the
    ``Scheduler`` affecting different transitions here under-the-hood. In
    the background ``Worker``s also engage with the ``Scheduler``
    affecting these state transitions as well.
    """

    bandwidth: int

    #: Clients currently connected to the scheduler
    clients: dict[str, ClientState]

    extensions: dict[str, Any]  # TODO write a scheduler extension Protocol
    plugins: dict[str, SchedulerPlugin]
    host_info: dict[str, dict[str, Any]]

    #: If True, enable expensive internal consistency check.
    #: Typically disabled in production.
    validate: bool

    #######################
    # Workers-related state
    #######################

    #: Workers currently connected to the scheduler
    #: (actually a SortedDict, but the sortedcontainers package isn't annotated)
    workers: dict[str, WorkerState]
    #: Worker {name: address}
    aliases: dict[Hashable, str]
    #: Workers that are currently in running state
    running: set[WorkerState]
    #: Workers that are currently in running state and not fully utilized
    #: Definition based on occupancy
    #: (actually a SortedDict, but the sortedcontainers package isn't annotated)
    idle: dict[str, WorkerState]
    #: Similar to `idle`
    #: Definition based on assigned tasks
    idle_task_count: set[WorkerState]
    #: Workers that are fully utilized. May include non-running workers.
    saturated: set[WorkerState]
    total_nthreads: int
    #: Cluster-wide resources. {resource name: {worker address: amount}}
    resources: dict[str, dict[str, float]]

    #####################
    # Tasks-related state
    #####################

    #: Total number of tasks ever processed
    n_tasks: int

    #: All tasks currently known to the scheduler
    tasks: dict[str, TaskState]

    #: Tasks in the "queued" state, ordered by priority
    queued: HeapSet[TaskState]

    #: Tasks in the "no-worker" state
    unrunnable: set[TaskState]

    #: Subset of tasks that exist in memory on more than one worker
    replicated_tasks: set[TaskState]

    unknown_durations: dict[str, set[TaskState]]
    task_groups: dict[str, TaskGroup]
    task_prefixes: dict[str, TaskPrefix]
    task_metadata: dict[str, Any]

    #########
    # History
    #########

    #: History of computations.
    #: The length can be tweaked through
    #: distributed.diagnostics.computations.max-history
    computations: deque[Computation]

    #: History of erred tasks.
    #: The length can be tweaked through
    #: distributed.diagnostics.erred-tasks.max-history
    erred_tasks: deque[ErredTask]

    #: History of task state transitions.
    #: The length can be tweaked through
    #: distributed.scheduler.transition-log-length
    transition_log: deque[Transition]

    #: Total number of transitions since the cluster was started
    transition_counter: int

    #: Total number of transitions as of the previous call to check_idle()
    _idle_transition_counter: int

    #: Raise an error if the :attr:`transition_counter` ever reaches this value.
    #: This is meant for debugging only, to catch infinite recursion loops.
    #: In production, it should always be set to False.
    transition_counter_max: int | Literal[False]

    _task_prefix_count_global: defaultdict[str, int]
    _network_occ_global: float
    ######################
    # Cached configuration
    ######################

    #: distributed.scheduler.unknown-task-duration
    UNKNOWN_TASK_DURATION: float
    #: distributed.worker.memory.recent-to-old-time
    MEMORY_RECENT_TO_OLD_TIME: float
    #: distributed.worker.memory.rebalance.measure
    MEMORY_REBALANCE_MEASURE: str
    #: distributed.worker.memory.rebalance.sender-min
    MEMORY_REBALANCE_SENDER_MIN: float
    #: distributed.worker.memory.rebalance.recipient-max
    MEMORY_REBALANCE_RECIPIENT_MAX: float
    #: distributed.worker.memory.rebalance.sender-recipient-gap / 2
    MEMORY_REBALANCE_HALF_GAP: float
    #: distributed.scheduler.worker-saturation
    WORKER_SATURATION: float

    __slots__ = tuple(__annotations__)

    def __init__(
        self,
        aliases: dict[Hashable, str],
        clients: dict[str, ClientState],
        workers: SortedDict[str, WorkerState],
        host_info: dict[str, dict[str, Any]],
        resources: dict[str, dict[str, float]],
        tasks: dict[str, TaskState],
        unrunnable: set[TaskState],
        queued: HeapSet[TaskState],
        validate: bool,
        plugins: Iterable[SchedulerPlugin] = (),
        transition_counter_max: int | Literal[False] = False,
        **kwargs: Any,  # Passed verbatim to Server.__init__()
    ):
        logger.info("State start")
        self.aliases = aliases
        self.bandwidth = parse_bytes(dask.config.get("distributed.scheduler.bandwidth"))
        self.clients = clients
        self.clients["fire-and-forget"] = ClientState("fire-and-forget")
        self.extensions = {}
        self.host_info = host_info
        self.idle = SortedDict()
        self.idle_task_count = set()
        self.n_tasks = 0
        self.resources = resources
        self.saturated = set()
        self.tasks = tasks
        self.replicated_tasks = {
            ts for ts in self.tasks.values() if len(ts.who_has) > 1
        }
        self.computations = deque(
            maxlen=dask.config.get("distributed.diagnostics.computations.max-history")
        )
        self.erred_tasks = deque(
            maxlen=dask.config.get("distributed.diagnostics.erred-tasks.max-history")
        )
        self.task_groups = {}
        self.task_prefixes = {}
        self.task_metadata = {}
        self.total_nthreads = 0
        self.unknown_durations = {}
        self.queued = queued
        self.unrunnable = unrunnable
        self.validate = validate
        self.workers = workers
        self._task_prefix_count_global = defaultdict(int)
        self._network_occ_global = 0.0
        self.running = {
            ws for ws in self.workers.values() if ws.status == Status.running
        }
        self.plugins = {} if not plugins else {_get_plugin_name(p): p for p in plugins}

        self.transition_log = deque(
            maxlen=dask.config.get("distributed.scheduler.transition-log-length")
        )
        self.transition_counter = 0
        self._idle_transition_counter = 0
        self.transition_counter_max = transition_counter_max

        # Variables from dask.config, cached by __init__ for performance
        self.UNKNOWN_TASK_DURATION = parse_timedelta(
            dask.config.get("distributed.scheduler.unknown-task-duration")
        )
        self.MEMORY_RECENT_TO_OLD_TIME = parse_timedelta(
            dask.config.get("distributed.worker.memory.recent-to-old-time")
        )
        self.MEMORY_REBALANCE_MEASURE = dask.config.get(
            "distributed.worker.memory.rebalance.measure"
        )
        self.MEMORY_REBALANCE_SENDER_MIN = dask.config.get(
            "distributed.worker.memory.rebalance.sender-min"
        )
        self.MEMORY_REBALANCE_RECIPIENT_MAX = dask.config.get(
            "distributed.worker.memory.rebalance.recipient-max"
        )
        self.MEMORY_REBALANCE_HALF_GAP = (
            dask.config.get("distributed.worker.memory.rebalance.sender-recipient-gap")
            / 2.0
        )

        self.WORKER_SATURATION = dask.config.get(
            "distributed.scheduler.worker-saturation"
        )
        if self.WORKER_SATURATION == "inf":
            # Special case necessary because there's no way to parse a float infinity
            # from a DASK_* environment variable
            self.WORKER_SATURATION = math.inf
        if (
            not isinstance(self.WORKER_SATURATION, (int, float))
            or self.WORKER_SATURATION <= 0
        ):
            raise ValueError(  # pragma: nocover
                "`distributed.scheduler.worker-saturation` must be a float > 0; got "
                + repr(self.WORKER_SATURATION)
            )

    @property
    def memory(self) -> MemoryState:
        return MemoryState.sum(*(w.memory for w in self.workers.values()))

    @property
    def __pdict__(self) -> dict[str, Any]:
        return {
            "bandwidth": self.bandwidth,
            "resources": self.resources,
            "saturated": self.saturated,
            "unrunnable": self.unrunnable,
            "queued": self.queued,
            "n_tasks": self.n_tasks,
            "unknown_durations": self.unknown_durations,
            "validate": self.validate,
            "tasks": self.tasks,
            "task_groups": self.task_groups,
            "task_prefixes": self.task_prefixes,
            "total_nthreads": self.total_nthreads,
            "total_occupancy": self.total_occupancy,
            "erred_tasks": self.erred_tasks,
            "extensions": self.extensions,
            "clients": self.clients,
            "workers": self.workers,
            "idle": self.idle,
            "host_info": self.host_info,
        }

    def new_task(
        self,
        key: str,
        spec: object,
        state: TaskStateState,
        computation: Computation | None = None,
    ) -> TaskState:
        """Create a new task, and associated states"""
        ts = TaskState(key, spec, state)

        prefix_key = key_split(key)
        tp = self.task_prefixes.get(prefix_key)
        if tp is None:
            self.task_prefixes[prefix_key] = tp = TaskPrefix(prefix_key)
        ts.prefix = tp

        group_key = ts.group_key
        tg = self.task_groups.get(group_key)
        if tg is None:
            self.task_groups[group_key] = tg = TaskGroup(group_key)
            if computation:
                computation.groups.add(tg)
            tg.prefix = tp
            tp.groups.append(tg)
        tg.add(ts)

        self.tasks[key] = ts

        return ts

    def _clear_task_state(self) -> None:
        logger.debug("Clear task state")
        for collection in (
            self.unrunnable,
            self.erred_tasks,
            self.computations,
            self.task_prefixes,
            self.task_groups,
            self.task_metadata,
            self.unknown_durations,
            self.replicated_tasks,
        ):
            collection.clear()  # type: ignore

    @property
    def total_occupancy(self) -> float:
        return self._calc_occupancy(
            self._task_prefix_count_global,
            self._network_occ_global,
        )

    def _calc_occupancy(
        self,
        task_prefix_count: dict[str, int],
        network_occ: float,
    ) -> float:
        res = 0.0
        for prefix_name, count in task_prefix_count.items():
            # TODO: Deal with unknown tasks better
            prefix = self.task_prefixes[prefix_name]
            assert prefix is not None
            duration = prefix.duration_average
            if duration < 0:
                if prefix.max_exec_time > 0:
                    duration = 2 * prefix.max_exec_time
                else:
                    duration = self.UNKNOWN_TASK_DURATION
            res += duration * count
        occ = res + network_occ / self.bandwidth
        assert occ >= 0, occ
        return occ

    #####################
    # State Transitions #
    #####################

    def _transition(
        self, key: str, finish: TaskStateState, stimulus_id: str, **kwargs: Any
    ) -> RecsMsgs:
        """Transition a key from its current state to the finish state

        Examples
        --------
        >>> self._transition('x', 'waiting')
        {'x': 'processing'}, {}, {}

        Returns
        -------
        Tuple of:

        - Dictionary of recommendations for future transitions {key: new state}
        - Messages to clients {client address: [msg, msg, ...]}
        - Messages to workers {worker address: [msg, msg, ...]}

        See Also
        --------
        Scheduler.transitions : transitive version of this function
        """
        try:
            ts = self.tasks.get(key)
            if ts is None:
                return {}, {}, {}
            start = ts._state
            if start == finish:
                return {}, {}, {}

            # Notes:
            # - in case of transition through released, this counter is incremented by 2
            # - this increase happens before the actual transitions, so that it can
            #   catch potential infinite recursions
            self.transition_counter += 1
            if self.transition_counter_max:
                assert self.transition_counter < self.transition_counter_max

            recommendations: dict = {}
            worker_msgs: dict = {}
            client_msgs: dict = {}

            if self.plugins:
                dependents = set(ts.dependents)
                dependencies = set(ts.dependencies)

            func = self._TRANSITIONS_TABLE.get((start, finish))
            if func is not None:
                recommendations, client_msgs, worker_msgs = func(
                    self, key, stimulus_id, **kwargs
                )

            elif "released" not in (start, finish):
                assert not kwargs, (kwargs, start, finish)
                a_recs, a_cmsgs, a_wmsgs = self._transition(
                    key, "released", stimulus_id
                )

                v = a_recs.get(key, finish)
                func = self._TRANSITIONS_TABLE["released", v]
                b_recs, b_cmsgs, b_wmsgs = func(self, key, stimulus_id)

                recommendations.update(a_recs)
                for c, new_msgs in a_cmsgs.items():
                    client_msgs.setdefault(c, []).extend(new_msgs)
                for w, new_msgs in a_wmsgs.items():
                    worker_msgs.setdefault(w, []).extend(new_msgs)

                recommendations.update(b_recs)
                for c, new_msgs in b_cmsgs.items():
                    client_msgs.setdefault(c, []).extend(new_msgs)
                for w, new_msgs in b_wmsgs.items():
                    worker_msgs.setdefault(w, []).extend(new_msgs)

                start = "released"
            else:
                raise RuntimeError(
                    f"Impossible transition from {start} to {finish} for {key!r}: "
                    f"{stimulus_id=}, {kwargs=}, story={self.story(ts)}"
                )

            if not stimulus_id:
                stimulus_id = STIMULUS_ID_UNSET

            actual_finish = ts._state
            self.transition_log.append(
                Transition(
                    key, start, actual_finish, recommendations, stimulus_id, time()
                )
            )
            if self.validate:
                if stimulus_id == STIMULUS_ID_UNSET:
                    raise RuntimeError(
                        "stimulus_id not set during Scheduler transition"
                    )
                logger.debug(
                    "Transitioned %r %s->%s (actual: %s).  Consequence: %s",
                    key,
                    start,
                    finish,
                    actual_finish,
                    dict(recommendations),
                )
            if self.plugins:
                # Temporarily put back forgotten key for plugin to retrieve it
                if ts._state == "forgotten":
                    ts.dependents = dependents
                    ts.dependencies = dependencies
                    self.tasks[ts.key] = ts
                for plugin in list(self.plugins.values()):
                    try:
                        plugin.transition(key, start, actual_finish, **kwargs)
                    except Exception:
                        logger.info("Plugin failed with exception", exc_info=True)
                if ts.state == "forgotten":
                    del self.tasks[ts.key]

            tg = ts.group
            if ts.state == "forgotten" and tg.name in self.task_groups:
                # Remove TaskGroup if all tasks are in the forgotten state
                if all(v == 0 or k == "forgotten" for k, v in tg.states.items()):
                    ts.prefix.groups.remove(tg)
                    del self.task_groups[tg.name]

            return recommendations, client_msgs, worker_msgs
        except Exception:
            logger.exception("Error transitioning %r from %r to %r", key, start, finish)
            if LOG_PDB:
                import pdb

                pdb.set_trace()
            raise

    def _transitions(
        self,
        recommendations: Recs,
        client_msgs: Msgs,
        worker_msgs: Msgs,
        stimulus_id: str,
    ) -> None:
        """Process transitions until none are left

        This includes feedback from previous transitions and continues until we
        reach a steady state
        """
        keys: set[str] = set()
        recommendations = recommendations.copy()

        while recommendations:
            key, finish = recommendations.popitem()
            keys.add(key)

            new_recs, new_cmsgs, new_wmsgs = self._transition(key, finish, stimulus_id)

            recommendations.update(new_recs)
            for c, new_msgs in new_cmsgs.items():
                client_msgs.setdefault(c, []).extend(new_msgs)
            for w, new_msgs in new_wmsgs.items():
                worker_msgs.setdefault(w, []).extend(new_msgs)

        if self.validate:
            # FIXME downcast antipattern
            scheduler = cast(Scheduler, self)
            for key in keys:
                scheduler.validate_key(key)

    def transition_released_waiting(self, key: str, stimulus_id: str) -> RecsMsgs:
        ts = self.tasks[key]

        if self.validate:
            assert ts.run_spec
            assert not ts.waiting_on
            assert not ts.who_has
            assert not ts.processing_on
            for dts in ts.dependencies:
                assert dts.state not in {"forgotten", "erred"}

        if ts.has_lost_dependencies:
            return {key: "forgotten"}, {}, {}

        ts.state = "waiting"

        recommendations: Recs = {}

        for dts in ts.dependencies:
            if not dts.who_has:
                ts.waiting_on.add(dts)
            if dts.state == "released":
                recommendations[dts.key] = "waiting"
            else:
                dts.waiters.add(ts)

        ts.waiters = {dts for dts in ts.dependents if dts.state == "waiting"}

        if not ts.waiting_on:
            # NOTE: waiting->processing will send tasks to queued or no-worker as
            # necessary
            recommendations[key] = "processing"

        return recommendations, {}, {}

    def transition_no_worker_processing(self, key: str, stimulus_id: str) -> RecsMsgs:
        ts = self.tasks[key]
        worker_msgs: Msgs = {}

        if self.validate:
            assert not ts.actor, f"Actors can't be in `no-worker`: {ts}"
            assert ts in self.unrunnable

        if ws := self.decide_worker_non_rootish(ts):
            self.unrunnable.discard(ts)
            worker_msgs = self._add_to_processing(ts, ws)
        # If no worker, task just stays in `no-worker`

        return {}, {}, worker_msgs

    def decide_worker_rootish_queuing_disabled(
        self, ts: TaskState
    ) -> WorkerState | None:
        """Pick a worker for a runnable root-ish task, without queuing.

        This attempts to schedule sibling tasks on the same worker, reducing future data
        transfer. It does not consider the location of dependencies, since they'll end
        up on every worker anyway.

        It assumes it's being called on a batch of tasks in priority order, and
        maintains state in `SchedulerState.last_root_worker` and
        `SchedulerState.last_root_worker_tasks_left` to achieve this.

        This will send every runnable task to a worker, often causing root task
        overproduction.

        Returns
        -------
        ws: WorkerState | None
            The worker to assign the task to. If there are no workers in the cluster,
            returns None, in which case the task should be transitioned to
            ``no-worker``.
        """
        if self.validate:
            # See root-ish-ness note below in `decide_worker_rootish_queuing_enabled`
            assert math.isinf(self.WORKER_SATURATION)

        pool = self.idle.values() if self.idle else self.running
        if not pool:
            return None

        tg = ts.group
        lws = tg.last_worker
        if (
            lws
            and tg.last_worker_tasks_left
            and lws.status == Status.running
            and self.workers.get(lws.address) is lws
        ):
            ws = lws
        else:
            # Last-used worker is full, unknown, retiring, or paused;
            # pick a new worker for the next few tasks
            ws = min(pool, key=partial(self.worker_objective, ts))
            tg.last_worker_tasks_left = math.floor(
                (len(tg) / self.total_nthreads) * ws.nthreads
            )

        # Record `last_worker`, or clear it on the final task
        tg.last_worker = (
            ws if tg.states["released"] + tg.states["waiting"] > 1 else None
        )
        tg.last_worker_tasks_left -= 1

        if self.validate and ws is not None:
            assert self.workers.get(ws.address) is ws
            assert ws in self.running, (ws, self.running)

        return ws

    def decide_worker_rootish_queuing_enabled(self) -> WorkerState | None:
        """Pick a worker for a runnable root-ish task, if not all are busy.

        Picks the least-busy worker out of the ``idle`` workers (idle workers have fewer
        tasks running than threads, as set by ``distributed.scheduler.worker-saturation``).
        It does not consider the location of dependencies, since they'll end up on every
        worker anyway.

        If all workers are full, returns None, meaning the task should transition to
        ``queued``. The scheduler will wait to send it to a worker until a thread opens
        up. This ensures that downstream tasks always run before new root tasks are
        started.

        This does not try to schedule sibling tasks on the same worker; in fact, it
        usually does the opposite. Even though this increases subsequent data transfer,
        it typically reduces overall memory use by eliminating root task overproduction.

        Returns
        -------
        ws: WorkerState | None
            The worker to assign the task to. If there are no idle workers, returns
            None, in which case the task should be transitioned to ``queued``.

        """
        if self.validate:
            # We don't `assert self.is_rootish(ts)` here, because that check is
            # dependent on cluster size. It's possible a task looked root-ish when it
            # was queued, but the cluster has since scaled up and it no longer does when
            # coming out of the queue. If `is_rootish` changes to a static definition,
            # then add that assertion here (and actually pass in the task).
            assert not math.isinf(self.WORKER_SATURATION)

        if not self.idle_task_count:
            # All workers busy? Task gets/stays queued.
            return None

        # Just pick the least busy worker.
        # NOTE: this will lead to worst-case scheduling with regards to co-assignment.
        ws = min(
            self.idle_task_count,
            key=lambda ws: len(ws.processing) / ws.nthreads,
        )
        if self.validate:
            assert not _worker_full(ws, self.WORKER_SATURATION), (
                ws,
                _task_slots_available(ws, self.WORKER_SATURATION),
            )
            assert ws in self.running, (ws, self.running)

        if self.validate and ws is not None:
            assert self.workers.get(ws.address) is ws
            assert ws in self.running, (ws, self.running)

        return ws

    def decide_worker_non_rootish(self, ts: TaskState) -> WorkerState | None:
        """Pick a worker for a runnable non-root task, considering dependencies and
        restrictions.

        Out of eligible workers holding dependencies of ``ts``, selects the worker
        where, considering worker backlong and data-transfer costs, the task is
        estimated to start running the soonest.

        Returns
        -------
        ws: WorkerState | None
            The worker to assign the task to. If no workers satisfy the restrictions of
            ``ts`` or there are no running workers, returns None, in which case the task
            should be transitioned to ``no-worker``.
        """
        if not self.running:
            return None

        valid_workers = self.valid_workers(ts)
        if valid_workers is None and len(self.running) < len(self.workers):
            if not self.running:
                return None

            # If there were no restrictions, `valid_workers()` didn't subset by
            # `running`.
            valid_workers = self.running

        if ts.dependencies or valid_workers is not None:
            ws = decide_worker(
                ts,
                self.running,
                valid_workers,
                partial(self.worker_objective, ts),
            )
        else:
            # TODO if `is_rootish` would always return True for tasks without
            # dependencies, we could remove all this logic. The rootish assignment logic
            # would behave more or less the same as this, maybe without guaranteed
            # round-robin though? This path is only reachable when `ts` doesn't have
            # dependencies, but its group is also smaller than the cluster.

            # Fastpath when there are no related tasks or restrictions
            worker_pool = self.idle or self.workers
            # FIXME idle and workers are SortedDict's declared as dicts
            #       because sortedcontainers is not annotated
            wp_vals = cast("Sequence[WorkerState]", worker_pool.values())
            n_workers = len(wp_vals)
            if n_workers < 20:  # smart but linear in small case
                ws = min(wp_vals, key=operator.attrgetter("occupancy"))
                assert ws
                if ws.occupancy == 0:
                    # special case to use round-robin; linear search
                    # for next worker with zero occupancy (or just
                    # land back where we started).
                    start = self.n_tasks % n_workers
                    for i in range(n_workers):
                        wp_i = wp_vals[(i + start) % n_workers]
                        if wp_i.occupancy == 0:
                            ws = wp_i
                            break
            else:  # dumb but fast in large case
                ws = wp_vals[self.n_tasks % n_workers]

        if self.validate and ws is not None:
            assert self.workers.get(ws.address) is ws
            assert ws in self.running, (ws, self.running)

        return ws

    def transition_waiting_processing(self, key: str, stimulus_id: str) -> RecsMsgs:
        """Possibly schedule a ready task. This is the primary dispatch for ready tasks.

        If there's no appropriate worker for the task (but the task is otherwise
        runnable), it will be recommended to ``no-worker`` or ``queued``.
        """
        ts = self.tasks[key]

        if self.is_rootish(ts):
            # NOTE: having two root-ish methods is temporary. When the feature flag is
            # removed, there should only be one, which combines co-assignment and
            # queuing. Eventually, special-casing root tasks might be removed entirely,
            # with better heuristics.
            if math.isinf(self.WORKER_SATURATION):
                if not (ws := self.decide_worker_rootish_queuing_disabled(ts)):
                    return {ts.key: "no-worker"}, {}, {}
            else:
                if not (ws := self.decide_worker_rootish_queuing_enabled()):
                    return {ts.key: "queued"}, {}, {}
        else:
            if not (ws := self.decide_worker_non_rootish(ts)):
                return {ts.key: "no-worker"}, {}, {}

        worker_msgs = self._add_to_processing(ts, ws)
        return {}, {}, worker_msgs

    def transition_waiting_memory(
        self,
        key: str,
        stimulus_id: str,
        *,
        nbytes: int | None = None,
        type: bytes | None = None,
        typename: str | None = None,
        worker: str,
        **kwargs: Any,
    ) -> RecsMsgs:
        """This transition exclusively happens in a race condition where the scheduler
        believes that the only copy of a dependency task has just been lost, so it
        transitions all dependents back to waiting, but actually a replica has already
        been acquired by a worker computing the dependency - the scheduler just doesn't
        know yet - and the execution finishes before the cancellation message from the
        scheduler has a chance to reach the worker. Shortly, the cancellation request
        will reach the worker, thus deleting the data from memory.
        """
        ts = self.tasks[key]

        if self.validate:
            assert not ts.processing_on
            assert ts.waiting_on
            assert ts.state == "waiting"

        return {}, {}, {}

    def transition_processing_memory(
        self,
        key: str,
        stimulus_id: str,
        *,
        nbytes: int | None = None,
        type: bytes | None = None,
        typename: str | None = None,
        worker: str,
        startstops: list[dict] | None = None,
        **kwargs: Any,
    ) -> RecsMsgs:
        ts = self.tasks[key]

        assert worker
        assert isinstance(worker, str)

        if self.validate:
            assert ts.processing_on
            wss = ts.processing_on
            assert wss
            assert ts in wss.processing
            del wss
            assert not ts.waiting_on
            assert not ts.who_has, (ts, ts.who_has)
            assert not ts.exception_blame
            assert ts.state == "processing"

        ws = self.workers.get(worker)
        if ws is None:
            return {key: "released"}, {}, {}

        if ws != ts.processing_on:  # pragma: nocover
            assert ts.processing_on
            raise RuntimeError(
                f"Task {ts.key!r} transitioned from processing to memory on worker "
                f"{ws}, while it was expected from {ts.processing_on}. This should "
                f"be impossible. {stimulus_id=}, story={self.story(ts)}"
            )

        #############################
        # Update Timing Information #
        #############################
        if startstops:
            for startstop in startstops:
                ts.group.add_duration(
                    stop=startstop["stop"],
                    start=startstop["start"],
                    action=startstop["action"],
                )

        s = self.unknown_durations.pop(ts.prefix.name, set())
        steal = self.extensions.get("stealing")
        if steal:
            for tts in s:
                if tts.processing_on:
                    steal.recalculate_cost(tts)

        ############################
        # Update State Information #
        ############################
        if nbytes is not None:
            ts.set_nbytes(nbytes)

        self._exit_processing_common(ts)

        recommendations: Recs = {}
        client_msgs: Msgs = {}
        self._add_to_memory(
            ts, ws, recommendations, client_msgs, type=type, typename=typename
        )

        if self.validate:
            assert not ts.processing_on
            assert not ts.waiting_on

        return recommendations, client_msgs, {}

    def transition_memory_released(
        self, key: str, stimulus_id: str, *, safe: bool = False
    ) -> RecsMsgs:
        ts = self.tasks[key]

        if self.validate:
            assert not ts.waiting_on
            assert not ts.processing_on
            if safe:
                assert not ts.waiters

        if ts.actor:
            for ws in ts.who_has:
                ws.actors.discard(ts)
            if ts.who_wants:
                ts.exception_blame = ts
                ts.exception = Serialized(
                    *serialize(ValueError("Worker holding Actor was lost"))
                )
                return {ts.key: "erred"}, {}, {}  # don't try to recreate

        recommendations: Recs = {}
        client_msgs: Msgs = {}
        worker_msgs: Msgs = {}

        # XXX factor this out?
        worker_msg = {
            "op": "free-keys",
            "keys": [key],
            "stimulus_id": stimulus_id,
        }
        for ws in ts.who_has:
            worker_msgs[ws.address] = [worker_msg]
        self.remove_all_replicas(ts)

        ts.state = "released"

        report_msg = {"op": "lost-data", "key": key}
        for cs in ts.who_wants:
            client_msgs[cs.client_key] = [report_msg]

        if not ts.run_spec:  # pure data
            recommendations[key] = "forgotten"
        elif ts.has_lost_dependencies:
            recommendations[key] = "forgotten"
        elif ts.who_wants or ts.waiters:
            recommendations[key] = "waiting"

        for dts in ts.waiters:
            if dts.state in ("no-worker", "processing"):
                recommendations[dts.key] = "waiting"
            elif dts.state == "waiting":
                dts.waiting_on.add(ts)

        if self.validate:
            assert not ts.waiting_on

        return recommendations, client_msgs, worker_msgs

    def transition_released_erred(self, key: str, stimulus_id: str) -> RecsMsgs:
        ts = self.tasks[key]
        recommendations: Recs = {}
        client_msgs: Msgs = {}

        if self.validate:
            with log_errors(pdb=LOG_PDB):
                assert ts.exception_blame
                assert not ts.who_has
                assert not ts.waiting_on
                assert not ts.waiters

        failing_ts = ts.exception_blame
        assert failing_ts

        for dts in ts.dependents:
            dts.exception_blame = failing_ts
            if not dts.who_has:
                recommendations[dts.key] = "erred"

        report_msg = {
            "op": "task-erred",
            "key": key,
            "exception": failing_ts.exception,
            "traceback": failing_ts.traceback,
        }
        for cs in ts.who_wants:
            client_msgs[cs.client_key] = [report_msg]

        ts.state = "erred"

        # TODO: waiting data?
        return recommendations, client_msgs, {}

    def transition_erred_released(self, key: str, stimulus_id: str) -> RecsMsgs:
        ts = self.tasks[key]
        recommendations: Recs = {}
        client_msgs: Msgs = {}
        worker_msgs: Msgs = {}

        if self.validate:
            with log_errors(pdb=LOG_PDB):
                assert ts.exception_blame
                assert not ts.who_has
                assert not ts.waiting_on
                assert not ts.waiters

        ts.exception = None
        ts.exception_blame = None
        ts.traceback = None

        for dts in ts.dependents:
            if dts.state == "erred":
                recommendations[dts.key] = "waiting"

        w_msg = {
            "op": "free-keys",
            "keys": [key],
            "stimulus_id": stimulus_id,
        }
        for ws_addr in ts.erred_on:
            worker_msgs[ws_addr] = [w_msg]
        ts.erred_on.clear()

        report_msg = {"op": "task-retried", "key": key}
        for cs in ts.who_wants:
            client_msgs[cs.client_key] = [report_msg]

        ts.state = "released"

        return recommendations, client_msgs, worker_msgs

    def transition_waiting_released(self, key: str, stimulus_id: str) -> RecsMsgs:
        ts = self.tasks[key]
        recommendations: Recs = {}

        if self.validate:
            assert not ts.who_has
            assert not ts.processing_on

        for dts in ts.dependencies:
            if ts in dts.waiters:
                dts.waiters.discard(ts)
                if not dts.waiters and not dts.who_wants:
                    recommendations[dts.key] = "released"
        ts.waiting_on.clear()

        ts.state = "released"

        if ts.has_lost_dependencies:
            recommendations[key] = "forgotten"
        elif not ts.exception_blame and (ts.who_wants or ts.waiters):
            recommendations[key] = "waiting"
        else:
            ts.waiters.clear()

        return recommendations, {}, {}

    def transition_processing_released(self, key: str, stimulus_id: str) -> RecsMsgs:
        ts = self.tasks[key]
        recommendations: Recs = {}
        worker_msgs: Msgs = {}

        if self.validate:
            assert ts.processing_on
            assert not ts.who_has
            assert not ts.waiting_on
            assert ts.state == "processing"

        ws = self._exit_processing_common(ts)
        if ws:
            worker_msgs[ws.address] = [
                {
                    "op": "free-keys",
                    "keys": [key],
                    "stimulus_id": stimulus_id,
                }
            ]

        self._propagate_released(ts, recommendations)
        return recommendations, {}, worker_msgs

    def transition_processing_erred(
        self,
        key: str,
        stimulus_id: str,
        *,
        worker: str,
        cause: str | None = None,
        exception: Serialized | None = None,
        traceback: Serialized | None = None,
        exception_text: str | None = None,
        traceback_text: str | None = None,
        **kwargs: Any,
    ) -> RecsMsgs:
        """Processed a recommended transition processing -> erred.

        Parameters
        ----------
        key
           Key of the task to transition
        stimulus_id
            ID of the stimulus causing the transition
        worker
            Address of the worker where the task erred.
            Not necessarily ``ts.processing_on``.
        cause
            Address of the task that caused this task to be transitioned to erred
        exception
            Exception caused by the task
        traceback
            Traceback caused by the task
        exception_text
            String representation of the exception
        traceback_text
            String representation of the traceback

        Returns
        -------
        Recommendations, client messages and worker messages to process
        """
        ts = self.tasks[key]
        recommendations: Recs = {}
        client_msgs: Msgs = {}

        if self.validate:
            assert cause or ts.exception_blame
            assert ts.processing_on
            assert not ts.who_has
            assert not ts.waiting_on

        if ts.actor:
            ws = ts.processing_on
            assert ws
            ws.actors.remove(ts)

        self._exit_processing_common(ts)

        ts.erred_on.add(worker)
        if exception is not None:
            ts.exception = exception
            ts.exception_text = exception_text  # type: ignore
        if traceback is not None:
            ts.traceback = traceback
            ts.traceback_text = traceback_text  # type: ignore
        if cause is not None:
            failing_ts = self.tasks[cause]
            ts.exception_blame = failing_ts
        else:
            failing_ts = ts.exception_blame  # type: ignore

        self.erred_tasks.appendleft(
            ErredTask(
                ts.key,
                time(),
                ts.erred_on.copy(),
                exception_text or "",
                traceback_text or "",
            )
        )

        for dts in ts.dependents:
            dts.exception_blame = failing_ts
            recommendations[dts.key] = "erred"

        for dts in ts.dependencies:
            dts.waiters.discard(ts)
            if not dts.waiters and not dts.who_wants:
                recommendations[dts.key] = "released"

        ts.waiters.clear()  # do anything with this?

        ts.state = "erred"

        report_msg = {
            "op": "task-erred",
            "key": key,
            "exception": failing_ts.exception,
            "traceback": failing_ts.traceback,
        }
        for cs in ts.who_wants:
            client_msgs[cs.client_key] = [report_msg]

        cs = self.clients["fire-and-forget"]
        if ts in cs.wants_what:
            self._client_releases_keys(
                cs=cs,
                keys=[key],
                recommendations=recommendations,
            )

        if self.validate:
            assert not ts.processing_on

        return recommendations, client_msgs, {}

    def transition_no_worker_released(self, key: str, stimulus_id: str) -> RecsMsgs:
        ts = self.tasks[key]

        if self.validate:
            assert self.tasks[key].state == "no-worker"
            assert not ts.who_has
            assert not ts.waiting_on

        self.unrunnable.remove(ts)
        ts.state = "released"

        for dts in ts.dependencies:
            dts.waiters.discard(ts)

        ts.waiters.clear()

        return {}, {}, {}

    def transition_waiting_queued(self, key: str, stimulus_id: str) -> RecsMsgs:
        ts = self.tasks[key]

        if self.validate:
            assert not self.idle_task_count, (ts, self.idle_task_count)
            self._validate_ready(ts)

        ts.state = "queued"
        self.queued.add(ts)

        return {}, {}, {}

    def transition_waiting_no_worker(self, key: str, stimulus_id: str) -> RecsMsgs:
        ts = self.tasks[key]

        if self.validate:
            self._validate_ready(ts)

        ts.state = "no-worker"
        self.unrunnable.add(ts)

        return {}, {}, {}

    def transition_queued_released(self, key: str, stimulus_id: str) -> RecsMsgs:
        ts = self.tasks[key]

        if self.validate:
            assert ts in self.queued
            assert not ts.processing_on

        self.queued.remove(ts)

        recommendations: Recs = {}
        self._propagate_released(ts, recommendations)
        return recommendations, {}, {}

    def transition_queued_processing(self, key: str, stimulus_id: str) -> RecsMsgs:
        ts = self.tasks[key]
        recommendations: Recs = {}
        worker_msgs: Msgs = {}

        if self.validate:
            assert not ts.actor, f"Actors can't be queued: {ts}"
            assert ts in self.queued

        if ws := self.decide_worker_rootish_queuing_enabled():
            self.queued.discard(ts)
            worker_msgs = self._add_to_processing(ts, ws)
        # If no worker, task just stays `queued`

        return recommendations, {}, worker_msgs

    def _remove_key(self, key: str) -> None:
        ts = self.tasks.pop(key)
        assert ts.state == "forgotten"
        self.unrunnable.discard(ts)
        for cs in ts.who_wants:
            cs.wants_what.remove(ts)
        ts.who_wants.clear()
        ts.processing_on = None
        ts.exception_blame = ts.exception = ts.traceback = None
        self.task_metadata.pop(key, None)

    def transition_memory_forgotten(self, key: str, stimulus_id: str) -> RecsMsgs:
        ts = self.tasks[key]

        if self.validate:
            assert ts.state == "memory"
            assert not ts.processing_on
            assert not ts.waiting_on
            if not ts.run_spec:
                # It's ok to forget a pure data task
                pass
            elif ts.has_lost_dependencies:
                # It's ok to forget a task with forgotten dependencies
                pass
            elif not ts.who_wants and not ts.waiters and not ts.dependents:
                # It's ok to forget a task that nobody needs
                pass
            else:
                raise AssertionError("Unreachable", ts)  # pragma: nocover

        if ts.actor:
            for ws in ts.who_has:
                ws.actors.discard(ts)

        recommendations: Recs = {}
        worker_msgs: Msgs = {}
        self._propagate_forgotten(ts, recommendations, worker_msgs, stimulus_id)

        client_msgs = _task_to_client_msgs(ts)
        self._remove_key(key)

        return recommendations, client_msgs, worker_msgs

    def transition_released_forgotten(self, key: str, stimulus_id: str) -> RecsMsgs:
        ts = self.tasks[key]

        if self.validate:
            assert ts.state in ("released", "erred")
            assert not ts.who_has
            assert not ts.processing_on
            assert ts not in self.queued
            assert not ts.waiting_on, (ts, ts.waiting_on)
            if not ts.run_spec:
                # It's ok to forget a pure data task
                pass
            elif ts.has_lost_dependencies:
                # It's ok to forget a task with forgotten dependencies
                pass
            elif not ts.who_wants and not ts.waiters and not ts.dependents:
                # It's ok to forget a task that nobody needs
                pass
            else:
                raise AssertionError("Unreachable", str(ts))  # pragma: nocover

        recommendations: Recs = {}
        worker_msgs: Msgs = {}
        self._propagate_forgotten(ts, recommendations, worker_msgs, stimulus_id)

        client_msgs = _task_to_client_msgs(ts)
        self._remove_key(key)

        return recommendations, client_msgs, worker_msgs

    # {
    #     (start, finish):
    #     transition_<start>_<finish>(
    #         self, key: str, stimulus_id: str, **kwargs
    #     ) -> (recommendations, client_msgs, worker_msgs)
    # }
    _TRANSITIONS_TABLE: ClassVar[
        Mapping[
            tuple[TaskStateState, TaskStateState],
            Callable[..., RecsMsgs],
        ]
    ] = {
        ("released", "waiting"): transition_released_waiting,
        ("waiting", "released"): transition_waiting_released,
        ("waiting", "processing"): transition_waiting_processing,
        ("waiting", "no-worker"): transition_waiting_no_worker,
        ("waiting", "queued"): transition_waiting_queued,
        ("waiting", "memory"): transition_waiting_memory,
        ("queued", "released"): transition_queued_released,
        ("queued", "processing"): transition_queued_processing,
        ("processing", "released"): transition_processing_released,
        ("processing", "memory"): transition_processing_memory,
        ("processing", "erred"): transition_processing_erred,
        ("no-worker", "released"): transition_no_worker_released,
        ("no-worker", "processing"): transition_no_worker_processing,
        ("released", "forgotten"): transition_released_forgotten,
        ("memory", "forgotten"): transition_memory_forgotten,
        ("erred", "released"): transition_erred_released,
        ("memory", "released"): transition_memory_released,
        ("released", "erred"): transition_released_erred,
    }

    def story(self, *keys_or_tasks_or_stimuli: str | TaskState) -> list[Transition]:
        """Get all transitions that touch one of the input keys or stimulus_id's"""
        keys_or_stimuli = {
            key.key if isinstance(key, TaskState) else key
            for key in keys_or_tasks_or_stimuli
        }
        return scheduler_story(keys_or_stimuli, self.transition_log)

    ##############################
    # Assigning Tasks to Workers #
    ##############################

    def is_rootish(self, ts: TaskState) -> bool:
        """
        Whether ``ts`` is a root or root-like task.

        Root-ish tasks are part of a group that's much larger than the cluster,
        and have few or no dependencies.
        """
        if ts.resource_restrictions or ts.worker_restrictions or ts.host_restrictions:
            return False
        tg = ts.group
        # TODO short-circuit to True if `not ts.dependencies`?
        return (
            len(tg) > self.total_nthreads * 2
            and len(tg.dependencies) < 5
            and sum(map(len, tg.dependencies)) < 5
        )

    def check_idle_saturated(self, ws: WorkerState, occ: float = -1.0) -> None:
        """Update the status of the idle and saturated state

        The scheduler keeps track of workers that are ..

        -  Saturated: have enough work to stay busy
        -  Idle: do not have enough work to stay busy

        They are considered saturated if they both have enough tasks to occupy
        all of their threads, and if the expected runtime of those tasks is
        large enough.

        If ``distributed.scheduler.worker-saturation`` is not ``inf``
        (scheduler-side queuing is enabled), they are considered idle
        if they have fewer tasks processing than the ``worker-saturation``
        threshold dictates.

        Otherwise, they are considered idle if they have fewer tasks processing
        than threads, or if their tasks' total expected runtime is less than half
        the expected runtime of the same number of average tasks.

        This is useful for load balancing and adaptivity.
        """
        if self.total_nthreads == 0 or ws.status == Status.closed:
            return
        if occ < 0:
            occ = ws.occupancy

        p = len(ws.processing)

        idle = self.idle
        saturated = self.saturated
        saturated.discard(ws)
        if self.is_unoccupied(ws, occ, p):
            if ws.status == Status.running:
                idle[ws.address] = ws
        else:
            idle.pop(ws.address, None)
            nc = ws.nthreads
            if p > nc:
                pending = occ * (p - nc) / (p * nc)
                if 0.4 < pending > 1.9 * (self.total_occupancy / self.total_nthreads):
                    saturated.add(ws)

        if not _worker_full(ws, self.WORKER_SATURATION):
            if ws.status == Status.running:
                self.idle_task_count.add(ws)
        else:
            self.idle_task_count.discard(ws)

    def is_unoccupied(
        self, ws: WorkerState, occupancy: float, nprocessing: int
    ) -> bool:
        nthreads = ws.nthreads
        return (
            nprocessing < nthreads
            or occupancy < nthreads * (self.total_occupancy / self.total_nthreads) / 2
        )

    def get_comm_cost(self, ts: TaskState, ws: WorkerState) -> float:
        """
        Get the estimated communication cost (in s.) to compute the task
        on the given worker.
        """
        if 10 * len(ts.dependencies) < len(ws.has_what):
            # In the common case where the number of dependencies is
            # much less than the number of tasks that we have,
            # construct the set of deps that require communication in
            # O(len(dependencies)) rather than O(len(has_what)) time.
            # Factor of 10 is a guess at the overhead of explicit
            # iteration as opposed to just calling set.difference
            deps = {dep for dep in ts.dependencies if dep not in ws.has_what}
        else:
            deps = ts.dependencies.difference(ws.has_what)
        nbytes = sum(dts.nbytes for dts in deps)
        return nbytes / self.bandwidth

    def get_task_duration(self, ts: TaskState) -> float:
        """Get the estimated computation cost of the given task (not including
        any communication cost).

        If no data has been observed, value of
        `distributed.scheduler.default-task-durations` are used. If none is set
        for this task, `distributed.scheduler.unknown-task-duration` is used
        instead.
        """
        duration: float = ts.prefix.duration_average
        if duration >= 0:
            return duration

        s = self.unknown_durations.get(ts.prefix.name)
        if s is None:
            self.unknown_durations[ts.prefix.name] = s = set()
        s.add(ts)
        return self.UNKNOWN_TASK_DURATION

    def valid_workers(self, ts: TaskState) -> set[WorkerState] | None:
        """Return set of currently valid workers for key

        If all workers are valid then this returns ``None``, in which case
        any *running* worker can be used.
        Otherwise, the subset of running workers valid for this task
        is returned.
        This checks tracks the following state:

        *  worker_restrictions
        *  host_restrictions
        *  resource_restrictions
        """
        s: set[str] | None = None

        if ts.worker_restrictions:
            s = {addr for addr in ts.worker_restrictions if addr in self.workers}

        if ts.host_restrictions:
            # Resolve the alias here rather than early, for the worker
            # may not be connected when host_restrictions is populated
            hr = [self.coerce_hostname(h) for h in ts.host_restrictions]
            # XXX need HostState?
            sl = []
            for h in hr:
                dh = self.host_info.get(h)
                if dh is not None:
                    sl.append(dh["addresses"])

            ss = set.union(*sl) if sl else set()
            if s is None:
                s = ss
            else:
                s |= ss

        if ts.resource_restrictions:
            dw = {}
            for resource, required in ts.resource_restrictions.items():
                dr = self.resources.get(resource)
                if dr is None:
                    self.resources[resource] = dr = {}

                sw = set()
                for addr, supplied in dr.items():
                    if supplied >= required:
                        sw.add(addr)

                dw[resource] = sw

            ww = set.intersection(*dw.values())
            if s is None:
                s = ww
            else:
                s &= ww

        if s is None:
            return None  # All workers are valid
        if not s:
            return set()  # No workers are valid

        # Some workers are valid
        s_ws = {self.workers[addr] for addr in s}
        if len(self.running) < len(self.workers):
            s_ws &= self.running
        return s_ws

    def acquire_resources(self, ts: TaskState, ws: WorkerState) -> None:
        for r, required in ts.resource_restrictions.items():
            ws.used_resources[r] += required

    def release_resources(self, ts: TaskState, ws: WorkerState) -> None:
        for r, required in ts.resource_restrictions.items():
            ws.used_resources[r] -= required

    def coerce_hostname(self, host: Hashable) -> str:
        """
        Coerce the hostname of a worker.
        """
        alias = self.aliases.get(host)
        if alias is not None:
            ws = self.workers[alias]
            return ws.host
        else:
            assert isinstance(host, str)
            return host

    def worker_objective(self, ts: TaskState, ws: WorkerState) -> tuple:
        """Objective function to determine which worker should get the task

        Minimize expected start time.  If a tie then break with data storage.
        """
        comm_bytes = sum(
            dts.get_nbytes() for dts in ts.dependencies if ws not in dts.who_has
        )

        stack_time = ws.occupancy / ws.nthreads
        start_time = stack_time + comm_bytes / self.bandwidth

        if ts.actor:
            return (len(ws.actors), start_time, ws.nbytes)
        else:
            return (start_time, ws.nbytes)

    def add_replica(self, ts: TaskState, ws: WorkerState) -> None:
        """Note that a worker holds a replica of a task with state='memory'"""
        ws.add_replica(ts)
        if len(ts.who_has) == 2:
            self.replicated_tasks.add(ts)

    def remove_replica(self, ts: TaskState, ws: WorkerState) -> None:
        """Note that a worker no longer holds a replica of a task"""
        ws.remove_replica(ts)
        if len(ts.who_has) == 1:
            self.replicated_tasks.remove(ts)

    def remove_all_replicas(self, ts: TaskState) -> None:
        """Remove all replicas of a task from all workers"""
        nbytes = ts.get_nbytes()
        for ws in ts.who_has:
            ws.nbytes -= nbytes
            del ws._has_what[ts]
        if len(ts.who_has) > 1:
            self.replicated_tasks.remove(ts)
        ts.who_has.clear()

    def bulk_schedule_unrunnable_after_adding_worker(self, ws: WorkerState) -> Recs:
        """Send ``no-worker`` tasks to ``processing`` that this worker can handle.

        Returns priority-ordered recommendations.
        """
        runnable: list[TaskState] = []
        for ts in self.unrunnable:
            valid = self.valid_workers(ts)
            if valid is None or ws in valid:
                runnable.append(ts)

        # Recommendations are processed LIFO, hence the reversed order
        runnable.sort(key=operator.attrgetter("priority"), reverse=True)
        return {ts.key: "processing" for ts in runnable}

    def _validate_ready(self, ts: TaskState) -> None:
        """Validation for ready states (processing, queued, no-worker)"""
        assert not ts.waiting_on
        assert not ts.who_has
        assert not ts.exception_blame
        assert not ts.processing_on
        assert not ts.has_lost_dependencies
        assert ts not in self.unrunnable
        assert ts not in self.queued
        assert all(dts.who_has for dts in ts.dependencies)

    def _add_to_processing(self, ts: TaskState, ws: WorkerState) -> Msgs:
        """Set a task as processing on a worker and return the worker messages to send"""
        if self.validate:
            self._validate_ready(ts)
            assert ws in self.running, self.running
            assert (o := self.workers.get(ws.address)) is ws, (ws, o)

        ws.add_to_processing(ts)
        ts.processing_on = ws
        ts.state = "processing"
        self.acquire_resources(ts, ws)
        self.check_idle_saturated(ws)
        self.n_tasks += 1

        if ts.actor:
            ws.actors.add(ts)

        return {ws.address: [self._task_to_msg(ts)]}

    def _exit_processing_common(self, ts: TaskState) -> WorkerState | None:
        """Remove *ts* from the set of processing tasks.

        Returns
        -------
        Worker state of the worker that processed *ts* if the worker is current,
        None if the worker is stale.

        See also
        --------
        Scheduler._set_duration_estimate
        """
        ws = ts.processing_on
        assert ws
        ts.processing_on = None

        ws.remove_from_processing(ts)
        if self.workers.get(ws.address) is not ws:  # may have been removed
            return None

        self.check_idle_saturated(ws)
        self.release_resources(ts, ws)

        return ws

    def _add_to_memory(
        self,
        ts: TaskState,
        ws: WorkerState,
        recommendations: Recs,
        client_msgs: Msgs,
        type: bytes | None = None,
        typename: str | None = None,
    ) -> None:
        """Add ts to the set of in-memory tasks"""
        if self.validate:
            assert ts not in ws.has_what

        self.add_replica(ts, ws)

        deps = list(ts.dependents)
        if len(deps) > 1:
            deps.sort(key=operator.attrgetter("priority"), reverse=True)

        for dts in deps:
            s = dts.waiting_on
            if ts in s:
                s.discard(ts)
                if not s:  # new task ready to run
                    recommendations[dts.key] = "processing"

        for dts in ts.dependencies:
            s = dts.waiters
            s.discard(ts)
            if not s and not dts.who_wants:
                recommendations[dts.key] = "released"

        if not ts.waiters and not ts.who_wants:
            recommendations[ts.key] = "released"
        else:
            report_msg: dict[str, Any] = {"op": "key-in-memory", "key": ts.key}
            if type is not None:
                report_msg["type"] = type
            for cs in ts.who_wants:
                client_msgs[cs.client_key] = [report_msg]

        ts.state = "memory"
        ts.type = typename  # type: ignore
        ts.group.types.add(typename)  # type: ignore

        cs = self.clients["fire-and-forget"]
        if ts in cs.wants_what:
            self._client_releases_keys(
                cs=cs,
                keys=[ts.key],
                recommendations=recommendations,
            )

    def _propagate_released(self, ts: TaskState, recommendations: Recs) -> None:
        ts.state = "released"
        key = ts.key

        if ts.has_lost_dependencies:
            recommendations[key] = "forgotten"
        elif ts.waiters or ts.who_wants:
            recommendations[key] = "waiting"

        if recommendations.get(key) != "waiting":
            for dts in ts.dependencies:
                if dts.state != "released":
                    dts.waiters.discard(ts)
                    if not dts.waiters and not dts.who_wants:
                        recommendations[dts.key] = "released"
            ts.waiters.clear()

        if self.validate:
            assert not ts.processing_on
            assert ts not in self.queued

    def _propagate_forgotten(
        self,
        ts: TaskState,
        recommendations: Recs,
        worker_msgs: Msgs,
        stimulus_id: str,
    ) -> None:
        ts.state = "forgotten"
        for dts in ts.dependents:
            dts.has_lost_dependencies = True
            dts.dependencies.remove(ts)
            dts.waiting_on.discard(ts)
            if dts.state not in ("memory", "erred"):
                # Cannot compute task anymore
                recommendations[dts.key] = "forgotten"
        ts.dependents.clear()
        ts.waiters.clear()

        for dts in ts.dependencies:
            dts.dependents.remove(ts)
            dts.waiters.discard(ts)
            if not dts.dependents and not dts.who_wants:
                # Task not needed anymore
                assert dts is not ts
                recommendations[dts.key] = "forgotten"
        ts.dependencies.clear()
        ts.waiting_on.clear()

        for ws in ts.who_has:
            if ws.address in self.workers:  # in case worker has died
                worker_msgs[ws.address] = [
                    {
                        "op": "free-keys",
                        "keys": [ts.key],
                        "stimulus_id": stimulus_id,
                    }
                ]
        self.remove_all_replicas(ts)

    def _client_releases_keys(
        self,
        keys: Collection[str],
        cs: ClientState,
        recommendations: Recs,
    ) -> None:
        """Remove keys from client desired list"""
        logger.debug("Client %s releases keys: %s", cs.client_key, keys)
        for key in keys:
            ts = self.tasks.get(key)
            if ts is not None and ts in cs.wants_what:
                cs.wants_what.remove(ts)
                ts.who_wants.remove(cs)
                if not ts.who_wants:
                    if not ts.dependents:
                        # No live dependents, can forget
                        recommendations[ts.key] = "forgotten"
                    elif ts.state != "erred" and not ts.waiters:
                        recommendations[ts.key] = "released"

    def _task_to_msg(self, ts: TaskState, duration: float = -1) -> dict[str, Any]:
        """Convert a single computational task to a message"""
        # FIXME: The duration attribute is not used on worker. We could save ourselves the
        #        time to compute and submit this
        if duration < 0:
            duration = self.get_task_duration(ts)

        msg: dict[str, Any] = {
            "op": "compute-task",
            "key": ts.key,
            "priority": ts.priority,
            "duration": duration,
            "stimulus_id": f"compute-task-{time()}",
            "who_has": {
                dts.key: [ws.address for ws in dts.who_has] for dts in ts.dependencies
            },
            "nbytes": {dts.key: dts.nbytes for dts in ts.dependencies},
            "run_spec": None,
            "function": None,
            "args": None,
            "kwargs": None,
            "resource_restrictions": ts.resource_restrictions,
            "actor": ts.actor,
            "annotations": ts.annotations,
        }
        if self.validate:
            assert all(msg["who_has"].values())

        if isinstance(ts.run_spec, dict):
            msg.update(ts.run_spec)
        else:
            msg["run_spec"] = ts.run_spec

        return msg


class Scheduler(SchedulerState, ServerNode):
    """Dynamic distributed task scheduler

    The scheduler tracks the current state of workers, data, and computations.
    The scheduler listens for events and responds by controlling workers
    appropriately.  It continuously tries to use the workers to execute an ever
    growing dask graph.

    All events are handled quickly, in linear time with respect to their input
    (which is often of constant size) and generally within a millisecond.  To
    accomplish this the scheduler tracks a lot of state.  Every operation
    maintains the consistency of this state.

    The scheduler communicates with the outside world through Comm objects.
    It maintains a consistent and valid view of the world even when listening
    to several clients at once.

    A Scheduler is typically started either with the ``dask scheduler``
    executable::

         $ dask scheduler
         Scheduler started at 127.0.0.1:8786

    Or within a LocalCluster a Client starts up without connection
    information::

        >>> c = Client()  # doctest: +SKIP
        >>> c.cluster.scheduler  # doctest: +SKIP
        Scheduler(...)

    Users typically do not interact with the scheduler directly but rather with
    the client object ``Client``.

    The ``contact_address`` parameter allows to advertise a specific address to
    the workers for communication with the scheduler, which is different than
    the address the scheduler binds to. This is useful when the scheduler
    listens on a private address, which therefore cannot be used by the workers
    to contact it.

    **State**

    The scheduler contains the following state variables.  Each variable is
    listed along with what it stores and a brief description.

    * **tasks:** ``{task key: TaskState}``
        Tasks currently known to the scheduler
    * **unrunnable:** ``{TaskState}``
        Tasks in the "no-worker" state

    * **workers:** ``{worker key: WorkerState}``
        Workers currently connected to the scheduler
    * **idle:** ``{WorkerState}``:
        Set of workers that are not fully utilized
    * **saturated:** ``{WorkerState}``:
        Set of workers that are not over-utilized

    * **host_info:** ``{hostname: dict}``:
        Information about each worker host

    * **clients:** ``{client key: ClientState}``
        Clients currently connected to the scheduler

    * **services:** ``{str: port}``:
        Other services running on this scheduler, like Bokeh
    * **loop:** ``IOLoop``:
        The running Tornado IOLoop
    * **client_comms:** ``{client key: Comm}``
        For each client, a Comm object used to receive task requests and
        report task status updates.
    * **stream_comms:** ``{worker key: Comm}``
        For each worker, a Comm object from which we both accept stimuli and
        report results
    * **task_duration:** ``{key-prefix: time}``
        Time we expect certain functions to take, e.g. ``{'sum': 0.25}``
    """

    default_port = 8786
    _instances: ClassVar[weakref.WeakSet[Scheduler]] = weakref.WeakSet()

    def __init__(
        self,
        loop=None,
        delete_interval="500ms",
        synchronize_worker_interval="60s",
        services=None,
        service_kwargs=None,
        allowed_failures=None,
        extensions=None,
        validate=None,
        scheduler_file=None,
        security=None,
        worker_ttl=None,
        idle_timeout=None,
        interface=None,
        host=None,
        port=0,
        protocol=None,
        dashboard_address=None,
        dashboard=None,
        http_prefix="/",
        preload=None,
        preload_argv=(),
        plugins=(),
        contact_address=None,
        transition_counter_max=False,
        jupyter=False,
        **kwargs,
    ):
        if loop is not None:
            warnings.warn(
                "the loop kwarg to Scheduler is deprecated",
                DeprecationWarning,
                stacklevel=2,
            )

        self.loop = self.io_loop = IOLoop.current()
        self._setup_logging(logger)

        # Attributes
        if contact_address is None:
            contact_address = dask.config.get("distributed.scheduler.contact-address")
        self.contact_address = contact_address
        if allowed_failures is None:
            allowed_failures = dask.config.get("distributed.scheduler.allowed-failures")
        self.allowed_failures = allowed_failures
        if validate is None:
            validate = dask.config.get("distributed.scheduler.validate")
        self.proc = psutil.Process()
        self.delete_interval = parse_timedelta(delete_interval, default="ms")
        self.synchronize_worker_interval = parse_timedelta(
            synchronize_worker_interval, default="ms"
        )
        self.service_specs = services or {}
        self.service_kwargs = service_kwargs or {}
        self.services = {}
        self.scheduler_file = scheduler_file
        worker_ttl = worker_ttl or dask.config.get("distributed.scheduler.worker-ttl")
        self.worker_ttl = parse_timedelta(worker_ttl) if worker_ttl else None
        idle_timeout = idle_timeout or dask.config.get(
            "distributed.scheduler.idle-timeout"
        )
        if idle_timeout:
            self.idle_timeout = parse_timedelta(idle_timeout)
        else:
            self.idle_timeout = None
        self.idle_since = time()
        self.time_started = self.idle_since  # compatibility for dask-gateway
        self._lock = asyncio.Lock()
        self.bandwidth_workers = defaultdict(float)
        self.bandwidth_types = defaultdict(float)

        if not preload:
            preload = dask.config.get("distributed.scheduler.preload")
        if not preload_argv:
            preload_argv = dask.config.get("distributed.scheduler.preload-argv")
        self.preloads = preloading.process_preloads(self, preload, preload_argv)

        if isinstance(security, dict):
            security = Security(**security)
        self.security = security or Security()
        assert isinstance(self.security, Security)
        self.connection_args = self.security.get_connection_args("scheduler")
        self.connection_args["handshake_overrides"] = {  # common denominator
            "pickle-protocol": 4
        }

        self._start_address = addresses_from_user_args(
            host=host,
            port=port,
            interface=interface,
            protocol=protocol,
            security=security,
            default_port=self.default_port,
        )

        http_server_modules = dask.config.get("distributed.scheduler.http.routes")
        show_dashboard = dashboard or (dashboard is None and dashboard_address)
        # install vanilla route if show_dashboard but bokeh is not installed
        if show_dashboard:
            try:
                import distributed.dashboard.scheduler
            except ImportError:
                show_dashboard = False
                http_server_modules.append("distributed.http.scheduler.missing_bokeh")
        routes = get_handlers(
            server=self, modules=http_server_modules, prefix=http_prefix
        )
        self.start_http_server(routes, dashboard_address, default_port=8787)
        if show_dashboard:
            distributed.dashboard.scheduler.connect(
                self.http_application, self.http_server, self, prefix=http_prefix
            )
        self.jupyter = jupyter
        if self.jupyter:
            try:
                from jupyter_server.serverapp import ServerApp
            except ImportError:
                raise ImportError(
                    "In order to use the Dask jupyter option you "
                    "need to have jupyterlab installed"
                )
            from traitlets.config import Config

            j = ServerApp.instance(
                config=Config(
                    {
                        "ServerApp": {
                            "base_url": "jupyter",
                            # SECURITY: We usually expect the dashboard to be a read-only view into
                            # the scheduler activity. However, by adding an open Jupyter application
                            # we are allowing arbitrary remote code execution on the scheduler via the
                            # dashboard server. This option should only be used when the dashboard is
                            # protected via other means, or when you don't care about cluster security.
                            "token": "",
                            "allow_remote_access": True,
                        }
                    }
                )
            )
            j.initialize(
                new_httpserver=False,
            )
            self._jupyter_server_application = j
            self.http_application.add_application(j.web_app)

        # Communication state
        self.client_comms = {}
        self.stream_comms = {}

        # Task state
        tasks = {}

        self.generation = 0
        self._last_client = None
        self._last_time = 0
        unrunnable = set()
        queued: HeapSet[TaskState] = HeapSet(key=operator.attrgetter("priority"))

        self.datasets = {}

        # Prefix-keyed containers

        # Client state
        clients = {}

        # Worker state
        workers = SortedDict()

        host_info = {}
        resources = {}
        aliases = {}

        self._worker_collections = [
            workers,
            host_info,
            resources,
            aliases,
        ]

        self.events = defaultdict(
            partial(
                deque, maxlen=dask.config.get("distributed.scheduler.events-log-length")
            )
        )
        self.event_counts = defaultdict(int)
        self.event_subscriber = defaultdict(set)
        self.worker_plugins = {}
        self.nanny_plugins = {}

        worker_handlers = {
            "task-finished": self.handle_task_finished,
            "task-erred": self.handle_task_erred,
            "release-worker-data": self.release_worker_data,
            "add-keys": self.add_keys,
            "long-running": self.handle_long_running,
            "reschedule": self._reschedule,
            "keep-alive": lambda *args, **kwargs: None,
            "log-event": self.log_worker_event,
            "worker-status-change": self.handle_worker_status_change,
            "request-refresh-who-has": self.handle_request_refresh_who_has,
        }

        client_handlers = {
            "update-graph": self.update_graph,
            "update-graph-hlg": self.update_graph_hlg,
            "client-desires-keys": self.client_desires_keys,
            "update-data": self.update_data,
            "report-key": self.report_on_key,
            "client-releases-keys": self.client_releases_keys,
            "heartbeat-client": self.client_heartbeat,
            "close-client": self.remove_client,
            "subscribe-topic": self.subscribe_topic,
            "unsubscribe-topic": self.unsubscribe_topic,
        }

        self.handlers = {
            "register-client": self.add_client,
            "scatter": self.scatter,
            "register-worker": self.add_worker,
            "register_nanny": self.add_nanny,
            "unregister": self.remove_worker,
            "gather": self.gather,
            "cancel": self.stimulus_cancel,
            "retry": self.stimulus_retry,
            "feed": self.feed,
            "terminate": self.close,
            "broadcast": self.broadcast,
            "proxy": self.proxy,
            "ncores": self.get_ncores,
            "ncores_running": self.get_ncores_running,
            "has_what": self.get_has_what,
            "who_has": self.get_who_has,
            "processing": self.get_processing,
            "call_stack": self.get_call_stack,
            "profile": self.get_profile,
            "performance_report": self.performance_report,
            "get_logs": self.get_logs,
            "logs": self.get_logs,
            "worker_logs": self.get_worker_logs,
            "log_event": self.log_event,
            "events": self.get_events,
            "nbytes": self.get_nbytes,
            "versions": self.versions,
            "add_keys": self.add_keys,
            "rebalance": self.rebalance,
            "replicate": self.replicate,
            "run_function": self.run_function,
            "restart": self.restart,
            "update_data": self.update_data,
            "set_resources": self.add_resources,
            "retire_workers": self.retire_workers,
            "get_metadata": self.get_metadata,
            "set_metadata": self.set_metadata,
            "set_restrictions": self.set_restrictions,
            "heartbeat_worker": self.heartbeat_worker,
            "get_task_status": self.get_task_status,
            "get_task_stream": self.get_task_stream,
            "get_task_prefix_states": self.get_task_prefix_states,
            "register_scheduler_plugin": self.register_scheduler_plugin,
            "register_worker_plugin": self.register_worker_plugin,
            "unregister_worker_plugin": self.unregister_worker_plugin,
            "register_nanny_plugin": self.register_nanny_plugin,
            "unregister_nanny_plugin": self.unregister_nanny_plugin,
            "adaptive_target": self.adaptive_target,
            "workers_to_close": self.workers_to_close,
            "subscribe_worker_status": self.subscribe_worker_status,
            "start_task_metadata": self.start_task_metadata,
            "stop_task_metadata": self.stop_task_metadata,
            "get_cluster_state": self.get_cluster_state,
            "dump_cluster_state_to_url": self.dump_cluster_state_to_url,
            "benchmark_hardware": self.benchmark_hardware,
            "get_story": self.get_story,
        }

        connection_limit = get_fileno_limit() / 2

        SchedulerState.__init__(
            self,
            aliases=aliases,
            clients=clients,
            workers=workers,
            host_info=host_info,
            resources=resources,
            tasks=tasks,
            unrunnable=unrunnable,
            queued=queued,
            validate=validate,
            plugins=plugins,
            transition_counter_max=transition_counter_max,
        )
        ServerNode.__init__(
            self,
            handlers=self.handlers,
            stream_handlers=merge(worker_handlers, client_handlers),
            connection_limit=connection_limit,
            deserialize=False,
            connection_args=self.connection_args,
            **kwargs,
        )

        if self.worker_ttl:
            pc = PeriodicCallback(self.check_worker_ttl, self.worker_ttl * 1000)
            self.periodic_callbacks["worker-ttl"] = pc

        if self.idle_timeout:
            pc = PeriodicCallback(self.check_idle, self.idle_timeout * 1000 / 4)
            self.periodic_callbacks["idle-timeout"] = pc

        if extensions is None:
            extensions = DEFAULT_EXTENSIONS.copy()
            if not dask.config.get("distributed.scheduler.work-stealing"):
                if "stealing" in extensions:
                    del extensions["stealing"]

        for name, extension in extensions.items():
            self.extensions[name] = extension(self)

        setproctitle("dask scheduler [not started]")
        Scheduler._instances.add(self)
        self.rpc.allow_offload = False

    ##################
    # Administration #
    ##################

    def __repr__(self):
        return (
            f"<Scheduler {self.address_safe!r}, "
            f"workers: {len(self.workers)}, "
            f"cores: {self.total_nthreads}, "
            f"tasks: {len(self.tasks)}>"
        )

    def _repr_html_(self):
        return get_template("scheduler.html.j2").render(
            address=self.address,
            workers=self.workers,
            threads=self.total_nthreads,
            tasks=self.tasks,
        )

    def identity(self):
        """Basic information about ourselves and our cluster"""
        d = {
            "type": type(self).__name__,
            "id": str(self.id),
            "address": self.address,
            "services": {key: v.port for (key, v) in self.services.items()},
            "started": self.time_started,
            "workers": {
                worker.address: worker.identity() for worker in self.workers.values()
            },
        }
        return d

    def _to_dict(self, *, exclude: Container[str] = ()) -> dict:
        """Dictionary representation for debugging purposes.
        Not type stable and not intended for roundtrips.

        See also
        --------
        Server.identity
        Client.dump_cluster_state
        distributed.utils.recursive_to_dict
        """
        info = super()._to_dict(exclude=exclude)
        extra = {
            "transition_log": self.transition_log,
            "transition_counter": self.transition_counter,
            "tasks": self.tasks,
            "task_groups": self.task_groups,
            # Overwrite dict of WorkerState.identity from info
            "workers": self.workers,
            "clients": self.clients,
            "memory": self.memory,
            "events": self.events,
            "extensions": self.extensions,
        }
        extra = {k: v for k, v in extra.items() if k not in exclude}
        info.update(recursive_to_dict(extra, exclude=exclude))
        return info

    async def get_cluster_state(
        self,
        exclude: "Collection[str]",
    ) -> dict:
        "Produce the state dict used in a cluster state dump"
        # Kick off state-dumping on workers before we block the event loop in `self._to_dict`.
        workers_future = asyncio.gather(
            self.broadcast(
                msg={"op": "dump_state", "exclude": exclude},
                on_error="return",
            ),
            self.broadcast(
                msg={"op": "versions"},
                on_error="ignore",
            ),
        )
        try:
            scheduler_state = self._to_dict(exclude=exclude)

            worker_states, worker_versions = await workers_future
        finally:
            # Ensure the tasks aren't left running if anything fails.
            # Someday (py3.11), use a trio-style TaskGroup for this.
            workers_future.cancel()

        # Convert any RPC errors to strings
        worker_states = {
            k: repr(v) if isinstance(v, Exception) else v
            for k, v in worker_states.items()
        }

        return {
            "scheduler": scheduler_state,
            "workers": worker_states,
            "versions": {"scheduler": self.versions(), "workers": worker_versions},
        }

    async def dump_cluster_state_to_url(
        self,
        url: str,
        exclude: "Collection[str]",
        format: Literal["msgpack", "yaml"],
        **storage_options: dict[str, Any],
    ) -> None:
        "Write a cluster state dump to an fsspec-compatible URL."
        await cluster_dump.write_state(
            partial(self.get_cluster_state, exclude), url, format, **storage_options
        )

    def get_worker_service_addr(
        self, worker: str, service_name: str, protocol: bool = False
    ) -> tuple[str, int] | str | None:
        """
        Get the (host, port) address of the named service on the *worker*.
        Returns None if the service doesn't exist.

        Parameters
        ----------
        worker : address
        service_name : str
            Common services include 'bokeh' and 'nanny'
        protocol : boolean
            Whether or not to include a full address with protocol (True)
            or just a (host, port) pair
        """
        ws = self.workers[worker]
        port = ws.services.get(service_name)
        if port is None:
            return None
        elif protocol:
            return "%(protocol)s://%(host)s:%(port)d" % {
                "protocol": ws.address.split("://")[0],
                "host": ws.host,
                "port": port,
            }
        else:
            return ws.host, port

    async def start_unsafe(self):
        """Clear out old state and restart all running coroutines"""
        await super().start_unsafe()

        enable_gc_diagnosis()

        self._clear_task_state()

        for addr in self._start_address:
            await self.listen(
                addr,
                allow_offload=False,
                handshake_overrides={"pickle-protocol": 4, "compression": None},
                **self.security.get_listen_args("scheduler"),
            )
            self.ip = get_address_host(self.listen_address)
            listen_ip = self.ip

            if listen_ip == "0.0.0.0":
                listen_ip = ""

        if self.address.startswith("inproc://"):
            listen_ip = "localhost"

        # Services listen on all addresses
        self.start_services(listen_ip)

        for listener in self.listeners:
            logger.info("  Scheduler at: %25s", listener.contact_address)
        for k, v in self.services.items():
            logger.info("%11s at: %25s", k, "%s:%d" % (listen_ip, v.port))

        if self.scheduler_file:
            with open(self.scheduler_file, "w") as f:
                json.dump(self.identity(), f, indent=2)

            fn = self.scheduler_file  # remove file when we close the process

            def del_scheduler_file():
                if os.path.exists(fn):
                    os.remove(fn)

            weakref.finalize(self, del_scheduler_file)

        for preload in self.preloads:
            try:
                await preload.start()
            except Exception:
                logger.exception("Failed to start preload")

        if self.jupyter:
            # Allow insecure communications from local users
            if self.address.startswith("tls://"):
                await self.listen("tcp://localhost:0")
            os.environ["DASK_SCHEDULER_ADDRESS"] = self.listeners[-1].contact_address

        await asyncio.gather(
            *[plugin.start(self) for plugin in list(self.plugins.values())]
        )

        self.start_periodic_callbacks()

        setproctitle(f"dask scheduler [{self.address}]")
        return self

    async def close(self, fast=None, close_workers=None):
        """Send cleanup signal to all coroutines then wait until finished

        See Also
        --------
        Scheduler.cleanup
        """
        if fast is not None or close_workers is not None:
            warnings.warn(
                "The 'fast' and 'close_workers' parameters in Scheduler.close have no effect and will be removed in a future version of distributed.",
                FutureWarning,
            )
        if self.status in (Status.closing, Status.closed):
            await self.finished()
            return

        async def log_errors(func):
            try:
                await func()
            except Exception:
                logger.exception("Plugin call failed during scheduler.close")

        await asyncio.gather(
            *[log_errors(plugin.before_close) for plugin in list(self.plugins.values())]
        )

        self.status = Status.closing

        logger.info("Scheduler closing...")
        setproctitle("dask scheduler [closing]")

        for preload in self.preloads:
            try:
                await preload.teardown()
            except Exception:
                logger.exception("Failed to tear down preload")

        await asyncio.gather(
            *[log_errors(plugin.close) for plugin in list(self.plugins.values())]
        )

        for pc in self.periodic_callbacks.values():
            pc.stop()
        self.periodic_callbacks.clear()

        self.stop_services()

        for ext in self.extensions.values():
            with suppress(AttributeError):
                ext.teardown()
        logger.info("Scheduler closing all comms")

        futures = []
        for _, comm in list(self.stream_comms.items()):
            # FIXME use `self.remove_worker()` instead after https://github.com/dask/distributed/issues/6390
            if not comm.closed():
                # This closes the Worker and ensures that if a Nanny is around,
                # it is closed as well
                comm.send({"op": "close", "reason": "scheduler-close"})
                comm.send({"op": "close-stream"})
                # ^ TODO remove? `Worker.close` will close the stream anyway.
            with suppress(AttributeError):
                futures.append(comm.close())

        await asyncio.gather(*futures)

        if self.jupyter:
            await self._jupyter_server_application._cleanup()

        for comm in self.client_comms.values():
            comm.abort()

        await self.rpc.close()

        self.status = Status.closed
        self.stop()
        await super().close()

        setproctitle("dask scheduler [closed]")
        disable_gc_diagnosis()

    ###########
    # Stimuli #
    ###########

    def heartbeat_worker(
        self,
        comm=None,
        *,
        address,
        resolve_address: bool = True,
        now: float | None = None,
        resources: dict[str, float] | None = None,
        host_info: dict | None = None,
        metrics: dict,
        executing: dict[str, float] | None = None,
        extensions: dict | None = None,
    ) -> dict[str, Any]:
        address = self.coerce_address(address, resolve_address)
        address = normalize_address(address)
        ws = self.workers.get(address)
        if ws is None:
            logger.warning(f"Received heartbeat from unregistered worker {address!r}.")
            return {"status": "missing"}

        host = get_address_host(address)
        local_now = time()
        host_info = host_info or {}

        dh: dict = self.host_info.setdefault(host, {})
        dh["last-seen"] = local_now

        frac = 1 / len(self.workers)
        self.bandwidth = (
            self.bandwidth * (1 - frac) + metrics["bandwidth"]["total"] * frac
        )
        for other, (bw, count) in metrics["bandwidth"]["workers"].items():
            if (address, other) not in self.bandwidth_workers:
                self.bandwidth_workers[address, other] = bw / count
            else:
                alpha = (1 - frac) ** count
                self.bandwidth_workers[address, other] = self.bandwidth_workers[
                    address, other
                ] * alpha + bw * (1 - alpha)
        for typ, (bw, count) in metrics["bandwidth"]["types"].items():
            if typ not in self.bandwidth_types:
                self.bandwidth_types[typ] = bw / count
            else:
                alpha = (1 - frac) ** count
                self.bandwidth_types[typ] = self.bandwidth_types[typ] * alpha + bw * (
                    1 - alpha
                )

        ws.last_seen = local_now
        if executing is not None:
            # NOTE: the executing dict is unused
            ws.executing = {}
            for key, duration in executing.items():
                if key in self.tasks:
                    ts = self.tasks[key]
                    ws.executing[ts] = duration
                    ts.prefix.add_exec_time(duration)

        ws.metrics = metrics

        # Calculate RSS - dask keys, separating "old" and "new" usage
        # See MemoryState for details
        max_memory_unmanaged_old_hist_age = local_now - self.MEMORY_RECENT_TO_OLD_TIME
        memory_unmanaged_old = ws._memory_unmanaged_old
        while ws._memory_unmanaged_history:
            timestamp, size = ws._memory_unmanaged_history[0]
            if timestamp >= max_memory_unmanaged_old_hist_age:
                break
            ws._memory_unmanaged_history.popleft()
            if size == memory_unmanaged_old:
                memory_unmanaged_old = 0  # recalculate min()

        # ws._nbytes is updated at a different time and sizeof() may not be accurate,
        # so size may be (temporarily) negative; floor it to zero.
        size = max(
            0, metrics["memory"] - ws.nbytes + metrics["spilled_bytes"]["memory"]
        )

        ws._memory_unmanaged_history.append((local_now, size))
        if not memory_unmanaged_old:
            # The worker has just been started or the previous minimum has been expunged
            # because too old.
            # Note: this algorithm is capped to 200 * MEMORY_RECENT_TO_OLD_TIME elements
            # cluster-wide by heartbeat_interval(), regardless of the number of workers
            ws._memory_unmanaged_old = min(map(second, ws._memory_unmanaged_history))
        elif size < memory_unmanaged_old:
            ws._memory_unmanaged_old = size

        if host_info:
            dh = self.host_info.setdefault(host, {})
            dh.update(host_info)

        if now:
            ws.time_delay = local_now - now

        if resources:
            self.add_resources(worker=address, resources=resources)

        if extensions:
            for name, data in extensions.items():
                self.extensions[name].heartbeat(ws, data)

        return {
            "status": "OK",
            "time": local_now,
            "heartbeat-interval": heartbeat_interval(len(self.workers)),
        }

    @log_errors
    async def add_worker(
        self,
        comm: Comm,
        *,
        address: str,
        status: str,
        server_id: str,
        keys=(),
        nthreads=None,
        name=None,
        resolve_address=True,
        nbytes=None,
        types=None,
        now=None,
        resources=None,
        host_info=None,
        memory_limit=None,
        metrics=None,
        pid=0,
        services=None,
        local_directory=None,
        versions: dict[str, Any] | None = None,
        nanny=None,
        extra=None,
        stimulus_id: str,
    ) -> None:
        """Add a new worker to the cluster"""
        address = self.coerce_address(address, resolve_address)
        address = normalize_address(address)
        host = get_address_host(address)

        if address in self.workers:
            raise ValueError("Worker already exists %s" % address)

        if nbytes:
            err = (
                f"Worker {address!r} connected with {len(nbytes)} key(s) in memory! Worker reconnection is not supported. "
                f"Keys: {list(nbytes)}"
            )
            logger.error(err)
            await comm.write({"status": "error", "message": err, "time": time()})
            return

        if name in self.aliases:
            logger.warning("Worker tried to connect with a duplicate name: %s", name)
            msg = {
                "status": "error",
                "message": "name taken, %s" % name,
                "time": time(),
            }
            await comm.write(msg)
            return

        self.log_event(address, {"action": "add-worker"})
        self.log_event("all", {"action": "add-worker", "worker": address})

        self.workers[address] = ws = WorkerState(
            address=address,
            status=Status.lookup[status],  # type: ignore
            pid=pid,
            nthreads=nthreads,
            memory_limit=memory_limit or 0,
            name=name,
            local_directory=local_directory,
            services=services,
            versions=versions,
            nanny=nanny,
            extra=extra,
            server_id=server_id,
            scheduler=self,
        )
        if ws.status == Status.running:
            self.running.add(ws)

        dh = self.host_info.get(host)
        if dh is None:
            self.host_info[host] = dh = {}

        dh_addresses = dh.get("addresses")
        if dh_addresses is None:
            dh["addresses"] = dh_addresses = set()
            dh["nthreads"] = 0

        dh_addresses.add(address)
        dh["nthreads"] += nthreads

        self.total_nthreads += nthreads
        self.aliases[name] = address

        self.heartbeat_worker(
            address=address,
            resolve_address=resolve_address,
            now=now,
            resources=resources,
            host_info=host_info,
            metrics=metrics,
        )

        # Do not need to adjust self.total_occupancy as self.occupancy[ws] cannot
        # exist before this.
        self.check_idle_saturated(ws)

        # for key in keys:  # TODO
        #     self.mark_key_in_memory(key, [address])

        self.stream_comms[address] = BatchedSend(interval="5ms", loop=self.loop)

        for plugin in list(self.plugins.values()):
            try:
                result = plugin.add_worker(scheduler=self, worker=address)
                if result is not None and inspect.isawaitable(result):
                    await result
            except Exception as e:
                logger.exception(e)

        if ws.status == Status.running:
            self.transitions(
                self.bulk_schedule_unrunnable_after_adding_worker(ws), stimulus_id
            )
            self.stimulus_queue_slots_maybe_opened(stimulus_id=stimulus_id)

        logger.info("Register worker %s", ws)

        msg = {
            "status": "OK",
            "time": time(),
            "heartbeat-interval": heartbeat_interval(len(self.workers)),
            "worker-plugins": self.worker_plugins,
        }

        version_warning = version_module.error_message(
            version_module.get_versions(),
            {w: ws.versions for w, ws in self.workers.items()},
            versions,
            source_name=str(ws.server_id),
        )
        msg.update(version_warning)

        await comm.write(msg)
        # This will keep running until the worker is removed
        await self.handle_worker(comm, address)

    async def add_nanny(self) -> dict[str, Any]:
        msg = {
            "status": "OK",
            "nanny-plugins": self.nanny_plugins,
        }
        return msg

    def update_graph_hlg(
        self,
        client=None,
        hlg=None,
        keys=None,
        dependencies=None,
        restrictions=None,
        priority=None,
        loose_restrictions=None,
        resources=None,
        submitting_task=None,
        retries=None,
        user_priority=0,
        actors=None,
        fifo_timeout=0,
        code=None,
    ):
        unpacked_graph = HighLevelGraph.__dask_distributed_unpack__(hlg)
        dsk = unpacked_graph["dsk"]
        dependencies = unpacked_graph["deps"]
        annotations = unpacked_graph["annotations"]

        # Remove any self-dependencies (happens on test_publish_bag() and others)
        for k, v in dependencies.items():
            deps = set(v)
            if k in deps:
                deps.remove(k)
            dependencies[k] = deps

        if priority is None:
            # Removing all non-local keys before calling order()
            dsk_keys = set(dsk)  # intersection() of sets is much faster than dict_keys
            stripped_deps = {
                k: v.intersection(dsk_keys)
                for k, v in dependencies.items()
                if k in dsk_keys
            }
            priority = dask.order.order(dsk, dependencies=stripped_deps)

        return self.update_graph(
            client,
            dsk,
            keys,
            dependencies,
            restrictions,
            priority,
            loose_restrictions,
            resources,
            submitting_task,
            retries,
            user_priority,
            actors,
            fifo_timeout,
            annotations,
            code=code,
            stimulus_id=f"update-graph-{time()}",
        )

    def update_graph(
        self,
        client=None,
        tasks=None,
        keys=None,
        dependencies=None,
        restrictions=None,
        priority=None,
        loose_restrictions=None,
        resources=None,
        submitting_task=None,
        retries=None,
        user_priority=0,
        actors=None,
        fifo_timeout=0,
        annotations=None,
        code=None,
        stimulus_id=None,
    ):
        """
        Add new computations to the internal dask graph

        This happens whenever the Client calls submit, map, get, or compute.
        """
        stimulus_id = stimulus_id or f"update-graph-{time()}"
        start = time()
        fifo_timeout = parse_timedelta(fifo_timeout)
        keys = set(keys)
        if len(tasks) > 1:
            self.log_event(
                ["all", client], {"action": "update_graph", "count": len(tasks)}
            )

        # Remove aliases
        for k in list(tasks):
            if tasks[k] is k:
                del tasks[k]

        dependencies = dependencies or {}

        if self.total_occupancy > 1e-9 and self.computations:
            # Still working on something. Assign new tasks to same computation
            computation = self.computations[-1]
        else:
            computation = Computation()
            self.computations.append(computation)

        if code and code not in computation.code:  # add new code blocks
            computation.code.add(code)

        n = 0
        while len(tasks) != n:  # walk through new tasks, cancel any bad deps
            n = len(tasks)
            for k, deps in list(dependencies.items()):
                if any(
                    dep not in self.tasks and dep not in tasks for dep in deps
                ):  # bad key
                    logger.info("User asked for computation on lost data, %s", k)
                    del tasks[k]
                    del dependencies[k]
                    if k in keys:
                        keys.remove(k)
                    self.report({"op": "cancelled-key", "key": k}, client=client)
                    self.client_releases_keys(
                        keys=[k], client=client, stimulus_id=stimulus_id
                    )

        # Avoid computation that is already finished
        already_in_memory = set()  # tasks that are already done
        for k, v in dependencies.items():
            if v and k in self.tasks:
                ts = self.tasks[k]
                if ts.state in ("memory", "erred"):
                    already_in_memory.add(k)

        if already_in_memory:
            dependents = dask.core.reverse_dict(dependencies)
            stack = list(already_in_memory)
            done = set(already_in_memory)
            while stack:  # remove unnecessary dependencies
                key = stack.pop()
                try:
                    deps = dependencies[key]
                except KeyError:
                    deps = self.tasks[key].dependencies
                for dep in deps:
                    if dep in dependents:
                        child_deps = dependents[dep]
                    elif dep in self.tasks:
                        child_deps = self.tasks[dep].dependencies
                    else:
                        child_deps = set()
                    if all(d in done for d in child_deps):
                        if dep in self.tasks and dep not in done:
                            done.add(dep)
                            stack.append(dep)

            for d in done:
                tasks.pop(d, None)
                dependencies.pop(d, None)

        # Get or create task states
        stack = list(keys)
        touched_keys = set()
        touched_tasks = []
        while stack:
            k = stack.pop()
            if k in touched_keys:
                continue
            # XXX Have a method get_task_state(self, k) ?
            ts = self.tasks.get(k)
            if ts is None:
                ts = self.new_task(k, tasks.get(k), "released", computation=computation)
            elif not ts.run_spec:
                ts.run_spec = tasks.get(k)

            touched_keys.add(k)
            touched_tasks.append(ts)
            stack.extend(dependencies.get(k, ()))

        self.client_desires_keys(keys=keys, client=client)

        # Add dependencies
        for key, deps in dependencies.items():
            ts = self.tasks.get(key)
            if ts is None or ts.dependencies:
                continue
            for dep in deps:
                dts = self.tasks[dep]
                ts.add_dependency(dts)

        # Compute priorities
        if isinstance(user_priority, Number):
            user_priority = {k: user_priority for k in tasks}

        annotations = annotations or {}
        restrictions = restrictions or {}
        loose_restrictions = loose_restrictions or []
        resources = resources or {}
        retries = retries or {}

        # Override existing taxonomy with per task annotations
        if annotations:
            if "priority" in annotations:
                user_priority.update(annotations["priority"])

            if "workers" in annotations:
                restrictions.update(annotations["workers"])

            if "allow_other_workers" in annotations:
                loose_restrictions.extend(
                    k for k, v in annotations["allow_other_workers"].items() if v
                )

            if "retries" in annotations:
                retries.update(annotations["retries"])

            if "resources" in annotations:
                resources.update(annotations["resources"])

            for a, kv in annotations.items():
                for k, v in kv.items():
                    # Tasks might have been culled, in which case
                    # we have nothing to annotate.
                    ts = self.tasks.get(k)
                    if ts is not None:
                        ts.annotations[a] = v

        # Add actors
        if actors is True:
            actors = list(keys)
        for actor in actors or []:
            ts = self.tasks[actor]
            ts.actor = True

        priority = priority or dask.order.order(
            tasks
        )  # TODO: define order wrt old graph

        if submitting_task:  # sub-tasks get better priority than parent tasks
            ts = self.tasks.get(submitting_task)
            if ts is not None:
                generation = ts.priority[0] - 0.01
            else:  # super-task already cleaned up
                generation = self.generation
        elif self._last_time + fifo_timeout < start:
            self.generation += 1  # older graph generations take precedence
            generation = self.generation
            self._last_time = start
        else:
            generation = self.generation

        for key in set(priority) & touched_keys:
            ts = self.tasks[key]
            if ts.priority is None:
                ts.priority = (-(user_priority.get(key, 0)), generation, priority[key])

        # Ensure all runnables have a priority
        runnables = [ts for ts in touched_tasks if ts.run_spec]
        for ts in runnables:
            if ts.priority is None and ts.run_spec:
                ts.priority = (self.generation, 0)

        if restrictions:
            # *restrictions* is a dict keying task ids to lists of
            # restriction specifications (either worker names or addresses)
            for k, v in restrictions.items():
                if v is None:
                    continue
                ts = self.tasks.get(k)
                if ts is None:
                    continue
                ts.host_restrictions = set()
                ts.worker_restrictions = set()
                # Make sure `v` is a collection and not a single worker name / address
                if not isinstance(v, (list, tuple, set)):
                    v = [v]
                for w in v:
                    try:
                        w = self.coerce_address(w)
                    except ValueError:
                        # Not a valid address, but perhaps it's a hostname
                        ts.host_restrictions.add(w)
                    else:
                        ts.worker_restrictions.add(w)

            if loose_restrictions:
                for k in loose_restrictions:
                    ts = self.tasks[k]
                    ts.loose_restrictions = True

        if resources:
            for k, v in resources.items():
                if v is None:
                    continue
                assert isinstance(v, dict)
                ts = self.tasks.get(k)
                if ts is None:
                    continue
                ts.resource_restrictions = v

        if retries:
            for k, v in retries.items():
                assert isinstance(v, int)
                ts = self.tasks.get(k)
                if ts is None:
                    continue
                ts.retries = v

        # Compute recommendations
        recommendations: Recs = {}

        for ts in sorted(runnables, key=operator.attrgetter("priority"), reverse=True):
            if ts.state == "released" and ts.run_spec:
                recommendations[ts.key] = "waiting"

        for ts in touched_tasks:
            for dts in ts.dependencies:
                if dts.exception_blame:
                    ts.exception_blame = dts.exception_blame
                    recommendations[ts.key] = "erred"
                    break

        for plugin in list(self.plugins.values()):
            try:
                plugin.update_graph(
                    self,
                    client=client,
                    tasks=tasks,
                    keys=keys,
                    restrictions=restrictions or {},
                    dependencies=dependencies,
                    priority=priority,
                    loose_restrictions=loose_restrictions,
                    resources=resources,
                    annotations=annotations,
                )
            except Exception as e:
                logger.exception(e)

        self.transitions(recommendations, stimulus_id)

        for ts in touched_tasks:
            if ts.state in ("memory", "erred"):
                self.report_on_key(ts=ts, client=client)

        end = time()
        self.digest_metric("update-graph-duration", end - start)

        # TODO: balance workers

    def stimulus_queue_slots_maybe_opened(self, *, stimulus_id: str) -> None:
        """Respond to an event which may have opened spots on worker threadpools

        Selects the appropriate number of tasks from the front of the queue according to
        the total number of task slots available on workers (potentially 0), and
        transitions them to ``processing``.

        Notes
        -----
        Other transitions related to this stimulus should be fully processed beforehand,
        so any tasks that became runnable are already in ``processing``. Otherwise,
        overproduction can occur if queued tasks get scheduled before downstream tasks.

        Must be called after `check_idle_saturated`; i.e. `idle_task_count` must be up
        to date.
        """
        if not self.queued:
            return
        slots_available = sum(
            _task_slots_available(ws, self.WORKER_SATURATION)
            for ws in self.idle_task_count
        )
        if slots_available == 0:
            return

        recommendations: Recs = {}
        for qts in self.queued.peekn(slots_available):
            if self.validate:
                assert qts.state == "queued", qts.state
                assert not qts.processing_on, (qts, qts.processing_on)
                assert not qts.waiting_on, (qts, qts.processing_on)
                assert qts.who_wants or qts.waiters, qts
            recommendations[qts.key] = "processing"

        self.transitions(recommendations, stimulus_id)

    def stimulus_task_finished(self, key=None, worker=None, stimulus_id=None, **kwargs):
        """Mark that a task has finished execution on a particular worker"""
        logger.debug("Stimulus task finished %s, %s", key, worker)

        recommendations: Recs = {}
        client_msgs: Msgs = {}
        worker_msgs: Msgs = {}

        ws: WorkerState = self.workers[worker]
        ts: TaskState = self.tasks.get(key)
        if ts is None or ts.state in ("released", "queued"):
            logger.debug(
                "Received already computed task, worker: %s, state: %s"
                ", key: %s, who_has: %s",
                worker,
                ts.state if ts else "forgotten",
                key,
                ts.who_has if ts else {},
            )
            worker_msgs[worker] = [
                {
                    "op": "free-keys",
                    "keys": [key],
                    "stimulus_id": stimulus_id,
                }
            ]
        elif ts.state == "memory":
            self.add_keys(worker=worker, keys=[key])
        else:
            ts.metadata.update(kwargs["metadata"])
            r: tuple = self._transition(
                key, "memory", stimulus_id, worker=worker, **kwargs
            )
            recommendations, client_msgs, worker_msgs = r

            if ts.state == "memory":
                assert ws in ts.who_has
        return recommendations, client_msgs, worker_msgs

    def stimulus_task_erred(
        self,
        key=None,
        worker=None,
        exception=None,
        stimulus_id=None,
        traceback=None,
        **kwargs,
    ):
        """Mark that a task has erred on a particular worker"""
        logger.debug("Stimulus task erred %s, %s", key, worker)

        ts: TaskState = self.tasks.get(key)
        if ts is None or ts.state != "processing":
            return {}, {}, {}

        if ts.retries > 0:
            ts.retries -= 1
            return self._transition(key, "waiting", stimulus_id)
        else:
            return self._transition(
                key,
                "erred",
                stimulus_id,
                cause=key,
                exception=exception,
                traceback=traceback,
                worker=worker,
                **kwargs,
            )

    def stimulus_retry(self, keys, client=None):
        logger.info("Client %s requests to retry %d keys", client, len(keys))
        if client:
            self.log_event(client, {"action": "retry", "count": len(keys)})

        stack = list(keys)
        seen = set()
        roots = []
        ts: TaskState
        dts: TaskState
        while stack:
            key = stack.pop()
            seen.add(key)
            ts = self.tasks[key]
            erred_deps = [dts.key for dts in ts.dependencies if dts.state == "erred"]
            if erred_deps:
                stack.extend(erred_deps)
            else:
                roots.append(key)

        recommendations: Recs = {key: "waiting" for key in roots}
        self.transitions(recommendations, f"stimulus-retry-{time()}")

        if self.validate:
            for key in seen:
                assert not self.tasks[key].exception_blame

        return tuple(seen)

    def close_worker(self, worker: str) -> None:
        """Ask a worker to shut itself down. Do not wait for it to take effect.
        Note that there is no guarantee that the worker will actually accept the
        command.

        Note that :meth:`remove_worker` sends the same command internally if close=True.

        See also
        --------
        retire_workers
        remove_worker
        """
        if worker not in self.workers:
            return

        logger.info("Closing worker %s", worker)
        self.log_event(worker, {"action": "close-worker"})
        self.worker_send(worker, {"op": "close", "reason": "scheduler-close-worker"})

    @log_errors
    async def remove_worker(
        self, address: str, *, stimulus_id: str, safe: bool = False, close: bool = True
    ) -> Literal["OK", "already-removed"]:
        """Remove worker from cluster.

        We do this when a worker reports that it plans to leave or when it appears to be
        unresponsive. This may send its tasks back to a released state.

        See also
        --------
        retire_workers
        close_worker
        """
        if self.status == Status.closed:
            return "already-removed"

        address = self.coerce_address(address)

        if address not in self.workers:
            return "already-removed"

        host = get_address_host(address)

        ws: WorkerState = self.workers[address]

        event_msg = {
            "action": "remove-worker",
            "processing-tasks": {ts.key for ts in ws.processing},
        }
        self.log_event(address, event_msg.copy())
        event_msg["worker"] = address
        self.log_event("all", event_msg)

        logger.info("Remove worker %s", ws)
        if close:
            with suppress(AttributeError, CommClosedError):
                self.stream_comms[address].send(
                    {"op": "close", "reason": "scheduler-remove-worker"}
                )

        self.remove_resources(address)

        dh: dict = self.host_info[host]
        dh_addresses: set = dh["addresses"]
        dh_addresses.remove(address)
        dh["nthreads"] -= ws.nthreads
        self.total_nthreads -= ws.nthreads
        if not dh_addresses:
            del self.host_info[host]

        self.rpc.remove(address)
        del self.stream_comms[address]
        del self.aliases[ws.name]
        self.idle.pop(ws.address, None)
        self.idle_task_count.discard(ws)
        self.saturated.discard(ws)
        del self.workers[address]
        ws.status = Status.closed
        self.running.discard(ws)

        recommendations: Recs = {}

        ts: TaskState
        for ts in list(ws.processing):
            k = ts.key
            recommendations[k] = "released"
            if not safe:
                ts.suspicious += 1
                ts.prefix.suspicious += 1
                if ts.suspicious > self.allowed_failures:
                    del recommendations[k]
                    e = pickle.dumps(
                        KilledWorker(
                            task=k,
                            last_worker=ws.clean(),
                            allowed_failures=self.allowed_failures,
                        ),
                    )
                    r = self.transition(
                        k,
                        "erred",
                        exception=e,
                        cause=k,
                        stimulus_id=stimulus_id,
                        worker=address,
                    )
                    recommendations.update(r)
                    logger.info(
                        "Task %s marked as failed because %d workers died"
                        " while trying to run it",
                        ts.key,
                        self.allowed_failures,
                    )

        for ts in list(ws.has_what):
            self.remove_replica(ts, ws)
            if not ts.who_has:
                if ts.run_spec:
                    recommendations[ts.key] = "released"
                else:  # pure data
                    recommendations[ts.key] = "forgotten"

        self.transitions(recommendations, stimulus_id=stimulus_id)

        for plugin in list(self.plugins.values()):
            try:
                result = plugin.remove_worker(scheduler=self, worker=address)
                if inspect.isawaitable(result):
                    await result
            except Exception as e:
                logger.exception(e)

        if not self.workers:
            logger.info("Lost all workers")

        for w in self.workers:
            self.bandwidth_workers.pop((address, w), None)
            self.bandwidth_workers.pop((w, address), None)

        async def remove_worker_from_events():
            # If the worker isn't registered anymore after the delay, remove from events
            if address not in self.workers and address in self.events:
                del self.events[address]

        cleanup_delay = parse_timedelta(
            dask.config.get("distributed.scheduler.events-cleanup-delay")
        )

        self._ongoing_background_tasks.call_later(
            cleanup_delay, remove_worker_from_events
        )
        logger.debug("Removed worker %s", ws)

        return "OK"

    async def stimulus_cancel(self, keys, client, force=False):
        """Stop execution on a list of keys"""
        logger.info("Client %s requests to cancel %d keys", client, len(keys))
        if client:
            self.log_event(
                client, {"action": "cancel", "count": len(keys), "force": force}
            )

        await asyncio.gather(
            *[self._cancel_key(key, client, force=force) for key in keys]
        )

    async def _cancel_key(self, key, client, force=False):
        """Cancel a particular key and all dependents"""
        # TODO: this should be converted to use the transition mechanism
        ts: TaskState | None = self.tasks.get(key)
        dts: TaskState
        try:
            cs: ClientState = self.clients[client]
        except KeyError:
            return

        # no key yet, lets try again in a moment
        start = time()
        while ts is None or not ts.who_wants:
            await asyncio.sleep(0.1)
            ts = self.tasks.get(key)
            if time() - start >= 1:
                return

        if force or ts.who_wants == {cs}:  # no one else wants this key
            await asyncio.gather(
                *[
                    self._cancel_key(dts.key, client, force=force)
                    for dts in ts.dependents
                ]
            )
            logger.info("Scheduler cancels key %s.  Force=%s", key, force)
            self.report({"op": "cancelled-key", "key": key})
        clients = list(ts.who_wants) if force else [cs]
        for cs in clients:
            self.client_releases_keys(
                keys=[key], client=cs.client_key, stimulus_id=f"cancel-key-{time()}"
            )

    def client_desires_keys(self, keys=None, client=None):
        cs: ClientState = self.clients.get(client)
        if cs is None:
            # For publish, queues etc.
            self.clients[client] = cs = ClientState(client)
        for k in keys:
            ts = self.tasks.get(k)
            if ts is None:
                # For publish, queues etc.
                ts = self.new_task(k, None, "released")
            ts.who_wants.add(cs)
            cs.wants_what.add(ts)

            if ts.state in ("memory", "erred"):
                self.report_on_key(ts=ts, client=client)

    def client_releases_keys(self, keys=None, client=None, stimulus_id=None):
        """Remove keys from client desired list"""
        stimulus_id = stimulus_id or f"client-releases-keys-{time()}"
        if not isinstance(keys, list):
            keys = list(keys)
        cs = self.clients[client]
        recommendations: Recs = {}

        self._client_releases_keys(keys=keys, cs=cs, recommendations=recommendations)
        self.transitions(recommendations, stimulus_id)

        self.stimulus_queue_slots_maybe_opened(stimulus_id=stimulus_id)

    def client_heartbeat(self, client=None):
        """Handle heartbeats from Client"""
        cs: ClientState = self.clients[client]
        cs.last_seen = time()

    ###################
    # Task Validation #
    ###################

    def validate_released(self, key):
        ts: TaskState = self.tasks[key]
        assert ts.state == "released"
        assert not ts.waiters
        assert not ts.waiting_on
        assert not ts.who_has
        assert not ts.processing_on
        assert not any([ts in dts.waiters for dts in ts.dependencies])
        assert ts not in self.unrunnable
        assert ts not in self.queued

    def validate_waiting(self, key):
        ts: TaskState = self.tasks[key]
        assert ts.waiting_on
        assert not ts.who_has
        assert not ts.processing_on
        assert ts not in self.unrunnable
        assert ts not in self.queued
        for dts in ts.dependencies:
            # We are waiting on a dependency iff it's not stored
            assert bool(dts.who_has) != (dts in ts.waiting_on)
            assert ts in dts.waiters  # XXX even if dts._who_has?

    def validate_queued(self, key):
        ts: TaskState = self.tasks[key]
        dts: TaskState
        assert ts in self.queued
        assert not ts.waiting_on
        assert not ts.who_has
        assert not ts.processing_on
        assert not (
            ts.worker_restrictions or ts.host_restrictions or ts.resource_restrictions
        )
        for dts in ts.dependencies:
            assert dts.who_has
            assert ts in dts.waiters

    def validate_processing(self, key):
        ts: TaskState = self.tasks[key]
        dts: TaskState
        assert not ts.waiting_on
        ws = ts.processing_on
        assert ws
        assert ts in ws.processing
        assert not ts.who_has
        assert ts not in self.queued
        for dts in ts.dependencies:
            assert dts.who_has
            assert ts in dts.waiters

    def validate_memory(self, key):
        ts: TaskState = self.tasks[key]
        dts: TaskState
        assert ts.who_has
        assert bool(ts in self.replicated_tasks) == (len(ts.who_has) > 1)
        assert not ts.processing_on
        assert not ts.waiting_on
        assert ts not in self.unrunnable
        assert ts not in self.queued
        for dts in ts.dependents:
            assert (dts in ts.waiters) == (
                dts.state in ("waiting", "queued", "processing", "no-worker")
            )
            assert ts not in dts.waiting_on

    def validate_no_worker(self, key):
        ts: TaskState = self.tasks[key]
        assert ts in self.unrunnable
        assert not ts.waiting_on
        assert ts in self.unrunnable
        assert not ts.processing_on
        assert not ts.who_has
        assert ts not in self.queued
        for dts in ts.dependencies:
            assert dts.who_has

    def validate_erred(self, key):
        ts: TaskState = self.tasks[key]
        assert ts.exception_blame
        assert not ts.who_has
        assert ts not in self.queued

    def validate_key(self, key, ts: TaskState | None = None):
        try:
            if ts is None:
                ts = self.tasks.get(key)
            if ts is None:
                logger.debug("Key lost: %s", key)
            else:
                ts.validate()
                try:
                    func = getattr(self, "validate_" + ts.state.replace("-", "_"))
                except AttributeError:
                    logger.error(
                        "self.validate_%s not found", ts.state.replace("-", "_")
                    )
                else:
                    func(key)
        except Exception as e:
            logger.exception(e)
            if LOG_PDB:
                import pdb

                pdb.set_trace()
            raise

    def validate_state(self, allow_overlap: bool = False) -> None:
        validate_state(self.tasks, self.workers, self.clients)

        if not (set(self.workers) == set(self.stream_comms)):
            raise ValueError("Workers not the same in all collections")

        assert self.running.issuperset(self.idle.values()), (
            self.running,
            list(self.idle.values()),
        )
        task_prefix_counts: defaultdict[str, int] = defaultdict(int)
        for w, ws in self.workers.items():
            assert isinstance(w, str), (type(w), w)
            assert isinstance(ws, WorkerState), (type(ws), ws)
            assert ws.address == w
            if ws.status != Status.running:
                assert ws.address not in self.idle
            assert ws.long_running.issubset(ws.processing)
            if not ws.processing:
                assert not ws.occupancy
                if ws.status == Status.running:
                    assert ws.address in self.idle
            assert not ws.needs_what.keys() & ws.has_what
            actual_needs_what: defaultdict[TaskState, int] = defaultdict(int)
            for ts in ws.processing:
                for tss in ts.dependencies:
                    if tss not in ws.has_what:
                        actual_needs_what[tss] += 1
            assert actual_needs_what == ws.needs_what
            assert (ws.status == Status.running) == (ws in self.running)
            for name, count in ws.task_prefix_count.items():
                task_prefix_counts[name] += count

        assert task_prefix_counts.keys() == self._task_prefix_count_global.keys()
        for name, global_count in self._task_prefix_count_global.items():
            assert (
                task_prefix_counts[name] == global_count
            ), f"{name}: {task_prefix_counts[name]} (wss), {global_count} (global)"

        for ws in self.running:
            assert ws.status == Status.running
            assert ws.address in self.workers

        for k, ts in self.tasks.items():
            assert isinstance(ts, TaskState), (type(ts), ts)
            assert ts.key == k
            assert bool(ts in self.replicated_tasks) == (len(ts.who_has) > 1)
            self.validate_key(k, ts)

        for ts in self.replicated_tasks:
            assert ts.state == "memory"
            assert ts.key in self.tasks

        for c, cs in self.clients.items():
            # client=None is often used in tests...
            assert c is None or type(c) == str, (type(c), c)
            assert type(cs) == ClientState, (type(cs), cs)
            assert cs.client_key == c

        a = {w: ws.nbytes for w, ws in self.workers.items()}
        b = {
            w: sum(ts.get_nbytes() for ts in ws.has_what)
            for w, ws in self.workers.items()
        }
        assert a == b, (a, b)

        if self.transition_counter_max:
            assert self.transition_counter < self.transition_counter_max

    ###################
    # Manage Messages #
    ###################

    def report(self, msg: dict, ts: TaskState | None = None, client: str | None = None):
        """
        Publish updates to all listening Queues and Comms

        If the message contains a key then we only send the message to those
        comms that care about the key.
        """
        if ts is None:
            msg_key = msg.get("key")
            if msg_key is not None:
                tasks: dict = self.tasks
                ts = tasks.get(msg_key)

        client_comms: dict = self.client_comms
        if ts is None:
            # Notify all clients
            client_keys = list(client_comms)
        elif client is None:
            # Notify clients interested in key
            client_keys = [cs.client_key for cs in ts.who_wants]
        else:
            # Notify clients interested in key (including `client`)
            client_keys = [
                cs.client_key for cs in ts.who_wants if cs.client_key != client
            ]
            client_keys.append(client)

        k: str
        for k in client_keys:
            c = client_comms.get(k)
            if c is None:
                continue
            try:
                c.send(msg)
                # logger.debug("Scheduler sends message to client %s", msg)
            except CommClosedError:
                if self.status == Status.running:
                    logger.critical(
                        "Closed comm %r while trying to write %s", c, msg, exc_info=True
                    )

    async def add_client(
        self, comm: Comm, client: str, versions: dict[str, Any]
    ) -> None:
        """Add client to network

        We listen to all future messages from this Comm.
        """
        assert client is not None
        comm.name = "Scheduler->Client"
        logger.info("Receive client connection: %s", client)
        self.log_event(["all", client], {"action": "add-client", "client": client})
        self.clients[client] = ClientState(client, versions=versions)

        for plugin in list(self.plugins.values()):
            try:
                plugin.add_client(scheduler=self, client=client)
            except Exception as e:
                logger.exception(e)

        try:
            bcomm = BatchedSend(interval="2ms", loop=self.loop)
            bcomm.start(comm)
            self.client_comms[client] = bcomm
            msg = {"op": "stream-start"}
            version_warning = version_module.error_message(
                version_module.get_versions(),
                {w: ws.versions for w, ws in self.workers.items()},
                versions,
            )
            msg.update(version_warning)
            bcomm.send(msg)

            try:
                await self.handle_stream(comm=comm, extra={"client": client})
            finally:
                self.remove_client(client=client, stimulus_id=f"remove-client-{time()}")
                logger.debug("Finished handling client %s", client)
        finally:
            if not comm.closed():
                self.client_comms[client].send({"op": "stream-closed"})
            try:
                if not sys.is_finalizing():
                    await self.client_comms[client].close()
                    del self.client_comms[client]
                    if self.status == Status.running:
                        logger.info("Close client connection: %s", client)
            except TypeError:  # comm becomes None during GC
                pass

    def remove_client(self, client: str, stimulus_id: str | None = None) -> None:
        """Remove client from network"""
        stimulus_id = stimulus_id or f"remove-client-{time()}"
        if self.status == Status.running:
            logger.info("Remove client %s", client)
        self.log_event(["all", client], {"action": "remove-client", "client": client})
        try:
            cs: ClientState = self.clients[client]
        except KeyError:
            # XXX is this a legitimate condition?
            pass
        else:
            self.client_releases_keys(
                keys=[ts.key for ts in cs.wants_what],
                client=cs.client_key,
                stimulus_id=stimulus_id,
            )
            del self.clients[client]

            for plugin in list(self.plugins.values()):
                try:
                    plugin.remove_client(scheduler=self, client=client)
                except Exception as e:
                    logger.exception(e)

        async def remove_client_from_events():
            # If the client isn't registered anymore after the delay, remove from events
            if client not in self.clients and client in self.events:
                del self.events[client]

        cleanup_delay = parse_timedelta(
            dask.config.get("distributed.scheduler.events-cleanup-delay")
        )
        if not self._ongoing_background_tasks.closed:
            self._ongoing_background_tasks.call_later(
                cleanup_delay, remove_client_from_events
            )

    def send_task_to_worker(self, worker, ts: TaskState, duration: float = -1):
        """Send a single computational task to a worker"""
        try:
            msg: dict = self._task_to_msg(ts, duration)
            self.worker_send(worker, msg)
        except Exception as e:
            logger.exception(e)
            if LOG_PDB:
                import pdb

                pdb.set_trace()
            raise

    def handle_uncaught_error(self, **msg):
        logger.exception(clean_exception(**msg)[1])

    def handle_task_finished(
        self, key: str, worker: str, stimulus_id: str, **msg
    ) -> None:
        if worker not in self.workers:
            return
        validate_key(key)

        r: tuple = self.stimulus_task_finished(
            key=key, worker=worker, stimulus_id=stimulus_id, **msg
        )
        recommendations, client_msgs, worker_msgs = r
        self._transitions(recommendations, client_msgs, worker_msgs, stimulus_id)
        self.send_all(client_msgs, worker_msgs)

        self.stimulus_queue_slots_maybe_opened(stimulus_id=stimulus_id)

    def handle_task_erred(self, key: str, stimulus_id: str, **msg) -> None:
        r: tuple = self.stimulus_task_erred(key=key, stimulus_id=stimulus_id, **msg)
        recommendations, client_msgs, worker_msgs = r
        self._transitions(recommendations, client_msgs, worker_msgs, stimulus_id)
        self.send_all(client_msgs, worker_msgs)

        self.stimulus_queue_slots_maybe_opened(stimulus_id=stimulus_id)

    def release_worker_data(self, key: str, worker: str, stimulus_id: str) -> None:
        ts = self.tasks.get(key)
        ws = self.workers.get(worker)
        if not ts or not ws or ws not in ts.who_has:
            return

        self.remove_replica(ts, ws)
        if not ts.who_has:
            self.transitions({key: "released"}, stimulus_id)

    def handle_long_running(
        self, key: str, worker: str, compute_duration: float | None, stimulus_id: str
    ) -> None:
        """A task has seceded from the thread pool

        We stop the task from being stolen in the future, and change task
        duration accounting as if the task has stopped.
        """
        if key not in self.tasks:
            logger.debug("Skipping long_running since key %s was already released", key)
            return
        ts = self.tasks[key]
        steal = self.extensions.get("stealing")
        if steal is not None:
            steal.remove_key_from_stealable(ts)

        ws = ts.processing_on
        if ws is None:
            logger.debug("Received long-running signal from duplicate task. Ignoring.")
            return

        if compute_duration is not None:
            old_duration = ts.prefix.duration_average
            if old_duration < 0:
                ts.prefix.duration_average = compute_duration
            else:
                ts.prefix.duration_average = (old_duration + compute_duration) / 2

        ws.add_to_long_running(ts)
        self.check_idle_saturated(ws)

        self.stimulus_queue_slots_maybe_opened(stimulus_id=stimulus_id)

    def handle_worker_status_change(
        self, status: str | Status, worker: str | WorkerState, stimulus_id: str
    ) -> None:
        ws = self.workers.get(worker) if isinstance(worker, str) else worker
        if not ws:
            return
        prev_status = ws.status
        ws.status = Status[status] if isinstance(status, str) else status
        if ws.status == prev_status:
            return

        self.log_event(
            ws.address,
            {
                "action": "worker-status-change",
                "prev-status": prev_status.name,
                "status": ws.status.name,
            },
        )
        logger.debug(f"Worker status {prev_status.name} -> {status} - {ws}")

        if ws.status == Status.running:
            self.running.add(ws)
            self.check_idle_saturated(ws)
            self.transitions(
                self.bulk_schedule_unrunnable_after_adding_worker(ws), stimulus_id
            )
            self.stimulus_queue_slots_maybe_opened(stimulus_id=stimulus_id)
        else:
            self.running.discard(ws)
            self.idle.pop(ws.address, None)
            self.idle_task_count.discard(ws)

    async def handle_request_refresh_who_has(
        self, keys: Iterable[str], worker: str, stimulus_id: str
    ) -> None:
        """Asynchronous request (through bulk comms) from a Worker to refresh the
        who_has for some keys. Not to be confused with scheduler.who_has, which is a
        synchronous RPC request from a Client.
        """
        who_has = {}
        free_keys = []
        for key in keys:
            if key in self.tasks:
                who_has[key] = [ws.address for ws in self.tasks[key].who_has]
            else:
                free_keys.append(key)

        if who_has:
            self.stream_comms[worker].send(
                {
                    "op": "refresh-who-has",
                    "who_has": who_has,
                    "stimulus_id": stimulus_id,
                }
            )
        if free_keys:
            self.stream_comms[worker].send(
                {
                    "op": "free-keys",
                    "keys": free_keys,
                    "stimulus_id": stimulus_id,
                }
            )

    async def handle_worker(self, comm: Comm, worker: str) -> None:
        """
        Listen to responses from a single worker

        This is the main loop for scheduler-worker interaction

        See Also
        --------
        Scheduler.handle_client: Equivalent coroutine for clients
        """
        comm.name = "Scheduler connection to worker"
        worker_comm = self.stream_comms[worker]
        worker_comm.start(comm)
        logger.info("Starting worker compute stream, %s", worker)
        try:
            await self.handle_stream(comm=comm, extra={"worker": worker})
        finally:
            if worker in self.stream_comms:
                worker_comm.abort()
                await self.remove_worker(
                    worker, stimulus_id=f"handle-worker-cleanup-{time()}"
                )

    def add_plugin(
        self,
        plugin: SchedulerPlugin,
        *,
        idempotent: bool = False,
        name: str | None = None,
        **kwargs,
    ):
        """Add external plugin to scheduler.

        See https://distributed.readthedocs.io/en/latest/plugins.html

        Parameters
        ----------
        plugin : SchedulerPlugin
            SchedulerPlugin instance to add
        idempotent : bool
            If true, the plugin is assumed to already exist and no
            action is taken.
        name : str
            A name for the plugin, if None, the name attribute is
            checked on the Plugin instance and generated if not
            discovered.
        """
        if name is None:
            name = _get_plugin_name(plugin)

        if name in self.plugins:
            if idempotent:
                return
            warnings.warn(
                f"Scheduler already contains a plugin with name {name}; overwriting.",
                category=UserWarning,
            )

        self.plugins[name] = plugin

    def remove_plugin(
        self,
        name: str | None = None,
        plugin: SchedulerPlugin | None = None,
    ) -> None:
        """Remove external plugin from scheduler

        Parameters
        ----------
        name : str
            Name of the plugin to remove
        """
        assert name is not None

        try:
            del self.plugins[name]
        except KeyError:
            raise ValueError(
                f"Could not find plugin {name!r} among the current scheduler plugins"
            )

    async def register_scheduler_plugin(self, plugin, name=None, idempotent=None):
        """Register a plugin on the scheduler."""
        if not dask.config.get("distributed.scheduler.pickle"):
            raise ValueError(
                "Cannot register a scheduler plugin as the scheduler "
                "has been explicitly disallowed from deserializing "
                "arbitrary bytestrings using pickle via the "
                "'distributed.scheduler.pickle' configuration setting."
            )
        if not isinstance(plugin, SchedulerPlugin):
            plugin = loads(plugin)

        if name is None:
            name = _get_plugin_name(plugin)

        if name in self.plugins and idempotent:
            return

        if hasattr(plugin, "start"):
            result = plugin.start(self)
            if inspect.isawaitable(result):
                await result

        self.add_plugin(plugin, name=name, idempotent=idempotent)

    def worker_send(self, worker: str, msg: dict[str, Any]) -> None:
        """Send message to worker

        This also handles connection failures by adding a callback to remove
        the worker on the next cycle.
        """
        stream_comms: dict = self.stream_comms
        try:
            stream_comms[worker].send(msg)
        except (CommClosedError, AttributeError):
            self._ongoing_background_tasks.call_soon(
                self.remove_worker,
                address=worker,
                stimulus_id=f"worker-send-comm-fail-{time()}",
            )

    def client_send(self, client, msg):
        """Send message to client"""
        client_comms: dict = self.client_comms
        c = client_comms.get(client)
        if c is None:
            return
        try:
            c.send(msg)
        except CommClosedError:
            if self.status == Status.running:
                logger.critical(
                    "Closed comm %r while trying to write %s", c, msg, exc_info=True
                )

    def send_all(self, client_msgs: Msgs, worker_msgs: Msgs) -> None:
        """Send messages to client and workers"""

        for client, msgs in client_msgs.items():
            c = self.client_comms.get(client)
            if c is None:
                continue
            try:
                c.send(*msgs)
            except CommClosedError:
                if self.status == Status.running:
                    logger.critical(
                        "Closed comm %r while trying to write %s",
                        c,
                        msgs,
                        exc_info=True,
                    )

        for worker, msgs in worker_msgs.items():
            try:
                w = self.stream_comms[worker]
                w.send(*msgs)
            except KeyError:
                # worker already gone
                pass
            except (CommClosedError, AttributeError):
                self._ongoing_background_tasks.call_soon(
                    self.remove_worker,
                    address=worker,
                    stimulus_id=f"send-all-comm-fail-{time()}",
                )

    ############################
    # Less common interactions #
    ############################

    async def scatter(
        self,
        comm=None,
        data=None,
        workers=None,
        client=None,
        broadcast=False,
        timeout=2,
    ):
        """Send data out to workers

        See also
        --------
        Scheduler.broadcast:
        """
        start = time()
        while True:
            if workers is None:
                wss = self.running
            else:
                workers = [self.coerce_address(w) for w in workers]
                wss = {self.workers[w] for w in workers}
                wss = {ws for ws in wss if ws.status == Status.running}

            if wss:
                break
            if time() > start + timeout:
                raise TimeoutError("No valid workers found")
            await asyncio.sleep(0.1)

        nthreads = {ws.address: ws.nthreads for ws in wss}

        assert isinstance(data, dict)

        keys, who_has, nbytes = await scatter_to_workers(
            nthreads, data, rpc=self.rpc, report=False
        )

        self.update_data(who_has=who_has, nbytes=nbytes, client=client)

        if broadcast:
            n = len(nthreads) if broadcast is True else broadcast
            await self.replicate(keys=keys, workers=workers, n=n)

        self.log_event(
            [client, "all"], {"action": "scatter", "client": client, "count": len(data)}
        )
        return keys

    async def gather(self, keys, serializers=None):
        """Collect data from workers to the scheduler"""
        stimulus_id = f"gather-{time()}"
        keys = list(keys)
        who_has = {}
        for key in keys:
            ts: TaskState = self.tasks.get(key)
            if ts is not None:
                who_has[key] = [ws.address for ws in ts.who_has]
            else:
                who_has[key] = []

        data, missing_keys, missing_workers = await gather_from_workers(
            who_has, rpc=self.rpc, close=False, serializers=serializers
        )
        if not missing_keys:
            result = {"status": "OK", "data": data}
        else:
            missing_states = [
                (self.tasks[key].state if key in self.tasks else None)
                for key in missing_keys
            ]
            logger.exception(
                "Couldn't gather keys %s state: %s workers: %s",
                missing_keys,
                missing_states,
                missing_workers,
            )
            result = {"status": "error", "keys": missing_keys}
            with log_errors():
                # Remove suspicious workers from the scheduler and shut them down.
                await asyncio.gather(
                    *(
                        self.remove_worker(
                            address=worker, close=True, stimulus_id=stimulus_id
                        )
                        for worker in missing_workers
                    )
                )
                for key, workers in missing_keys.items():
                    logger.exception(
                        "Shut down workers that don't have promised key: %s, %s",
                        str(workers),
                        str(key),
                    )

        self.log_event("all", {"action": "gather", "count": len(keys)})
        return result

    @log_errors
    async def restart(self, client=None, timeout=30, wait_for_workers=True):
        """
        Restart all workers. Reset local state. Optionally wait for workers to return.

        Workers without nannies are shut down, hoping an external deployment system
        will restart them. Therefore, if not using nannies and your deployment system
        does not automatically restart workers, ``restart`` will just shut down all
        workers, then time out!

        After ``restart``, all connected workers are new, regardless of whether ``TimeoutError``
        was raised. Any workers that failed to shut down in time are removed, and
        may or may not shut down on their own in the future.

        Parameters
        ----------
        timeout:
            How long to wait for workers to shut down and come back, if ``wait_for_workers``
            is True, otherwise just how long to wait for workers to shut down.
            Raises ``asyncio.TimeoutError`` if this is exceeded.
        wait_for_workers:
            Whether to wait for all workers to reconnect, or just for them to shut down
            (default True). Use ``restart(wait_for_workers=False)`` combined with
            :meth:`Client.wait_for_workers` for granular control over how many workers to
            wait for.

        See also
        --------
        Client.restart
        Client.restart_workers
        """
        stimulus_id = f"restart-{time()}"

        logger.info("Restarting workers and releasing all keys.")
        for cs in self.clients.values():
            self.client_releases_keys(
                keys=[ts.key for ts in cs.wants_what],
                client=cs.client_key,
                stimulus_id=stimulus_id,
            )

        self._clear_task_state()
        assert not self.tasks
        self.report({"op": "restart"})

        for plugin in list(self.plugins.values()):
            try:
                plugin.restart(self)
            except Exception as e:
                logger.exception(e)

        n_workers = len(self.workers)
        nanny_workers = {
            addr: ws.nanny for addr, ws in self.workers.items() if ws.nanny
        }
        # Close non-Nanny workers. We have no way to restart them, so we just let them go,
        # and assume a deployment system is going to restart them for us.
        await asyncio.gather(
            *(
                self.remove_worker(address=addr, stimulus_id=stimulus_id)
                for addr in self.workers
                if addr not in nanny_workers
            )
        )

        logger.debug("Send kill signal to nannies: %s", nanny_workers)
        async with contextlib.AsyncExitStack() as stack:
            nannies = await asyncio.gather(
                *(
                    stack.enter_async_context(
                        rpc(nanny_address, connection_args=self.connection_args)
                    )
                    for nanny_address in nanny_workers.values()
                )
            )

            start = monotonic()
            resps = await asyncio.gather(
                *(
                    asyncio.wait_for(
                        # FIXME does not raise if the process fails to shut down,
                        # see https://github.com/dask/distributed/pull/6427/files#r894917424
                        # NOTE: Nanny will automatically restart worker process when it's killed
                        nanny.kill(
                            reason="scheduler-restart",
                            timeout=timeout,
                        ),
                        timeout,
                    )
                    for nanny in nannies
                ),
                return_exceptions=True,
            )
            # NOTE: the `WorkerState` entries for these workers will be removed
            # naturally when they disconnect from the scheduler.

            # Remove any workers that failed to shut down, so we can guarantee
            # that after `restart`, there are no old workers around.
            bad_nannies = [
                addr for addr, resp in zip(nanny_workers, resps) if resp is not None
            ]
            if bad_nannies:
                await asyncio.gather(
                    *(
                        self.remove_worker(addr, stimulus_id=stimulus_id)
                        for addr in bad_nannies
                    )
                )

                raise TimeoutError(
                    f"{len(bad_nannies)}/{len(nannies)} nanny worker(s) did not shut down within {timeout}s"
                )

        self.log_event([client, "all"], {"action": "restart", "client": client})

        if wait_for_workers:
            while len(self.workers) < n_workers:
                # NOTE: if new (unrelated) workers join while we're waiting, we may return before
                # our shut-down workers have come back up. That's fine; workers are interchangeable.
                if monotonic() < start + timeout:
                    await asyncio.sleep(0.2)
                else:
                    msg = (
                        f"Waited for {n_workers} worker(s) to reconnect after restarting, "
                        f"but after {timeout}s, only {len(self.workers)} have returned. "
                        "Consider a longer timeout, or `wait_for_workers=False`."
                    )

                    if (n_nanny := len(nanny_workers)) < n_workers:
                        msg += (
                            f" The {n_workers - n_nanny} worker(s) not using Nannies were just shut "
                            "down instead of restarted (restart is only possible with Nannies). If "
                            "your deployment system does not automatically re-launch terminated "
                            "processes, then those workers will never come back, and `Client.restart` "
                            "will always time out. Do not use `Client.restart` in that case."
                        )
                    raise TimeoutError(msg) from None
        logger.info("Restarting finished.")

    async def broadcast(
        self,
        comm=None,
        *,
        msg: dict,
        workers: "list[str] | None" = None,
        hosts: "list[str] | None" = None,
        nanny: bool = False,
        serializers=None,
        on_error: "Literal['raise', 'return', 'return_pickle', 'ignore']" = "raise",
    ) -> dict:  # dict[str, Any]
        """Broadcast message to workers, return all results"""
        if workers is None:
            if hosts is None:
                workers = list(self.workers)
            else:
                workers = []
        if hosts is not None:
            for host in hosts:
                dh: dict = self.host_info.get(host)  # type: ignore
                if dh is not None:
                    workers.extend(dh["addresses"])
        # TODO replace with worker_list

        if nanny:
            addresses = [self.workers[w].nanny for w in workers]
        else:
            addresses = workers

        ERROR = object()

        async def send_message(addr):
            try:
                comm = await self.rpc.connect(addr)
                comm.name = "Scheduler Broadcast"
                try:
                    resp = await send_recv(
                        comm, close=True, serializers=serializers, **msg
                    )
                finally:
                    self.rpc.reuse(addr, comm)
                return resp
            except Exception as e:
                logger.error(f"broadcast to {addr} failed: {e.__class__.__name__}: {e}")
                if on_error == "raise":
                    raise
                elif on_error == "return":
                    return e
                elif on_error == "return_pickle":
                    return dumps(e)
                elif on_error == "ignore":
                    return ERROR
                else:
                    raise ValueError(
                        "on_error must be 'raise', 'return', 'return_pickle', "
                        f"or 'ignore'; got {on_error!r}"
                    )

        results = await All(
            [send_message(address) for address in addresses if address is not None]
        )

        return {k: v for k, v in zip(workers, results) if v is not ERROR}

    async def proxy(self, comm=None, msg=None, worker=None, serializers=None):
        """Proxy a communication through the scheduler to some other worker"""
        d = await self.broadcast(
            comm=comm, msg=msg, workers=[worker], serializers=serializers
        )
        return d[worker]

    async def gather_on_worker(
        self, worker_address: str, who_has: "dict[str, list[str]]"
    ) -> set:
        """Peer-to-peer copy of keys from multiple workers to a single worker

        Parameters
        ----------
        worker_address: str
            Recipient worker address to copy keys to
        who_has: dict[Hashable, list[str]]
            {key: [sender address, sender address, ...], key: ...}

        Returns
        -------
        returns:
            set of keys that failed to be copied
        """
        try:
            result = await retry_operation(
                self.rpc(addr=worker_address).gather, who_has=who_has
            )
        except OSError as e:
            # This can happen e.g. if the worker is going through controlled shutdown;
            # it doesn't necessarily mean that it went unexpectedly missing
            logger.warning(
                f"Communication with worker {worker_address} failed during "
                f"replication: {e.__class__.__name__}: {e}"
            )
            return set(who_has)

        ws = self.workers.get(worker_address)

        if not ws:
            logger.warning(f"Worker {worker_address} lost during replication")
            return set(who_has)
        elif result["status"] == "OK":
            keys_failed = set()
            keys_ok: Set = who_has.keys()
        elif result["status"] == "partial-fail":
            keys_failed = set(result["keys"])
            keys_ok = who_has.keys() - keys_failed
            logger.warning(
                f"Worker {worker_address} failed to acquire keys: {result['keys']}"
            )
        else:  # pragma: nocover
            raise ValueError(f"Unexpected message from {worker_address}: {result}")

        for key in keys_ok:
            ts: TaskState = self.tasks.get(key)  # type: ignore
            if ts is None or ts.state != "memory":
                logger.warning(f"Key lost during replication: {key}")
                continue
            if ws not in ts.who_has:
                self.add_replica(ts, ws)

        return keys_failed

    async def delete_worker_data(
        self, worker_address: str, keys: "Collection[str]", stimulus_id: str
    ) -> None:
        """Delete data from a worker and update the corresponding worker/task states

        Parameters
        ----------
        worker_address: str
            Worker address to delete keys from
        keys: list[str]
            List of keys to delete on the specified worker
        """
        try:
            await retry_operation(
                self.rpc(addr=worker_address).free_keys,
                keys=list(keys),
                stimulus_id=f"delete-data-{time()}",
            )
        except OSError as e:
            # This can happen e.g. if the worker is going through controlled shutdown;
            # it doesn't necessarily mean that it went unexpectedly missing
            logger.warning(
                f"Communication with worker {worker_address} failed during "
                f"replication: {e.__class__.__name__}: {e}"
            )
            return

        ws = self.workers.get(worker_address)
        if not ws:
            return

        for key in keys:
            ts: TaskState = self.tasks.get(key)  # type: ignore
            if ts is not None and ws in ts.who_has:
                assert ts.state == "memory"
                self.remove_replica(ts, ws)
                if not ts.who_has:
                    # Last copy deleted
                    self.transitions({key: "released"}, stimulus_id)

        self.log_event(ws.address, {"action": "remove-worker-data", "keys": keys})

    @log_errors
    async def rebalance(
        self,
        comm=None,
        keys: Iterable[str] | None = None,
        workers: Iterable[str] | None = None,
        stimulus_id: str | None = None,
    ) -> dict:
        """Rebalance keys so that each worker ends up with roughly the same process
        memory (managed+unmanaged).

        .. warning::
           This operation is generally not well tested against normal operation of the
           scheduler. It is not recommended to use it while waiting on computations.

        **Algorithm**

        #. Find the mean occupancy of the cluster, defined as data managed by dask +
           unmanaged process memory that has been there for at least 30 seconds
           (``distributed.worker.memory.recent-to-old-time``).
           This lets us ignore temporary spikes caused by task heap usage.

           Alternatively, you may change how memory is measured both for the individual
           workers as well as to calculate the mean through
           ``distributed.worker.memory.rebalance.measure``. Namely, this can be useful
           to disregard inaccurate OS memory measurements.

        #. Discard workers whose occupancy is within 5% of the mean cluster occupancy
           (``distributed.worker.memory.rebalance.sender-recipient-gap`` / 2).
           This helps avoid data from bouncing around the cluster repeatedly.
        #. Workers above the mean are senders; those below are recipients.
        #. Discard senders whose absolute occupancy is below 30%
           (``distributed.worker.memory.rebalance.sender-min``). In other words, no data
           is moved regardless of imbalancing as long as all workers are below 30%.
        #. Discard recipients whose absolute occupancy is above 60%
           (``distributed.worker.memory.rebalance.recipient-max``).
           Note that this threshold by default is the same as
           ``distributed.worker.memory.target`` to prevent workers from accepting data
           and immediately spilling it out to disk.
        #. Iteratively pick the sender and recipient that are farthest from the mean and
           move the *least recently inserted* key between the two, until either all
           senders or all recipients fall within 5% of the mean.

           A recipient will be skipped if it already has a copy of the data. In other
           words, this method does not degrade replication.
           A key will be skipped if there are no recipients available with enough memory
           to accept the key and that don't already hold a copy.

        The least recently insertd (LRI) policy is a greedy choice with the advantage of
        being O(1), trivial to implement (it relies on python dict insertion-sorting)
        and hopefully good enough in most cases. Discarded alternative policies were:

        - Largest first. O(n*log(n)) save for non-trivial additional data structures and
          risks causing the largest chunks of data to repeatedly move around the
          cluster like pinballs.
        - Least recently used (LRU). This information is currently available on the
          workers only and not trivial to replicate on the scheduler; transmitting it
          over the network would be very expensive. Also, note that dask will go out of
          its way to minimise the amount of time intermediate keys are held in memory,
          so in such a case LRI is a close approximation of LRU.

        Parameters
        ----------
        keys: optional
            allowlist of dask keys that should be considered for moving. All other keys
            will be ignored. Note that this offers no guarantee that a key will actually
            be moved (e.g. because it is unnecessary or because there are no viable
            recipient workers for it).
        workers: optional
            allowlist of workers addresses to be considered as senders or recipients.
            All other workers will be ignored. The mean cluster occupancy will be
            calculated only using the allowed workers.
        """
        stimulus_id = stimulus_id or f"rebalance-{time()}"

        wss: Collection[WorkerState]
        if workers is not None:
            wss = [self.workers[w] for w in workers]
        else:
            wss = self.workers.values()
        if not wss:
            return {"status": "OK"}

        if keys is not None:
            if not isinstance(keys, Set):
                keys = set(keys)  # unless already a set-like
            if not keys:
                return {"status": "OK"}
            missing_data = [
                k for k in keys if k not in self.tasks or not self.tasks[k].who_has
            ]
            if missing_data:
                return {"status": "partial-fail", "keys": missing_data}

        msgs = self._rebalance_find_msgs(keys, wss)
        if not msgs:
            return {"status": "OK"}

        async with self._lock:
            result = await self._rebalance_move_data(msgs, stimulus_id)
            if result["status"] == "partial-fail" and keys is None:
                # Only return failed keys if the client explicitly asked for them
                result = {"status": "OK"}
            return result

    def _rebalance_find_msgs(
        self,
        keys: Set[Hashable] | None,
        workers: Iterable[WorkerState],
    ) -> list[tuple[WorkerState, WorkerState, TaskState]]:
        """Identify workers that need to lose keys and those that can receive them,
        together with how many bytes each needs to lose/receive. Then, pair a sender
        worker with a recipient worker for each key, until the cluster is rebalanced.

        This method only defines the work to be performed; it does not start any network
        transfers itself.

        The big-O complexity is O(wt + ke*log(we)), where

        - wt is the total number of workers on the cluster (or the number of allowed
          workers, if explicitly stated by the user)
        - we is the number of workers that are eligible to be senders or recipients
        - kt is the total number of keys on the cluster (or on the allowed workers)
        - ke is the number of keys that need to be moved in order to achieve a balanced
          cluster

        There is a degenerate edge case O(wt + kt*log(we)) when kt is much greater than
        the number of allowed keys, or when most keys are replicated or cannot be
        moved for some other reason.

        Returns list of tuples to feed into _rebalance_move_data:

        - sender worker
        - recipient worker
        - task to be transferred
        """
        # Heaps of workers, managed by the heapq module, that need to send/receive data,
        # with how many bytes each needs to send/receive.
        #
        # Each element of the heap is a tuple constructed as follows:
        # - snd_bytes_max/rec_bytes_max: maximum number of bytes to send or receive.
        #   This number is negative, so that the workers farthest from the cluster mean
        #   are at the top of the smallest-first heaps.
        # - snd_bytes_min/rec_bytes_min: minimum number of bytes after sending/receiving
        #   which the worker should not be considered anymore. This is also negative.
        # - arbitrary unique number, there just to to make sure that WorkerState objects
        #   are never used for sorting in the unlikely event that two processes have
        #   exactly the same number of bytes allocated.
        # - WorkerState
        # - iterator of all tasks in memory on the worker (senders only), insertion
        #   sorted (least recently inserted first).
        #   Note that this iterator will typically *not* be exhausted. It will only be
        #   exhausted if, after moving away from the worker all keys that can be moved,
        #   is insufficient to drop snd_bytes_min above 0.
        senders: list[tuple[int, int, int, WorkerState, Iterator[TaskState]]] = []
        recipients: list[tuple[int, int, int, WorkerState]] = []

        # Output: [(sender, recipient, task), ...]
        msgs: list[tuple[WorkerState, WorkerState, TaskState]] = []

        # By default, this is the optimistic memory, meaning total process memory minus
        # unmanaged memory that appeared over the last 30 seconds
        # (distributed.worker.memory.recent-to-old-time).
        # This lets us ignore temporary spikes caused by task heap usage.
        memory_by_worker = [
            (ws, getattr(ws.memory, self.MEMORY_REBALANCE_MEASURE)) for ws in workers
        ]
        mean_memory = sum(m for _, m in memory_by_worker) // len(memory_by_worker)

        for ws, ws_memory in memory_by_worker:
            if ws.memory_limit:
                half_gap = int(self.MEMORY_REBALANCE_HALF_GAP * ws.memory_limit)
                sender_min = self.MEMORY_REBALANCE_SENDER_MIN * ws.memory_limit
                recipient_max = self.MEMORY_REBALANCE_RECIPIENT_MAX * ws.memory_limit
            else:
                half_gap = 0
                sender_min = 0.0
                recipient_max = math.inf

            if (
                ws._has_what
                and ws_memory >= mean_memory + half_gap
                and ws_memory >= sender_min
            ):
                # This may send the worker below sender_min (by design)
                snd_bytes_max = mean_memory - ws_memory  # negative
                snd_bytes_min = snd_bytes_max + half_gap  # negative
                # See definition of senders above
                senders.append(
                    (snd_bytes_max, snd_bytes_min, id(ws), ws, iter(ws._has_what))
                )
            elif ws_memory < mean_memory - half_gap and ws_memory < recipient_max:
                # This may send the worker above recipient_max (by design)
                rec_bytes_max = ws_memory - mean_memory  # negative
                rec_bytes_min = rec_bytes_max + half_gap  # negative
                # See definition of recipients above
                recipients.append((rec_bytes_max, rec_bytes_min, id(ws), ws))

        # Fast exit in case no transfers are necessary or possible
        if not senders or not recipients:
            self.log_event(
                "all",
                {
                    "action": "rebalance",
                    "senders": len(senders),
                    "recipients": len(recipients),
                    "moved_keys": 0,
                },
            )
            return []

        heapq.heapify(senders)
        heapq.heapify(recipients)

        while senders and recipients:
            snd_bytes_max, snd_bytes_min, _, snd_ws, ts_iter = senders[0]

            # Iterate through tasks in memory, least recently inserted first
            for ts in ts_iter:
                if keys is not None and ts.key not in keys:
                    continue
                nbytes = ts.nbytes
                if nbytes + snd_bytes_max > 0:
                    # Moving this task would cause the sender to go below mean and
                    # potentially risk becoming a recipient, which would cause tasks to
                    # bounce around. Move on to the next task of the same sender.
                    continue

                # Find the recipient, farthest from the mean, which
                # 1. has enough available RAM for this task, and
                # 2. doesn't hold a copy of this task already
                # There may not be any that satisfies these conditions; in this case
                # this task won't be moved.
                skipped_recipients = []
                use_recipient = False
                while recipients and not use_recipient:
                    rec_bytes_max, rec_bytes_min, _, rec_ws = recipients[0]
                    if nbytes + rec_bytes_max > 0:
                        # recipients are sorted by rec_bytes_max.
                        # The next ones will be worse; no reason to continue iterating
                        break
                    use_recipient = ts not in rec_ws._has_what
                    if not use_recipient:
                        skipped_recipients.append(heapq.heappop(recipients))

                for recipient in skipped_recipients:
                    heapq.heappush(recipients, recipient)

                if not use_recipient:
                    # This task has no recipients available. Leave it on the sender and
                    # move on to the next task of the same sender.
                    continue

                # Schedule task for transfer from sender to recipient
                msgs.append((snd_ws, rec_ws, ts))

                # *_bytes_max/min are all negative for heap sorting
                snd_bytes_max += nbytes
                snd_bytes_min += nbytes
                rec_bytes_max += nbytes
                rec_bytes_min += nbytes

                # Stop iterating on the tasks of this sender for now and, if it still
                # has bytes to lose, push it back into the senders heap; it may or may
                # not come back on top again.
                if snd_bytes_min < 0:
                    # See definition of senders above
                    heapq.heapreplace(
                        senders,
                        (snd_bytes_max, snd_bytes_min, id(snd_ws), snd_ws, ts_iter),
                    )
                else:
                    heapq.heappop(senders)

                # If recipient still has bytes to gain, push it back into the recipients
                # heap; it may or may not come back on top again.
                if rec_bytes_min < 0:
                    # See definition of recipients above
                    heapq.heapreplace(
                        recipients,
                        (rec_bytes_max, rec_bytes_min, id(rec_ws), rec_ws),
                    )
                else:
                    heapq.heappop(recipients)

                # Move to next sender with the most data to lose.
                # It may or may not be the same sender again.
                break

            else:  # for ts in ts_iter
                # Exhausted tasks on this sender
                heapq.heappop(senders)

        return msgs

    async def _rebalance_move_data(
        self, msgs: "list[tuple[WorkerState, WorkerState, TaskState]]", stimulus_id: str
    ) -> dict:
        """Perform the actual transfer of data across the network in rebalance().
        Takes in input the output of _rebalance_find_msgs(), that is a list of tuples:

        - sender worker
        - recipient worker
        - task to be transferred

        FIXME this method is not robust when the cluster is not idle.
        """
        to_recipients: defaultdict[str, defaultdict[str, list[str]]] = defaultdict(
            lambda: defaultdict(list)
        )
        for snd_ws, rec_ws, ts in msgs:
            to_recipients[rec_ws.address][ts.key].append(snd_ws.address)
        failed_keys_by_recipient = dict(
            zip(
                to_recipients,
                await asyncio.gather(
                    *(
                        # Note: this never raises exceptions
                        self.gather_on_worker(w, who_has)
                        for w, who_has in to_recipients.items()
                    )
                ),
            )
        )

        to_senders = defaultdict(list)
        for snd_ws, rec_ws, ts in msgs:
            if ts.key not in failed_keys_by_recipient[rec_ws.address]:
                to_senders[snd_ws.address].append(ts.key)

        # Note: this never raises exceptions
        await asyncio.gather(
            *(self.delete_worker_data(r, v, stimulus_id) for r, v in to_senders.items())
        )

        for r, v in to_recipients.items():
            self.log_event(r, {"action": "rebalance", "who_has": v})
        self.log_event(
            "all",
            {
                "action": "rebalance",
                "senders": valmap(len, to_senders),
                "recipients": valmap(len, to_recipients),
                "moved_keys": len(msgs),
            },
        )

        missing_keys = {k for r in failed_keys_by_recipient.values() for k in r}
        if missing_keys:
            return {"status": "partial-fail", "keys": list(missing_keys)}
        else:
            return {"status": "OK"}

    async def replicate(
        self,
        comm=None,
        keys=None,
        n=None,
        workers=None,
        branching_factor=2,
        delete=True,
        lock=True,
        stimulus_id=None,
    ):
        """Replicate data throughout cluster

        This performs a tree copy of the data throughout the network
        individually on each piece of data.

        Parameters
        ----------
        keys: Iterable
            list of keys to replicate
        n: int
            Number of replications we expect to see within the cluster
        branching_factor: int, optional
            The number of workers that can copy data in each generation.
            The larger the branching factor, the more data we copy in
            a single step, but the more a given worker risks being
            swamped by data requests.

        See also
        --------
        Scheduler.rebalance
        """
        stimulus_id = stimulus_id or f"replicate-{time()}"
        assert branching_factor > 0
        async with self._lock if lock else empty_context:
            if workers is not None:
                workers = {self.workers[w] for w in self.workers_list(workers)}
                workers = {ws for ws in workers if ws.status == Status.running}
            else:
                workers = self.running

            if n is None:
                n = len(workers)
            else:
                n = min(n, len(workers))
            if n == 0:
                raise ValueError("Can not use replicate to delete data")

            tasks = {self.tasks[k] for k in keys}
            missing_data = [ts.key for ts in tasks if not ts.who_has]
            if missing_data:
                return {"status": "partial-fail", "keys": missing_data}

            # Delete extraneous data
            if delete:
                del_worker_tasks = defaultdict(set)
                for ts in tasks:
                    del_candidates = tuple(ts.who_has & workers)
                    if len(del_candidates) > n:
                        for ws in random.sample(
                            del_candidates, len(del_candidates) - n
                        ):
                            del_worker_tasks[ws].add(ts)

                # Note: this never raises exceptions
                await asyncio.gather(
                    *[
                        self.delete_worker_data(
                            ws.address, [t.key for t in tasks], stimulus_id
                        )
                        for ws, tasks in del_worker_tasks.items()
                    ]
                )

            # Copy not-yet-filled data
            while tasks:
                gathers = defaultdict(dict)
                for ts in list(tasks):
                    if ts.state == "forgotten":
                        # task is no longer needed by any client or dependent task
                        tasks.remove(ts)
                        continue
                    n_missing = n - len(ts.who_has & workers)
                    if n_missing <= 0:
                        # Already replicated enough
                        tasks.remove(ts)
                        continue

                    count = min(n_missing, branching_factor * len(ts.who_has))
                    assert count > 0

                    for ws in random.sample(tuple(workers - ts.who_has), count):
                        gathers[ws.address][ts.key] = [
                            wws.address for wws in ts.who_has
                        ]

                await asyncio.gather(
                    *(
                        # Note: this never raises exceptions
                        self.gather_on_worker(w, who_has)
                        for w, who_has in gathers.items()
                    )
                )
                for r, v in gathers.items():
                    self.log_event(r, {"action": "replicate-add", "who_has": v})

            self.log_event(
                "all",
                {
                    "action": "replicate",
                    "workers": list(workers),
                    "key-count": len(keys),
                    "branching-factor": branching_factor,
                },
            )

    def workers_to_close(
        self,
        comm=None,
        memory_ratio: int | float | None = None,
        n: int | None = None,
        key: Callable[[WorkerState], Hashable] | bytes | None = None,
        minimum: int | None = None,
        target: int | None = None,
        attribute: str = "address",
    ) -> list[str]:
        """
        Find workers that we can close with low cost

        This returns a list of workers that are good candidates to retire.
        These workers are not running anything and are storing
        relatively little data relative to their peers.  If all workers are
        idle then we still maintain enough workers to have enough RAM to store
        our data, with a comfortable buffer.

        This is for use with systems like ``distributed.deploy.adaptive``.

        Parameters
        ----------
        memory_ratio : Number
            Amount of extra space we want to have for our stored data.
            Defaults to 2, or that we want to have twice as much memory as we
            currently have data.
        n : int
            Number of workers to close
        minimum : int
            Minimum number of workers to keep around
        key : Callable(WorkerState)
            An optional callable mapping a WorkerState object to a group
            affiliation. Groups will be closed together. This is useful when
            closing workers must be done collectively, such as by hostname.
        target : int
            Target number of workers to have after we close
        attribute : str
            The attribute of the WorkerState object to return, like "address"
            or "name".  Defaults to "address".

        Examples
        --------
        >>> scheduler.workers_to_close()
        ['tcp://192.168.0.1:1234', 'tcp://192.168.0.2:1234']

        Group workers by hostname prior to closing

        >>> scheduler.workers_to_close(key=lambda ws: ws.host)
        ['tcp://192.168.0.1:1234', 'tcp://192.168.0.1:4567']

        Remove two workers

        >>> scheduler.workers_to_close(n=2)

        Keep enough workers to have twice as much memory as we we need.

        >>> scheduler.workers_to_close(memory_ratio=2)

        Returns
        -------
        to_close: list of worker addresses that are OK to close

        See Also
        --------
        Scheduler.retire_workers
        """
        if target is not None and n is None:
            n = len(self.workers) - target
        if n is not None:
            if n < 0:
                n = 0
            target = len(self.workers) - n

        if n is None and memory_ratio is None:
            memory_ratio = 2

        with log_errors():
            if not n and all([ws.processing for ws in self.workers.values()]):
                return []

            if key is None:
                key = operator.attrgetter("address")
            if isinstance(key, bytes) and dask.config.get(
                "distributed.scheduler.pickle"
            ):
                key = pickle.loads(key)

            groups = groupby(key, self.workers.values())

            limit_bytes = {
                k: sum(ws.memory_limit for ws in v) for k, v in groups.items()
            }
            group_bytes = {k: sum(ws.nbytes for ws in v) for k, v in groups.items()}

            limit = sum(limit_bytes.values())
            total = sum(group_bytes.values())

            def _key(group):
                is_idle = not any([wws.processing for wws in groups[group]])
                bytes = -group_bytes[group]
                return is_idle, bytes

            idle = sorted(groups, key=_key)

            to_close = []
            n_remain = len(self.workers)

            while idle:
                group = idle.pop()
                if n is None and any([ws.processing for ws in groups[group]]):
                    break

                if minimum and n_remain - len(groups[group]) < minimum:
                    break

                limit -= limit_bytes[group]

                if (
                    n is not None and n_remain - len(groups[group]) >= (target or 0)
                ) or (memory_ratio is not None and limit >= memory_ratio * total):
                    to_close.append(group)
                    n_remain -= len(groups[group])

                else:
                    break

            result = [getattr(ws, attribute) for g in to_close for ws in groups[g]]
            if result:
                logger.debug("Suggest closing workers: %s", result)

            return result

    @log_errors
    async def retire_workers(
        self,
        workers: list[str] | None = None,
        *,
        names: list | None = None,
        close_workers: bool = False,
        remove: bool = True,
        stimulus_id: str | None = None,
        **kwargs: Any,
    ) -> dict[str, Any]:
        """Gracefully retire workers from cluster. Any key that is in memory exclusively
        on the retired workers is replicated somewhere else.

        Parameters
        ----------
        workers: list[str] (optional)
            List of worker addresses to retire.
        names: list (optional)
            List of worker names to retire.
            Mutually exclusive with ``workers``.
            If neither ``workers`` nor ``names`` are provided, we call
            ``workers_to_close`` which finds a good set.
        close_workers: bool (defaults to False)
            Whether or not to actually close the worker explicitly from here.
            Otherwise we expect some external job scheduler to finish off the
            worker.
        remove: bool (defaults to True)
            Whether or not to remove the worker metadata immediately or else
            wait for the worker to contact us.

            If close_workers=False and remove=False, this method just flushes the tasks
            in memory out of the workers and then returns.
            If close_workers=True and remove=False, this method will return while the
            workers are still in the cluster, although they won't accept new tasks.
            If close_workers=False or for whatever reason a worker doesn't accept the
            close command, it will be left permanently unable to accept new tasks and
            it is expected to be closed in some other way.

        **kwargs: dict
            Extra options to pass to workers_to_close to determine which
            workers we should drop

        Returns
        -------
        Dictionary mapping worker ID/address to dictionary of information about
        that worker for each retired worker.

        If there are keys that exist in memory only on the workers being retired and it
        was impossible to replicate them somewhere else (e.g. because there aren't
        any other running workers), the workers holding such keys won't be retired and
        won't appear in the returned dict.

        See Also
        --------
        Scheduler.workers_to_close
        """
        stimulus_id = stimulus_id or f"retire-workers-{time()}"
        # This lock makes retire_workers, rebalance, and replicate mutually
        # exclusive and will no longer be necessary once rebalance and replicate are
        # migrated to the Active Memory Manager.
        # Note that, incidentally, it also prevents multiple calls to retire_workers
        # from running in parallel - this is unnecessary.
        async with self._lock:
            if names is not None:
                if workers is not None:
                    raise TypeError("names and workers are mutually exclusive")
                if names:
                    logger.info("Retire worker names %s", names)
                # Support cases where names are passed through a CLI and become
                # strings
                names_set = {str(name) for name in names}
                wss = {ws for ws in self.workers.values() if str(ws.name) in names_set}
            elif workers is not None:
                wss = {
                    self.workers[address]
                    for address in workers
                    if address in self.workers
                }
            else:
                wss = {
                    self.workers[address] for address in self.workers_to_close(**kwargs)
                }
            if not wss:
                return {}

            stop_amm = False
            amm: ActiveMemoryManagerExtension = self.extensions["amm"]
            if not amm.running:
                amm = ActiveMemoryManagerExtension(
                    self, policies=set(), register=False, start=True, interval=2.0
                )
                stop_amm = True

            try:
                coros = []
                for ws in wss:
                    logger.info("Retiring worker %s", ws.address)

                    policy = RetireWorker(ws.address)
                    amm.add_policy(policy)

                    # Change Worker.status to closing_gracefully. Immediately set
                    # the same on the scheduler to prevent race conditions.
                    prev_status = ws.status
                    self.handle_worker_status_change(
                        Status.closing_gracefully, ws, stimulus_id
                    )
                    # FIXME: We should send a message to the nanny first;
                    # eventually workers won't be able to close their own nannies.
                    self.stream_comms[ws.address].send(
                        {
                            "op": "worker-status-change",
                            "status": ws.status.name,
                            "stimulus_id": stimulus_id,
                        }
                    )

                    coros.append(
                        self._track_retire_worker(
                            ws,
                            policy,
                            prev_status=prev_status,
                            close=close_workers,
                            remove=remove,
                            stimulus_id=stimulus_id,
                        )
                    )

                # Give the AMM a kick, in addition to its periodic running. This is
                # to avoid unnecessarily waiting for a potentially arbitrarily long
                # time (depending on interval settings)
                amm.run_once()

                workers_info = dict(await asyncio.gather(*coros))
                workers_info.pop(None, None)
            finally:
                if stop_amm:
                    amm.stop()

        self.log_event("all", {"action": "retire-workers", "workers": workers_info})
        self.log_event(list(workers_info), {"action": "retired"})

        return workers_info

    async def _track_retire_worker(
        self,
        ws: WorkerState,
        policy: RetireWorker,
        prev_status: Status,
        close: bool,
        remove: bool,
        stimulus_id: str,
    ) -> tuple:  # tuple[str | None, dict]
        while not policy.done():
            # Sleep 0.01s when there are 4 tasks or less
            # Sleep 0.5s when there are 200 or more
            poll_interval = max(0.01, min(0.5, len(ws.has_what) / 400))
            await asyncio.sleep(poll_interval)

        if policy.no_recipients:
            # Abort retirement. This time we don't need to worry about race
            # conditions and we can wait for a scheduler->worker->scheduler
            # round-trip.
            self.stream_comms[ws.address].send(
                {
                    "op": "worker-status-change",
                    "status": prev_status.name,
                    "stimulus_id": stimulus_id,
                }
            )
            return None, {}

        logger.debug(
            "All unique keys on worker %s have been replicated elsewhere", ws.address
        )

        if remove:
            await self.remove_worker(
                ws.address, safe=True, close=close, stimulus_id=stimulus_id
            )
        elif close:
            self.close_worker(ws.address)

        logger.info("Retired worker %s", ws.address)
        return ws.address, ws.identity()

    def add_keys(self, worker=None, keys=(), stimulus_id=None):
        """
        Learn that a worker has certain keys

        This should not be used in practice and is mostly here for legacy
        reasons.  However, it is sent by workers from time to time.
        """
        if worker not in self.workers:
            return "not found"
        ws: WorkerState = self.workers[worker]
        redundant_replicas = []
        for key in keys:
            ts: TaskState = self.tasks.get(key)
            if ts is not None and ts.state == "memory":
                if ws not in ts.who_has:
                    self.add_replica(ts, ws)
            else:
                redundant_replicas.append(key)

        if redundant_replicas:
            if not stimulus_id:
                stimulus_id = f"redundant-replicas-{time()}"
            self.worker_send(
                worker,
                {
                    "op": "remove-replicas",
                    "keys": redundant_replicas,
                    "stimulus_id": stimulus_id,
                },
            )

        return "OK"

    @log_errors
    def update_data(
        self,
        *,
        who_has: dict,
        nbytes: dict,
        client=None,
    ):
        """
        Learn that new data has entered the network from an external source

        See Also
        --------
        Scheduler.mark_key_in_memory
        """
        who_has = {k: [self.coerce_address(vv) for vv in v] for k, v in who_has.items()}
        logger.debug("Update data %s", who_has)

        for key, workers in who_has.items():
            ts = self.tasks.get(key)
            if ts is None:
                ts = self.new_task(key, None, "memory")
            ts.state = "memory"
            ts_nbytes = nbytes.get(key, -1)
            if ts_nbytes >= 0:
                ts.set_nbytes(ts_nbytes)

            for w in workers:
                ws = self.workers[w]
                if ws not in ts.who_has:
                    self.add_replica(ts, ws)
            self.report({"op": "key-in-memory", "key": key, "workers": list(workers)})

        if client:
            self.client_desires_keys(keys=list(who_has), client=client)

    @overload
    def report_on_key(self, key: str, *, client: str | None = None) -> None:
        ...

    @overload
    def report_on_key(self, *, ts: TaskState, client: str | None = None) -> None:
        ...

    def report_on_key(self, key=None, *, ts=None, client=None):
        if (ts is None) == (key is None):
            raise ValueError(  # pragma: nocover
                f"ts and key are mutually exclusive; received {key=!r}, {ts=!r}"
            )
        if ts is None:
            assert key is not None
            ts = self.tasks.get(key)
        else:
            key = ts.key

        if ts is not None:
            report_msg = _task_to_report_msg(ts)
        else:
            report_msg = {"op": "cancelled-key", "key": key}
        if report_msg is not None:
            self.report(report_msg, ts=ts, client=client)

    @log_errors
    async def feed(
        self, comm, function=None, setup=None, teardown=None, interval="1s", **kwargs
    ):
        """
        Provides a data Comm to external requester

        Caution: this runs arbitrary Python code on the scheduler.  This should
        eventually be phased out.  It is mostly used by diagnostics.
        """
        if not dask.config.get("distributed.scheduler.pickle"):
            logger.warning(
                "Tried to call 'feed' route with custom functions, but "
                "pickle is disallowed.  Set the 'distributed.scheduler.pickle'"
                "config value to True to use the 'feed' route (this is mostly "
                "commonly used with progress bars)"
            )
            return

        interval = parse_timedelta(interval)
        if function:
            function = pickle.loads(function)
        if setup:
            setup = pickle.loads(setup)
        if teardown:
            teardown = pickle.loads(teardown)
        state = setup(self) if setup else None
        if inspect.isawaitable(state):
            state = await state
        try:
            while self.status == Status.running:
                if state is None:
                    response = function(self)
                else:
                    response = function(self, state)
                await comm.write(response)
                await asyncio.sleep(interval)
        except OSError:
            pass
        finally:
            if teardown:
                teardown(self, state)

    def log_worker_event(
        self, worker: str, topic: str | Collection[str], msg: Any
    ) -> None:
        if isinstance(msg, dict):
            msg["worker"] = worker
        self.log_event(topic, msg)

    def subscribe_worker_status(self, comm=None):
        WorkerStatusPlugin(self, comm)
        ident = self.identity()
        for v in ident["workers"].values():
            del v["metrics"]
            del v["last_seen"]
        return ident

    def get_processing(self, workers=None):
        if workers is not None:
            workers = set(map(self.coerce_address, workers))
            return {w: [ts.key for ts in self.workers[w].processing] for w in workers}
        else:
            return {
                w: [ts.key for ts in ws.processing] for w, ws in self.workers.items()
            }

    def get_who_has(self, keys: Iterable[str] | None = None) -> dict[str, list[str]]:
        if keys is not None:
            return {
                key: [ws.address for ws in self.tasks[key].who_has]
                if key in self.tasks
                else []
                for key in keys
            }
        else:
            return {
                key: [ws.address for ws in ts.who_has] for key, ts in self.tasks.items()
            }

    def get_has_what(self, workers=None):
        if workers is not None:
            workers = map(self.coerce_address, workers)
            return {
                w: [ts.key for ts in self.workers[w].has_what]
                if w in self.workers
                else []
                for w in workers
            }
        else:
            return {w: [ts.key for ts in ws.has_what] for w, ws in self.workers.items()}

    def get_ncores(self, workers=None):
        if workers is not None:
            workers = map(self.coerce_address, workers)
            return {w: self.workers[w].nthreads for w in workers if w in self.workers}
        else:
            return {w: ws.nthreads for w, ws in self.workers.items()}

    def get_ncores_running(self, workers=None):
        ncores = self.get_ncores(workers=workers)
        return {
            w: n for w, n in ncores.items() if self.workers[w].status == Status.running
        }

    async def get_call_stack(self, keys=None):
        if keys is not None:
            stack = list(keys)
            processing = set()
            while stack:
                key = stack.pop()
                ts = self.tasks[key]
                if ts.state == "waiting":
                    stack.extend([dts.key for dts in ts.dependencies])
                elif ts.state == "processing":
                    processing.add(ts)

            workers = defaultdict(list)
            for ts in processing:
                if ts.processing_on:
                    workers[ts.processing_on.address].append(ts.key)
        else:
            workers = {w: None for w in self.workers}

        if not workers:
            return {}

        results = await asyncio.gather(
            *(self.rpc(w).call_stack(keys=v) for w, v in workers.items())
        )
        response = {w: r for w, r in zip(workers, results) if r}
        return response

    async def benchmark_hardware(self) -> "dict[str, dict[str, float]]":
        """
        Run a benchmark on the workers for memory, disk, and network bandwidths

        Returns
        -------
        result: dict
            A dictionary mapping the names "disk", "memory", and "network" to
            dictionaries mapping sizes to bandwidths.  These bandwidths are
            averaged over many workers running computations across the cluster.
        """
        out: dict[str, defaultdict[str, list[float]]] = {
            name: defaultdict(list) for name in ["disk", "memory", "network"]
        }

        # disk
        result = await self.broadcast(msg={"op": "benchmark_disk"})
        for d in result.values():
            for size, duration in d.items():
                out["disk"][size].append(duration)

        # memory
        result = await self.broadcast(msg={"op": "benchmark_memory"})
        for d in result.values():
            for size, duration in d.items():
                out["memory"][size].append(duration)

        # network
        workers = list(self.workers)
        # On an adaptive cluster, if multiple workers are started on the same physical host,
        # they are more likely to connect to the Scheduler in sequence, ending up next to
        # each other in this list.
        # The transfer speed within such clusters of workers will be effectively that of
        # localhost. This could happen across different VMs and/or docker images, so
        # implementing logic based on IP addresses would not necessarily help.
        # Randomize the connections to even out the mean measures.
        random.shuffle(workers)
        futures = [
            self.rpc(a).benchmark_network(address=b) for a, b in partition(2, workers)
        ]
        responses = await asyncio.gather(*futures)

        for d in responses:
            for size, duration in d.items():
                out["network"][size].append(duration)

        result = {}
        for mode in out:
            result[mode] = {
                size: sum(durations) / len(durations)
                for size, durations in out[mode].items()
            }

        return result

    @log_errors
    def get_nbytes(self, keys=None, summary=True):
        if keys is not None:
            result = {k: self.tasks[k].nbytes for k in keys}
        else:
            result = {k: ts.nbytes for k, ts in self.tasks.items() if ts.nbytes >= 0}

        if summary:
            out = defaultdict(lambda: 0)
            for k, v in result.items():
                out[key_split(k)] += v
            result = dict(out)

        return result

    def run_function(self, comm, function, args=(), kwargs=None, wait=True):
        """Run a function within this process

        See Also
        --------
        Client.run_on_scheduler
        """
        from distributed.worker import run

        if not dask.config.get("distributed.scheduler.pickle"):
            raise ValueError(
                "Cannot run function as the scheduler has been explicitly disallowed from "
                "deserializing arbitrary bytestrings using pickle via the "
                "'distributed.scheduler.pickle' configuration setting."
            )
        kwargs = kwargs or {}
        self.log_event("all", {"action": "run-function", "function": function})
        return run(self, comm, function=function, args=args, kwargs=kwargs, wait=wait)

    def set_metadata(self, keys: list[str], value: object = None) -> None:
        metadata = self.task_metadata
        for key in keys[:-1]:
            if key not in metadata or not isinstance(metadata[key], (dict, list)):
                metadata[key] = {}
            metadata = metadata[key]
        metadata[keys[-1]] = value

    def get_metadata(self, keys: list[str], default=no_default):
        metadata = self.task_metadata
        try:
            for key in keys:
                metadata = metadata[key]
            return metadata
        except KeyError:
            if default != no_default:
                return default
            else:
                raise

    def set_restrictions(self, worker: dict[str, Collection[str] | str]):
        for key, restrictions in worker.items():
            ts = self.tasks[key]
            if isinstance(restrictions, str):
                restrictions = {restrictions}
            ts.worker_restrictions = set(restrictions)

    @log_errors
    def get_task_prefix_states(self):
        state = {}

        for tp in self.task_prefixes.values():
            active_states = tp.active_states
            if any(
                active_states.get(s)
                for s in {"memory", "erred", "released", "processing", "waiting"}
            ):
                state[tp.name] = {
                    "memory": active_states["memory"],
                    "erred": active_states["erred"],
                    "released": active_states["released"],
                    "processing": active_states["processing"],
                    "waiting": active_states["waiting"],
                }

        return state

    def get_task_status(self, keys=None):
        return {
            key: (self.tasks[key].state if key in self.tasks else None) for key in keys
        }

    def get_task_stream(self, start=None, stop=None, count=None):
        from distributed.diagnostics.task_stream import TaskStreamPlugin

        if TaskStreamPlugin.name not in self.plugins:
            self.add_plugin(TaskStreamPlugin(self))

        plugin = self.plugins[TaskStreamPlugin.name]

        return plugin.collect(start=start, stop=stop, count=count)

    def start_task_metadata(self, name=None):
        plugin = CollectTaskMetaDataPlugin(scheduler=self, name=name)
        self.add_plugin(plugin)

    def stop_task_metadata(self, name=None):
        plugins = [
            p
            for p in list(self.plugins.values())
            if isinstance(p, CollectTaskMetaDataPlugin) and p.name == name
        ]
        if len(plugins) != 1:
            raise ValueError(
                "Expected to find exactly one CollectTaskMetaDataPlugin "
                f"with name {name} but found {len(plugins)}."
            )

        plugin = plugins[0]
        self.remove_plugin(name=plugin.name)
        return {"metadata": plugin.metadata, "state": plugin.state}

    async def register_worker_plugin(self, comm, plugin, name=None):
        """Registers a worker plugin on all running and future workers"""
        self.worker_plugins[name] = plugin

        responses = await self.broadcast(
            msg=dict(op="plugin-add", plugin=plugin, name=name)
        )
        return responses

    async def unregister_worker_plugin(self, comm, name):
        """Unregisters a worker plugin"""
        try:
            self.worker_plugins.pop(name)
        except KeyError:
            raise ValueError(f"The worker plugin {name} does not exist")

        responses = await self.broadcast(msg=dict(op="plugin-remove", name=name))
        return responses

    async def register_nanny_plugin(self, comm, plugin, name=None):
        """Registers a setup function, and call it on every worker"""
        self.nanny_plugins[name] = plugin

        responses = await self.broadcast(
            msg=dict(op="plugin_add", plugin=plugin, name=name),
            nanny=True,
        )
        return responses

    async def unregister_nanny_plugin(self, comm, name):
        """Unregisters a worker plugin"""
        try:
            self.nanny_plugins.pop(name)
        except KeyError:
            raise ValueError(f"The nanny plugin {name} does not exist")

        responses = await self.broadcast(
            msg=dict(op="plugin_remove", name=name), nanny=True
        )
        return responses

    def transition(
        self,
        key: str,
        finish: TaskStateState,
        stimulus_id: str,
        **kwargs: Any,
    ) -> Recs:
        """Transition a key from its current state to the finish state

        Examples
        --------
        >>> self.transition('x', 'waiting')
        {'x': 'processing'}

        Returns
        -------
        Dictionary of recommendations for future transitions

        See Also
        --------
        Scheduler.transitions: transitive version of this function
        """
        recommendations, client_msgs, worker_msgs = self._transition(
            key, finish, stimulus_id, **kwargs
        )
        self.send_all(client_msgs, worker_msgs)
        return recommendations

    def transitions(self, recommendations: Recs, stimulus_id: str) -> None:
        """Process transitions until none are left

        This includes feedback from previous transitions and continues until we
        reach a steady state
        """
        client_msgs: Msgs = {}
        worker_msgs: Msgs = {}
        self._transitions(recommendations, client_msgs, worker_msgs, stimulus_id)
        self.send_all(client_msgs, worker_msgs)

    async def get_story(self, keys_or_stimuli: Iterable[str]) -> list[Transition]:
        """RPC hook for :meth:`SchedulerState.story`.

        Note that the msgpack serialization/deserialization round-trip will transform
        the :class:`Transition` namedtuples into regular tuples.
        """
        return self.story(*keys_or_stimuli)

    def _reschedule(
        self, key: str, worker: str | None = None, *, stimulus_id: str
    ) -> None:
        """Reschedule a task.

        This function should only be used when the task has already been released in
        some way on the worker it's assigned to — either via cancellation or a
        Reschedule exception — and you are certain the worker will not send any further
        updates about the task to the scheduler.
        """
        try:
            ts = self.tasks[key]
        except KeyError:
            logger.warning(
                f"Attempting to reschedule task {key}, which was not "
                "found on the scheduler. Aborting reschedule."
            )
            return
        if ts.state != "processing":
            return
        if worker and ts.processing_on and ts.processing_on.address != worker:
            return
        # transition_processing_released will immediately suggest an additional
        # transition to waiting if the task has any waiters or clients holding a future.
        self.transitions({key: "released"}, stimulus_id=stimulus_id)

    #####################
    # Utility functions #
    #####################

    def add_resources(self, worker: str, resources=None):
        ws: WorkerState = self.workers[worker]
        if resources:
            ws.resources.update(resources)
        ws.used_resources = {}
        for resource, quantity in ws.resources.items():
            ws.used_resources[resource] = 0
            dr = self.resources.get(resource, None)
            if dr is None:
                self.resources[resource] = dr = {}
            dr[worker] = quantity
        return "OK"

    def remove_resources(self, worker):
        ws: WorkerState = self.workers[worker]
        for resource in ws.resources:
            dr: dict = self.resources.get(resource, None)
            if dr is None:
                self.resources[resource] = dr = {}
            del dr[worker]

    def coerce_address(self, addr, resolve=True):
        """
        Coerce possible input addresses to canonical form.
        *resolve* can be disabled for testing with fake hostnames.

        Handles strings, tuples, or aliases.
        """
        # XXX how many address-parsing routines do we have?
        if addr in self.aliases:
            addr = self.aliases[addr]
        if isinstance(addr, tuple):
            addr = unparse_host_port(*addr)
        if not isinstance(addr, str):
            raise TypeError(f"addresses should be strings or tuples, got {addr!r}")

        if resolve:
            addr = resolve_address(addr)
        else:
            addr = normalize_address(addr)

        return addr

    def workers_list(self, workers):
        """
        List of qualifying workers

        Takes a list of worker addresses or hostnames.
        Returns a list of all worker addresses that match
        """
        if workers is None:
            return list(self.workers)

        out = set()
        for w in workers:
            if ":" in w:
                out.add(w)
            else:
                out.update({ww for ww in self.workers if w in ww})  # TODO: quadratic
        return list(out)

    async def get_profile(
        self,
        comm=None,
        workers=None,
        scheduler=False,
        server=False,
        merge_workers=True,
        start=None,
        stop=None,
        key=None,
    ):
        if workers is None:
            workers = self.workers
        else:
            workers = set(self.workers) & set(workers)

        if scheduler:
            return profile.get_profile(self.io_loop.profile, start=start, stop=stop)

        results = await asyncio.gather(
            *(
                self.rpc(w).profile(start=start, stop=stop, key=key, server=server)
                for w in workers
            ),
            return_exceptions=True,
        )

        results = [r for r in results if not isinstance(r, Exception)]

        if merge_workers:
            response = profile.merge(*results)
        else:
            response = dict(zip(workers, results))
        return response

    async def get_profile_metadata(
        self,
        workers: "Iterable[str] | None" = None,
        start: float = 0,
        stop: "float | None" = None,
        profile_cycle_interval: "str | float | None" = None,
    ):
        dt = profile_cycle_interval or dask.config.get(
            "distributed.worker.profile.cycle"
        )
        dt = parse_timedelta(dt, default="ms")

        if workers is None:
            workers = self.workers
        else:
            workers = set(self.workers) & set(workers)
        results = await asyncio.gather(
            *(self.rpc(w).profile_metadata(start=start, stop=stop) for w in workers),
            return_exceptions=True,
        )

        results = [r for r in results if not isinstance(r, Exception)]
        counts = [
            (time, sum(pluck(1, group)))
            for time, group in itertools.groupby(
                merge_sorted(
                    *(v["counts"] for v in results),
                ),
                lambda t: t[0] // dt * dt,
            )
        ]

        keys: dict[str, list[list]] = {
            k: [] for v in results for t, d in v["keys"] for k in d
        }

        groups1 = [v["keys"] for v in results]
        groups2 = list(merge_sorted(*groups1, key=first))

        last = 0
        for t, d in groups2:
            tt = t // dt * dt
            if tt > last:
                last = tt
                for v in keys.values():
                    v.append([tt, 0])
            for k, v in d.items():
                keys[k][-1][1] += v

        return {"counts": counts, "keys": keys}

    async def performance_report(
        self, start: float, last_count: int, code="", mode=None
    ):
        stop = time()
        # Profiles
        compute, scheduler, workers = await asyncio.gather(
            *[
                self.get_profile(start=start),
                self.get_profile(scheduler=True, start=start),
                self.get_profile(server=True, start=start),
            ]
        )
        from distributed import profile

        def profile_to_figure(state):
            data = profile.plot_data(state)
            figure, source = profile.plot_figure(data, sizing_mode="stretch_both")
            return figure

        compute, scheduler, workers = map(
            profile_to_figure, (compute, scheduler, workers)
        )

        # Task stream
        task_stream = self.get_task_stream(start=start)
        total_tasks = len(task_stream)
        timespent: defaultdict[str, float] = defaultdict(float)
        for d in task_stream:
            for x in d["startstops"]:
                timespent[x["action"]] += x["stop"] - x["start"]
        tasks_timings = ""
        for k in sorted(timespent.keys()):
            tasks_timings += f"\n<li> {k} time: {format_time(timespent[k])} </li>"

        from distributed.dashboard.components.scheduler import task_stream_figure
        from distributed.diagnostics.task_stream import rectangles

        rects = rectangles(task_stream)
        source, task_stream = task_stream_figure(sizing_mode="stretch_both")
        source.data.update(rects)

        # Bandwidth
        from distributed.dashboard.components.scheduler import (
            BandwidthTypes,
            BandwidthWorkers,
        )

        bandwidth_workers = BandwidthWorkers(self, sizing_mode="stretch_both")
        bandwidth_workers.update()
        bandwidth_types = BandwidthTypes(self, sizing_mode="stretch_both")
        bandwidth_types.update()

        # System monitor
        from distributed.dashboard.components.shared import SystemMonitor

        sysmon = SystemMonitor(self, last_count=last_count, sizing_mode="stretch_both")
        sysmon.update()

        # Scheduler logs
        from distributed.dashboard.components.scheduler import (
            _BOKEH_STYLES_KWARGS,
            SchedulerLogs,
        )

        logs = SchedulerLogs(self, start=start)

        from bokeh.models import Div, Tabs

        import distributed
        from distributed.dashboard.core import TabPanel

        # HTML
        ws: WorkerState
        html = """
        <h1> Dask Performance Report </h1>

        <i> Select different tabs on the top for additional information </i>

        <h2> Duration: {time} </h2>
        <h2> Tasks Information </h2>
        <ul>
         <li> number of tasks: {ntasks} </li>
         {tasks_timings}
        </ul>

        <h2> Scheduler Information </h2>
        <ul>
          <li> Address: {address} </li>
          <li> Workers: {nworkers} </li>
          <li> Threads: {threads} </li>
          <li> Memory: {memory} </li>
          <li> Dask Version: {dask_version} </li>
          <li> Dask.Distributed Version: {distributed_version} </li>
        </ul>

        <h2> Calling Code </h2>
        <pre>
{code}
        </pre>
        """.format(
            time=format_time(stop - start),
            ntasks=total_tasks,
            tasks_timings=tasks_timings,
            address=self.address,
            nworkers=len(self.workers),
            threads=sum(ws.nthreads for ws in self.workers.values()),
            memory=format_bytes(sum(ws.memory_limit for ws in self.workers.values())),
            code=code,
            dask_version=dask.__version__,
            distributed_version=distributed.__version__,
        )
        html = Div(text=html, **_BOKEH_STYLES_KWARGS)

        html = TabPanel(child=html, title="Summary")
        compute = TabPanel(child=compute, title="Worker Profile (compute)")
        workers = TabPanel(child=workers, title="Worker Profile (administrative)")
        scheduler = TabPanel(
            child=scheduler, title="Scheduler Profile (administrative)"
        )
        task_stream = TabPanel(child=task_stream, title="Task Stream")
        bandwidth_workers = TabPanel(
            child=bandwidth_workers.root, title="Bandwidth (Workers)"
        )
        bandwidth_types = TabPanel(
            child=bandwidth_types.root, title="Bandwidth (Types)"
        )
        system = TabPanel(child=sysmon.root, title="System")
        logs = TabPanel(child=logs.root, title="Scheduler Logs")

        tabs = Tabs(
            tabs=[
                html,
                task_stream,
                system,
                logs,
                compute,
                workers,
                scheduler,
                bandwidth_workers,
                bandwidth_types,
            ],
            sizing_mode="stretch_both",
        )

        from bokeh.core.templates import get_env
        from bokeh.plotting import output_file, save

        with tmpfile(extension=".html") as fn:
            output_file(filename=fn, title="Dask Performance Report", mode=mode)
            template_directory = os.path.join(
                os.path.dirname(os.path.abspath(__file__)), "dashboard", "templates"
            )
            template_environment = get_env()
            template_environment.loader.searchpath.append(template_directory)
            template = template_environment.get_template("performance_report.html")
            save(tabs, filename=fn, template=template)

            with open(fn) as f:
                data = f.read()

        return data

    async def get_worker_logs(self, n=None, workers=None, nanny=False):
        results = await self.broadcast(
            msg={"op": "get_logs", "n": n}, workers=workers, nanny=nanny
        )
        return results

    def log_event(self, topic: str | Collection[str], msg: Any) -> None:
        event = (time(), msg)
        if not isinstance(topic, str):
            for t in topic:
                self.events[t].append(event)
                self.event_counts[t] += 1
                self._report_event(t, event)
        else:
            self.events[topic].append(event)
            self.event_counts[topic] += 1
            self._report_event(topic, event)

            for plugin in list(self.plugins.values()):
                try:
                    plugin.log_event(topic, msg)
                except Exception:
                    logger.info("Plugin failed with exception", exc_info=True)

    def _report_event(self, name, event):
        msg = {
            "op": "event",
            "topic": name,
            "event": event,
        }
        client_msgs = {client: [msg] for client in self.event_subscriber[name]}
        self.send_all(client_msgs, worker_msgs={})

    def subscribe_topic(self, topic, client):
        self.event_subscriber[topic].add(client)

    def unsubscribe_topic(self, topic, client):
        self.event_subscriber[topic].discard(client)

    def get_events(self, topic=None):
        if topic is not None:
            return tuple(self.events[topic])
        else:
            return valmap(tuple, self.events)

    async def get_worker_monitor_info(self, recent=False, starts=None):
        if starts is None:
            starts = {}
        results = await asyncio.gather(
            *(
                self.rpc(w).get_monitor_info(recent=recent, start=starts.get(w, 0))
                for w in self.workers
            )
        )
        return dict(zip(self.workers, results))

    ###########
    # Cleanup #
    ###########

    async def check_worker_ttl(self):
        now = time()
        stimulus_id = f"check-worker-ttl-{now}"
        for ws in self.workers.values():
            if (ws.last_seen < now - self.worker_ttl) and (
                ws.last_seen < now - 10 * heartbeat_interval(len(self.workers))
            ):
                logger.warning(
                    "Worker failed to heartbeat within %s seconds. Closing: %s",
                    self.worker_ttl,
                    ws,
                )
                await self.remove_worker(address=ws.address, stimulus_id=stimulus_id)

    def check_idle(self):
        assert self.idle_timeout
        if self.status in (Status.closing, Status.closed):
            return

        if self.transition_counter != self._idle_transition_counter:
            self._idle_transition_counter = self.transition_counter
            self.idle_since = None
            return

        if (
            self.queued
            or self.unrunnable
            or any([ws.processing for ws in self.workers.values()])
        ):
            self.idle_since = None
            return

        if not self.idle_since:
            self.idle_since = time()

        if time() > self.idle_since + self.idle_timeout:
            assert self.idle_since
            logger.info(
                "Scheduler closing after being idle for %s",
                format_time(self.idle_timeout),
            )
            self._ongoing_background_tasks.call_soon(self.close)

    def adaptive_target(self, target_duration=None):
        """Desired number of workers based on the current workload

        This looks at the current running tasks and memory use, and returns a
        number of desired workers.  This is often used by adaptive scheduling.

        Parameters
        ----------
        target_duration : str
            A desired duration of time for computations to take.  This affects
            how rapidly the scheduler will ask to scale.

        See Also
        --------
        distributed.deploy.Adaptive
        """
        if target_duration is None:
            target_duration = dask.config.get("distributed.adaptive.target-duration")
        target_duration = parse_timedelta(target_duration)

        # CPU

        # TODO consider any user-specified default task durations for queued tasks
        queued_occupancy = len(self.queued) * self.UNKNOWN_TASK_DURATION
        cpu = math.ceil(
            (self.total_occupancy + queued_occupancy) / target_duration
        )  # TODO: threads per worker

        # Avoid a few long tasks from asking for many cores
        tasks_ready = len(self.queued)
        for ws in self.workers.values():
            tasks_ready += len(ws.processing)

            if tasks_ready > cpu:
                break
        else:
            cpu = min(tasks_ready, cpu)

        if (self.unrunnable or self.queued) and not self.workers:
            cpu = max(1, cpu)

        # add more workers if more than 60% of memory is used
        limit = sum(ws.memory_limit for ws in self.workers.values())
        used = sum(ws.nbytes for ws in self.workers.values())
        memory = 0
        if used > 0.6 * limit and limit > 0:
            memory = 2 * len(self.workers)

        target = max(memory, cpu)
        if target >= len(self.workers):
            return target
        else:  # Scale down?
            to_close = self.workers_to_close()
            return len(self.workers) - len(to_close)

    def request_acquire_replicas(
        self, addr: str, keys: Iterable[str], *, stimulus_id: str
    ) -> None:
        """Asynchronously ask a worker to acquire a replica of the listed keys from
        other workers. This is a fire-and-forget operation which offers no feedback for
        success or failure, and is intended for housekeeping and not for computation.
        """
        who_has = {}
        nbytes = {}
        for key in keys:
            ts = self.tasks[key]
            assert ts.who_has
            who_has[key] = [ws.address for ws in ts.who_has]
            nbytes[key] = ts.nbytes

        self.stream_comms[addr].send(
            {
                "op": "acquire-replicas",
                "who_has": who_has,
                "nbytes": nbytes,
                "stimulus_id": stimulus_id,
            },
        )

    def request_remove_replicas(
        self, addr: str, keys: list[str], *, stimulus_id: str
    ) -> None:
        """Asynchronously ask a worker to discard its replica of the listed keys.
        This must never be used to destroy the last replica of a key. This is a
        fire-and-forget operation, intended for housekeeping and not for computation.

        The replica disappears immediately from TaskState.who_has on the Scheduler side;
        if the worker refuses to delete, e.g. because the task is a dependency of
        another task running on it, it will (also asynchronously) inform the scheduler
        to re-add itself to who_has. If the worker agrees to discard the task, there is
        no feedback.
        """
        ws = self.workers[addr]

        # The scheduler immediately forgets about the replica and suggests the worker to
        # drop it. The worker may refuse, at which point it will send back an add-keys
        # message to reinstate it.
        for key in keys:
            ts = self.tasks[key]
            if self.validate:
                # Do not destroy the last copy
                assert len(ts.who_has) > 1
            self.remove_replica(ts, ws)

        self.stream_comms[addr].send(
            {
                "op": "remove-replicas",
                "keys": keys,
                "stimulus_id": stimulus_id,
            }
        )


def _task_to_report_msg(ts: TaskState) -> dict[str, Any] | None:
    if ts.state == "forgotten":
        return {"op": "cancelled-key", "key": ts.key}
    elif ts.state == "memory":
        return {"op": "key-in-memory", "key": ts.key}
    elif ts.state == "erred":
        failing_ts = ts.exception_blame
        assert failing_ts
        return {
            "op": "task-erred",
            "key": ts.key,
            "exception": failing_ts.exception,
            "traceback": failing_ts.traceback,
        }
    else:
        return None


def _task_to_client_msgs(ts: TaskState) -> dict[str, list[dict[str, Any]]]:
    if ts.who_wants:
        report_msg = _task_to_report_msg(ts)
        if report_msg is not None:
            return {cs.client_key: [report_msg] for cs in ts.who_wants}
    return {}


def decide_worker(
    ts: TaskState,
    all_workers: Iterable[WorkerState],
    valid_workers: set[WorkerState] | None,
    objective: Callable[[WorkerState], Any],
) -> WorkerState | None:
    """
    Decide which worker should take task *ts*.

    We choose the worker that has the data on which *ts* depends.

    If several workers have dependencies then we choose the less-busy worker.

    Optionally provide *valid_workers* of where jobs are allowed to occur
    (if all workers are allowed to take the task, pass None instead).

    If the task requires data communication because no eligible worker has
    all the dependencies already, then we choose to minimize the number
    of bytes sent between workers.  This is determined by calling the
    *objective* function.
    """
    assert all(dts.who_has for dts in ts.dependencies)
    if ts.actor:
        candidates = set(all_workers)
    else:
        candidates = {wws for dts in ts.dependencies for wws in dts.who_has}
    if valid_workers is None:
        if not candidates:
            candidates = set(all_workers)
    else:
        candidates &= valid_workers
        if not candidates:
            candidates = valid_workers
            if not candidates:
                if ts.loose_restrictions:
                    return decide_worker(ts, all_workers, None, objective)

    if not candidates:
        return None
    elif len(candidates) == 1:
        return next(iter(candidates))
    else:
        return min(candidates, key=objective)


def validate_task_state(ts: TaskState) -> None:
    """Validate the given TaskState"""
    assert ts.state in ALL_TASK_STATES, ts

    if ts.waiting_on:
        assert ts.waiting_on.issubset(ts.dependencies), (
            "waiting not subset of dependencies",
            str(ts.waiting_on),
            str(ts.dependencies),
        )
    if ts.waiters:
        assert ts.waiters.issubset(ts.dependents), (
            "waiters not subset of dependents",
            str(ts.waiters),
            str(ts.dependents),
        )

    for dts in ts.waiting_on:
        assert not dts.who_has, ("waiting on in-memory dep", str(ts), str(dts))
        assert dts.state != "released", ("waiting on released dep", str(ts), str(dts))
    for dts in ts.dependencies:
        assert ts in dts.dependents, (
            "not in dependency's dependents",
            str(ts),
            str(dts),
            str(dts.dependents),
        )
        if ts.state in ("waiting", "queued", "processing", "no-worker"):
            assert dts in ts.waiting_on or dts.who_has, (
                "dep missing",
                str(ts),
                str(dts),
            )
        assert dts.state != "forgotten"

    for dts in ts.waiters:
        assert dts.state in ("waiting", "queued", "processing", "no-worker"), (
            "waiter not in play",
            str(ts),
            str(dts),
        )
    for dts in ts.dependents:
        assert ts in dts.dependencies, (
            "not in dependent's dependencies",
            str(ts),
            str(dts),
            str(dts.dependencies),
        )
        assert dts.state != "forgotten"

    assert (ts.processing_on is not None) == (ts.state == "processing")
    assert bool(ts.who_has) == (ts.state == "memory"), (ts, ts.who_has, ts.state)

    if ts.state == "queued":
        assert not ts.processing_on
        assert not ts.who_has
        assert all(dts.who_has for dts in ts.dependencies), (
            "task queued without all deps",
            str(ts),
            str(ts.dependencies),
        )

    if ts.state == "processing":
        assert all(dts.who_has for dts in ts.dependencies), (
            "task processing without all deps",
            str(ts),
            str(ts.dependencies),
        )
        assert not ts.waiting_on

    if ts.who_has:
        assert ts.waiters or ts.who_wants, (
            "unneeded task in memory",
            str(ts),
            str(ts.who_has),
        )
        if ts.run_spec:  # was computed
            assert ts.type
            assert isinstance(ts.type, str)
        assert not any([ts in dts.waiting_on for dts in ts.dependents])
        for ws in ts.who_has:
            assert ts in ws.has_what, (
                "not in who_has' has_what",
                str(ts),
                str(ws),
                str(ws.has_what),
            )

    for cs in ts.who_wants:
        assert ts in cs.wants_what, (
            "not in who_wants' wants_what",
            str(ts),
            str(cs),
            str(cs.wants_what),
        )

    if ts.actor:
        if ts.state == "memory":
            assert sum(ts in ws.actors for ws in ts.who_has) == 1
        if ts.state == "processing":
            assert ts.processing_on
            assert ts in ts.processing_on.actors
        assert ts.state != "queued"


def validate_worker_state(ws: WorkerState) -> None:
    for ts in ws.has_what:
        assert ws in ts.who_has, (
            "not in has_what' who_has",
            str(ws),
            str(ts),
            str(ts.who_has),
        )

    for ts in ws.actors:
        assert ts.state in ("memory", "processing")


def validate_state(
    tasks: dict[str, TaskState],
    workers: dict[str, WorkerState],
    clients: dict[str, ClientState],
) -> None:
    """Validate a current runtime state.

    This performs a sequence of checks on the entire graph, running in about linear
    time. This raises assert errors if anything doesn't check out.
    """
    for ts in tasks.values():
        validate_task_state(ts)

    for ws in workers.values():
        validate_worker_state(ws)

    for cs in clients.values():
        for ts in cs.wants_what:
            assert cs in ts.who_wants, (
                "not in wants_what' who_wants",
                str(cs),
                str(ts),
                str(ts.who_wants),
            )


def heartbeat_interval(n: int) -> float:
    """Interval in seconds that we desire heartbeats based on number of workers"""
    if n <= 10:
        return 0.5
    elif n < 50:
        return 1
    elif n < 200:
        return 2
    else:
        # No more than 200 heartbeats a second scaled by workers
        return n / 200 + 1


def _task_slots_available(ws: WorkerState, saturation_factor: float) -> int:
    """Number of tasks that can be sent to this worker without oversaturating it"""
    assert not math.isinf(saturation_factor)
    return max(math.ceil(saturation_factor * ws.nthreads), 1) - (
        len(ws.processing) - len(ws.long_running)
    )


def _worker_full(ws: WorkerState, saturation_factor: float) -> bool:
    if math.isinf(saturation_factor):
        return False
    return _task_slots_available(ws, saturation_factor) <= 0


class KilledWorker(Exception):
    def __init__(self, task: str, last_worker: WorkerState, allowed_failures: int):
        super().__init__(task, last_worker, allowed_failures)

    @property
    def task(self) -> str:
        return self.args[0]

    @property
    def last_worker(self) -> WorkerState:
        return self.args[1]

    @property
    def allowed_failures(self) -> int:
        return self.args[2]

    def __str__(self) -> str:
        return (
            f"Attempted to run task {self.task} on {self.allowed_failures} different "
            "workers, but all those workers died while running it. "
            f"The last worker that attempt to run the task was {self.last_worker.address}. "
            "Inspecting worker logs is often a good next step to diagnose what went wrong. "
            "For more information see https://distributed.dask.org/en/stable/killed.html."
        )


class WorkerStatusPlugin(SchedulerPlugin):
    """A plugin to share worker status with a remote observer

    This is used in cluster managers to keep updated about the status of the scheduler.
    """

    name: ClassVar[str] = "worker-status"
    bcomm: BatchedSend

    def __init__(self, scheduler: Scheduler, comm: Comm):
        self.bcomm = BatchedSend(interval="5ms")
        self.bcomm.start(comm)
        scheduler.add_plugin(self)

    def add_worker(self, scheduler: Scheduler, worker: str) -> None:
        ident = scheduler.workers[worker].identity()
        del ident["metrics"]
        del ident["last_seen"]
        try:
            self.bcomm.send(["add", {"workers": {worker: ident}}])
        except CommClosedError:
            scheduler.remove_plugin(name=self.name)

    def remove_worker(self, scheduler: Scheduler, worker: str) -> None:
        try:
            self.bcomm.send(["remove", worker])
        except CommClosedError:
            scheduler.remove_plugin(name=self.name)

    def teardown(self) -> None:
        self.bcomm.close()


class CollectTaskMetaDataPlugin(SchedulerPlugin):
    scheduler: Scheduler
    name: str
    keys: set[str]
    metadata: dict[str, Any]
    state: dict[str, str]

    def __init__(self, scheduler: Scheduler, name: str):
        self.scheduler = scheduler
        self.name = name
        self.keys = set()
        self.metadata = {}
        self.state = {}

    def update_graph(
        self,
        scheduler: Scheduler,
        keys: set[str],
        restrictions: dict[str, float],
        **kwargs: Any,
    ) -> None:
        self.keys.update(keys)

    def transition(
        self,
        key: str,
        start: TaskStateState,
        finish: TaskStateState,
        *args: Any,
        **kwargs: Any,
    ) -> None:
        if finish in ("memory", "erred"):
            ts = self.scheduler.tasks.get(key)
            if ts is not None and ts.key in self.keys:
                self.metadata[key] = ts.metadata
                self.state[key] = finish
                self.keys.discard(key)