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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
from __future__ import annotations

import asyncio
import atexit
import copy
import inspect
import json
import logging
import os
import pickle
import re
import sys
import threading
import traceback
import uuid
import warnings
import weakref
from collections import defaultdict
from collections.abc import Collection, Iterator
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures._base import DoneAndNotDoneFutures
from contextlib import asynccontextmanager, contextmanager, suppress
from contextvars import ContextVar
from functools import partial
from importlib.metadata import PackageNotFoundError, version
from numbers import Number
from queue import Queue as pyQueue
from typing import Any, ClassVar, Coroutine, Literal, Sequence, TypedDict

from packaging.version import parse as parse_version
from tlz import first, groupby, keymap, merge, partition_all, valmap

import dask
from dask.base import collections_to_dsk, normalize_token, tokenize
from dask.core import flatten
from dask.highlevelgraph import HighLevelGraph
from dask.optimization import SubgraphCallable
from dask.utils import (
    apply,
    ensure_dict,
    format_bytes,
    funcname,
    parse_timedelta,
    stringify,
    typename,
)
from dask.widgets import get_template

try:
    from dask.delayed import single_key
except ImportError:
    single_key = first
from tornado import gen
from tornado.ioloop import IOLoop

import distributed.utils
from distributed import cluster_dump, preloading
from distributed import versions as version_module
from distributed.batched import BatchedSend
from distributed.cfexecutor import ClientExecutor
from distributed.compatibility import PeriodicCallback
from distributed.core import (
    CommClosedError,
    ConnectionPool,
    PooledRPCCall,
    Status,
    clean_exception,
    connect,
    rpc,
)
from distributed.diagnostics.plugin import (
    NannyPlugin,
    UploadFile,
    WorkerPlugin,
    _get_plugin_name,
)
from distributed.metrics import time
from distributed.objects import HasWhat, SchedulerInfo, WhoHas
from distributed.protocol import to_serialize
from distributed.protocol.pickle import dumps, loads
from distributed.publish import Datasets
from distributed.pubsub import PubSubClientExtension
from distributed.security import Security
from distributed.sizeof import sizeof
from distributed.threadpoolexecutor import rejoin
from distributed.utils import (
    CancelledError,
    LoopRunner,
    NoOpAwaitable,
    SyncMethodMixin,
    TimeoutError,
    format_dashboard_link,
    has_keyword,
    import_term,
    is_python_shutting_down,
    log_errors,
    no_default,
    sync,
    thread_state,
)
from distributed.utils_comm import (
    WrappedKey,
    gather_from_workers,
    pack_data,
    retry_operation,
    scatter_to_workers,
    unpack_remotedata,
)
from distributed.worker import get_client, get_worker, secede

logger = logging.getLogger(__name__)

_global_clients: weakref.WeakValueDictionary[
    int, Client
] = weakref.WeakValueDictionary()
_global_client_index = [0]

_current_client: ContextVar[Client | None] = ContextVar("_current_client", default=None)

DEFAULT_EXTENSIONS = {
    "pubsub": PubSubClientExtension,
}


def _get_global_client() -> Client | None:
    c = _current_client.get()
    if c:
        return c
    L = sorted(list(_global_clients), reverse=True)
    for k in L:
        c = _global_clients[k]
        if c.status != "closed":
            return c
        else:
            del _global_clients[k]
    return None


def _set_global_client(c: Client | None) -> None:
    if c is not None:
        _global_clients[_global_client_index[0]] = c
        _global_client_index[0] += 1


def _del_global_client(c: Client) -> None:
    for k in list(_global_clients):
        try:
            if _global_clients[k] is c:
                del _global_clients[k]
        except KeyError:  # pragma: no cover
            pass


class Future(WrappedKey):
    """A remotely running computation

    A Future is a local proxy to a result running on a remote worker.  A user
    manages future objects in the local Python process to determine what
    happens in the larger cluster.

    Parameters
    ----------
    key: str, or tuple
        Key of remote data to which this future refers
    client: Client
        Client that should own this future.  Defaults to _get_global_client()
    inform: bool
        Do we inform the scheduler that we need an update on this future
    state: FutureState
        The state of the future

    Examples
    --------
    Futures typically emerge from Client computations

    >>> my_future = client.submit(add, 1, 2)  # doctest: +SKIP

    We can track the progress and results of a future

    >>> my_future  # doctest: +SKIP
    <Future: status: finished, key: add-8f6e709446674bad78ea8aeecfee188e>

    We can get the result or the exception and traceback from the future

    >>> my_future.result()  # doctest: +SKIP

    See Also
    --------
    Client:  Creates futures
    """

    _cb_executor = None
    _cb_executor_pid = None

    def __init__(self, key, client=None, inform=True, state=None):
        self.key = key
        self._cleared = False
        tkey = stringify(key)
        self.client = client or Client.current()
        self.client._inc_ref(tkey)
        self._generation = self.client.generation

        if tkey in self.client.futures:
            self._state = self.client.futures[tkey]
        else:
            self._state = self.client.futures[tkey] = FutureState()

        if inform:
            self.client._send_to_scheduler(
                {
                    "op": "client-desires-keys",
                    "keys": [stringify(key)],
                    "client": self.client.id,
                }
            )

        if state is not None:
            try:
                handler = self.client._state_handlers[state]
            except KeyError:
                pass
            else:
                handler(key=key)

    @property
    def executor(self):
        """Returns the executor, which is the client.

        Returns
        -------
        Client
            The executor
        """
        return self.client

    @property
    def status(self):
        """Returns the status

        Returns
        -------
        str
            The status
        """
        return self._state.status

    def done(self):
        """Returns whether or not the computation completed.

        Returns
        -------
        bool
            True if the computation is complete, otherwise False
        """
        return self._state.done()

    def result(self, timeout=None):
        """Wait until computation completes, gather result to local process.

        Parameters
        ----------
        timeout : number, optional
            Time in seconds after which to raise a
            ``dask.distributed.TimeoutError``

        Raises
        ------
        dask.distributed.TimeoutError
            If *timeout* seconds are elapsed before returning, a
            ``dask.distributed.TimeoutError`` is raised.

        Returns
        -------
        result
            The result of the computation. Or a coroutine if the client is asynchronous.
        """
        if self.client.asynchronous:
            return self.client.sync(self._result, callback_timeout=timeout)

        # shorten error traceback
        result = self.client.sync(self._result, callback_timeout=timeout, raiseit=False)
        if self.status == "error":
            typ, exc, tb = result
            raise exc.with_traceback(tb)
        elif self.status == "cancelled":
            raise result
        else:
            return result

    async def _result(self, raiseit=True):
        await self._state.wait()
        if self.status == "error":
            exc = clean_exception(self._state.exception, self._state.traceback)
            if raiseit:
                typ, exc, tb = exc
                raise exc.with_traceback(tb)
            else:
                return exc
        elif self.status == "cancelled":
            exception = CancelledError(self.key)
            if raiseit:
                raise exception
            else:
                return exception
        else:
            result = await self.client._gather([self])
            return result[0]

    async def _exception(self):
        await self._state.wait()
        if self.status == "error":
            return self._state.exception
        else:
            return None

    def exception(self, timeout=None, **kwargs):
        """Return the exception of a failed task

        Parameters
        ----------
        timeout : number, optional
            Time in seconds after which to raise a
            ``dask.distributed.TimeoutError``
        **kwargs : dict
            Optional keyword arguments for the function

        Returns
        -------
        Exception
            The exception that was raised
            If *timeout* seconds are elapsed before returning, a
            ``dask.distributed.TimeoutError`` is raised.

        See Also
        --------
        Future.traceback
        """
        return self.client.sync(self._exception, callback_timeout=timeout, **kwargs)

    def add_done_callback(self, fn):
        """Call callback on future when callback has finished

        The callback ``fn`` should take the future as its only argument.  This
        will be called regardless of if the future completes successfully,
        errs, or is cancelled

        The callback is executed in a separate thread.

        Parameters
        ----------
        fn : callable
            The method or function to be called
        """
        cls = Future
        if cls._cb_executor is None or cls._cb_executor_pid != os.getpid():
            try:
                cls._cb_executor = ThreadPoolExecutor(
                    1, thread_name_prefix="Dask-Callback-Thread"
                )
            except TypeError:
                cls._cb_executor = ThreadPoolExecutor(1)
            cls._cb_executor_pid = os.getpid()

        def execute_callback(fut):
            try:
                fn(fut)
            except BaseException:
                logger.exception("Error in callback %s of %s:", fn, fut)

        self.client.loop.add_callback(
            done_callback, self, partial(cls._cb_executor.submit, execute_callback)
        )

    def cancel(self, **kwargs):
        """Cancel the request to run this future

        See Also
        --------
        Client.cancel
        """
        return self.client.cancel([self], **kwargs)

    def retry(self, **kwargs):
        """Retry this future if it has failed

        See Also
        --------
        Client.retry
        """
        return self.client.retry([self], **kwargs)

    def cancelled(self):
        """Returns True if the future has been cancelled

        Returns
        -------
        bool
            True if the future was 'cancelled', otherwise False
        """
        return self._state.status == "cancelled"

    async def _traceback(self):
        await self._state.wait()
        if self.status == "error":
            return self._state.traceback
        else:
            return None

    def traceback(self, timeout=None, **kwargs):
        """Return the traceback of a failed task

        This returns a traceback object.  You can inspect this object using the
        ``traceback`` module.  Alternatively if you call ``future.result()``
        this traceback will accompany the raised exception.

        Parameters
        ----------
        timeout : number, optional
            Time in seconds after which to raise a
            ``dask.distributed.TimeoutError``
            If *timeout* seconds are elapsed before returning, a
            ``dask.distributed.TimeoutError`` is raised.

        Examples
        --------
        >>> import traceback  # doctest: +SKIP
        >>> tb = future.traceback()  # doctest: +SKIP
        >>> traceback.format_tb(tb)  # doctest: +SKIP
        [...]

        Returns
        -------
        traceback
            The traceback object. Or a coroutine if the client is asynchronous.

        See Also
        --------
        Future.exception
        """
        return self.client.sync(self._traceback, callback_timeout=timeout, **kwargs)

    @property
    def type(self):
        """Returns the type"""
        return self._state.type

    def release(self):
        """
        Notes
        -----
        This method can be called from different threads
        (see e.g. Client.get() or Future.__del__())
        """
        if not self._cleared and self.client.generation == self._generation:
            self._cleared = True
            try:
                self.client.loop.add_callback(self.client._dec_ref, stringify(self.key))
            except TypeError:  # pragma: no cover
                pass  # Shutting down, add_callback may be None

    def __getstate__(self):
        return self.key, self.client.scheduler.address

    def __setstate__(self, state):
        key, address = state
        try:
            c = Client.current(allow_global=False)
        except ValueError:
            c = get_client(address)
        self.__init__(key, c)
        c._send_to_scheduler(
            {
                "op": "update-graph",
                "tasks": {},
                "keys": [stringify(self.key)],
                "client": c.id,
            }
        )

    def __del__(self):
        try:
            self.release()
        except AttributeError:
            # Occasionally we see this error when shutting down the client
            # https://github.com/dask/distributed/issues/4305
            if not sys.is_finalizing():
                raise
        except RuntimeError:  # closed event loop
            pass

    def __repr__(self):
        if self.type:
            return (
                f"<Future: {self.status}, type: {typename(self.type)}, key: {self.key}>"
            )
        else:
            return f"<Future: {self.status}, key: {self.key}>"

    def _repr_html_(self):
        return get_template("future.html.j2").render(
            key=str(self.key),
            type=typename(self.type),
            status=self.status,
        )

    def __await__(self):
        return self.result().__await__()


class FutureState:
    """A Future's internal state.

    This is shared between all Futures with the same key and client.
    """

    __slots__ = ("_event", "status", "type", "exception", "traceback")

    def __init__(self):
        self._event = None
        self.status = "pending"
        self.type = None

    def _get_event(self):
        # Can't create Event eagerly in constructor as it can fetch
        # its IOLoop from the wrong thread
        # (https://github.com/tornadoweb/tornado/issues/2189)
        event = self._event
        if event is None:
            event = self._event = asyncio.Event()
        return event

    def cancel(self):
        """Cancels the operation"""
        self.status = "cancelled"
        self.exception = CancelledError()
        self._get_event().set()

    def finish(self, type=None):
        """Sets the status to 'finished' and sets the event

        Parameters
        ----------
        type : any
            The type
        """
        self.status = "finished"
        self._get_event().set()
        if type is not None:
            self.type = type

    def lose(self):
        """Sets the status to 'lost' and clears the event"""
        self.status = "lost"
        self._get_event().clear()

    def retry(self):
        """Sets the status to 'pending' and clears the event"""
        self.status = "pending"
        self._get_event().clear()

    def set_error(self, exception, traceback):
        """Sets the error data

        Sets the status to 'error'. Sets the exception, the traceback,
        and the event

        Parameters
        ----------
        exception: Exception
            The exception
        traceback: Exception
            The traceback
        """
        _, exception, traceback = clean_exception(exception, traceback)

        self.status = "error"
        self.exception = exception
        self.traceback = traceback
        self._get_event().set()

    def done(self):
        """Returns 'True' if the event is not None and the event is set"""
        return self._event is not None and self._event.is_set()

    def reset(self):
        """Sets the status to 'pending' and clears the event"""
        self.status = "pending"
        if self._event is not None:
            self._event.clear()

    async def wait(self, timeout=None):
        """Wait for the awaitable to complete with a timeout.

        Parameters
        ----------
        timeout : number, optional
            Time in seconds after which to raise a
            ``dask.distributed.TimeoutError``
        """
        await asyncio.wait_for(self._get_event().wait(), timeout)

    def __repr__(self):
        return f"<{self.__class__.__name__}: {self.status}>"


async def done_callback(future, callback):
    """Coroutine that waits on the future, then calls the callback

    Parameters
    ----------
    future : asyncio.Future
        The future
    callback : callable
        The callback
    """
    while future.status == "pending":
        await future._state.wait()
    callback(future)


@partial(normalize_token.register, Future)
def normalize_future(f):
    """Returns the key and the type as a list

    Parameters
    ----------
    list
        The key and the type
    """
    return [f.key, type(f)]


class AllExit(Exception):
    """Custom exception class to exit All(...) early."""


def _handle_print(event):
    _, msg = event
    if not isinstance(msg, dict):
        # someone must have manually logged a print event with a hand-crafted
        # payload, rather than by calling worker.print(). In that case simply
        # print the payload and hope it works.
        print(msg)
        return

    args = msg.get("args")
    if not isinstance(args, tuple):
        # worker.print() will always send us a tuple of args, even if it's an
        # empty tuple.
        raise TypeError(
            f"_handle_print: client received non-tuple print args: {args!r}"
        )

    file = msg.get("file")
    if file == 1:
        file = sys.stdout
    elif file == 2:
        file = sys.stderr
    elif file is not None:
        raise TypeError(
            f"_handle_print: client received unsupported file kwarg: {file!r}"
        )

    print(
        *args, sep=msg.get("sep"), end=msg.get("end"), file=file, flush=msg.get("flush")
    )


def _handle_warn(event):
    _, msg = event
    if not isinstance(msg, dict):
        # someone must have manually logged a warn event with a hand-crafted
        # payload, rather than by calling worker.warn(). In that case simply
        # warn the payload and hope it works.
        warnings.warn(msg)
    else:
        if "message" not in msg:
            # TypeError makes sense here because it's analogous to calling a
            # function without a required positional argument
            raise TypeError(
                "_handle_warn: client received a warn event missing the required "
                '"message" argument.'
            )
        if "category" in msg:
            category = pickle.loads(msg["category"])
        else:
            category = None
        warnings.warn(
            pickle.loads(msg["message"]),
            category=category,
        )


def _maybe_call_security_loader(address):
    security_loader_term = dask.config.get("distributed.client.security-loader")
    if security_loader_term:
        try:
            security_loader = import_term(security_loader_term)
        except Exception as exc:
            raise ImportError(
                f"Failed to import `{security_loader_term}` configured at "
                f"`distributed.client.security-loader` - is this module "
                f"installed?"
            ) from exc
        return security_loader({"address": address})
    return None


class VersionsDict(TypedDict):
    scheduler: dict[str, dict[str, Any]]
    workers: dict[str, dict[str, dict[str, Any]]]
    client: dict[str, dict[str, Any]]


