forked from dask/distributed
/
test_scheduler.py
3192 lines (2458 loc) · 98 KB
/
test_scheduler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import gc
import json
import logging
import operator
import re
import sys
from itertools import product
from textwrap import dedent
from time import sleep
from unittest import mock
import cloudpickle
import psutil
import pytest
from tlz import concat, first, frequencies, merge, valmap
import dask
from dask import delayed
from dask.utils import apply, parse_timedelta, stringify, tmpfile, typename
from distributed import Client, Nanny, Worker, fire_and_forget, wait
from distributed.comm import Comm
from distributed.compatibility import LINUX, WINDOWS
from distributed.core import ConnectionPool, Status, clean_exception, connect, rpc
from distributed.metrics import time
from distributed.protocol.pickle import dumps
from distributed.scheduler import MemoryState, Scheduler
from distributed.utils import TimeoutError
from distributed.utils_test import (
captured_logger,
cluster,
dec,
div,
gen_cluster,
gen_test,
inc,
nodebug,
slowadd,
slowdec,
slowinc,
tls_only_security,
varying,
)
from distributed.worker import dumps_function, dumps_task, get_worker
if sys.version_info < (3, 8):
try:
import pickle5 as pickle
except ImportError:
import pickle
else:
import pickle
pytestmark = pytest.mark.ci1
alice = "alice:1234"
bob = "bob:1234"
@gen_cluster()
async def test_administration(s, a, b):
assert isinstance(s.address, str)
assert s.address in str(s)
assert str(sum(s.nthreads.values())) in repr(s)
assert str(len(s.nthreads)) in repr(s)
@gen_cluster(client=True, nthreads=[("127.0.0.1", 1)])
async def test_respect_data_in_memory(c, s, a):
x = delayed(inc)(1)
y = delayed(inc)(x)
f = c.persist(y)
await wait([f])
assert s.tasks[y.key].who_has == {s.workers[a.address]}
z = delayed(operator.add)(x, y)
f2 = c.persist(z)
while f2.key not in s.tasks or not s.tasks[f2.key]:
assert s.tasks[y.key].who_has
await asyncio.sleep(0.0001)
@gen_cluster(client=True)
async def test_recompute_released_results(c, s, a, b):
x = delayed(inc)(1)
y = delayed(inc)(x)
yy = c.persist(y)
await wait(yy)
while s.tasks[x.key].who_has or x.key in a.data or x.key in b.data: # let x go away
await asyncio.sleep(0.01)
z = delayed(dec)(x)
zz = c.compute(z)
result = await zz
assert result == 1
@gen_cluster(client=True)
async def test_decide_worker_with_many_independent_leaves(c, s, a, b):
xs = await asyncio.gather(
c.scatter(list(range(0, 100, 2)), workers=a.address),
c.scatter(list(range(1, 100, 2)), workers=b.address),
)
xs = list(concat(zip(*xs)))
ys = [delayed(inc)(x) for x in xs]
y2s = c.persist(ys)
await wait(y2s)
nhits = sum(y.key in a.data for y in y2s[::2]) + sum(
y.key in b.data for y in y2s[1::2]
)
assert nhits > 80
@gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 3)
async def test_decide_worker_with_restrictions(client, s, a, b, c):
x = client.submit(inc, 1, workers=[a.address, b.address])
await x
assert x.key in a.data or x.key in b.data
@pytest.mark.parametrize("ndeps", [0, 1, 4])
@pytest.mark.parametrize(
"nthreads",
[
[("127.0.0.1", 1)] * 5,
[("127.0.0.1", 3), ("127.0.0.1", 2), ("127.0.0.1", 1)],
],
)
def test_decide_worker_coschedule_order_neighbors(ndeps, nthreads):
@gen_cluster(
client=True,
nthreads=nthreads,
config={"distributed.scheduler.work-stealing": False},
)
async def test(c, s, *workers):
r"""
Ensure that sibling root tasks are scheduled to the same node, reducing future data transfer.
We generate a wide layer of "root" tasks (random NumPy arrays). All of those tasks share 0-5
trivial dependencies. The ``ndeps=0`` and ``ndeps=1`` cases are most common in real-world use
(``ndeps=1`` is basically ``da.from_array(..., inline_array=False)`` or ``da.from_zarr``).
The graph is structured like this (though the number of tasks and workers is different):
|-W1-| |-W2-| |-W3-| |-W4-| < ---- ideal task scheduling
q r s t < --- `sum-aggregate-`
/ \ / \ / \ / \
i j k l m n o p < --- `sum-`
| | | | | | | |
a b c d e f g h < --- `random-`
\ \ \ | | / / /
TRIVIAL * 0..5
Neighboring `random-` tasks should be scheduled on the same worker. We test that generally,
only one worker holds each row of the array, that the `random-` tasks are never transferred,
and that there are few transfers overall.
"""
da = pytest.importorskip("dask.array")
np = pytest.importorskip("numpy")
if ndeps == 0:
x = da.random.random((100, 100), chunks=(10, 10))
else:
def random(**kwargs):
assert len(kwargs) == ndeps
return np.random.random((10, 10))
trivial_deps = {f"k{i}": delayed(object()) for i in range(ndeps)}
# TODO is there a simpler (non-blockwise) way to make this sort of graph?
x = da.blockwise(
random,
"yx",
new_axes={"y": (10,) * 10, "x": (10,) * 10},
dtype=float,
**trivial_deps,
)
xx, xsum = dask.persist(x, x.sum(axis=1, split_every=20))
await xsum
# Check that each chunk-row of the array is (mostly) stored on the same worker
primary_worker_key_fractions = []
secondary_worker_key_fractions = []
for i, keys in enumerate(x.__dask_keys__()):
# Iterate along rows of the array.
keys = {stringify(k) for k in keys}
# No more than 2 workers should have any keys
assert sum(any(k in w.data for k in keys) for w in workers) <= 2
# What fraction of the keys for this row does each worker hold?
key_fractions = [
len(set(w.data).intersection(keys)) / len(keys) for w in workers
]
key_fractions.sort()
# Primary worker: holds the highest percentage of keys
# Secondary worker: holds the second highest percentage of keys
primary_worker_key_fractions.append(key_fractions[-1])
secondary_worker_key_fractions.append(key_fractions[-2])
# There may be one or two rows that were poorly split across workers,
# but the vast majority of rows should only be on one worker.
assert np.mean(primary_worker_key_fractions) >= 0.9
assert np.median(primary_worker_key_fractions) == 1.0
assert np.mean(secondary_worker_key_fractions) <= 0.1
assert np.median(secondary_worker_key_fractions) == 0.0
# Check that there were few transfers
unexpected_transfers = []
for worker in workers:
for log in worker.incoming_transfer_log:
keys = log["keys"]
# The root-ish tasks should never be transferred
assert not any(k.startswith("random") for k in keys), keys
# `object-` keys (the trivial deps of the root random tasks) should be transferred
if any(not k.startswith("object") for k in keys):
# But not many other things should be
unexpected_transfers.append(list(keys))
# A transfer at the very end to move aggregated results is fine (necessary with unbalanced workers in fact),
# but generally there should be very very few transfers.
assert len(unexpected_transfers) <= 3, unexpected_transfers
test()
@gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 3)
async def test_move_data_over_break_restrictions(client, s, a, b, c):
[x] = await client.scatter([1], workers=b.address)
y = client.submit(inc, x, workers=[a.address, b.address])
await wait(y)
assert y.key in a.data or y.key in b.data
@gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 3)
async def test_balance_with_restrictions(client, s, a, b, c):
[x], [y] = await asyncio.gather(
client.scatter([[1, 2, 3]], workers=a.address),
client.scatter([1], workers=c.address),
)
z = client.submit(inc, 1, workers=[a.address, c.address])
await wait(z)
assert s.tasks[z.key].who_has == {s.workers[c.address]}
@gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 3)
async def test_no_valid_workers(client, s, a, b, c):
x = client.submit(inc, 1, workers="127.0.0.5:9999")
while not s.tasks:
await asyncio.sleep(0.01)
assert s.tasks[x.key] in s.unrunnable
with pytest.raises(TimeoutError):
await asyncio.wait_for(x, 0.05)
@gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 3)
async def test_no_valid_workers_loose_restrictions(client, s, a, b, c):
x = client.submit(inc, 1, workers="127.0.0.5:9999", allow_other_workers=True)
result = await x
assert result == 2
@gen_cluster(client=True, nthreads=[])
async def test_no_workers(client, s):
x = client.submit(inc, 1)
while not s.tasks:
await asyncio.sleep(0.01)
assert s.tasks[x.key] in s.unrunnable
with pytest.raises(TimeoutError):
await asyncio.wait_for(x, 0.05)
@gen_cluster(nthreads=[])
async def test_retire_workers_empty(s):
await s.retire_workers(workers=[])
@gen_cluster()
async def test_remove_client(s, a, b):
s.update_graph(
tasks={"x": dumps_task((inc, 1)), "y": dumps_task((inc, "x"))},
dependencies={"x": [], "y": ["x"]},
keys=["y"],
client="ident",
)
assert s.tasks
assert s.dependencies
s.remove_client(client="ident")
assert not s.tasks
assert not s.dependencies
@gen_cluster()
async def test_server_listens_to_other_ops(s, a, b):
with rpc(s.address) as r:
ident = await r.identity()
assert ident["type"] == "Scheduler"
assert ident["id"].lower().startswith("scheduler")
@gen_cluster()
async def test_remove_worker_from_scheduler(s, a, b):
dsk = {("x-%d" % i): (inc, i) for i in range(20)}
s.update_graph(
tasks=valmap(dumps_task, dsk),
keys=list(dsk),
dependencies={k: set() for k in dsk},
)
assert a.address in s.stream_comms
await s.remove_worker(address=a.address)
assert a.address not in s.nthreads
assert len(s.workers[b.address].processing) == len(dsk) # b owns everything
@gen_cluster()
async def test_remove_worker_by_name_from_scheduler(s, a, b):
assert a.address in s.stream_comms
assert await s.remove_worker(address=a.name) == "OK"
assert a.address not in s.nthreads
assert await s.remove_worker(address=a.address) == "already-removed"
@gen_cluster(config={"distributed.scheduler.events-cleanup-delay": "10 ms"})
async def test_clear_events_worker_removal(s, a, b):
assert a.address in s.events
assert a.address in s.nthreads
assert b.address in s.events
assert b.address in s.nthreads
await s.remove_worker(address=a.address)
# Shortly after removal, the events should still be there
assert a.address in s.events
assert a.address not in s.nthreads
s.validate_state()
start = time()
while a.address in s.events:
await asyncio.sleep(0.01)
assert time() < start + 2
assert b.address in s.events
@gen_cluster(
config={"distributed.scheduler.events-cleanup-delay": "10 ms"}, client=True
)
async def test_clear_events_client_removal(c, s, a, b):
assert c.id in s.events
s.remove_client(c.id)
assert c.id in s.events
assert c.id not in s.clients
assert c not in s.clients
s.remove_client(c.id)
# If it doesn't reconnect after a given time, the events log should be cleared
start = time()
while c.id in s.events:
await asyncio.sleep(0.01)
assert time() < start + 2
@gen_cluster()
async def test_add_worker(s, a, b):
w = Worker(s.address, nthreads=3)
w.data["x-5"] = 6
w.data["y"] = 1
dsk = {("x-%d" % i): (inc, i) for i in range(10)}
s.update_graph(
tasks=valmap(dumps_task, dsk),
keys=list(dsk),
client="client",
dependencies={k: set() for k in dsk},
)
s.validate_state()
await w
s.validate_state()
assert w.ip in s.host_info
assert s.host_info[w.ip]["addresses"] == {a.address, b.address, w.address}
await w.close()
@gen_cluster(scheduler_kwargs={"blocked_handlers": ["feed"]})
async def test_blocked_handlers_are_respected(s, a, b):
def func(scheduler):
return dumps(dict(scheduler.worker_info))
comm = await connect(s.address)
await comm.write({"op": "feed", "function": dumps(func), "interval": 0.01})
response = await comm.read()
_, exc, _ = clean_exception(response["exception"], response["traceback"])
assert isinstance(exc, ValueError)
assert "'feed' handler has been explicitly disallowed" in repr(exc)
await comm.close()
@gen_cluster(
nthreads=[], config={"distributed.scheduler.blocked-handlers": ["test-handler"]}
)
def test_scheduler_init_pulls_blocked_handlers_from_config(s):
assert s.blocked_handlers == ["test-handler"]
@gen_cluster()
async def test_feed(s, a, b):
def func(scheduler):
return dumps(dict(scheduler.worker_info))
comm = await connect(s.address)
await comm.write({"op": "feed", "function": dumps(func), "interval": 0.01})
for i in range(5):
response = await comm.read()
expected = dict(s.worker_info)
assert cloudpickle.loads(response) == expected
await comm.close()
@gen_cluster()
async def test_feed_setup_teardown(s, a, b):
def setup(scheduler):
return 1
def func(scheduler, state):
assert state == 1
return "OK"
def teardown(scheduler, state):
scheduler.flag = "done"
comm = await connect(s.address)
await comm.write(
{
"op": "feed",
"function": dumps(func),
"setup": dumps(setup),
"teardown": dumps(teardown),
"interval": 0.01,
}
)
for i in range(5):
response = await comm.read()
assert response == "OK"
await comm.close()
start = time()
while not hasattr(s, "flag"):
await asyncio.sleep(0.01)
assert time() - start < 5
@gen_cluster()
async def test_feed_large_bytestring(s, a, b):
np = pytest.importorskip("numpy")
x = np.ones(10000000)
def func(scheduler):
y = x
return True
comm = await connect(s.address)
await comm.write({"op": "feed", "function": dumps(func), "interval": 0.05})
for i in range(5):
response = await comm.read()
assert response is True
await comm.close()
@gen_cluster(client=True)
async def test_delete_data(c, s, a, b):
d = await c.scatter({"x": 1, "y": 2, "z": 3})
assert {ts.key for ts in s.tasks.values() if ts.who_has} == {"x", "y", "z"}
assert set(a.data) | set(b.data) == {"x", "y", "z"}
assert merge(a.data, b.data) == {"x": 1, "y": 2, "z": 3}
del d["x"]
del d["y"]
start = time()
while set(a.data) | set(b.data) != {"z"}:
await asyncio.sleep(0.01)
assert time() < start + 5
@gen_cluster(client=True, nthreads=[("127.0.0.1", 1)])
async def test_delete(c, s, a):
x = c.submit(inc, 1)
await x
assert x.key in s.tasks
assert x.key in a.data
await c._cancel(x)
start = time()
while x.key in a.data:
await asyncio.sleep(0.01)
assert time() < start + 5
assert x.key not in s.tasks
s.report_on_key(key=x.key)
@gen_cluster()
async def test_filtered_communication(s, a, b):
c = await connect(s.address)
f = await connect(s.address)
await c.write({"op": "register-client", "client": "c", "versions": {}})
await f.write({"op": "register-client", "client": "f", "versions": {}})
await c.read()
await f.read()
assert set(s.client_comms) == {"c", "f"}
await c.write(
{
"op": "update-graph",
"tasks": {"x": dumps_task((inc, 1)), "y": dumps_task((inc, "x"))},
"dependencies": {"x": [], "y": ["x"]},
"client": "c",
"keys": ["y"],
}
)
await f.write(
{
"op": "update-graph",
"tasks": {
"x": dumps_task((inc, 1)),
"z": dumps_task((operator.add, "x", 10)),
},
"dependencies": {"x": [], "z": ["x"]},
"client": "f",
"keys": ["z"],
}
)
(msg,) = await c.read()
assert msg["op"] == "key-in-memory"
assert msg["key"] == "y"
(msg,) = await f.read()
assert msg["op"] == "key-in-memory"
assert msg["key"] == "z"
def test_dumps_function():
a = dumps_function(inc)
assert cloudpickle.loads(a)(10) == 11
b = dumps_function(inc)
assert a is b
c = dumps_function(dec)
assert a != c
def test_dumps_task():
d = dumps_task((inc, 1))
assert set(d) == {"function", "args"}
f = lambda x, y=2: x + y
d = dumps_task((apply, f, (1,), {"y": 10}))
assert cloudpickle.loads(d["function"])(1, 2) == 3
assert cloudpickle.loads(d["args"]) == (1,)
assert cloudpickle.loads(d["kwargs"]) == {"y": 10}
d = dumps_task((apply, f, (1,)))
assert cloudpickle.loads(d["function"])(1, 2) == 3
assert cloudpickle.loads(d["args"]) == (1,)
assert set(d) == {"function", "args"}
@gen_cluster()
async def test_ready_remove_worker(s, a, b):
s.update_graph(
tasks={"x-%d" % i: dumps_task((inc, i)) for i in range(20)},
keys=["x-%d" % i for i in range(20)],
client="client",
dependencies={"x-%d" % i: [] for i in range(20)},
)
assert all(len(w.processing) > w.nthreads for w in s.workers.values())
await s.remove_worker(address=a.address)
assert set(s.workers) == {b.address}
assert all(len(w.processing) > w.nthreads for w in s.workers.values())
@gen_cluster(client=True, Worker=Nanny, timeout=60)
async def test_restart(c, s, a, b):
futures = c.map(inc, range(20))
await wait(futures)
await s.restart()
assert len(s.workers) == 2
for ws in s.workers.values():
assert not ws.occupancy
assert not ws.processing
assert not s.tasks
assert not s.dependencies
@gen_cluster()
async def test_broadcast(s, a, b):
result = await s.broadcast(msg={"op": "ping"})
assert result == {a.address: b"pong", b.address: b"pong"}
result = await s.broadcast(msg={"op": "ping"}, workers=[a.address])
assert result == {a.address: b"pong"}
result = await s.broadcast(msg={"op": "ping"}, hosts=[a.ip])
assert result == {a.address: b"pong", b.address: b"pong"}
@gen_cluster(security=tls_only_security())
async def test_broadcast_tls(s, a, b):
result = await s.broadcast(msg={"op": "ping"})
assert result == {a.address: b"pong", b.address: b"pong"}
result = await s.broadcast(msg={"op": "ping"}, workers=[a.address])
assert result == {a.address: b"pong"}
result = await s.broadcast(msg={"op": "ping"}, hosts=[a.ip])
assert result == {a.address: b"pong", b.address: b"pong"}
@gen_cluster(Worker=Nanny)
async def test_broadcast_nanny(s, a, b):
result1 = await s.broadcast(msg={"op": "identity"}, nanny=True)
assert all(d["type"] == "Nanny" for d in result1.values())
result2 = await s.broadcast(
msg={"op": "identity"}, workers=[a.worker_address], nanny=True
)
assert len(result2) == 1
assert first(result2.values())["id"] == a.id
result3 = await s.broadcast(msg={"op": "identity"}, hosts=[a.ip], nanny=True)
assert result1 == result3
@gen_cluster(nthreads=[])
async def test_worker_name(s):
w = await Worker(s.address, name="alice")
assert s.workers[w.address].name == "alice"
assert s.aliases["alice"] == w.address
with pytest.raises(ValueError):
w2 = await Worker(s.address, name="alice")
await w2.close()
await w.close()
@gen_cluster(nthreads=[])
async def test_coerce_address(s):
print("scheduler:", s.address, s.listen_address)
a = Worker(s.address, name="alice")
b = Worker(s.address, name=123)
c = Worker("127.0.0.1", s.port, name="charlie")
await asyncio.gather(a, b, c)
assert s.coerce_address("127.0.0.1:8000") == "tcp://127.0.0.1:8000"
assert s.coerce_address("[::1]:8000") == "tcp://[::1]:8000"
assert s.coerce_address("tcp://127.0.0.1:8000") == "tcp://127.0.0.1:8000"
assert s.coerce_address("tcp://[::1]:8000") == "tcp://[::1]:8000"
assert s.coerce_address("localhost:8000") in (
"tcp://127.0.0.1:8000",
"tcp://[::1]:8000",
)
assert s.coerce_address("localhost:8000") in (
"tcp://127.0.0.1:8000",
"tcp://[::1]:8000",
)
assert s.coerce_address(a.address) == a.address
# Aliases
assert s.coerce_address("alice") == a.address
assert s.coerce_address(123) == b.address
assert s.coerce_address("charlie") == c.address
assert s.coerce_hostname("127.0.0.1") == "127.0.0.1"
assert s.coerce_hostname("alice") == a.ip
assert s.coerce_hostname(123) == b.ip
assert s.coerce_hostname("charlie") == c.ip
assert s.coerce_hostname("jimmy") == "jimmy"
assert s.coerce_address("zzzt:8000", resolve=False) == "tcp://zzzt:8000"
await asyncio.gather(a.close(), b.close(), c.close())
@gen_cluster(nthreads=[], config={"distributed.scheduler.work-stealing": True})
async def test_config_stealing(s):
"""Regression test for https://github.com/dask/distributed/issues/3409"""
assert "stealing" in s.extensions
@gen_cluster(nthreads=[], config={"distributed.scheduler.work-stealing": False})
async def test_config_no_stealing(s):
assert "stealing" not in s.extensions
@pytest.mark.skipif(WINDOWS, reason="num_fds not supported on windows")
@gen_cluster(nthreads=[])
async def test_file_descriptors_dont_leak(s):
proc = psutil.Process()
before = proc.num_fds()
async with Worker(s.address):
assert proc.num_fds() > before
while proc.num_fds() > before:
await asyncio.sleep(0.01)
@gen_cluster()
async def test_update_graph_culls(s, a, b):
s.update_graph(
tasks={
"x": dumps_task((inc, 1)),
"y": dumps_task((inc, "x")),
"z": dumps_task((inc, 2)),
},
keys=["y"],
dependencies={"y": "x", "x": [], "z": []},
client="client",
)
assert "z" not in s.tasks
assert "z" not in s.dependencies
def test_io_loop(loop):
s = Scheduler(loop=loop, dashboard_address=":0", validate=True)
assert s.io_loop is loop
@gen_cluster(client=True)
async def test_story(c, s, a, b):
x = delayed(inc)(1)
y = delayed(inc)(x)
f = c.persist(y)
await wait([f])
assert s.transition_log
story = s.story(x.key)
assert all(line in s.transition_log for line in story)
assert len(story) < len(s.transition_log)
assert all(x.key == line[0] or x.key in line[-2] for line in story)
assert len(s.story(x.key, y.key)) > len(story)
assert s.story(x.key) == s.story(s.tasks[x.key])
@gen_cluster(nthreads=[], client=True)
async def test_scatter_no_workers(c, s):
with pytest.raises(TimeoutError):
await s.scatter(data={"x": 1}, client="alice", timeout=0.1)
start = time()
with pytest.raises(TimeoutError):
await c.scatter(123, timeout=0.1)
assert time() < start + 1.5
w = Worker(s.address, nthreads=3)
await asyncio.gather(c.scatter(data={"y": 2}, timeout=5), w)
assert w.data["y"] == 2
await w.close()
@gen_cluster(nthreads=[])
async def test_scheduler_sees_memory_limits(s):
w = await Worker(s.address, nthreads=3, memory_limit=12345)
assert s.workers[w.address].memory_limit == 12345
await w.close()
@gen_cluster(client=True)
async def test_retire_workers(c, s, a, b):
[x] = await c.scatter([1], workers=a.address)
[y] = await c.scatter([list(range(1000))], workers=b.address)
assert s.workers_to_close() == [a.address]
workers = await s.retire_workers()
assert list(workers) == [a.address]
assert workers[a.address]["nthreads"] == a.nthreads
assert list(s.nthreads) == [b.address]
assert s.workers_to_close() == []
assert s.workers[b.address].has_what == {s.tasks[x.key], s.tasks[y.key]}
workers = await s.retire_workers()
assert not workers
@gen_cluster(client=True)
async def test_retire_workers_n(c, s, a, b):
await s.retire_workers(n=1, close_workers=True)
assert len(s.workers) == 1
await s.retire_workers(n=0, close_workers=True)
assert len(s.workers) == 1
await s.retire_workers(n=1, close_workers=True)
assert len(s.workers) == 0
await s.retire_workers(n=0, close_workers=True)
assert len(s.workers) == 0
while not (
a.status in (Status.closed, Status.closing, Status.closing_gracefully)
and b.status in (Status.closed, Status.closing, Status.closing_gracefully)
):
await asyncio.sleep(0.01)
@gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4)
async def test_workers_to_close(cl, s, *workers):
with dask.config.set(
{"distributed.scheduler.default-task-durations": {"a": 4, "b": 4, "c": 1}}
):
futures = cl.map(slowinc, [1, 1, 1], key=["a-4", "b-4", "c-1"])
while sum(len(w.processing) for w in s.workers.values()) < 3:
await asyncio.sleep(0.001)
wtc = s.workers_to_close()
assert all(not s.workers[w].processing for w in wtc)
assert len(wtc) == 1
@gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 4)
async def test_workers_to_close_grouped(c, s, *workers):
groups = {
workers[0].address: "a",
workers[1].address: "a",
workers[2].address: "b",
workers[3].address: "b",
}
def key(ws):
return groups[ws.address]
assert set(s.workers_to_close(key=key)) == {w.address for w in workers}
# Assert that job in one worker blocks closure of group
future = c.submit(slowinc, 1, delay=0.2, workers=workers[0].address)
while len(s.rprocessing) < 1:
await asyncio.sleep(0.001)
assert set(s.workers_to_close(key=key)) == {workers[2].address, workers[3].address}
del future
while len(s.rprocessing) > 0:
await asyncio.sleep(0.001)
# Assert that *total* byte count in group determines group priority
av = await c.scatter("a" * 100, workers=workers[0].address)
bv = await c.scatter("b" * 75, workers=workers[2].address)
bv2 = await c.scatter("b" * 75, workers=workers[3].address)
assert set(s.workers_to_close(key=key)) == {workers[0].address, workers[1].address}
@gen_cluster(client=True)
async def test_retire_workers_no_suspicious_tasks(c, s, a, b):
future = c.submit(
slowinc, 100, delay=0.5, workers=a.address, allow_other_workers=True
)
await asyncio.sleep(0.2)
await s.retire_workers(workers=[a.address])
assert all(ts.suspicious == 0 for ts in s.tasks.values())
assert all(tp.suspicious == 0 for tp in s.task_prefixes.values())
@pytest.mark.slow
@pytest.mark.skipif(WINDOWS, reason="num_fds not supported on windows")
@gen_cluster(client=True, nthreads=[], timeout=120)
async def test_file_descriptors(c, s):
await asyncio.sleep(0.1)
da = pytest.importorskip("dask.array")
proc = psutil.Process()
num_fds_1 = proc.num_fds()
N = 20
nannies = await asyncio.gather(*(Nanny(s.address, loop=s.loop) for _ in range(N)))
while len(s.nthreads) < N:
await asyncio.sleep(0.1)
num_fds_2 = proc.num_fds()
await asyncio.sleep(0.2)
num_fds_3 = proc.num_fds()
assert num_fds_3 <= num_fds_2 + N # add some heartbeats
x = da.random.random(size=(1000, 1000), chunks=(25, 25))
x = c.persist(x)
await wait(x)
num_fds_4 = proc.num_fds()
assert num_fds_4 <= num_fds_2 + 2 * N
y = c.persist(x + x.T)
await wait(y)
num_fds_5 = proc.num_fds()
assert num_fds_5 < num_fds_4 + N
await asyncio.sleep(1)
num_fds_6 = proc.num_fds()
assert num_fds_6 < num_fds_5 + N
await asyncio.gather(*(n.close() for n in nannies))
await c.close()
assert not s.rpc.open
for addr, occ in c.rpc.occupied.items():
for comm in occ:
assert comm.closed() or comm.peer_address != s.address, comm
assert not s.stream_comms
while proc.num_fds() > num_fds_1 + N:
await asyncio.sleep(0.01)
@pytest.mark.slow
@nodebug
@gen_cluster(client=True)
async def test_learn_occupancy(c, s, a, b):
futures = c.map(slowinc, range(1000), delay=0.2)
while sum(len(ts.who_has) for ts in s.tasks.values()) < 10:
await asyncio.sleep(0.01)
assert 100 < s.total_occupancy < 1000
for w in [a, b]:
assert 50 < s.workers[w.address].occupancy < 700
@pytest.mark.slow
@nodebug
@gen_cluster(client=True)
async def test_learn_occupancy_2(c, s, a, b):
future = c.map(slowinc, range(1000), delay=0.2)
while not any(ts.who_has for ts in s.tasks.values()):
await asyncio.sleep(0.01)
assert 100 < s.total_occupancy < 1000
@gen_cluster(client=True)
async def test_occupancy_cleardown(c, s, a, b):
s.validate = False
# Inject excess values in s.occupancy
s.workers[a.address].occupancy = 2
s.total_occupancy += 2
futures = c.map(slowinc, range(100), delay=0.01)
await wait(futures)
# Verify that occupancy values have been zeroed out