class Client(SyncMethodMixin):
    """Connect to and submit computation to a Dask cluster

    The Client connects users to a Dask cluster.  It provides an asynchronous
    user interface around functions and futures.  This class resembles
    executors in ``concurrent.futures`` but also allows ``Future`` objects
    within ``submit/map`` calls.  When a Client is instantiated it takes over
    all ``dask.compute`` and ``dask.persist`` calls by default.

    It is also common to create a Client without specifying the scheduler
    address , like ``Client()``.  In this case the Client creates a
    :class:`LocalCluster` in the background and connects to that.  Any extra
    keywords are passed from Client to LocalCluster in this case.  See the
    LocalCluster documentation for more information.

    Parameters
    ----------
    address: string, or Cluster
        This can be the address of a ``Scheduler`` server like a string
        ``'127.0.0.1:8786'`` or a cluster object like ``LocalCluster()``
    loop
        The event loop
    timeout: int (defaults to configuration ``distributed.comm.timeouts.connect``)
        Timeout duration for initial connection to the scheduler
    set_as_default: bool (True)
        Use this Client as the global dask scheduler
    scheduler_file: string (optional)
        Path to a file with scheduler information if available
    security: Security or bool, optional
        Optional security information. If creating a local cluster can also
        pass in ``True``, in which case temporary self-signed credentials will
        be created automatically.
    asynchronous: bool (False by default)
        Set to True if using this client within async/await functions or within
        Tornado gen.coroutines.  Otherwise this should remain False for normal
        use.
    name: string (optional)
        Gives the client a name that will be included in logs generated on
        the scheduler for matters relating to this client
    heartbeat_interval: int (optional)
        Time in milliseconds between heartbeats to scheduler
    serializers
        Iterable of approaches to use when serializing the object.
        See :ref:`serialization` for more.
    deserializers
        Iterable of approaches to use when deserializing the object.
        See :ref:`serialization` for more.
    extensions : list
        The extensions
    direct_to_workers: bool (optional)
        Whether or not to connect directly to the workers, or to ask
        the scheduler to serve as intermediary.
    connection_limit : int
        The number of open comms to maintain at once in the connection pool

    **kwargs:
        If you do not pass a scheduler address, Client will create a
        ``LocalCluster`` object, passing any extra keyword arguments.

    Examples
    --------
    Provide cluster's scheduler node address on initialization:

    >>> client = Client('127.0.0.1:8786')  # doctest: +SKIP

    Use ``submit`` method to send individual computations to the cluster

    >>> a = client.submit(add, 1, 2)  # doctest: +SKIP
    >>> b = client.submit(add, 10, 20)  # doctest: +SKIP

    Continue using submit or map on results to build up larger computations

    >>> c = client.submit(add, a, b)  # doctest: +SKIP

    Gather results with the ``gather`` method.

    >>> client.gather(c)  # doctest: +SKIP
    33

    You can also call Client with no arguments in order to create your own
    local cluster.

    >>> client = Client()  # makes your own local "cluster" # doctest: +SKIP

    Extra keywords will be passed directly to LocalCluster

    >>> client = Client(n_workers=2, threads_per_worker=4)  # doctest: +SKIP

    See Also
    --------
    distributed.scheduler.Scheduler: Internal scheduler
    distributed.LocalCluster:
    """

    _instances: ClassVar[weakref.WeakSet[Client]] = weakref.WeakSet()

    _default_event_handlers = {"print": _handle_print, "warn": _handle_warn}

    preloads: list[preloading.Preload]
    __loop: IOLoop | None = None

    def __init__(
        self,
        address=None,
        loop=None,
        timeout=no_default,
        set_as_default=True,
        scheduler_file=None,
        security=None,
        asynchronous=False,
        name=None,
        heartbeat_interval=None,
        serializers=None,
        deserializers=None,
        extensions=DEFAULT_EXTENSIONS,
        direct_to_workers=None,
        connection_limit=512,
        **kwargs,
    ):
        if timeout == no_default:
            timeout = dask.config.get("distributed.comm.timeouts.connect")
        if timeout is not None:
            timeout = parse_timedelta(timeout, "s")
        self._timeout = timeout

        self.futures = dict()
        self.refcount = defaultdict(lambda: 0)
        self._handle_report_task = None
        if name is None:
            name = dask.config.get("client-name", None)
        self.id = (
            type(self).__name__
            + ("-" + name + "-" if name else "-")
            + str(uuid.uuid1(clock_seq=os.getpid()))
        )
        self.generation = 0
        self.status = "newly-created"
        self._pending_msg_buffer = []
        self.extensions = {}
        self.scheduler_file = scheduler_file
        self._startup_kwargs = kwargs
        self.cluster = None
        self.scheduler = None
        self._scheduler_identity = {}
        # A reentrant-lock on the refcounts for futures associated with this
        # client. Should be held by individual operations modifying refcounts,
        # or any bulk operation that needs to ensure the set of futures doesn't
        # change during operation.
        self._refcount_lock = threading.RLock()
        self.datasets = Datasets(self)
        self._serializers = serializers
        if deserializers is None:
            deserializers = serializers
        self._deserializers = deserializers
        self.direct_to_workers = direct_to_workers

        # Communication
        self.scheduler_comm = None

        if address is None:
            address = dask.config.get("scheduler-address", None)
            if address:
                logger.info("Config value `scheduler-address` found: %s", address)

        if address is not None and kwargs:
            raise ValueError(f"Unexpected keyword arguments: {sorted(kwargs)}")

        if isinstance(address, (rpc, PooledRPCCall)):
            self.scheduler = address
        elif isinstance(getattr(address, "scheduler_address", None), str):
            # It's a LocalCluster or LocalCluster-compatible object
            self.cluster = address
            status = self.cluster.status
            if status in (Status.closed, Status.closing):
                raise RuntimeError(
                    f"Trying to connect to an already closed or closing Cluster {self.cluster}."
                )
            with suppress(AttributeError):
                loop = address.loop
            if security is None:
                security = getattr(self.cluster, "security", None)
        elif address is not None and not isinstance(address, str):
            raise TypeError(
                "Scheduler address must be a string or a Cluster instance, got {}".format(
                    type(address)
                )
            )

        # If connecting to an address and no explicit security is configured, attempt
        # to load security credentials with a security loader (if configured).
        if security is None and isinstance(address, str):
            security = _maybe_call_security_loader(address)

        if security is None:
            security = Security()
        elif isinstance(security, dict):
            security = Security(**security)
        elif security is True:
            security = Security.temporary()
            self._startup_kwargs["security"] = security
        elif not isinstance(security, Security):  # pragma: no cover
            raise TypeError("security must be a Security object")

        self.security = security

        if name == "worker":
            self.connection_args = self.security.get_connection_args("worker")
        else:
            self.connection_args = self.security.get_connection_args("client")

        self._asynchronous = asynchronous
        self._loop_runner = LoopRunner(loop=loop, asynchronous=asynchronous)
        self._connecting_to_scheduler = False

        self._gather_keys = None
        self._gather_future = None

        if heartbeat_interval is None:
            heartbeat_interval = dask.config.get("distributed.client.heartbeat")
        heartbeat_interval = parse_timedelta(heartbeat_interval, default="ms")

        scheduler_info_interval = parse_timedelta(
            dask.config.get("distributed.client.scheduler-info-interval", default="ms")
        )

        self._periodic_callbacks = dict()
        self._periodic_callbacks["scheduler-info"] = PeriodicCallback(
            self._update_scheduler_info, scheduler_info_interval * 1000
        )
        self._periodic_callbacks["heartbeat"] = PeriodicCallback(
            self._heartbeat, heartbeat_interval * 1000
        )

        self._start_arg = address
        self._set_as_default = set_as_default

        self._event_handlers = {}

        self._stream_handlers = {
            "key-in-memory": self._handle_key_in_memory,
            "lost-data": self._handle_lost_data,
            "cancelled-key": self._handle_cancelled_key,
            "task-retried": self._handle_retried_key,
            "task-erred": self._handle_task_erred,
            "restart": self._handle_restart,
            "error": self._handle_error,
            "event": self._handle_event,
        }

        self._state_handlers = {
            "memory": self._handle_key_in_memory,
            "lost": self._handle_lost_data,
            "erred": self._handle_task_erred,
        }

        self.rpc = ConnectionPool(
            limit=connection_limit,
            serializers=serializers,
            deserializers=deserializers,
            deserialize=True,
            connection_args=self.connection_args,
            timeout=timeout,
            server=self,
        )

        self.extensions = {
            name: extension(self) for name, extension in extensions.items()
        }

        preload = dask.config.get("distributed.client.preload")
        preload_argv = dask.config.get("distributed.client.preload-argv")
        self.preloads = preloading.process_preloads(self, preload, preload_argv)

        self.start(timeout=timeout)
        Client._instances.add(self)

        from distributed.recreate_tasks import ReplayTaskClient

        ReplayTaskClient(self)

    @property
    def io_loop(self) -> IOLoop | None:
        warnings.warn(
            "The io_loop property is deprecated", DeprecationWarning, stacklevel=2
        )
        return self.loop

    @io_loop.setter
    def io_loop(self, value: IOLoop) -> None:
        warnings.warn(
            "The io_loop property is deprecated", DeprecationWarning, stacklevel=2
        )
        self.loop = value

    @property
    def loop(self) -> IOLoop | None:
        loop = self.__loop
        if loop is None:
            # If the loop is not running when this is called, the LoopRunner.loop
            # property will raise a DeprecationWarning
            # However subsequent calls might occur - eg atexit, where a stopped
            # loop is still acceptable - so we cache access to the loop.
            self.__loop = loop = self._loop_runner.loop
        return loop

    @loop.setter
    def loop(self, value: IOLoop) -> None:
        warnings.warn(
            "setting the loop property is deprecated", DeprecationWarning, stacklevel=2
        )
        self.__loop = value

    @contextmanager
    def as_current(self):
        """Thread-local, Task-local context manager that causes the Client.current
        class method to return self. Any Future objects deserialized inside this
        context manager will be automatically attached to this Client.
        """
        tok = _current_client.set(self)
        try:
            yield
        finally:
            _current_client.reset(tok)

    @classmethod
    def current(cls, allow_global=True):
        """When running within the context of `as_client`, return the context-local
        current client. Otherwise, return the latest initialised Client.
        If no Client instances exist, raise ValueError.
        If allow_global is set to False, raise ValueError if running outside of
        the `as_client` context manager.

        Parameters
        ----------
        allow_global : bool
            If True returns the default client

        Returns
        -------
        Client
            The current client

        Raises
        ------
        ValueError
            If there is no client set, a ValueError is raised
        """
        out = _current_client.get()
        if out:
            return out
        if allow_global:
            return default_client()
        raise ValueError("Not running inside the `as_current` context manager")

    @property
    def dashboard_link(self):
        """Link to the scheduler's dashboard.

        Returns
        -------
        str
            Dashboard URL.

        Examples
        --------
        Opening the dashboard in your default web browser:

        >>> import webbrowser
        >>> from distributed import Client
        >>> client = Client()
        >>> webbrowser.open(client.dashboard_link)

        """
        try:
            return self.cluster.dashboard_link
        except AttributeError:
            scheduler, info = self._get_scheduler_info()
            if scheduler is None:
                return None
            else:
                protocol, rest = scheduler.address.split("://")

            port = info["services"]["dashboard"]
            if protocol == "inproc":
                host = "localhost"
            else:
                host = rest.split(":")[0]

            return format_dashboard_link(host, port)

    def _get_scheduler_info(self):
        from distributed.scheduler import Scheduler

        if (
            self.cluster
            and hasattr(self.cluster, "scheduler")
            and isinstance(self.cluster.scheduler, Scheduler)
        ):
            info = self.cluster.scheduler.identity()
            scheduler = self.cluster.scheduler
        elif (
            self._loop_runner.is_started() and self.scheduler and not self.asynchronous
        ):
            info = sync(self.loop, self.scheduler.identity)
            scheduler = self.scheduler
        else:
            info = self._scheduler_identity
            scheduler = self.scheduler

        return scheduler, SchedulerInfo(info)

    def __repr__(self):
        # Note: avoid doing I/O here...
        info = self._scheduler_identity
        addr = info.get("address")
        if addr:
            workers = info.get("workers", {})
            nworkers = len(workers)
            nthreads = sum(w["nthreads"] for w in workers.values())
            text = "<%s: %r processes=%d threads=%d" % (
                self.__class__.__name__,
                addr,
                nworkers,
                nthreads,
            )
            memory = [w["memory_limit"] for w in workers.values()]
            if all(memory):
                text += ", memory=" + format_bytes(sum(memory))
            text += ">"
            return text

        elif self.scheduler is not None:
            return "<{}: scheduler={!r}>".format(
                self.__class__.__name__,
                self.scheduler.address,
            )
        else:
            return f"<{self.__class__.__name__}: No scheduler connected>"

    def _repr_html_(self):
        try:
            dle_version = parse_version(version("dask-labextension"))
            JUPYTERLAB = False if dle_version < parse_version("6.0.0") else True
        except PackageNotFoundError:
            JUPYTERLAB = False

        scheduler, info = self._get_scheduler_info()

        return get_template("client.html.j2").render(
            id=self.id,
            scheduler=scheduler,
            info=info,
            cluster=self.cluster,
            scheduler_file=self.scheduler_file,
            dashboard_link=self.dashboard_link,
            jupyterlab=JUPYTERLAB,
        )

    def start(self, **kwargs):
        """Start scheduler running in separate thread"""
        if self.status != "newly-created":
            return

        self._loop_runner.start()
        if self._set_as_default:
            _set_global_client(self)

        if self.asynchronous:
            self._started = asyncio.ensure_future(self._start(**kwargs))
        else:
            sync(self.loop, self._start, **kwargs)

    def __await__(self):
        if hasattr(self, "_started"):
            return self._started.__await__()
        else:

            async def _():
                return self

            return _().__await__()

    def _send_to_scheduler_safe(self, msg):
        if self.status in ("running", "closing"):
            try:
                self.scheduler_comm.send(msg)
            except (CommClosedError, AttributeError):
                if self.status == "running":
                    raise
        elif self.status in ("connecting", "newly-created"):
            self._pending_msg_buffer.append(msg)

    def _send_to_scheduler(self, msg):
        if self.status in ("running", "closing", "connecting", "newly-created"):
            self.loop.add_callback(self._send_to_scheduler_safe, msg)
        else:
            raise Exception(
                "Tried sending message after closing.  Status: %s\n"
                "Message: %s" % (self.status, msg)
            )

    async def _start(self, timeout=no_default, **kwargs):
        self.status = "connecting"

        await self.rpc.start()

        if timeout == no_default:
            timeout = self._timeout
        if timeout is not None:
            timeout = parse_timedelta(timeout, "s")

        address = self._start_arg
        if self.cluster is not None:
            # Ensure the cluster is started (no-op if already running)
            try:
                await self.cluster
            except Exception:
                logger.info(
                    "Tried to start cluster and received an error. Proceeding.",
                    exc_info=True,
                )
            address = self.cluster.scheduler_address
        elif self.scheduler_file is not None:
            while not os.path.exists(self.scheduler_file):
                await asyncio.sleep(0.01)
            for _ in range(10):
                try:
                    with open(self.scheduler_file) as f:
                        cfg = json.load(f)
                    address = cfg["address"]
                    break
                except (ValueError, KeyError):  # JSON file not yet flushed
                    await asyncio.sleep(0.01)
        elif self._start_arg is None:
            from distributed.deploy import LocalCluster

            self.cluster = await LocalCluster(
                loop=self.loop,
                asynchronous=self._asynchronous,
                **self._startup_kwargs,
            )
            address = self.cluster.scheduler_address

        self._gather_semaphore = asyncio.Semaphore(5)

        if self.scheduler is None:
            self.scheduler = self.rpc(address)
        self.scheduler_comm = None

        try:
            await self._ensure_connected(timeout=timeout)
        except (OSError, ImportError):
            await self._close()
            raise

        for pc in self._periodic_callbacks.values():
            pc.start()

        for topic, handler in Client._default_event_handlers.items():
            self.subscribe_topic(topic, handler)

        for preload in self.preloads:
            await preload.start()

        self._handle_report_task = asyncio.create_task(self._handle_report())

        return self

    @log_errors
    async def _reconnect(self):
        assert self.scheduler_comm.comm.closed()

        self.status = "connecting"
        self.scheduler_comm = None

        for st in self.futures.values():
            st.cancel()
        self.futures.clear()

        timeout = self._timeout
        deadline = time() + timeout
        while timeout > 0 and self.status == "connecting":
            try:
                await self._ensure_connected(timeout=timeout)
                break
            except OSError:
                # Wait a bit before retrying
                await asyncio.sleep(0.1)
                timeout = deadline - time()
            except ImportError:
                await self._close()
                break

        else:
            logger.error(
                "Failed to reconnect to scheduler after %.2f "
                "seconds, closing client",
                self._timeout,
            )
            await self._close()

    async def _ensure_connected(self, timeout=None):
        if (
            self.scheduler_comm
            and not self.scheduler_comm.closed()
            or self._connecting_to_scheduler
            or self.scheduler is None
        ):
            return

        self._connecting_to_scheduler = True

        try:
            comm = await connect(
                self.scheduler.address, timeout=timeout, **self.connection_args
            )
            comm.name = "Client->Scheduler"
            if timeout is not None:
                await asyncio.wait_for(self._update_scheduler_info(), timeout)
            else:
                await self._update_scheduler_info()
            await comm.write(
                {
                    "op": "register-client",
                    "client": self.id,
                    "reply": False,
                    "versions": version_module.get_versions(),
                }
            )
        except Exception:
            if self.status == "closed":
                return
            else:
                raise
        finally:
            self._connecting_to_scheduler = False
        if timeout is not None:
            msg = await asyncio.wait_for(comm.read(), timeout)
        else:
            msg = await comm.read()
        assert len(msg) == 1
        assert msg[0]["op"] == "stream-start"

        if msg[0].get("error"):
            raise ImportError(msg[0]["error"])
        if msg[0].get("warning"):
            warnings.warn(version_module.VersionMismatchWarning(msg[0]["warning"]))

        bcomm = BatchedSend(interval="10ms", loop=self.loop)
        bcomm.start(comm)
        self.scheduler_comm = bcomm
        if self._set_as_default:
            _set_global_client(self)
        self.status = "running"

        for msg in self._pending_msg_buffer:
            self._send_to_scheduler(msg)
        del self._pending_msg_buffer[:]

        logger.debug("Started scheduling coroutines. Synchronized")

    async def _update_scheduler_info(self):
        if self.status not in ("running", "connecting") or self.scheduler is None:
            return
        try:
            self._scheduler_identity = SchedulerInfo(await self.scheduler.identity())
        except OSError:
            logger.debug("Not able to query scheduler for identity")

    async def _wait_for_workers(
        self, n_workers: int, timeout: float | None = None
    ) -> None:
        info = await self.scheduler.identity()
        self._scheduler_identity = SchedulerInfo(info)
        if timeout:
            deadline = time() + parse_timedelta(timeout)
        else:
            deadline = None

        def running_workers(info):
            return len(
                [
                    ws
                    for ws in info["workers"].values()
                    if ws["status"] == Status.running.name
                ]
            )

        while running_workers(info) < n_workers:
            if deadline and time() > deadline:
                raise TimeoutError(
                    "Only %d/%d workers arrived after %s"
                    % (running_workers(info), n_workers, timeout)
                )
            await asyncio.sleep(0.1)
            info = await self.scheduler.identity()
            self._scheduler_identity = SchedulerInfo(info)

    def wait_for_workers(
        self,
        n_workers: int | str = no_default,
        timeout: float | None = None,
    ) -> None:
        """Blocking call to wait for n workers before continuing

        Parameters
        ----------
        n_workers : int
            The number of workers
        timeout : number, optional
            Time in seconds after which to raise a
            ``dask.distributed.TimeoutError``
        """
        if n_workers is no_default:
            warnings.warn(
                "Please specify the `n_workers` argument when using `Client.wait_for_workers`. Not specifying `n_workers` will no longer be supported in future versions.",
                FutureWarning,
            )
            n_workers = 0
        elif not isinstance(n_workers, int) or n_workers < 1:
            raise ValueError(
                f"`n_workers` must be a positive integer. Instead got {n_workers}."
            )
        return self.sync(self._wait_for_workers, n_workers, timeout=timeout)

    def _heartbeat(self):
        # Don't send heartbeat if scheduler comm or cluster are already closed
        if (self.scheduler_comm and not self.scheduler_comm.comm.closed()) or (
            self.cluster and self.cluster.status not in (Status.closed, Status.closing)
        ):
            self.scheduler_comm.send({"op": "heartbeat-client"})

    def __enter__(self):
        if not self._loop_runner.is_started():
            self.start()
        return self

    async def __aenter__(self):
        await self
        return self

    async def __aexit__(self, exc_type, exc_value, traceback):
        await self._close(
            # if we're handling an exception, we assume that it's more
            # important to deliver that exception than shutdown gracefully.
            fast=exc_type
            is not None
        )

    def __exit__(self, exc_type, exc_value, traceback):
        self.close()

    def __del__(self):
        # If the loop never got assigned, we failed early in the constructor,
        # nothing to do
        if self.__loop is not None:
            self.close()

    def _inc_ref(self, key):
        with self._refcount_lock:
            self.refcount[key] += 1

    def _dec_ref(self, key):
        with self._refcount_lock:
            self.refcount[key] -= 1
            if self.refcount[key] == 0:
                del self.refcount[key]
                self._release_key(key)

    def _release_key(self, key):
        """Release key from distributed memory"""
        logger.debug("Release key %s", key)
        st = self.futures.pop(key, None)
        if st is not None:
            st.cancel()
        if self.status != "closed":
            self._send_to_scheduler(
                {"op": "client-releases-keys", "keys": [key], "client": self.id}
            )

    @log_errors
    async def _handle_report(self):
        """Listen to scheduler"""
        try:
            while True:
                if self.scheduler_comm is None:
                    break
                try:
                    msgs = await self.scheduler_comm.comm.read()
                except CommClosedError:
                    if is_python_shutting_down():
                        return
                    if self.status == "running":
                        if self.cluster and self.cluster.status in (
                            Status.closed,
                            Status.closing,
                        ):
                            # Don't attempt to reconnect if cluster are already closed.
                            # Instead close down the client.
                            await self._close()
                            return
                        logger.info("Client report stream closed to scheduler")
                        logger.info("Reconnecting...")
                        self.status = "connecting"
                        await self._reconnect()
                        continue
                    else:
                        break
                if not isinstance(msgs, (list, tuple)):
                    msgs = (msgs,)

                breakout = False
                for msg in msgs:
                    logger.debug("Client receives message %s", msg)

                    if "status" in msg and "error" in msg["status"]:
                        typ, exc, tb = clean_exception(**msg)
                        raise exc.with_traceback(tb)

                    op = msg.pop("op")

                    if op == "close" or op == "stream-closed":
                        breakout = True
                        break

                    try:
                        handler = self._stream_handlers[op]
                        result = handler(**msg)
                        if inspect.isawaitable(result):
                            await result
                    except Exception as e:
                        logger.exception(e)
                if breakout:
                    break
        except (CancelledError, asyncio.CancelledError):
            pass

    def _handle_key_in_memory(self, key=None, type=None, workers=None):
        state = self.futures.get(key)
        if state is not None:
            if type and not state.type:  # Type exists and not yet set
                try:
                    type = loads(type)
                except Exception:
                    type = None
                # Here, `type` may be a str if actual type failed
                # serializing in Worker
            else:
                type = None
            state.finish(type)

    def _handle_lost_data(self, key=None):
        state = self.futures.get(key)
        if state is not None:
            state.lose()

    def _handle_cancelled_key(self, key=None):
        state = self.futures.get(key)
        if state is not None:
            state.cancel()

    def _handle_retried_key(self, key=None):
        state = self.futures.get(key)
        if state is not None:
            state.retry()

    def _handle_task_erred(self, key=None, exception=None, traceback=None):
        state = self.futures.get(key)
        if state is not None:
            state.set_error(exception, traceback)

    def _handle_restart(self):
        logger.info("Receive restart signal from scheduler")
        for state in self.futures.values():
            state.cancel()
        self.futures.clear()
        self.generation += 1
        with self._refcount_lock:
            self.refcount.clear()

    def _handle_error(self, exception=None):
        logger.warning("Scheduler exception:")
        logger.exception(exception)

    @asynccontextmanager
    async def _wait_for_handle_report_task(self, fast=False):
        current_task = asyncio.current_task()
        handle_report_task = self._handle_report_task
        # Give the scheduler 'stream-closed' message 100ms to come through
        # This makes the shutdown slightly smoother and quieter
        should_wait = (
            handle_report_task is not None and handle_report_task is not current_task
        )
        if should_wait:
            with suppress(asyncio.CancelledError, TimeoutError):
                await asyncio.wait_for(asyncio.shield(handle_report_task), 0.1)

        yield

        if should_wait:
            with suppress(TimeoutError, asyncio.CancelledError):
                await asyncio.wait_for(handle_report_task, 0 if fast else 2)

    async def _close(self, fast=False):
        """
        Send close signal and wait until scheduler completes

        If fast is True, the client will close forcefully, by cancelling tasks
        the background _handle_report_task.
        """
        # TODO: aclose more forcefully by aborting the RPC and cancelling all
        # background tasks.
        # see https://trio.readthedocs.io/en/stable/reference-io.html#trio.aclose_forcefully
        if self.status == "closed":
            return

        self.status = "closing"

        for preload in self.preloads:
            await preload.teardown()

        with suppress(AttributeError):
            for pc in self._periodic_callbacks.values():
                pc.stop()

        with log_errors():
            _del_global_client(self)
            self._scheduler_identity = {}
            if self.get == dask.config.get("get", None):
                del dask.config.config["get"]

            if (
                self.scheduler_comm
                and self.scheduler_comm.comm
                and not self.scheduler_comm.comm.closed()
            ):
                self._send_to_scheduler({"op": "close-client"})
                self._send_to_scheduler({"op": "close-stream"})
            async with self._wait_for_handle_report_task(fast=fast):
                if (
                    self.scheduler_comm
                    and self.scheduler_comm.comm
                    and not self.scheduler_comm.comm.closed()
                ):
                    await self.scheduler_comm.close()

                for key in list(self.futures):
                    self._release_key(key=key)

                if self._start_arg is None:
                    with suppress(AttributeError):
                        await self.cluster.close()

                await self.rpc.close()

                self.status = "closed"

                if _get_global_client() is self:
                    _set_global_client(None)

            with suppress(AttributeError):
                await self.scheduler.close_rpc()

            self.scheduler = None

        self.status = "closed"

    def close(self, timeout=no_default):
        """Close this client

        Clients will also close automatically when your Python session ends

        If you started a client without arguments like ``Client()`` then this
        will also close the local cluster that was started at the same time.


        Parameters
        ----------
        timeout : number
            Time in seconds after which to raise a
            ``dask.distributed.TimeoutError``

        See Also
        --------
        Client.restart
        """
        if timeout == no_default:
            timeout = self._timeout * 2
        # XXX handling of self.status here is not thread-safe
        if self.status in ["closed", "newly-created"]:
            if self.asynchronous:
                return NoOpAwaitable()
            return
        self.status = "closing"

        with suppress(AttributeError):
            for pc in self._periodic_callbacks.values():
                pc.stop()

        if self.asynchronous:
            coro = self._close()
            if timeout:
                coro = asyncio.wait_for(coro, timeout)
            return coro

        if self._start_arg is None:
            with suppress(AttributeError):
                f = self.cluster.close()
                if asyncio.iscoroutine(f):

                    async def _():
                        await f

                    self.sync(_)

        sync(self.loop, self._close, fast=True, callback_timeout=timeout)

        assert self.status == "closed"

        if not sys.is_finalizing():
            self._loop_runner.stop()

    async def _shutdown(self):
        logger.info("Shutting down scheduler from Client")

        self.status = "closing"
        for pc in self._periodic_callbacks.values():
            pc.stop()

        async with self._wait_for_handle_report_task():
            if self.cluster:
                await self.cluster.close()
            else:
                with suppress(CommClosedError):
                    await self.scheduler.terminate()

        await self._close()

    def shutdown(self):
        """Shut down the connected scheduler and workers

        Note, this may disrupt other clients that may be using the same
        scheduler and workers.

        See Also
        --------
        Client.close : close only this client
        """
        return self.sync(self._shutdown)

    def get_executor(self, **kwargs):
        """
        Return a concurrent.futures Executor for submitting tasks on this
        Client

        Parameters
        ----------
        **kwargs
            Any submit()- or map()- compatible arguments, such as
            `workers` or `resources`.

        Returns
        -------
        ClientExecutor
            An Executor object that's fully compatible with the
            concurrent.futures API.
        """
        return ClientExecutor(self, **kwargs)

    def submit(
        self,
        func,
        *args,
        key=None,
        workers=None,
        resources=None,
        retries=None,
        priority=0,
        fifo_timeout="100 ms",
        allow_other_workers=False,
        actor=False,
        actors=False,
        pure=None,
        **kwargs,
    ):
        """Submit a function application to the scheduler

        Parameters
        ----------
        func : callable
            Callable to be scheduled as ``func(*args **kwargs)``. If ``func`` returns a
            coroutine, it will be run on the main event loop of a worker. Otherwise
            ``func`` will be run in a worker's task executor pool (see
            ``Worker.executors`` for more information.)
        *args : tuple
            Optional positional arguments
        key : str
            Unique identifier for the task.  Defaults to function-name and hash
        workers : string or iterable of strings
            A set of worker addresses or hostnames on which computations may be
            performed. Leave empty to default to all workers (common case)
        resources : dict (defaults to {})
            Defines the ``resources`` each instance of this mapped task
            requires on the worker; e.g. ``{'GPU': 2}``.
            See :doc:`worker resources <resources>` for details on defining
            resources.
        retries : int (default to 0)
            Number of allowed automatic retries if the task fails
        priority : Number
            Optional prioritization of task.  Zero is default.
            Higher priorities take precedence
        fifo_timeout : str timedelta (default '100ms')
            Allowed amount of time between calls to consider the same priority
        allow_other_workers : bool (defaults to False)
            Used with ``workers``. Indicates whether or not the computations
            may be performed on workers that are not in the `workers` set(s).
        actor : bool (default False)
            Whether this task should exist on the worker as a stateful actor.
            See :doc:`actors` for additional details.
        actors : bool (default False)
            Alias for `actor`
        pure : bool (defaults to True)
            Whether or not the function is pure.  Set ``pure=False`` for
            impure functions like ``np.random.random``.
            See :ref:`pure functions` for more details.
        **kwargs

        Examples
        --------
        >>> c = client.submit(add, a, b)  # doctest: +SKIP

        Returns
        -------
        Future
            If running in asynchronous mode, returns the future. Otherwise
            returns the concrete value

        Raises
        ------
        TypeError
            If 'func' is not callable, a TypeError is raised
        ValueError
            If 'allow_other_workers'is True and 'workers' is None, a
            ValueError is raised

        See Also
        --------
        Client.map : Submit on many arguments at once
        """
        if not callable(func):
            raise TypeError("First input to submit must be a callable function")

        actor = actor or actors
        if pure is None:
            pure = not actor

        if allow_other_workers not in (True, False, None):
            raise TypeError("allow_other_workers= must be True or False")

        if key is None:
            if pure:
                key = funcname(func) + "-" + tokenize(func, kwargs, *args)
            else:
                key = funcname(func) + "-" + str(uuid.uuid4())

        skey = stringify(key)

        with self._refcount_lock:
            if skey in self.futures:
                return Future(key, self, inform=False)

        if allow_other_workers and workers is None:
            raise ValueError("Only use allow_other_workers= if using workers=")

        if isinstance(workers, (str, Number)):
            workers = [workers]

        if kwargs:
            dsk = {skey: (apply, func, list(args), kwargs)}
        else:
            dsk = {skey: (func,) + tuple(args)}

        futures = self._graph_to_futures(
            dsk,
            [skey],
            workers=workers,
            allow_other_workers=allow_other_workers,
            priority={skey: 0},
            user_priority=priority,
            resources=resources,
            retries=retries,
            fifo_timeout=fifo_timeout,
            actors=actor,
        )

        logger.debug("Submit %s(...), %s", funcname(func), key)

        return futures[skey]

    def map(
        self,
        func,
        *iterables,
        key=None,
        workers=None,
        retries=None,
        resources=None,
        priority=0,
        allow_other_workers=False,
        fifo_timeout="100 ms",
        actor=False,
        actors=False,
        pure=None,
        batch_size=None,
        **kwargs,
    ):
        """Map a function on a sequence of arguments

        Arguments can be normal objects or Futures

        Parameters
        ----------
        func : callable
            Callable to be scheduled for execution. If ``func`` returns a coroutine, it
            will be run on the main event loop of a worker. Otherwise ``func`` will be
            run in a worker's task executor pool (see ``Worker.executors`` for more
            information.)
        iterables : Iterables
            List-like objects to map over.  They should have the same length.
        key : str, list
            Prefix for task names if string.  Explicit names if list.
        workers : string or iterable of strings
            A set of worker hostnames on which computations may be performed.
            Leave empty to default to all workers (common case)
        retries : int (default to 0)
            Number of allowed automatic retries if a task fails
        resources : dict (defaults to {})
            Defines the `resources` each instance of this mapped task requires
            on the worker; e.g. ``{'GPU': 2}``.
            See :doc:`worker resources <resources>` for details on defining
            resources.
        priority : Number
            Optional prioritization of task.  Zero is default.
            Higher priorities take precedence
        allow_other_workers : bool (defaults to False)
            Used with `workers`. Indicates whether or not the computations
            may be performed on workers that are not in the `workers` set(s).
        fifo_timeout : str timedelta (default '100ms')
            Allowed amount of time between calls to consider the same priority
        actor : bool (default False)
            Whether these tasks should exist on the worker as stateful actors.
            See :doc:`actors` for additional details.
        actors : bool (default False)
            Alias for `actor`
        pure : bool (defaults to True)
            Whether or not the function is pure.  Set ``pure=False`` for
            impure functions like ``np.random.random``.
            See :ref:`pure functions` for more details.
        batch_size : int, optional
            Submit tasks to the scheduler in batches of (at most)
            ``batch_size``.
            Larger batch sizes can be useful for very large ``iterables``,
            as the cluster can start processing tasks while later ones are
            submitted asynchronously.
        **kwargs : dict
            Extra keyword arguments to send to the function.
            Large values will be included explicitly in the task graph.

        Examples
        --------
        >>> L = client.map(func, sequence)  # doctest: +SKIP

        Returns
        -------
        List, iterator, or Queue of futures, depending on the type of the
        inputs.

        See Also
        --------
        Client.submit : Submit a single function
        """
        if not callable(func):
            raise TypeError("First input to map must be a callable function")

        if all(isinstance(it, pyQueue) for it in iterables) or all(
            isinstance(i, Iterator) for i in iterables
        ):
            raise TypeError(
                "Dask no longer supports mapping over Iterators or Queues."
                "Consider using a normal for loop and Client.submit"
            )
        total_length = sum(len(x) for x in iterables)

        if batch_size and batch_size > 1 and total_length > batch_size:
            batches = list(
                zip(*(partition_all(batch_size, iterable) for iterable in iterables))
            )
            if isinstance(key, list):
                keys = [list(element) for element in partition_all(batch_size, key)]
            else:
                keys = [key for _ in range(len(batches))]
            return sum(
                (
                    self.map(
                        func,
                        *batch,
                        key=key,
                        workers=workers,
                        retries=retries,
                        priority=priority,
                        allow_other_workers=allow_other_workers,
                        fifo_timeout=fifo_timeout,
                        resources=resources,
                        actor=actor,
                        actors=actors,
                        pure=pure,
                        **kwargs,
                    )
                    for key, batch in zip(keys, batches)
                ),
                [],
            )

        key = key or funcname(func)
        actor = actor or actors
        if pure is None:
            pure = not actor

        if allow_other_workers and workers is None:
            raise ValueError("Only use allow_other_workers= if using workers=")

        iterables = list(zip(*zip(*iterables)))
        if isinstance(key, list):
            keys = key
        else:
            if pure:
                keys = [
                    key + "-" + tokenize(func, kwargs, *args)
                    for args in zip(*iterables)
                ]
            else:
                uid = str(uuid.uuid4())
                keys = (
                    [
                        key + "-" + uid + "-" + str(i)
                        for i in range(min(map(len, iterables)))
                    ]
                    if iterables
                    else []
                )

        if not kwargs:
            dsk = {key: (func,) + args for key, args in zip(keys, zip(*iterables))}
        else:
            kwargs2 = {}
            dsk = {}
            for k, v in kwargs.items():
                if sizeof(v) > 1e5:
                    vv = dask.delayed(v)
                    kwargs2[k] = vv._key
                    dsk.update(vv.dask)
                else:
                    kwargs2[k] = v
            dsk.update(
                {
                    key: (apply, func, (tuple, list(args)), kwargs2)
                    for key, args in zip(keys, zip(*iterables))
                }
            )

        if isinstance(workers, (str, Number)):
            workers = [workers]
        if workers is not None and not isinstance(workers, (list, set)):
            raise TypeError("Workers must be a list or set of workers or None")

        internal_priority = dict(zip(keys, range(len(keys))))

        futures = self._graph_to_futures(
            dsk,
            keys,
            workers=workers,
            allow_other_workers=allow_other_workers,
            priority=internal_priority,
            resources=resources,
            retries=retries,
            user_priority=priority,
            fifo_timeout=fifo_timeout,
            actors=actor,
        )
        logger.debug("map(%s, ...)", funcname(func))

        return [futures[stringify(k)] for k in keys]

    async def _gather(self, futures, errors="raise", direct=None, local_worker=None):
        unpacked, future_set = unpack_remotedata(futures, byte_keys=True)
        mismatched_futures = [f for f in future_set if f.client is not self]
        if mismatched_futures:
            raise ValueError(
                "Cannot gather Futures created by another client. "
                f"These are the {len(mismatched_futures)} (out of {len(futures)}) mismatched Futures and their client IDs "
                f"(this client is {self.id}): "
                f"{ {f: f.client.id for f in mismatched_futures} }"
            )
        keys = [stringify(future.key) for future in future_set]
        bad_data = dict()
        data = {}

        if direct is None:
            direct = self.direct_to_workers
        if direct is None:
            try:
                w = get_worker()
            except Exception:
                direct = False
            else:
                if w.scheduler.address == self.scheduler.address:
                    direct = True

        async def wait(k):
            """Want to stop the All(...) early if we find an error"""
            try:
                st = self.futures[k]
            except KeyError:
                raise AllExit()
            else:
                await st.wait()
            if st.status != "finished" and errors == "raise":
                raise AllExit()

        while True:
            logger.debug("Waiting on futures to clear before gather")

            with suppress(AllExit):
                await distributed.utils.All(
                    [wait(key) for key in keys if key in self.futures],
                    quiet_exceptions=AllExit,
                )

            failed = ("error", "cancelled")

            exceptions = set()
            bad_keys = set()
            for key in keys:
                if key not in self.futures or self.futures[key].status in failed:
                    exceptions.add(key)
                    if errors == "raise":
                        try:
                            st = self.futures[key]
                            exception = st.exception
                            traceback = st.traceback
                        except (KeyError, AttributeError):
                            exc = CancelledError(key)
                        else:
                            raise exception.with_traceback(traceback)
                        raise exc
                    if errors == "skip":
                        bad_keys.add(key)
                        bad_data[key] = None
                    else:  # pragma: no cover
                        raise ValueError("Bad value, `errors=%s`" % errors)

            keys = [k for k in keys if k not in bad_keys and k not in data]

            if local_worker:  # look inside local worker
                data.update(
                    {k: local_worker.data[k] for k in keys if k in local_worker.data}
                )
                keys = [k for k in keys if k not in data]

            # We now do an actual remote communication with workers or scheduler
            if self._gather_future:  # attach onto another pending gather request
                self._gather_keys |= set(keys)
                response = await self._gather_future
            else:  # no one waiting, go ahead
                self._gather_keys = set(keys)
                future = asyncio.ensure_future(
                    self._gather_remote(direct, local_worker)
                )
                if self._gather_keys is None:
                    self._gather_future = None
                else:
                    self._gather_future = future
                response = await future

            if response["status"] == "error":
                log = logger.warning if errors == "raise" else logger.debug
                log(
                    "Couldn't gather %s keys, rescheduling %s",
                    len(response["keys"]),
                    response["keys"],
                )
                for key in response["keys"]:
                    self._send_to_scheduler({"op": "report-key", "key": key})
                for key in response["keys"]:
                    try:
                        self.futures[key].reset()
                    except KeyError:  # TODO: verify that this is safe
                        pass
            else:  # pragma: no cover
                break

        if bad_data and errors == "skip" and isinstance(unpacked, list):
            unpacked = [f for f in unpacked if f not in bad_data]

        data.update(response["data"])
        result = pack_data(unpacked, merge(data, bad_data))
        return result

    async def _gather_remote(self, direct, local_worker):
        """Perform gather with workers or scheduler

        This method exists to limit and batch many concurrent gathers into a
        few.  In controls access using a Tornado semaphore, and picks up keys
        from other requests made recently.
        """
        async with self._gather_semaphore:
            keys = list(self._gather_keys)
            self._gather_keys = None  # clear state, these keys are being sent off
            self._gather_future = None

            if direct or local_worker:  # gather directly from workers
                who_has = await retry_operation(self.scheduler.who_has, keys=keys)
                data2, missing_keys, missing_workers = await gather_from_workers(
                    who_has, rpc=self.rpc, close=False
                )
                response = {"status": "OK", "data": data2}
                if missing_keys:
                    keys2 = [key for key in keys if key not in data2]
                    response = await retry_operation(self.scheduler.gather, keys=keys2)
                    if response["status"] == "OK":
                        response["data"].update(data2)

            else:  # ask scheduler to gather data for us
                response = await retry_operation(self.scheduler.gather, keys=keys)

        return response

    def gather(self, futures, errors="raise", direct=None, asynchronous=None):
        """Gather futures from distributed memory

        Accepts a future, nested container of futures, iterator, or queue.
        The return type will match the input type.

        Parameters
        ----------
        futures : Collection of futures
            This can be a possibly nested collection of Future objects.
            Collections can be lists, sets, or dictionaries
        errors : string
            Either 'raise' or 'skip' if we should raise if a future has erred
            or skip its inclusion in the output collection
        direct : boolean
            Whether or not to connect directly to the workers, or to ask
            the scheduler to serve as intermediary.  This can also be set when
            creating the Client.
        asynchronous: bool
            If True the client is in asynchronous mode

        Returns
        -------
        results: a collection of the same type as the input, but now with
        gathered results rather than futures

        Examples
        --------
        >>> from operator import add  # doctest: +SKIP
        >>> c = Client('127.0.0.1:8787')  # doctest: +SKIP
        >>> x = c.submit(add, 1, 2)  # doctest: +SKIP
        >>> c.gather(x)  # doctest: +SKIP
        3
        >>> c.gather([x, [x], x])  # support lists and dicts # doctest: +SKIP
        [3, [3], 3]

        See Also
        --------
        Client.scatter : Send data out to cluster
        """
        if isinstance(futures, pyQueue):
            raise TypeError(
                "Dask no longer supports gathering over Iterators and Queues. "
                "Consider using a normal for loop and Client.submit/gather"
            )

        elif isinstance(futures, Iterator):
            return (self.gather(f, errors=errors, direct=direct) for f in futures)
        else:
            if hasattr(thread_state, "execution_state"):  # within worker task
                local_worker = thread_state.execution_state["worker"]
            else:
                local_worker = None
            return self.sync(
                self._gather,
                futures,
                errors=errors,
                direct=direct,
                local_worker=local_worker,
                asynchronous=asynchronous,
            )

    async def _scatter(
        self,
        data,
        workers=None,
        broadcast=False,
        direct=None,
        local_worker=None,
        timeout=no_default,
        hash=True,
    ):
        if timeout == no_default:
            timeout = self._timeout
        if isinstance(workers, (str, Number)):
            workers = [workers]
        if isinstance(data, dict) and not all(
            isinstance(k, (bytes, str)) for k in data
        ):
            d = await self._scatter(keymap(stringify, data), workers, broadcast)
            return {k: d[stringify(k)] for k in data}

        if isinstance(data, type(range(0))):
            data = list(data)
        input_type = type(data)
        names = False
        unpack = False
        if isinstance(data, Iterator):
            data = list(data)
        if isinstance(data, (set, frozenset)):
            data = list(data)
        if not isinstance(data, (dict, list, tuple, set, frozenset)):
            unpack = True
            data = [data]
        if isinstance(data, (list, tuple)):
            if hash:
                names = [type(x).__name__ + "-" + tokenize(x) for x in data]
            else:
                names = [type(x).__name__ + "-" + uuid.uuid4().hex for x in data]
            data = dict(zip(names, data))

        assert isinstance(data, dict)

        types = valmap(type, data)

        if direct is None:
            direct = self.direct_to_workers
        if direct is None:
            try:
                w = get_worker()
            except Exception:
                direct = False
            else:
                if w.scheduler.address == self.scheduler.address:
                    direct = True

        if local_worker:  # running within task
            local_worker.update_data(data=data)

            await self.scheduler.update_data(
                who_has={key: [local_worker.address] for key in data},
                nbytes=valmap(sizeof, data),
                client=self.id,
            )

        else:
            data2 = valmap(to_serialize, data)
            if direct:
                nthreads = None
                start = time()
                while not nthreads:
                    if nthreads is not None:
                        await asyncio.sleep(0.1)
                    if time() > start + timeout:
                        raise TimeoutError("No valid workers found")
                    # Exclude paused and closing_gracefully workers
                    nthreads = await self.scheduler.ncores_running(workers=workers)
                if not nthreads:  # pragma: no cover
                    raise ValueError("No valid workers found")

                _, who_has, nbytes = await scatter_to_workers(
                    nthreads, data2, rpc=self.rpc
                )

                await self.scheduler.update_data(
                    who_has=who_has, nbytes=nbytes, client=self.id
                )
            else:
                await self.scheduler.scatter(
                    data=data2,
                    workers=workers,
                    client=self.id,
                    broadcast=broadcast,
                    timeout=timeout,
                )

        out = {k: Future(k, self, inform=False) for k in data}
        for key, typ in types.items():
            self.futures[key].finish(type=typ)

        if direct and broadcast:
            n = None if broadcast is True else broadcast
            await self._replicate(list(out.values()), workers=workers, n=n)

        if issubclass(input_type, (list, tuple, set, frozenset)):
            out = input_type(out[k] for k in names)

        if unpack:
            assert len(out) == 1
            out = list(out.values())[0]
        return out

    def scatter(
        self,
        data,
        workers=None,
        broadcast=False,
        direct=None,
        hash=True,
        timeout=no_default,
        asynchronous=None,
    ):
        """Scatter data into distributed memory

        This moves data from the local client process into the workers of the
        distributed scheduler.  Note that it is often better to submit jobs to
        your workers to have them load the data rather than loading data
        locally and then scattering it out to them.

        Parameters
        ----------
        data : list, dict, or object
            Data to scatter out to workers.  Output type matches input type.
        workers : list of tuples (optional)
            Optionally constrain locations of data.
            Specify workers as hostname/port pairs, e.g.
            ``('127.0.0.1', 8787)``.
        broadcast : bool (defaults to False)
            Whether to send each data element to all workers.
            By default we round-robin based on number of cores.

            .. note::
               Setting this flag to True is incompatible with the Active Memory
               Manager's :ref:`ReduceReplicas` policy. If you wish to use it, you must
               first disable the policy or disable the AMM entirely.
        direct : bool (defaults to automatically check)
            Whether or not to connect directly to the workers, or to ask
            the scheduler to serve as intermediary.  This can also be set when
            creating the Client.
        hash : bool (optional)
            Whether or not to hash data to determine key.
            If False then this uses a random key
        timeout : number, optional
            Time in seconds after which to raise a
            ``dask.distributed.TimeoutError``
        asynchronous: bool
            If True the client is in asynchronous mode

        Returns
        -------
        List, dict, iterator, or queue of futures matching the type of input.

        Examples
        --------
        >>> c = Client('127.0.0.1:8787')  # doctest: +SKIP
        >>> c.scatter(1) # doctest: +SKIP
        <Future: status: finished, key: c0a8a20f903a4915b94db8de3ea63195>

        >>> c.scatter([1, 2, 3])  # doctest: +SKIP
        [<Future: status: finished, key: c0a8a20f903a4915b94db8de3ea63195>,
         <Future: status: finished, key: 58e78e1b34eb49a68c65b54815d1b158>,
         <Future: status: finished, key: d3395e15f605bc35ab1bac6341a285e2>]

        >>> c.scatter({'x': 1, 'y': 2, 'z': 3})  # doctest: +SKIP
        {'x': <Future: status: finished, key: x>,
         'y': <Future: status: finished, key: y>,
         'z': <Future: status: finished, key: z>}

        Constrain location of data to subset of workers

        >>> c.scatter([1, 2, 3], workers=[('hostname', 8788)])   # doctest: +SKIP

        Broadcast data to all workers

        >>> [future] = c.scatter([element], broadcast=True)  # doctest: +SKIP

        Send scattered data to parallelized function using client futures
        interface

        >>> data = c.scatter(data, broadcast=True)  # doctest: +SKIP
        >>> res = [c.submit(func, data, i) for i in range(100)]

        See Also
        --------
        Client.gather : Gather data back to local process
        """
        if timeout == no_default:
            timeout = self._timeout
        if isinstance(data, pyQueue) or isinstance(data, Iterator):
            raise TypeError(
                "Dask no longer supports mapping over Iterators or Queues."
                "Consider using a normal for loop and Client.submit"
            )

        if hasattr(thread_state, "execution_state"):  # within worker task
            local_worker = thread_state.execution_state["worker"]
        else:
            local_worker = None
        return self.sync(
            self._scatter,
            data,
            workers=workers,
            broadcast=broadcast,
            direct=direct,
            local_worker=local_worker,
            timeout=timeout,
            asynchronous=asynchronous,
            hash=hash,
        )

    async def _cancel(self, futures, force=False):
        keys = list({stringify(f.key) for f in futures_of(futures)})
        await self.scheduler.cancel(keys=keys, client=self.id, force=force)
        for k in keys:
            st = self.futures.pop(k, None)
            if st is not None:
                st.cancel()

    def cancel(self, futures, asynchronous=None, force=False):
        """
        Cancel running futures

        This stops future tasks from being scheduled if they have not yet run
        and deletes them if they have already run.  After calling, this result
        and all dependent results will no longer be accessible

        Parameters
        ----------
        futures : List[Future]
            The list of Futures
        asynchronous: bool
            If True the client is in asynchronous mode
        force : boolean (False)
            Cancel this future even if other clients desire it
        """
        return self.sync(self._cancel, futures, asynchronous=asynchronous, force=force)

    async def _retry(self, futures):
        keys = list({stringify(f.key) for f in futures_of(futures)})
        response = await self.scheduler.retry(keys=keys, client=self.id)
        for key in response:
            st = self.futures[key]
            st.retry()

    def retry(self, futures, asynchronous=None):
        """
        Retry failed futures

        Parameters
        ----------
        futures : list of Futures
            The list of Futures
        asynchronous: bool
            If True the client is in asynchronous mode
        """
        return self.sync(self._retry, futures, asynchronous=asynchronous)

    @log_errors
    async def _publish_dataset(self, *args, name=None, override=False, **kwargs):
        coroutines = []

        def add_coro(name, data):
            keys = [stringify(f.key) for f in futures_of(data)]
            coroutines.append(
                self.scheduler.publish_put(
                    keys=keys,
                    name=name,
                    data=to_serialize(data),
                    override=override,
                    client=self.id,
                )
            )

        if name:
            if len(args) == 0:
                raise ValueError(
                    "If name is provided, expecting call signature like"
                    " publish_dataset(df, name='ds')"
                )
            # in case this is a singleton, collapse it
            elif len(args) == 1:
                args = args[0]
            add_coro(name, args)

        for name, data in kwargs.items():
            add_coro(name, data)

        await asyncio.gather(*coroutines)

    def publish_dataset(self, *args, **kwargs):
        """
        Publish named datasets to scheduler

        This stores a named reference to a dask collection or list of futures
        on the scheduler.  These references are available to other Clients
        which can download the collection or futures with ``get_dataset``.

        Datasets are not immediately computed.  You may wish to call
        ``Client.persist`` prior to publishing a dataset.

        Parameters
        ----------
        args : list of objects to publish as name
        kwargs : dict
            named collections to publish on the scheduler

        Examples
        --------
        Publishing client:

        >>> df = dd.read_csv('s3://...')  # doctest: +SKIP
        >>> df = c.persist(df) # doctest: +SKIP
        >>> c.publish_dataset(my_dataset=df)  # doctest: +SKIP

        Alternative invocation
        >>> c.publish_dataset(df, name='my_dataset')

        Receiving client:

        >>> c.list_datasets()  # doctest: +SKIP
        ['my_dataset']
        >>> df2 = c.get_dataset('my_dataset')  # doctest: +SKIP

        Returns
        -------
        None

        See Also
        --------
        Client.list_datasets
        Client.get_dataset
        Client.unpublish_dataset
        Client.persist
        """
        return self.sync(self._publish_dataset, *args, **kwargs)

    def unpublish_dataset(self, name, **kwargs):
        """
        Remove named datasets from scheduler

        Parameters
        ----------
        name : str
            The name of the dataset to unpublish

        Examples
        --------
        >>> c.list_datasets()  # doctest: +SKIP
        ['my_dataset']
        >>> c.unpublish_dataset('my_dataset')  # doctest: +SKIP
        >>> c.list_datasets()  # doctest: +SKIP
        []

        See Also
        --------
        Client.publish_dataset
        """
        return self.sync(self.scheduler.publish_delete, name=name, **kwargs)

    def list_datasets(self, **kwargs):
        """
        List named datasets available on the scheduler

        See Also
        --------
        Client.publish_dataset
        Client.get_dataset
        """
        return self.sync(self.scheduler.publish_list, **kwargs)

    async def _get_dataset(self, name, default=no_default):
        with self.as_current():
            out = await self.scheduler.publish_get(name=name, client=self.id)

        if out is None:
            if default is no_default:
                raise KeyError(f"Dataset '{name}' not found")
            else:
                return default
        return out["data"]

    def get_dataset(self, name, default=no_default, **kwargs):
        """
        Get named dataset from the scheduler if present.
        Return the default or raise a KeyError if not present.

        Parameters
        ----------
        name : str
            name of the dataset to retrieve
        default : str
            optional, not set by default
            If set, do not raise a KeyError if the name is not present but
            return this default
        kwargs : dict
            additional keyword arguments to _get_dataset

        Returns
        -------
        The dataset from the scheduler, if present

        See Also
        --------
        Client.publish_dataset
        Client.list_datasets
        """
        return self.sync(self._get_dataset, name, default=default, **kwargs)

    async def _run_on_scheduler(self, function, *args, wait=True, **kwargs):
        response = await self.scheduler.run_function(
            function=dumps(function),
            args=dumps(args),
            kwargs=dumps(kwargs),
            wait=wait,
        )
        if response["status"] == "error":
            typ, exc, tb = clean_exception(**response)
            raise exc.with_traceback(tb)
        else:
            return response["result"]

    def run_on_scheduler(self, function, *args, **kwargs):
        """Run a function on the scheduler process

        This is typically used for live debugging.  The function should take a
        keyword argument ``dask_scheduler=``, which will be given the scheduler
        object itself.

        Parameters
        ----------
        function : callable
            The function to run on the scheduler process
        *args : tuple
            Optional arguments for the function
        **kwargs : dict
            Optional keyword arguments for the function

        Examples
        --------
        >>> def get_number_of_tasks(dask_scheduler=None):
        ...     return len(dask_scheduler.tasks)

        >>> client.run_on_scheduler(get_number_of_tasks)  # doctest: +SKIP
        100

        Run asynchronous functions in the background:

        >>> async def print_state(dask_scheduler):  # doctest: +SKIP
        ...    while True:
        ...        print(dask_scheduler.status)
        ...        await asyncio.sleep(1)

        >>> c.run(print_state, wait=False)  # doctest: +SKIP

        See Also
        --------
        Client.run : Run a function on all workers
        """
        return self.sync(self._run_on_scheduler, function, *args, **kwargs)

    async def _run(
        self,
        function,
        *args,
        nanny: bool = False,
        workers: list[str] | None = None,
        wait: bool = True,
        on_error: Literal["raise", "return", "ignore"] = "raise",
        **kwargs,
    ):
        responses = await self.scheduler.broadcast(
            msg=dict(
                op="run",
                function=dumps(function),
                args=dumps(args),
                wait=wait,
                kwargs=dumps(kwargs),
            ),
            workers=workers,
            nanny=nanny,
            on_error="return_pickle",
        )
        results = {}
        for key, resp in responses.items():
            if isinstance(resp, bytes):
                # Pickled RPC exception
                exc = loads(resp)
                assert isinstance(exc, Exception)
            elif resp["status"] == "error":
                # Exception raised by the remote function
                _, exc, tb = clean_exception(**resp)
                exc = exc.with_traceback(tb)
            else:
                assert resp["status"] == "OK"
                results[key] = resp["result"]
                continue

            if on_error == "raise":
                raise exc
            elif on_error == "return":
                results[key] = exc
            elif on_error != "ignore":
                raise ValueError(
                    "on_error must be 'raise', 'return', or 'ignore'; "
                    f"got {on_error!r}"
                )

        if wait:
            return results

    def run(
        self,
        function,
        *args,
        workers: list[str] | None = None,
        wait: bool = True,
        nanny: bool = False,
        on_error: Literal["raise", "return", "ignore"] = "raise",
        **kwargs,
    ):
        """
        Run a function on all workers outside of task scheduling system

        This calls a function on all currently known workers immediately,
        blocks until those results come back, and returns the results
        asynchronously as a dictionary keyed by worker address.  This method
        is generally used for side effects such as collecting diagnostic
        information or installing libraries.

        If your function takes an input argument named ``dask_worker`` then
        that variable will be populated with the worker itself.

        Parameters
        ----------
        function : callable
            The function to run
        *args : tuple
            Optional arguments for the remote function
        **kwargs : dict
            Optional keyword arguments for the remote function
        workers : list
            Workers on which to run the function. Defaults to all known
            workers.
        wait : boolean (optional)
            If the function is asynchronous whether or not to wait until that
            function finishes.
        nanny : bool, default False
            Whether to run ``function`` on the nanny. By default, the function
            is run on the worker process.  If specified, the addresses in
            ``workers`` should still be the worker addresses, not the nanny addresses.
        on_error: "raise" | "return" | "ignore"
            If the function raises an error on a worker:

            raise
                (default) Re-raise the exception on the client.
                The output from other workers will be lost.
            return
                Return the Exception object instead of the function output for
                the worker
            ignore
                Ignore the exception and remove the worker from the result dict

        Examples
        --------
        >>> c.run(os.getpid)  # doctest: +SKIP
        {'192.168.0.100:9000': 1234,
         '192.168.0.101:9000': 4321,
         '192.168.0.102:9000': 5555}

        Restrict computation to particular workers with the ``workers=``
        keyword argument.

        >>> c.run(os.getpid, workers=['192.168.0.100:9000',
        ...                           '192.168.0.101:9000'])  # doctest: +SKIP
        {'192.168.0.100:9000': 1234,
         '192.168.0.101:9000': 4321}

        >>> def get_status(dask_worker):
        ...     return dask_worker.status

        >>> c.run(get_status)  # doctest: +SKIP
        {'192.168.0.100:9000': 'running',
         '192.168.0.101:9000': 'running}

        Run asynchronous functions in the background:

        >>> async def print_state(dask_worker):  # doctest: +SKIP
        ...    while True:
        ...        print(dask_worker.status)
        ...        await asyncio.sleep(1)

        >>> c.run(print_state, wait=False)  # doctest: +SKIP
        """
        return self.sync(
            self._run,
            function,
            *args,
            workers=workers,
            wait=wait,
            nanny=nanny,
            on_error=on_error,
            **kwargs,
        )

    @staticmethod
    def _get_computation_code(stacklevel: int | None = None) -> str:
        """Walk up the stack to the user code and extract the code surrounding
        the compute/submit/persist call. All modules encountered which are
        ignored through the option
        `distributed.diagnostics.computations.ignore-modules` will be ignored.
        This can be used to exclude commonly used libraries which wrap
        dask/distributed compute calls.

        ``stacklevel`` may be used to explicitly indicate from which frame on
        the stack to get the source code.
        """
        ignore_modules = dask.config.get(
            "distributed.diagnostics.computations.ignore-modules"
        )
        if not isinstance(ignore_modules, list):
            raise TypeError(
                "Ignored modules must be a list. Instead got "
                f"({type(ignore_modules)}, {ignore_modules})"
            )
        if stacklevel is None:
            pattern: re.Pattern | None
            if ignore_modules:
                pattern = re.compile("|".join([f"(?:{mod})" for mod in ignore_modules]))
            else:
                pattern = None
        else:
            # stacklevel 0 or less - shows dask internals which likely isn't helpful
            stacklevel = stacklevel if stacklevel > 0 else 1

        for i, (fr, _) in enumerate(traceback.walk_stack(sys._getframe().f_back), 1):
            if stacklevel is not None:
                if i != stacklevel:
                    continue
            elif pattern is not None and (
                pattern.match(fr.f_globals.get("__name__", ""))
                or fr.f_code.co_name in ("<listcomp>", "<dictcomp>")
            ):
                continue
            try:
                return inspect.getsource(fr)
            except OSError:
                # Try to fine the source if we are in %%time or %%timeit magic.
                if (
                    fr.f_code.co_filename in {"<timed exec>", "<magic-timeit>"}
                    and "IPython" in sys.modules
                ):
                    from IPython import get_ipython

                    ip = get_ipython()
                    if ip is not None:
                        # The current cell
                        return ip.history_manager._i00
                break
        return "<Code not available>"

    def _graph_to_futures(
        self,
        dsk,
        keys,
        workers=None,
        allow_other_workers=None,
        priority=None,
        user_priority=0,
        resources=None,
        retries=None,
        fifo_timeout=0,
        actors=None,
    ):
        with self._refcount_lock:
            if actors is not None and actors is not True and actors is not False:
                actors = list(self._expand_key(actors))

            # Make sure `dsk` is a high level graph
            if not isinstance(dsk, HighLevelGraph):
                dsk = HighLevelGraph.from_collections(id(dsk), dsk, dependencies=())

            annotations = {}
            if user_priority:
                annotations["priority"] = user_priority
            if workers:
                if not isinstance(workers, (list, tuple, set)):
                    workers = [workers]
                annotations["workers"] = workers
            if retries:
                annotations["retries"] = retries
            if allow_other_workers not in (True, False, None):
                raise TypeError("allow_other_workers= must be True, False, or None")
            if allow_other_workers:
                annotations["allow_other_workers"] = allow_other_workers
            if resources:
                annotations["resources"] = resources

            # Merge global and local annotations
            annotations = merge(dask.config.get("annotations", {}), annotations)

            # Pack the high level graph before sending it to the scheduler
            keyset = set(keys)
            dsk = dsk.__dask_distributed_pack__(self, keyset, annotations)

            # Create futures before sending graph (helps avoid contention)
            futures = {key: Future(key, self, inform=False) for key in keyset}

            self._send_to_scheduler(
                {
                    "op": "update-graph-hlg",
                    "hlg": dsk,
                    "keys": list(map(stringify, keys)),
                    "priority": priority,
                    "submitting_task": getattr(thread_state, "key", None),
                    "fifo_timeout": fifo_timeout,
                    "actors": actors,
                    "code": self._get_computation_code(),
                }
            )
            return futures

    def get(
        self,
        dsk,
        keys,
        workers=None,
        allow_other_workers=None,
        resources=None,
        sync=True,
        asynchronous=None,
        direct=None,
        retries=None,
        priority=0,
        fifo_timeout="60s",
        actors=None,
        **kwargs,
    ):
        """Compute dask graph

        Parameters
        ----------
        dsk : dict
        keys : object, or nested lists of objects
        workers : string or iterable of strings
            A set of worker addresses or hostnames on which computations may be
            performed. Leave empty to default to all workers (common case)
        allow_other_workers : bool (defaults to False)
            Used with ``workers``. Indicates whether or not the computations
            may be performed on workers that are not in the `workers` set(s).
        resources : dict (defaults to {})
            Defines the ``resources`` each instance of this mapped task
            requires on the worker; e.g. ``{'GPU': 2}``.
            See :doc:`worker resources <resources>` for details on defining
            resources.
        sync : bool (optional)
            Returns Futures if False or concrete values if True (default).
        asynchronous: bool
            If True the client is in asynchronous mode
        direct : bool
            Whether or not to connect directly to the workers, or to ask
            the scheduler to serve as intermediary.  This can also be set when
            creating the Client.
        retries : int (default to 0)
            Number of allowed automatic retries if computing a result fails
        priority : Number
            Optional prioritization of task.  Zero is default.
            Higher priorities take precedence
        fifo_timeout : timedelta str (defaults to '60s')
            Allowed amount of time between calls to consider the same priority
        actors : bool or dict (default None)
            Whether these tasks should exist on the worker as stateful actors.
            Specified on a global (True/False) or per-task (``{'x': True,
            'y': False}``) basis. See :doc:`actors` for additional details.


        Returns
        -------
        results
            If 'sync' is True, returns the results. Otherwise, returns the
            known data packed
            If 'sync' is False, returns the known data. Otherwise, returns
            the results

        Examples
        --------
        >>> from operator import add  # doctest: +SKIP
        >>> c = Client('127.0.0.1:8787')  # doctest: +SKIP
        >>> c.get({'x': (add, 1, 2)}, 'x')  # doctest: +SKIP
        3

        See Also
        --------
        Client.compute : Compute asynchronous collections
        """
        futures = self._graph_to_futures(
            dsk,
            keys=set(flatten([keys])),
            workers=workers,
            allow_other_workers=allow_other_workers,
            resources=resources,
            fifo_timeout=fifo_timeout,
            retries=retries,
            user_priority=priority,
            actors=actors,
        )
        packed = pack_data(keys, futures)
        if sync:
            if getattr(thread_state, "key", False):
                try:
                    secede()
                    should_rejoin = True
                except Exception:
                    should_rejoin = False
            try:
                results = self.gather(packed, asynchronous=asynchronous, direct=direct)
            finally:
                for f in futures.values():
                    f.release()
                if getattr(thread_state, "key", False) and should_rejoin:
                    rejoin()
            return results
        return packed

    def _optimize_insert_futures(self, dsk, keys):
        """Replace known keys in dask graph with Futures

        When given a Dask graph that might have overlapping keys with our known
        results we replace the values of that graph with futures.  This can be
        used as an optimization to avoid recomputation.

        This returns the same graph if unchanged but a new graph if any changes
        were necessary.
        """
        with self._refcount_lock:
            changed = False
            for key in list(dsk):
                if stringify(key) in self.futures:
                    if not changed:
                        changed = True
                        dsk = ensure_dict(dsk)
                    dsk[key] = Future(key, self, inform=False)

        if changed:
            dsk, _ = dask.optimization.cull(dsk, keys)

        return dsk

    def normalize_collection(self, collection):
        """
        Replace collection's tasks by already existing futures if they exist

        This normalizes the tasks within a collections task graph against the
        known futures within the scheduler.  It returns a copy of the
        collection with a task graph that includes the overlapping futures.

        Parameters
        ----------
        collection : dask object
            Collection like dask.array or dataframe or dask.value objects

        Returns
        -------
        collection : dask object
            Collection with its tasks replaced with any existing futures.

        Examples
        --------
        >>> len(x.__dask_graph__())  # x is a dask collection with 100 tasks  # doctest: +SKIP
        100
        >>> set(client.futures).intersection(x.__dask_graph__())  # some overlap exists  # doctest: +SKIP
        10

        >>> x = client.normalize_collection(x)  # doctest: +SKIP
        >>> len(x.__dask_graph__())  # smaller computational graph  # doctest: +SKIP
        20

        See Also
        --------
        Client.persist : trigger computation of collection's tasks
        """
        dsk_orig = collection.__dask_graph__()
        dsk = self._optimize_insert_futures(dsk_orig, collection.__dask_keys__())

        if dsk is dsk_orig:
            return collection
        else:
            return redict_collection(collection, dsk)

    def compute(
        self,
        collections,
        sync=False,
        optimize_graph=True,
        workers=None,
        allow_other_workers=False,
        resources=None,
        retries=0,
        priority=0,
        fifo_timeout="60s",
        actors=None,
        traverse=True,
        **kwargs,
    ):
        """Compute dask collections on cluster

        Parameters
        ----------
        collections : iterable of dask objects or single dask object
            Collections like dask.array or dataframe or dask.value objects
        sync : bool (optional)
            Returns Futures if False (default) or concrete values if True
        optimize_graph : bool
            Whether or not to optimize the underlying graphs
        workers : string or iterable of strings
            A set of worker hostnames on which computations may be performed.
            Leave empty to default to all workers (common case)
        allow_other_workers : bool (defaults to False)
            Used with `workers`. Indicates whether or not the computations
            may be performed on workers that are not in the `workers` set(s).
        retries : int (default to 0)
            Number of allowed automatic retries if computing a result fails
        priority : Number
            Optional prioritization of task.  Zero is default.
            Higher priorities take precedence
        fifo_timeout : timedelta str (defaults to '60s')
            Allowed amount of time between calls to consider the same priority
        traverse : bool (defaults to True)
            By default dask traverses builtin python collections looking for
            dask objects passed to ``compute``. For large collections this can
            be expensive. If none of the arguments contain any dask objects,
            set ``traverse=False`` to avoid doing this traversal.
        resources : dict (defaults to {})
            Defines the `resources` each instance of this mapped task requires
            on the worker; e.g. ``{'GPU': 2}``.
            See :doc:`worker resources <resources>` for details on defining
            resources.
        actors : bool or dict (default None)
            Whether these tasks should exist on the worker as stateful actors.
            Specified on a global (True/False) or per-task (``{'x': True,
            'y': False}``) basis. See :doc:`actors` for additional details.
        **kwargs
            Options to pass to the graph optimize calls

        Returns
        -------
        List of Futures if input is a sequence, or a single future otherwise

        Examples
        --------
        >>> from dask import delayed
        >>> from operator import add
        >>> x = delayed(add)(1, 2)
        >>> y = delayed(add)(x, x)
        >>> xx, yy = client.compute([x, y])  # doctest: +SKIP
        >>> xx  # doctest: +SKIP
        <Future: status: finished, key: add-8f6e709446674bad78ea8aeecfee188e>
        >>> xx.result()  # doctest: +SKIP
        3
        >>> yy.result()  # doctest: +SKIP
        6

        Also support single arguments

        >>> xx = client.compute(x)  # doctest: +SKIP

        See Also
        --------
        Client.get : Normal synchronous dask.get function
        """
        if isinstance(collections, (list, tuple, set, frozenset)):
            singleton = False
        else:
            collections = [collections]
            singleton = True

        if traverse:
            collections = tuple(
                dask.delayed(a)
                if isinstance(a, (list, set, tuple, dict, Iterator))
                else a
                for a in collections
            )

        variables = [a for a in collections if dask.is_dask_collection(a)]

        dsk = self.collections_to_dsk(variables, optimize_graph, **kwargs)
        names = ["finalize-%s" % tokenize(v) for v in variables]
        dsk2 = {}
        for i, (name, v) in enumerate(zip(names, variables)):
            func, extra_args = v.__dask_postcompute__()
            keys = v.__dask_keys__()
            if func is single_key and len(keys) == 1 and not extra_args:
                names[i] = keys[0]
            else:
                dsk2[name] = (func, keys) + extra_args

        if not isinstance(dsk, HighLevelGraph):
            dsk = HighLevelGraph.from_collections(id(dsk), dsk, dependencies=())

        # Let's append the finalize graph to dsk
        finalize_name = tokenize(names)
        layers = {finalize_name: dsk2}
        layers.update(dsk.layers)
        dependencies = {finalize_name: set(dsk.layers.keys())}
        dependencies.update(dsk.dependencies)
        dsk = HighLevelGraph(layers, dependencies)

        futures_dict = self._graph_to_futures(
            dsk,
            names,
            workers=workers,
            allow_other_workers=allow_other_workers,
            resources=resources,
            retries=retries,
            user_priority=priority,
            fifo_timeout=fifo_timeout,
            actors=actors,
        )

        i = 0
        futures = []
        for arg in collections:
            if dask.is_dask_collection(arg):
                futures.append(futures_dict[names[i]])
                i += 1
            else:
                futures.append(arg)

        if sync:
            result = self.gather(futures)
        else:
            result = futures

        if singleton:
            return first(result)
        else:
            return result

    def persist(
        self,
        collections,
        optimize_graph=True,
        workers=None,
        allow_other_workers=None,
        resources=None,
        retries=None,
        priority=0,
        fifo_timeout="60s",
        actors=None,
        **kwargs,
    ):
        """Persist dask collections on cluster

        Starts computation of the collection on the cluster in the background.
        Provides a new dask collection that is semantically identical to the
        previous one, but now based off of futures currently in execution.

        Parameters
        ----------
        collections : sequence or single dask object
            Collections like dask.array or dataframe or dask.value objects
        optimize_graph : bool
            Whether or not to optimize the underlying graphs
        workers : string or iterable of strings
            A set of worker hostnames on which computations may be performed.
            Leave empty to default to all workers (common case)
        allow_other_workers : bool (defaults to False)
            Used with `workers`. Indicates whether or not the computations
            may be performed on workers that are not in the `workers` set(s).
        retries : int (default to 0)
            Number of allowed automatic retries if computing a result fails
        priority : Number
            Optional prioritization of task.  Zero is default.
            Higher priorities take precedence
        fifo_timeout : timedelta str (defaults to '60s')
            Allowed amount of time between calls to consider the same priority
        resources : dict (defaults to {})
            Defines the `resources` each instance of this mapped task requires
            on the worker; e.g. ``{'GPU': 2}``.
            See :doc:`worker resources <resources>` for details on defining
            resources.
        actors : bool or dict (default None)
            Whether these tasks should exist on the worker as stateful actors.
            Specified on a global (True/False) or per-task (``{'x': True,
            'y': False}``) basis. See :doc:`actors` for additional details.
        **kwargs
            Options to pass to the graph optimize calls

        Returns
        -------
        List of collections, or single collection, depending on type of input.

        Examples
        --------
        >>> xx = client.persist(x)  # doctest: +SKIP
        >>> xx, yy = client.persist([x, y])  # doctest: +SKIP

        See Also
        --------
        Client.compute
        """
        if isinstance(collections, (tuple, list, set, frozenset)):
            singleton = False
        else:
            singleton = True
            collections = [collections]

        assert all(map(dask.is_dask_collection, collections))

        dsk = self.collections_to_dsk(collections, optimize_graph, **kwargs)

        names = {k for c in collections for k in flatten(c.__dask_keys__())}

        futures = self._graph_to_futures(
            dsk,
            names,
            workers=workers,
            allow_other_workers=allow_other_workers,
            resources=resources,
            retries=retries,
            user_priority=priority,
            fifo_timeout=fifo_timeout,
            actors=actors,
        )

        postpersists = [c.__dask_postpersist__() for c in collections]
        result = [
            func({k: futures[k] for k in flatten(c.__dask_keys__())}, *args)
            for (func, args), c in zip(postpersists, collections)
        ]

        if singleton:
            return first(result)
        else:
            return result

    async def _restart(self, timeout=no_default, wait_for_workers=True):
        if timeout == no_default:
            timeout = self._timeout * 4
        if timeout is not None:
            timeout = parse_timedelta(timeout, "s")

        await self.scheduler.restart(timeout=timeout, wait_for_workers=wait_for_workers)
        return self

    def restart(self, timeout=no_default, 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
        --------
        Scheduler.restart
        Client.restart_workers
        """
        return self.sync(
            self._restart, timeout=timeout, wait_for_workers=wait_for_workers
        )

    async def _restart_workers(
        self, workers: list[str], timeout: int | float | None = None
    ):
        results = await self.scheduler.broadcast(
            msg={"op": "restart", "timeout": timeout}, workers=workers, nanny=True
        )
        timeout_workers = {
            key: value for key, value in results.items() if value == "timed out"
        }
        if timeout_workers:
            raise TimeoutError(
                f"The following workers failed to restart with {timeout} seconds: {list(timeout_workers.keys())}"
            )

    def restart_workers(self, workers: list[str], timeout: int | float | None = None):
        """Restart a specified set of workers

        .. note::

            Only workers being monitored by a :class:`distributed.Nanny` can be restarted.

        See ``Nanny.restart`` for more details.

        Parameters
        ----------
        workers : list[str]
            Workers to restart.
        timeout : int | float | None
            Number of seconds to wait

        Notes
        -----
        This method differs from :meth:`Client.restart` in that this method
        simply restarts the specified set of workers, while ``Client.restart``
        will restart all workers and also reset local state on the cluster
        (e.g. all keys are released).

        Additionally, this method does not gracefully handle tasks that are
        being executed when a worker is restarted. These tasks may fail or have
        their suspicious count incremented.

        Examples
        --------
        You can get information about active workers using the following:

        >>> workers = client.scheduler_info()['workers']

        From that list you may want to select some workers to restart

        >>> client.restart_workers(workers=['tcp://address:port', ...])

        See Also
        --------
        Client.restart
        """
        info = self.scheduler_info()
        for worker in workers:
            if info["workers"][worker]["nanny"] is None:
                raise ValueError(
                    f"Restarting workers requires a nanny to be used. Worker {worker} has type {info['workers'][worker]['type']}."
                )
        return self.sync(
            self._restart_workers,
            workers=workers,
            timeout=timeout,
        )

    async def _upload_large_file(self, local_filename, remote_filename=None):
        if remote_filename is None:
            remote_filename = os.path.split(local_filename)[1]

        with open(local_filename, "rb") as f:
            data = f.read()

        [future] = await self._scatter([data])
        key = future.key
        await self._replicate(future)

        def dump_to_file(dask_worker=None):
            if not os.path.isabs(remote_filename):
                fn = os.path.join(dask_worker.local_directory, remote_filename)
            else:
                fn = remote_filename
            with open(fn, "wb") as f:
                f.write(dask_worker.data[key])

            return len(dask_worker.data[key])

        response = await self._run(dump_to_file)

        assert all(len(data) == v for v in response.values())

    def upload_file(self, filename, **kwargs):
        """Upload local package to workers

        This sends a local file up to all worker nodes.  This file is placed
        into the working directory of the running worker, see config option
        ``temporary-directory`` (defaults to :py:func:`tempfile.gettempdir`).

        This directory will be added to the Python's system path so any .py,
        .egg or .zip  files will be importable.

        Parameters
        ----------
        filename : string
            Filename of .py, .egg or .zip file to send to workers
        **kwargs : dict
            Optional keyword arguments for the function

        Examples
        --------
        >>> client.upload_file('mylibrary.egg')  # doctest: +SKIP
        >>> from mylibrary import myfunc  # doctest: +SKIP
        >>> L = client.map(myfunc, seq)  # doctest: +SKIP
        """
        return self.register_worker_plugin(
            UploadFile(filename),
            name=filename + str(uuid.uuid4()),
        )

    async def _rebalance(self, futures=None, workers=None):
        if futures is not None:
            await _wait(futures)
            keys = list({stringify(f.key) for f in self.futures_of(futures)})
        else:
            keys = None
        result = await self.scheduler.rebalance(keys=keys, workers=workers)
        if result["status"] == "partial-fail":
            raise KeyError(f"Could not rebalance keys: {result['keys']}")
        assert result["status"] == "OK", result

    def rebalance(self, futures=None, workers=None, **kwargs):
        """Rebalance data within network

        Move data between workers to roughly balance memory burden.  This
        either affects a subset of the keys/workers or the entire network,
        depending on keyword arguments.

        For details on the algorithm and configuration options, refer to the matching
        scheduler-side method :meth:`~distributed.scheduler.Scheduler.rebalance`.

        .. 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.

        Parameters
        ----------
        futures : list, optional
            A list of futures to balance, defaults all data
        workers : list, optional
            A list of workers on which to balance, defaults to all workers
        **kwargs : dict
            Optional keyword arguments for the function
        """
        return self.sync(self._rebalance, futures, workers, **kwargs)

    async def _replicate(self, futures, n=None, workers=None, branching_factor=2):
        futures = self.futures_of(futures)
        await _wait(futures)
        keys = {stringify(f.key) for f in futures}
        await self.scheduler.replicate(
            keys=list(keys), n=n, workers=workers, branching_factor=branching_factor
        )

    def replicate(self, futures, n=None, workers=None, branching_factor=2, **kwargs):
        """Set replication of futures within network

        Copy data onto many workers.  This helps to broadcast frequently
        accessed data and can improve resilience.

        This performs a tree copy of the data throughout the network
        individually on each piece of data.  This operation blocks until
        complete.  It does not guarantee replication of data to future workers.

        .. note::
           This method is incompatible with the Active Memory Manager's
           :ref:`ReduceReplicas` policy. If you wish to use it, you must first disable
           the policy or disable the AMM entirely.

        Parameters
        ----------
        futures : list of futures
            Futures we wish to replicate
        n : int, optional
            Number of processes on the cluster on which to replicate the data.
            Defaults to all.
        workers : list of worker addresses
            Workers on which we want to restrict the replication.
            Defaults to all.
        branching_factor : int, optional
            The number of workers that can copy data in each generation
        **kwargs : dict
            Optional keyword arguments for the remote function

        Examples
        --------
        >>> x = c.submit(func, *args)  # doctest: +SKIP
        >>> c.replicate([x])  # send to all workers  # doctest: +SKIP
        >>> c.replicate([x], n=3)  # send to three workers  # doctest: +SKIP
        >>> c.replicate([x], workers=['alice', 'bob'])  # send to specific  # doctest: +SKIP
        >>> c.replicate([x], n=1, workers=['alice', 'bob'])  # send to one of specific workers  # doctest: +SKIP
        >>> c.replicate([x], n=1)  # reduce replications # doctest: +SKIP

        See Also
        --------
        Client.rebalance
        """
        return self.sync(
            self._replicate,
            futures,
            n=n,
            workers=workers,
            branching_factor=branching_factor,
            **kwargs,
        )

    def nthreads(self, workers=None, **kwargs):
        """The number of threads/cores available on each worker node

        Parameters
        ----------
        workers : list (optional)
            A list of workers that we care about specifically.
            Leave empty to receive information about all workers.
        **kwargs : dict
            Optional keyword arguments for the remote function

        Examples
        --------
        >>> c.nthreads()  # doctest: +SKIP
        {'192.168.1.141:46784': 8,
         '192.167.1.142:47548': 8,
         '192.167.1.143:47329': 8,
         '192.167.1.144:37297': 8}

        See Also
        --------
        Client.who_has
        Client.has_what
        """
        if isinstance(workers, tuple) and all(
            isinstance(i, (str, tuple)) for i in workers
        ):
            workers = list(workers)
        if workers is not None and not isinstance(workers, (tuple, list, set)):
            workers = [workers]
        return self.sync(self.scheduler.ncores, workers=workers, **kwargs)

    ncores = nthreads

    def who_has(self, futures=None, **kwargs):
        """The workers storing each future's data

        Parameters
        ----------
        futures : list (optional)
            A list of futures, defaults to all data
        **kwargs : dict
            Optional keyword arguments for the remote function

        Examples
        --------
        >>> x, y, z = c.map(inc, [1, 2, 3])  # doctest: +SKIP
        >>> wait([x, y, z])  # doctest: +SKIP
        >>> c.who_has()  # doctest: +SKIP
        {'inc-1c8dd6be1c21646c71f76c16d09304ea': ['192.168.1.141:46784'],
         'inc-1e297fc27658d7b67b3a758f16bcf47a': ['192.168.1.141:46784'],
         'inc-fd65c238a7ea60f6a01bf4c8a5fcf44b': ['192.168.1.141:46784']}

        >>> c.who_has([x, y])  # doctest: +SKIP
        {'inc-1c8dd6be1c21646c71f76c16d09304ea': ['192.168.1.141:46784'],
         'inc-1e297fc27658d7b67b3a758f16bcf47a': ['192.168.1.141:46784']}

        See Also
        --------
        Client.has_what
        Client.nthreads
        """
        if futures is not None:
            futures = self.futures_of(futures)
            keys = list(map(stringify, {f.key for f in futures}))
        else:
            keys = None

        async def _():
            return WhoHas(await self.scheduler.who_has(keys=keys, **kwargs))

        return self.sync(_)

    def has_what(self, workers=None, **kwargs):
        """Which keys are held by which workers

        This returns the keys of the data that are held in each worker's
        memory.

        Parameters
        ----------
        workers : list (optional)
            A list of worker addresses, defaults to all
        **kwargs : dict
            Optional keyword arguments for the remote function

        Examples
        --------
        >>> x, y, z = c.map(inc, [1, 2, 3])  # doctest: +SKIP
        >>> wait([x, y, z])  # doctest: +SKIP
        >>> c.has_what()  # doctest: +SKIP
        {'192.168.1.141:46784': ['inc-1c8dd6be1c21646c71f76c16d09304ea',
                                 'inc-fd65c238a7ea60f6a01bf4c8a5fcf44b',
                                 'inc-1e297fc27658d7b67b3a758f16bcf47a']}

        See Also
        --------
        Client.who_has
        Client.nthreads
        Client.processing
        """
        if isinstance(workers, tuple) and all(
            isinstance(i, (str, tuple)) for i in workers
        ):
            workers = list(workers)
        if workers is not None and not isinstance(workers, (tuple, list, set)):
            workers = [workers]

        async def _():
            return HasWhat(await self.scheduler.has_what(workers=workers, **kwargs))

        return self.sync(_)

    def processing(self, workers=None):
        """The tasks currently running on each worker

        Parameters
        ----------
        workers : list (optional)
            A list of worker addresses, defaults to all

        Examples
        --------
        >>> x, y, z = c.map(inc, [1, 2, 3])  # doctest: +SKIP
        >>> c.processing()  # doctest: +SKIP
        {'192.168.1.141:46784': ['inc-1c8dd6be1c21646c71f76c16d09304ea',
                                 'inc-fd65c238a7ea60f6a01bf4c8a5fcf44b',
                                 'inc-1e297fc27658d7b67b3a758f16bcf47a']}

        See Also
        --------
        Client.who_has
        Client.has_what
        Client.nthreads
        """
        if isinstance(workers, tuple) and all(
            isinstance(i, (str, tuple)) for i in workers
        ):
            workers = list(workers)
        if workers is not None and not isinstance(workers, (tuple, list, set)):
            workers = [workers]
        return self.sync(self.scheduler.processing, workers=workers)

    def nbytes(self, keys=None, summary=True, **kwargs):
        """The bytes taken up by each key on the cluster

        This is as measured by ``sys.getsizeof`` which may not accurately
        reflect the true cost.

        Parameters
        ----------
        keys : list (optional)
            A list of keys, defaults to all keys
        summary : boolean, (optional)
            Summarize keys into key types
        **kwargs : dict
            Optional keyword arguments for the remote function

        Examples
        --------
        >>> x, y, z = c.map(inc, [1, 2, 3])  # doctest: +SKIP
        >>> c.nbytes(summary=False)  # doctest: +SKIP
        {'inc-1c8dd6be1c21646c71f76c16d09304ea': 28,
         'inc-1e297fc27658d7b67b3a758f16bcf47a': 28,
         'inc-fd65c238a7ea60f6a01bf4c8a5fcf44b': 28}

        >>> c.nbytes(summary=True)  # doctest: +SKIP
        {'inc': 84}

        See Also
        --------
        Client.who_has
        """
        return self.sync(self.scheduler.nbytes, keys=keys, summary=summary, **kwargs)

    def call_stack(self, futures=None, keys=None):
        """The actively running call stack of all relevant keys

        You can specify data of interest either by providing futures or
        collections in the ``futures=`` keyword or a list of explicit keys in
        the ``keys=`` keyword.  If neither are provided then all call stacks
        will be returned.

        Parameters
        ----------
        futures : list (optional)
            List of futures, defaults to all data
        keys : list (optional)
            List of key names, defaults to all data

        Examples
        --------
        >>> df = dd.read_parquet(...).persist()  # doctest: +SKIP
        >>> client.call_stack(df)  # call on collections

        >>> client.call_stack()  # Or call with no arguments for all activity  # doctest: +SKIP
        """
        keys = keys or []
        if futures is not None:
            futures = self.futures_of(futures)
            keys += list(map(stringify, {f.key for f in futures}))
        return self.sync(self.scheduler.call_stack, keys=keys or None)

    def profile(
        self,
        key=None,
        start=None,
        stop=None,
        workers=None,
        merge_workers=True,
        plot=False,
        filename=None,
        server=False,
        scheduler=False,
    ):
        """Collect statistical profiling information about recent work

        Parameters
        ----------
        key : str
            Key prefix to select, this is typically a function name like 'inc'
            Leave as None to collect all data
        start : time
        stop : time
        workers : list
            List of workers to restrict profile information
        server : bool
            If true, return the profile of the worker's administrative thread
            rather than the worker threads.
            This is useful when profiling Dask itself, rather than user code.
        scheduler : bool
            If true, return the profile information from the scheduler's
            administrative thread rather than the workers.
            This is useful when profiling Dask's scheduling itself.
        plot : boolean or string
            Whether or not to return a plot object
        filename : str
            Filename to save the plot

        Examples
        --------
        >>> client.profile()  # call on collections
        >>> client.profile(filename='dask-profile.html')  # save to html file
        """
        return self.sync(
            self._profile,
            key=key,
            workers=workers,
            merge_workers=merge_workers,
            start=start,
            stop=stop,
            plot=plot,
            filename=filename,
            server=server,
            scheduler=scheduler,
        )

    async def _profile(
        self,
        key=None,
        start=None,
        stop=None,
        workers=None,
        merge_workers=True,
        plot=False,
        filename=None,
        server=False,
        scheduler=False,
    ):
        if isinstance(workers, (str, Number)):
            workers = [workers]

        state = await self.scheduler.profile(
            key=key,
            workers=workers,
            merge_workers=merge_workers,
            start=start,
            stop=stop,
            server=server,
            scheduler=scheduler,
        )

        if filename:
            plot = True

        if plot:
            from distributed import profile

            data = profile.plot_data(state)
            figure, source = profile.plot_figure(data, sizing_mode="stretch_both")

            if plot == "save" and not filename:
                filename = "dask-profile.html"

            if filename:
                from bokeh.plotting import output_file, save

                output_file(filename=filename, title="Dask Profile")
                save(figure, filename=filename)
            return (state, figure)

        else:
            return state

    def scheduler_info(self, **kwargs):
        """Basic information about the workers in the cluster

        Parameters
        ----------
        **kwargs : dict
            Optional keyword arguments for the remote function

        Examples
        --------
        >>> c.scheduler_info()  # doctest: +SKIP
        {'id': '2de2b6da-69ee-11e6-ab6a-e82aea155996',
         'services': {},
         'type': 'Scheduler',
         'workers': {'127.0.0.1:40575': {'active': 0,
                                         'last-seen': 1472038237.4845693,
                                         'name': '127.0.0.1:40575',
                                         'services': {},
                                         'stored': 0,
                                         'time-delay': 0.0061032772064208984}}}
        """
        if not self.asynchronous:
            self.sync(self._update_scheduler_info)
        return self._scheduler_identity

    def dump_cluster_state(
        self,
        filename: str = "dask-cluster-dump",
        write_from_scheduler: bool | None = None,
        exclude: Collection[str] = ("run_spec",),
        format: Literal["msgpack", "yaml"] = "msgpack",
        **storage_options,
    ):
        """Extract a dump of the entire cluster state and persist to disk or a URL.
        This is intended for debugging purposes only.

        Warning: Memory usage on the scheduler (and client, if writing the dump locally)
        can be large. On a large or long-running cluster, this can take several minutes.
        The scheduler may be unresponsive while the dump is processed.

        Results will be stored in a dict::

            {
                "scheduler": {...},  # scheduler state
                "workers": {
                    worker_addr: {...},  # worker state
                    ...
                }
                "versions": {
                    "scheduler": {...},
                    "workers": {
                        worker_addr: {...},
                        ...
                    }
                }
            }

        Parameters
        ----------
        filename:
            The path or URL to write to. The appropriate file suffix (``.msgpack.gz`` or
            ``.yaml``) will be appended automatically.

            Must be a path supported by :func:`fsspec.open` (like ``s3://my-bucket/cluster-dump``,
            or ``cluster-dumps/dump``). See ``write_from_scheduler`` to control whether
            the dump is written directly to ``filename`` from the scheduler, or sent
            back to the client over the network, then written locally.
        write_from_scheduler:
            If None (default), infer based on whether ``filename`` looks like a URL
            or a local path: True if the filename contains ``://`` (like
            ``s3://my-bucket/cluster-dump``), False otherwise (like ``local_dir/cluster-dump``).

            If True, write cluster state directly to ``filename`` from the scheduler.
            If ``filename`` is a local path, the dump will be written to that
            path on the *scheduler's* filesystem, so be careful if the scheduler is running
            on ephemeral hardware. Useful when the scheduler is attached to a network
            filesystem or persistent disk, or for writing to buckets.

            If False, transfer cluster state from the scheduler back to the client
            over the network, then write it to ``filename``. This is much less
            efficient for large dumps, but useful when the scheduler doesn't have
            access to any persistent storage.
        exclude:
            A collection of attribute names which are supposed to be excluded
            from the dump, e.g. to exclude code, tracebacks, logs, etc.

            Defaults to exclude ``run_spec``, which is the serialized user code.
            This is typically not required for debugging. To allow serialization
            of this, pass an empty tuple.
        format:
            Either ``"msgpack"`` or ``"yaml"``. If msgpack is used (default),
            the output will be stored in a gzipped file as msgpack.

            To read::

                import gzip, msgpack
                with gzip.open("filename") as fd:
                    state = msgpack.unpack(fd)

            or::

                import yaml
                try:
                    from yaml import CLoader as Loader
                except ImportError:
                    from yaml import Loader
                with open("filename") as fd:
                    state = yaml.load(fd, Loader=Loader)
        **storage_options:
            Any additional arguments to :func:`fsspec.open` when writing to a URL.
        """
        return self.sync(
            self._dump_cluster_state,
            filename=filename,
            write_from_scheduler=write_from_scheduler,
            exclude=exclude,
            format=format,
            **storage_options,
        )

    async def _dump_cluster_state(
        self,
        filename: str = "dask-cluster-dump",
        write_from_scheduler: bool | None = None,
        exclude: Collection[str] = cluster_dump.DEFAULT_CLUSTER_DUMP_EXCLUDE,
        format: Literal["msgpack", "yaml"] = cluster_dump.DEFAULT_CLUSTER_DUMP_FORMAT,
        **storage_options,
    ):
        filename = str(filename)
        if write_from_scheduler is None:
            write_from_scheduler = "://" in filename

        if write_from_scheduler:
            await self.scheduler.dump_cluster_state_to_url(
                url=filename,
                exclude=exclude,
                format=format,
                **storage_options,
            )
        else:
            await cluster_dump.write_state(
                partial(self.scheduler.get_cluster_state, exclude=exclude),
                filename,
                format,
                **storage_options,
            )

    def write_scheduler_file(self, scheduler_file):
        """Write the scheduler information to a json file.

        This facilitates easy sharing of scheduler information using a file
        system. The scheduler file can be used to instantiate a second Client
        using the same scheduler.

        Parameters
        ----------
        scheduler_file : str
            Path to a write the scheduler file.

        Examples
        --------
        >>> client = Client()  # doctest: +SKIP
        >>> client.write_scheduler_file('scheduler.json')  # doctest: +SKIP
        # connect to previous client's scheduler
        >>> client2 = Client(scheduler_file='scheduler.json')  # doctest: +SKIP
        """
        if self.scheduler_file:
            raise ValueError("Scheduler file already set")
        else:
            self.scheduler_file = scheduler_file

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

    def get_metadata(self, keys, default=no_default):
        """Get arbitrary metadata from scheduler

        See set_metadata for the full docstring with examples

        Parameters
        ----------
        keys : key or list
            Key to access.  If a list then gets within a nested collection
        default : optional
            If the key does not exist then return this value instead.
            If not provided then this raises a KeyError if the key is not
            present

        See Also
        --------
        Client.set_metadata
        """
        if not isinstance(keys, (list, tuple)):
            keys = (keys,)
        return self.sync(self.scheduler.get_metadata, keys=keys, default=default)

    def get_scheduler_logs(self, n=None):
        """Get logs from scheduler

        Parameters
        ----------
        n : int
            Number of logs to retrieve.  Maxes out at 10000 by default,
            configurable via the ``distributed.admin.log-length``
            configuration value.

        Returns
        -------
        Logs in reversed order (newest first)
        """
        return self.sync(self.scheduler.logs, n=n)

    def get_worker_logs(self, n=None, workers=None, nanny=False):
        """Get logs from workers

        Parameters
        ----------
        n : int
            Number of logs to retrieve.  Maxes out at 10000 by default,
            configurable via the ``distributed.admin.log-length``
            configuration value.
        workers : iterable
            List of worker addresses to retrieve.  Gets all workers by default.
        nanny : bool, default False
            Whether to get the logs from the workers (False) or the nannies
            (True). If specified, the addresses in `workers` should still be
            the worker addresses, not the nanny addresses.

        Returns
        -------
        Dictionary mapping worker address to logs.
        Logs are returned in reversed order (newest first)
        """
        return self.sync(self.scheduler.worker_logs, n=n, workers=workers, nanny=nanny)

    def benchmark_hardware(self) -> dict:
        """
        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.
        """
        return self.sync(self.scheduler.benchmark_hardware)

    def log_event(self, topic: str | Collection[str], msg: Any):
        """Log an event under a given topic

        Parameters
        ----------
        topic : str, list[str]
            Name of the topic under which to log an event. To log the same
            event under multiple topics, pass a list of topic names.
        msg
            Event message to log. Note this must be msgpack serializable.

        Examples
        --------
        >>> from time import time
        >>> client.log_event("current-time", time())
        """
        return self.sync(self.scheduler.log_event, topic=topic, msg=msg)

    def get_events(self, topic: str | None = None):
        """Retrieve structured topic logs

        Parameters
        ----------
        topic : str, optional
            Name of topic log to retrieve events for. If no ``topic`` is
            provided, then logs for all topics will be returned.
        """
        return self.sync(self.scheduler.events, topic=topic)

    async def _handle_event(self, topic, event):
        if topic not in self._event_handlers:
            self.unsubscribe_topic(topic)
            return
        handler = self._event_handlers[topic]
        ret = handler(event)
        if inspect.isawaitable(ret):
            await ret

    def subscribe_topic(self, topic, handler):
        """Subscribe to a topic and execute a handler for every received event

        Parameters
        ----------
        topic: str
            The topic name
        handler: callable or coroutine function
            A handler called for every received event. The handler must accept a
            single argument `event` which is a tuple `(timestamp, msg)` where
            timestamp refers to the clock on the scheduler.

        Examples
        --------

        >>> import logging
        >>> logger = logging.getLogger("myLogger")  # Log config not shown
        >>> client.subscribe_topic("topic-name", lambda: logger.info)

        See Also
        --------
        dask.distributed.Client.unsubscribe_topic
        dask.distributed.Client.get_events
        dask.distributed.Client.log_event
        """
        if topic in self._event_handlers:
            logger.info("Handler for %s already set. Overwriting.", topic)
        self._event_handlers[topic] = handler
        msg = {"op": "subscribe-topic", "topic": topic, "client": self.id}
        self._send_to_scheduler(msg)

    def unsubscribe_topic(self, topic):
        """Unsubscribe from a topic and remove event handler

        See Also
        --------
        dask.distributed.Client.subscribe_topic
        dask.distributed.Client.get_events
        dask.distributed.Client.log_event
        """
        if topic in self._event_handlers:
            msg = {"op": "unsubscribe-topic", "topic": topic, "client": self.id}
            self._send_to_scheduler(msg)
        else:
            raise ValueError(f"No event handler known for topic {topic}.")

    def retire_workers(
        self, workers: list[str] | None = None, close_workers: bool = True, **kwargs
    ):
        """Retire certain workers on the scheduler

        See :meth:`distributed.Scheduler.retire_workers` for the full docstring.

        Parameters
        ----------
        workers
        close_workers
        **kwargs : dict
            Optional keyword arguments for the remote function

        Examples
        --------
        You can get information about active workers using the following:

        >>> workers = client.scheduler_info()['workers']

        From that list you may want to select some workers to close

        >>> client.retire_workers(workers=['tcp://address:port', ...])

        See Also
        --------
        dask.distributed.Scheduler.retire_workers
        """
        return self.sync(
            self.scheduler.retire_workers,
            workers=workers,
            close_workers=close_workers,
            **kwargs,
        )

    def set_metadata(self, key, value):
        """Set arbitrary metadata in the scheduler

        This allows you to store small amounts of data on the central scheduler
        process for administrative purposes.  Data should be msgpack
        serializable (ints, strings, lists, dicts)

        If the key corresponds to a task then that key will be cleaned up when
        the task is forgotten by the scheduler.

        If the key is a list then it will be assumed that you want to index
        into a nested dictionary structure using those keys.  For example if
        you call the following::

            >>> client.set_metadata(['a', 'b', 'c'], 123)

        Then this is the same as setting

            >>> scheduler.task_metadata['a']['b']['c'] = 123

        The lower level dictionaries will be created on demand.

        Examples
        --------
        >>> client.set_metadata('x', 123)  # doctest: +SKIP
        >>> client.get_metadata('x')  # doctest: +SKIP
        123

        >>> client.set_metadata(['x', 'y'], 123)  # doctest: +SKIP
        >>> client.get_metadata('x')  # doctest: +SKIP
        {'y': 123}

        >>> client.set_metadata(['x', 'w', 'z'], 456)  # doctest: +SKIP
        >>> client.get_metadata('x')  # doctest: +SKIP
        {'y': 123, 'w': {'z': 456}}

        >>> client.get_metadata(['x', 'w'])  # doctest: +SKIP
        {'z': 456}

        See Also
        --------
        get_metadata
        """
        if not isinstance(key, list):
            key = (key,)
        return self.sync(self.scheduler.set_metadata, keys=key, value=value)

    def get_versions(
        self, check: bool = False, packages: Sequence[str] | None = None
    ) -> VersionsDict | Coroutine[Any, Any, VersionsDict]:
        """Return version info for the scheduler, all workers and myself

        Parameters
        ----------
        check
            raise ValueError if all required & optional packages
            do not match
        packages
            Extra package names to check

        Examples
        --------
        >>> c.get_versions()  # doctest: +SKIP

        >>> c.get_versions(packages=['sklearn', 'geopandas'])  # doctest: +SKIP
        """
        return self.sync(self._get_versions, check=check, packages=packages or [])

    async def _get_versions(
        self, check: bool = False, packages: Sequence[str] | None = None
    ) -> VersionsDict:
        packages = packages or []
        client = version_module.get_versions(packages=packages)
        scheduler = await self.scheduler.versions(packages=packages)
        workers = await self.scheduler.broadcast(
            msg={"op": "versions", "packages": packages},
            on_error="ignore",
        )
        result = VersionsDict(scheduler=scheduler, workers=workers, client=client)

        if check:
            msg = version_module.error_message(scheduler, workers, client)
            if msg["warning"]:
                warnings.warn(msg["warning"])
            if msg["error"]:
                raise ValueError(msg["error"])

        return result

    def futures_of(self, futures):
        """Wrapper method of futures_of

        Parameters
        ----------
        futures : tuple
            The futures
        """
        return futures_of(futures, client=self)

    @classmethod
    def _expand_key(cls, k):
        """
        Expand a user-provided task key specification, e.g. in a resources
        or retries dictionary.
        """
        if not isinstance(k, tuple):
            k = (k,)
        for kk in k:
            if dask.is_dask_collection(kk):
                for kkk in kk.__dask_keys__():
                    yield stringify(kkk)
            else:
                yield stringify(kk)

    @staticmethod
    def collections_to_dsk(collections, *args, **kwargs):
        """Convert many collections into a single dask graph, after optimization"""
        return collections_to_dsk(collections, *args, **kwargs)

    async def _story(self, *keys_or_stimuli: str, on_error="raise"):
        assert on_error in ("raise", "ignore")

        try:
            flat_stories = await self.scheduler.get_story(
                keys_or_stimuli=keys_or_stimuli
            )
            flat_stories = [("scheduler", *msg) for msg in flat_stories]
        except Exception:
            if on_error == "raise":
                raise
            elif on_error == "ignore":
                flat_stories = []
            else:
                raise ValueError(f"on_error not in {'raise', 'ignore'}")

        responses = await self.scheduler.broadcast(
            msg={"op": "get_story", "keys_or_stimuli": keys_or_stimuli},
            on_error=on_error,
        )
        for worker, stories in responses.items():
            flat_stories.extend((worker, *msg) for msg in stories)
        return flat_stories

    def story(self, *keys_or_stimuli, on_error="raise"):
        """Returns a cluster-wide story for the given keys or stimulus_id's"""
        return self.sync(self._story, *keys_or_stimuli, on_error=on_error)

    def get_task_stream(
        self,
        start=None,
        stop=None,
        count=None,
        plot=False,
        filename="task-stream.html",
        bokeh_resources=None,
    ):
        """Get task stream data from scheduler

        This collects the data present in the diagnostic "Task Stream" plot on
        the dashboard.  It includes the start, stop, transfer, and
        deserialization time of every task for a particular duration.

        Note that the task stream diagnostic does not run by default.  You may
        wish to call this function once before you start work to ensure that
        things start recording, and then again after you have completed.

        Parameters
        ----------
        start : Number or string
            When you want to start recording
            If a number it should be the result of calling time()
            If a string then it should be a time difference before now,
            like '60s' or '500 ms'
        stop : Number or string
            When you want to stop recording
        count : int
            The number of desired records, ignored if both start and stop are
            specified
        plot : boolean, str
            If true then also return a Bokeh figure
            If plot == 'save' then save the figure to a file
        filename : str (optional)
            The filename to save to if you set ``plot='save'``
        bokeh_resources : bokeh.resources.Resources (optional)
            Specifies if the resource component is INLINE or CDN

        Examples
        --------
        >>> client.get_task_stream()  # prime plugin if not already connected
        >>> x.compute()  # do some work
        >>> client.get_task_stream()
        [{'task': ...,
          'type': ...,
          'thread': ...,
          ...}]

        Pass the ``plot=True`` or ``plot='save'`` keywords to get back a Bokeh
        figure

        >>> data, figure = client.get_task_stream(plot='save', filename='myfile.html')

        Alternatively consider the context manager

        >>> from dask.distributed import get_task_stream
        >>> with get_task_stream() as ts:
        ...     x.compute()
        >>> ts.data
        [...]

        Returns
        -------
        L: List[Dict]

        See Also
        --------
        get_task_stream : a context manager version of this method
        """
        return self.sync(
            self._get_task_stream,
            start=start,
            stop=stop,
            count=count,
            plot=plot,
            filename=filename,
            bokeh_resources=bokeh_resources,
        )

    async def _get_task_stream(
        self,
        start=None,
        stop=None,
        count=None,
        plot=False,
        filename="task-stream.html",
        bokeh_resources=None,
    ):
        msgs = await self.scheduler.get_task_stream(start=start, stop=stop, count=count)
        if plot:
            from distributed.diagnostics.task_stream import rectangles

            rects = rectangles(msgs)
            from distributed.dashboard.components.scheduler import task_stream_figure

            source, figure = task_stream_figure(sizing_mode="stretch_both")
            source.data.update(rects)
            if plot == "save":
                from bokeh.plotting import output_file, save

                output_file(filename=filename, title="Dask Task Stream")
                save(figure, filename=filename, resources=bokeh_resources)
            return (msgs, figure)
        else:
            return msgs

    async def _register_scheduler_plugin(self, plugin, name, idempotent=False):
        return await self.scheduler.register_scheduler_plugin(
            plugin=dumps(plugin),
            name=name,
            idempotent=idempotent,
        )

    def register_scheduler_plugin(self, plugin, name=None, idempotent=False):
        """Register a scheduler plugin.

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

        Parameters
        ----------
        plugin : SchedulerPlugin
            SchedulerPlugin instance to pass to the scheduler.
        name : str
            Name for the plugin; if None, a name is taken from the
            plugin instance or automatically generated if not present.
        idempotent : bool
            Do not re-register if a plugin of the given name already exists.
        """
        if name is None:
            name = _get_plugin_name(plugin)

        return self.sync(
            self._register_scheduler_plugin,
            plugin=plugin,
            name=name,
            idempotent=idempotent,
        )

    def register_worker_callbacks(self, setup=None):
        """
        Registers a setup callback function for all current and future workers.

        This registers a new setup function for workers in this cluster. The
        function will run immediately on all currently connected workers. It
        will also be run upon connection by any workers that are added in the
        future. Multiple setup functions can be registered - these will be
        called in the order they were added.

        If the function takes an input argument named ``dask_worker`` then
        that variable will be populated with the worker itself.

        Parameters
        ----------
        setup : callable(dask_worker: Worker) -> None
            Function to register and run on all workers
        """
        return self.register_worker_plugin(_WorkerSetupPlugin(setup))

    async def _register_worker_plugin(self, plugin=None, name=None, nanny=None):
        if nanny or nanny is None and isinstance(plugin, NannyPlugin):
            method = self.scheduler.register_nanny_plugin
        else:
            method = self.scheduler.register_worker_plugin

        responses = await method(plugin=dumps(plugin), name=name)
        for response in responses.values():
            if response["status"] == "error":
                _, exc, tb = clean_exception(
                    response["exception"], response["traceback"]
                )
                raise exc.with_traceback(tb)
        return responses

    def register_worker_plugin(self, plugin=None, name=None, nanny=None):
        """
        Registers a lifecycle worker plugin for all current and future workers.

        This registers a new object to handle setup, task state transitions and
        teardown for workers in this cluster. The plugin will instantiate
        itself on all currently connected workers. It will also be run on any
        worker that connects in the future.

        The plugin may include methods ``setup``, ``teardown``, ``transition``,
        and ``release_key``.  See the
        ``dask.distributed.WorkerPlugin`` class or the examples below for the
        interface and docstrings.  It must be serializable with the pickle or
        cloudpickle modules.

        If the plugin has a ``name`` attribute, or if the ``name=`` keyword is
        used then that will control idempotency.  If a plugin with that name has
        already been registered, then it will be removed and replaced by the new one.

        For alternatives to plugins, you may also wish to look into preload
        scripts.

        Parameters
        ----------
        plugin : WorkerPlugin or NannyPlugin
            WorkerPlugin or NannyPlugin instance to register.
        name : str, optional
            A name for the plugin.
            Registering a plugin with the same name will have no effect.
            If plugin has no name attribute a random name is used.
        nanny : bool, optional
            Whether to register the plugin with workers or nannies.

        Examples
        --------
        >>> class MyPlugin(WorkerPlugin):
        ...     def __init__(self, *args, **kwargs):
        ...         pass  # the constructor is up to you
        ...     def setup(self, worker: dask.distributed.Worker):
        ...         pass
        ...     def teardown(self, worker: dask.distributed.Worker):
        ...         pass
        ...     def transition(self, key: str, start: str, finish: str,
        ...                    **kwargs):
        ...         pass
        ...     def release_key(self, key: str, state: str, cause: str | None, reason: None, report: bool):
        ...         pass

        >>> plugin = MyPlugin(1, 2, 3)
        >>> client.register_worker_plugin(plugin)

        You can get access to the plugin with the ``get_worker`` function

        >>> client.register_worker_plugin(other_plugin, name='my-plugin')
        >>> def f():
        ...    worker = get_worker()
        ...    plugin = worker.plugins['my-plugin']
        ...    return plugin.my_state

        >>> future = client.run(f)

        See Also
        --------
        distributed.WorkerPlugin
        unregister_worker_plugin
        """
        if name is None:
            name = _get_plugin_name(plugin)

        assert name

        return self.sync(
            self._register_worker_plugin, plugin=plugin, name=name, nanny=nanny
        )

    async def _unregister_worker_plugin(self, name, nanny=None):
        if nanny:
            responses = await self.scheduler.unregister_nanny_plugin(name=name)
        else:
            responses = await self.scheduler.unregister_worker_plugin(name=name)

        for response in responses.values():
            if response["status"] == "error":
                exc = response["exception"]
                tb = response["traceback"]
                raise exc.with_traceback(tb)
        return responses

    def unregister_worker_plugin(self, name, nanny=None):
        """Unregisters a lifecycle worker plugin

        This unregisters an existing worker plugin. As part of the unregistration process
        the plugin's ``teardown`` method will be called.

        Parameters
        ----------
        name : str
            Name of the plugin to unregister. See the :meth:`Client.register_worker_plugin`
            docstring for more information.

        Examples
        --------
        >>> class MyPlugin(WorkerPlugin):
        ...     def __init__(self, *args, **kwargs):
        ...         pass  # the constructor is up to you
        ...     def setup(self, worker: dask.distributed.Worker):
        ...         pass
        ...     def teardown(self, worker: dask.distributed.Worker):
        ...         pass
        ...     def transition(self, key: str, start: str, finish: str, **kwargs):
        ...         pass
        ...     def release_key(self, key: str, state: str, cause: str | None, reason: None, report: bool):
        ...         pass

        >>> plugin = MyPlugin(1, 2, 3)
        >>> client.register_worker_plugin(plugin, name='foo')
        >>> client.unregister_worker_plugin(name='foo')

        See Also
        --------
        register_worker_plugin
        """
        return self.sync(self._unregister_worker_plugin, name=name, nanny=nanny)

    @property
    def amm(self):
        """Convenience accessors for the :doc:`active_memory_manager`"""
        from distributed.active_memory_manager import AMMClientProxy

        return AMMClientProxy(self)


class _WorkerSetupPlugin(WorkerPlugin):
    """This is used to support older setup functions as callbacks"""

    def __init__(self, setup):
        self._setup = setup

    def setup(self, worker):
        if has_keyword(self._setup, "dask_worker"):
            return self._setup(dask_worker=worker)
        else:
            return self._setup()


def CompatibleExecutor(*args, **kwargs):
    raise Exception("This has been moved to the Client.get_executor() method")


ALL_COMPLETED = "ALL_COMPLETED"
FIRST_COMPLETED = "FIRST_COMPLETED"


async def _wait(fs, timeout=None, return_when=ALL_COMPLETED):
    if timeout is not None and not isinstance(timeout, Number):
        raise TypeError(
            "timeout= keyword received a non-numeric value.\n"
            "Beware that wait expects a list of values\n"
            "  Bad:  wait(x, y, z)\n"
            "  Good: wait([x, y, z])"
        )
    fs = futures_of(fs)
    if return_when == ALL_COMPLETED:
        wait_for = distributed.utils.All
    elif return_when == FIRST_COMPLETED:
        wait_for = distributed.utils.Any
    else:
        raise NotImplementedError(
            "Only return_when='ALL_COMPLETED' and 'FIRST_COMPLETED' are supported"
        )

    future = wait_for({f._state.wait() for f in fs})
    if timeout is not None:
        future = asyncio.wait_for(future, timeout)
    await future

    done, not_done = (
        {fu for fu in fs if fu.status != "pending"},
        {fu for fu in fs if fu.status == "pending"},
    )
    cancelled = [f.key for f in done if f.status == "cancelled"]
    if cancelled:
        raise CancelledError(cancelled)

    return DoneAndNotDoneFutures(done, not_done)


def wait(fs, timeout=None, return_when=ALL_COMPLETED):
    """Wait until all/any futures are finished

    Parameters
    ----------
    fs : List[Future]
    timeout : number, string, optional
        Time after which to raise a ``dask.distributed.TimeoutError``.
        Can be a string like ``"10 minutes"`` or a number of seconds to wait.
    return_when : str, optional
        One of `ALL_COMPLETED` or `FIRST_COMPLETED`

    Returns
    -------
    Named tuple of completed, not completed
    """
    if timeout is not None and isinstance(timeout, (Number, str)):
        timeout = parse_timedelta(timeout, default="s")
    client = default_client()
    result = client.sync(_wait, fs, timeout=timeout, return_when=return_when)
    return result


async def _as_completed(fs, queue):
    fs = futures_of(fs)
    groups = groupby(lambda f: f.key, fs)
    firsts = [v[0] for v in groups.values()]
    wait_iterator = gen.WaitIterator(
        *map(asyncio.ensure_future, [f._state.wait() for f in firsts])
    )

    while not wait_iterator.done():
        await wait_iterator.next()
        # TODO: handle case of restarted futures
        future = firsts[wait_iterator.current_index]
        for f in groups[future.key]:
            queue.put_nowait(f)


async def _first_completed(futures):
    """Return a single completed future

    See Also:
        _as_completed
    """
    q = asyncio.Queue()
    await _as_completed(futures, q)
    result = await q.get()
    return result


class as_completed:
    """
    Return futures in the order in which they complete

    This returns an iterator that yields the input future objects in the order
    in which they complete.  Calling ``next`` on the iterator will block until
    the next future completes, irrespective of order.

    Additionally, you can also add more futures to this object during
    computation with the ``.add`` method

    Parameters
    ----------
    futures: Collection of futures
        A list of Future objects to be iterated over in the order in which they
        complete
    with_results: bool (False)
        Whether to wait and include results of futures as well;
        in this case `as_completed` yields a tuple of (future, result)
    raise_errors: bool (True)
        Whether we should raise when the result of a future raises an
        exception; only affects behavior when `with_results=True`.

    Examples
    --------
    >>> x, y, z = client.map(inc, [1, 2, 3])  # doctest: +SKIP
    >>> for future in as_completed([x, y, z]):  # doctest: +SKIP
    ...     print(future.result())  # doctest: +SKIP
    3
    2
    4

    Add more futures during computation

    >>> x, y, z = client.map(inc, [1, 2, 3])  # doctest: +SKIP
    >>> ac = as_completed([x, y, z])  # doctest: +SKIP
    >>> for future in ac:  # doctest: +SKIP
    ...     print(future.result())  # doctest: +SKIP
    ...     if random.random() < 0.5:  # doctest: +SKIP
    ...         ac.add(c.submit(double, future))  # doctest: +SKIP
    4
    2
    8
    3
    6
    12
    24

    Optionally wait until the result has been gathered as well

    >>> ac = as_completed([x, y, z], with_results=True)  # doctest: +SKIP
    >>> for future, result in ac:  # doctest: +SKIP
    ...     print(result)  # doctest: +SKIP
    2
    4
    3
    """

    def __init__(self, futures=None, loop=None, with_results=False, raise_errors=True):
        if futures is None:
            futures = []
        self.futures = defaultdict(lambda: 0)
        self.queue = pyQueue()
        self.lock = threading.Lock()
        self.loop = loop or default_client().loop
        self.thread_condition = threading.Condition()
        self.with_results = with_results
        self.raise_errors = raise_errors

        if futures:
            self.update(futures)

    @property
    def condition(self):
        try:
            return self._condition
        except AttributeError:
            self._condition = asyncio.Condition()
            return self._condition

    async def _track_future(self, future):
        try:
            await _wait(future)
        except CancelledError:
            pass
        if self.with_results:
            try:
                result = await future._result(raiseit=False)
            except CancelledError as exc:
                result = exc
        with self.lock:
            if future in self.futures:
                self.futures[future] -= 1
                if not self.futures[future]:
                    del self.futures[future]
                if self.with_results:
                    self.queue.put_nowait((future, result))
                else:
                    self.queue.put_nowait(future)
                async with self.condition:
                    self.condition.notify()
                with self.thread_condition:
                    self.thread_condition.notify()

    def update(self, futures):
        """Add multiple futures to the collection.

        The added futures will emit from the iterator once they finish"""
        from distributed.actor import BaseActorFuture

        with self.lock:
            for f in futures:
                if not isinstance(f, (Future, BaseActorFuture)):
                    raise TypeError("Input must be a future, got %s" % f)
                self.futures[f] += 1
                self.loop.add_callback(self._track_future, f)

    def add(self, future):
        """Add a future to the collection

        This future will emit from the iterator once it finishes
        """
        self.update((future,))

    def is_empty(self):
        """Returns True if there no completed or computing futures"""
        return not self.count()

    def has_ready(self):
        """Returns True if there are completed futures available."""
        return not self.queue.empty()

    def count(self):
        """Return the number of futures yet to be returned

        This includes both the number of futures still computing, as well as
        those that are finished, but have not yet been returned from this
        iterator.
        """
        with self.lock:
            return len(self.futures) + len(self.queue.queue)

    def __repr__(self):
        return "<as_completed: waiting={} done={}>".format(
            len(self.futures), len(self.queue.queue)
        )

    def __iter__(self):
        return self

    def __aiter__(self):
        return self

    def _get_and_raise(self):
        res = self.queue.get()
        if self.with_results:
            future, result = res
            if self.raise_errors and future.status == "error":
                typ, exc, tb = result
                raise exc.with_traceback(tb)
            elif future.status == "cancelled":
                res = (res[0], CancelledError(future.key))
        return res

    def __next__(self):
        while self.queue.empty():
            if self.is_empty():
                raise StopIteration()
            with self.thread_condition:
                self.thread_condition.wait(timeout=0.100)
        return self._get_and_raise()

    async def __anext__(self):
        if not self.futures and self.queue.empty():
            raise StopAsyncIteration
        while self.queue.empty():
            if not self.futures:
                raise StopAsyncIteration
            async with self.condition:
                await self.condition.wait()

        return self._get_and_raise()

    next = __next__

    def next_batch(self, block=True):
        """Get the next batch of completed futures.

        Parameters
        ----------
        block : bool, optional
            If True then wait until we have some result, otherwise return
            immediately, even with an empty list.  Defaults to True.

        Examples
        --------
        >>> ac = as_completed(futures)  # doctest: +SKIP
        >>> client.gather(ac.next_batch())  # doctest: +SKIP
        [4, 1, 3]

        >>> client.gather(ac.next_batch(block=False))  # doctest: +SKIP
        []

        Returns
        -------
        List of futures or (future, result) tuples
        """
        if block:
            batch = [next(self)]
        else:
            batch = []
        while not self.queue.empty():
            batch.append(self.queue.get())
        return batch

    def batches(self):
        """
        Yield all finished futures at once rather than one-by-one

        This returns an iterator of lists of futures or lists of
        (future, result) tuples rather than individual futures or individual
        (future, result) tuples.  It will yield these as soon as possible
        without waiting.

        Examples
        --------
        >>> for batch in as_completed(futures).batches():  # doctest: +SKIP
        ...     results = client.gather(batch)
        ...     print(results)
        [4, 2]
        [1, 3, 7]
        [5]
        [6]
        """
        while True:
            try:
                yield self.next_batch(block=True)
            except StopIteration:
                return

    def clear(self):
        """Clear out all submitted futures"""
        with self.lock:
            self.futures.clear()
            while not self.queue.empty():
                self.queue.get()


def AsCompleted(*args, **kwargs):
    raise Exception("This has moved to as_completed")


def default_client(c=None):
    """Return a client if one has started

    Parameters
    ----------
    c : Client
        The client to return. If None, the default client is returned.

    Returns
    -------
    c : Client
        The client, if one has started
    """
    c = c or _get_global_client()
    if c:
        return c
    else:
        raise ValueError(
            "No clients found\n"
            "Start a client and point it to the scheduler address\n"
            "  from distributed import Client\n"
            "  client = Client('ip-addr-of-scheduler:8786')\n"
        )


def ensure_default_client(client):
    """Ensures the client passed as argument is set as the default

    Parameters
    ----------
    client : Client
        The client
    """
    _set_global_client(client)


def redict_collection(c, dsk):
    """Change the dictionary in the collection

    Parameters
    ----------
    c : collection
        The collection
    dsk : dict
        The dictionary

    Returns
    -------
    c : Delayed
        If the collection is a 'Delayed' object the collection is returned
    cc : collection
        If the collection is not a 'Delayed' object a copy of the
        collection with xthe new dictionary is returned

    """
    from dask.delayed import Delayed

    if isinstance(c, Delayed):
        return Delayed(c.key, dsk)
    else:
        cc = copy.copy(c)
        cc.dask = dsk
        return cc


def futures_of(o, client=None):
    """Future objects in a collection

    Parameters
    ----------
    o : collection
        A possibly nested collection of Dask objects
    client : Client, optional
        The client

    Examples
    --------
    >>> futures_of(my_dask_dataframe)
    [<Future: finished key: ...>,
     <Future: pending  key: ...>]

    Raises
    ------
    CancelledError
        If one of the futures is cancelled a CancelledError is raised

    Returns
    -------
    futures : List[Future]
        A list of futures held by those collections
    """
    stack = [o]
    seen = set()
    futures = list()
    while stack:
        x = stack.pop()
        if type(x) in (tuple, set, list):
            stack.extend(x)
        elif type(x) is dict:
            stack.extend(x.values())
        elif type(x) is SubgraphCallable:
            stack.extend(x.dsk.values())
        elif isinstance(x, Future):
            if x not in seen:
                seen.add(x)
                futures.append(x)
        elif dask.is_dask_collection(x):
            stack.extend(x.__dask_graph__().values())

    if client is not None:
        bad = {f for f in futures if f.cancelled()}
        if bad:
            raise CancelledError(bad)

    return futures[::-1]


def fire_and_forget(obj):
    """Run tasks at least once, even if we release the futures

    Under normal operation Dask will not run any tasks for which there is not
    an active future (this avoids unnecessary work in many situations).
    However sometimes you want to just fire off a task, not track its future,
    and expect it to finish eventually.  You can use this function on a future
    or collection of futures to ask Dask to complete the task even if no active
    client is tracking it.

    The results will not be kept in memory after the task completes (unless
    there is an active future) so this is only useful for tasks that depend on
    side effects.

    Parameters
    ----------
    obj : Future, list, dict, dask collection
        The futures that you want to run at least once

    Examples
    --------
    >>> fire_and_forget(client.submit(func, *args))  # doctest: +SKIP
    """
    futures = futures_of(obj)
    for future in futures:
        future.client._send_to_scheduler(
            {
                "op": "client-desires-keys",
                "keys": [stringify(future.key)],
                "client": "fire-and-forget",
            }
        )


class get_task_stream:
    """
    Collect task stream within a context block

    This provides diagnostic information about every task that was run during
    the time when this block was active.

    This must be used as a context manager.

    Parameters
    ----------
    plot: boolean, str
        If true then also return a Bokeh figure
        If plot == 'save' then save the figure to a file
    filename: str (optional)
        The filename to save to if you set ``plot='save'``

    Examples
    --------
    >>> with get_task_stream() as ts:
    ...     x.compute()
    >>> ts.data
    [...]

    Get back a Bokeh figure and optionally save to a file

    >>> with get_task_stream(plot='save', filename='task-stream.html') as ts:
    ...    x.compute()
    >>> ts.figure
    <Bokeh Figure>

    To share this file with others you may wish to upload and serve it online.
    A common way to do this is to upload the file as a gist, and then serve it
    on https://raw.githack.com ::

       $ python -m pip install gist
       $ gist task-stream.html
       https://gist.github.com/8a5b3c74b10b413f612bb5e250856ceb

    You can then navigate to that site, click the "Raw" button to the right of
    the ``task-stream.html`` file, and then provide that URL to
    https://raw.githack.com .  This process should provide a sharable link that
    others can use to see your task stream plot.

    See Also
    --------
    Client.get_task_stream: Function version of this context manager
    """

    def __init__(self, client=None, plot=False, filename="task-stream.html"):
        self.data = []
        self._plot = plot
        self._filename = filename
        self.figure = None
        self.client = client or default_client()
        self.client.get_task_stream(start=0, stop=0)  # ensure plugin

    def __enter__(self):
        self.start = time()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        L = self.client.get_task_stream(
            start=self.start, plot=self._plot, filename=self._filename
        )
        if self._plot:
            L, self.figure = L
        self.data.extend(L)

    async def __aenter__(self):
        return self

    async def __aexit__(self, exc_type, exc_value, traceback):
        L = await self.client.get_task_stream(
            start=self.start, plot=self._plot, filename=self._filename
        )
        if self._plot:
            L, self.figure = L
        self.data.extend(L)


class performance_report:
    """Gather performance report

    This creates a static HTML file that includes many of the same plots of the
    dashboard for later viewing.

    The resulting file uses JavaScript, and so must be viewed with a web
    browser.  Locally we recommend using ``python -m http.server`` or hosting
    the file live online.

    Parameters
    ----------
    filename: str, optional
        The filename to save the performance report locally

    stacklevel: int, optional
        The code execution frame utilized for populating the Calling Code section
        of the report. Defaults to `1` which is the frame calling ``performance_report``

    mode: str, optional
        Mode parameter to pass to :func:`bokeh.io.output.output_file`. Defaults to ``None``.

    Examples
    --------
    >>> with performance_report(filename="myfile.html", stacklevel=1):
    ...     x.compute()

    $ python -m http.server
    $ open myfile.html
    """

    def __init__(self, filename="dask-report.html", stacklevel=1, mode=None):
        self.filename = filename
        # stacklevel 0 or less - shows dask internals which likely isn't helpful
        self._stacklevel = stacklevel if stacklevel > 0 else 1
        self.mode = mode

    async def __aenter__(self):
        self.start = time()
        self.last_count = await get_client().run_on_scheduler(
            lambda dask_scheduler: dask_scheduler.monitor.count
        )
        await get_client().get_task_stream(start=0, stop=0)  # ensure plugin

    async def __aexit__(self, exc_type, exc_value, traceback, code=None):
        client = get_client()
        if code is None:
            code = client._get_computation_code(self._stacklevel + 1)
        data = await client.scheduler.performance_report(
            start=self.start, last_count=self.last_count, code=code, mode=self.mode
        )
        with open(self.filename, "w") as f:
            f.write(data)

    def __enter__(self):
        get_client().sync(self.__aenter__)

    def __exit__(self, exc_type, exc_value, traceback):
        client = get_client()
        code = client._get_computation_code(self._stacklevel + 1)
        client.sync(self.__aexit__, exc_type, exc_value, traceback, code=code)


class get_task_metadata:
    """Collect task metadata within a context block

    This gathers ``TaskState`` metadata and final state from the scheduler
    for tasks which are submitted and finished within the scope of this
    context manager.

    Examples
    --------
    >>> with get_task_metadata() as tasks:
    ...     x.compute()
    >>> tasks.metadata
    {...}
    >>> tasks.state
    {...}
    """

    def __init__(self):
        self.name = f"task-metadata-{uuid.uuid4().hex}"
        self.keys = set()
        self.metadata = None
        self.state = None

    async def __aenter__(self):
        await get_client().scheduler.start_task_metadata(name=self.name)
        return self

    async def __aexit__(self, exc_type, exc_value, traceback):
        response = await get_client().scheduler.stop_task_metadata(name=self.name)
        self.metadata = response["metadata"]
        self.state = response["state"]

    def __enter__(self):
        return get_client().sync(self.__aenter__)

    def __exit__(self, exc_type, exc_value, traceback):
        return get_client().sync(self.__aexit__, exc_type, exc_value, traceback)


@contextmanager
def temp_default_client(c):
    """Set the default client for the duration of the context

    .. note::
       This function should be used exclusively for unit testing the default
       client functionality. In all other cases, please use
       ``Client.as_current`` instead.

    .. note::
       Unlike ``Client.as_current``, this context manager is neither
       thread-local nor task-local.

    Parameters
    ----------
    c : Client
        This is what default_client() will return within the with-block.
    """
    old_exec = default_client()
    _set_global_client(c)
    try:
        yield
    finally:
        _set_global_client(old_exec)


def _close_global_client():
    """
    Force close of global client.  This cleans up when a client
    wasn't close explicitly, e.g. interactive sessions.
    """
    c = _get_global_client()
    if c is not None:
        c._should_close_loop = False
        with suppress(TimeoutError, RuntimeError):
            if c.asynchronous:
                c.loop.add_callback(c.close, timeout=3)
            else:
                c.close(timeout=3)


atexit.register(_close_global_client)