forked from cylc/cylc-flow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_task_pool.py
More file actions
2690 lines (2311 loc) · 80.1 KB
/
test_task_pool.py
File metadata and controls
2690 lines (2311 loc) · 80.1 KB
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
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from json import loads
import logging
from typing import (
TYPE_CHECKING,
AsyncGenerator,
Callable,
Iterable,
List,
Tuple,
Union,
cast,
)
import pytest
from pytest import param
import re
from cylc.flow import (
CYLC_LOG,
commands,
)
from cylc.flow.cycling.integer import IntegerPoint
from cylc.flow.cycling.iso8601 import ISO8601Point
from cylc.flow.data_messages_pb2 import PbPrerequisite
from cylc.flow.data_store_mgr import TASK_PROXIES
from cylc.flow.exceptions import WorkflowConfigError
from cylc.flow.flow_mgr import FLOW_NONE
from cylc.flow.id import TaskTokens, Tokens
from cylc.flow.run_modes import RunMode
from cylc.flow.task_events_mgr import TaskEventsManager
from cylc.flow.task_outputs import (
TASK_OUTPUT_FAILED,
TASK_OUTPUT_SUCCEEDED,
)
from cylc.flow.task_pool import TaskPool
from cylc.flow.task_state import (
TASK_STATUS_EXPIRED,
TASK_STATUS_FAILED,
TASK_STATUS_PREPARING,
TASK_STATUS_RUNNING,
TASK_STATUS_SUBMIT_FAILED,
TASK_STATUS_SUBMITTED,
TASK_STATUS_SUCCEEDED,
TASK_STATUS_WAITING,
)
if TYPE_CHECKING:
from cylc.flow.cycling import PointBase
from cylc.flow.scheduler import Scheduler
# NOTE: foo and bar have no parents so at start-up (even with the workflow
# paused) they get spawned out to the runahead limit. 2/pub spawns
# immediately too, because we spawn autospawn absolute-triggered tasks as
# well as parentless tasks. 3/asd does not spawn at start, however.
EXAMPLE_FLOW_CFG = {
'scheduling': {
'cycling mode': 'integer',
'initial cycle point': 1,
'final cycle point': 10,
'runahead limit': 'P3',
'graph': {
'P1': 'foo & bar',
'R1/2': 'foo[1] => pub',
'R1/3': 'foo[-P1] => asd'
}
},
'runtime': {
'FAM': {},
'bar': {'inherit': 'FAM'}
}
}
EXAMPLE_FLOW_2_CFG = {
'scheduler': {
'UTC mode': True
},
'scheduling': {
'initial cycle point': '2001',
'runahead limit': 'P3Y',
'graph': {
'P1Y': 'foo',
'R/2025/P1Y': 'foo => bar',
}
},
}
def get_task_ids(
name_point_list: Iterable[Tuple[str, Union['PointBase', str, int]]]
) -> List[str]:
"""Helper function to return sorted task identities
from a list of (name, point) tuples."""
return sorted(f'{point}/{name}' for name, point in name_point_list)
def assert_expected_log(
caplog_instance: pytest.LogCaptureFixture,
expected_log_substrings: List[str]
) -> List[str]:
"""Helper function to check that expected (substrings of) log messages
are actually in the log.
Returns the list of actual logged messages.
Args:
caplog_instance: The instance of the caplog fixture for the particular
test.
expected_log_substrings: The expected, possibly partial, log messages.
"""
logged_messages = [i[2] for i in caplog_instance.record_tuples]
assert len(logged_messages) == len(expected_log_substrings)
for actual, expected in zip(
sorted(logged_messages), sorted(expected_log_substrings)):
assert expected in actual
return logged_messages
@pytest.fixture(scope='module')
async def mod_example_flow(
mod_flow: Callable, mod_scheduler: Callable, mod_run: Callable
) -> AsyncGenerator['Scheduler', None]:
"""Return a scheduler for interrogating its task pool.
This is module-scoped so faster than example_flow, but should only be used
where the test does not mutate the state of the scheduler or task pool.
"""
id_ = mod_flow(EXAMPLE_FLOW_CFG)
schd: 'Scheduler' = mod_scheduler(id_, paused_start=True)
async with mod_run(schd, level=logging.DEBUG):
yield schd
@pytest.fixture
async def example_flow(
flow: Callable,
scheduler: Callable,
start,
caplog: pytest.LogCaptureFixture,
) -> AsyncGenerator['Scheduler', None]:
"""Return a scheduler for interrogating its task pool.
This is function-scoped so slower than mod_example_flow; only use this
when the test mutates the scheduler or task pool.
"""
# The run(schd) fixture doesn't work for modifying the DB, so have to
# set up caplog and do schd.install()/.initialise()/.configure() instead
caplog.set_level(logging.INFO, CYLC_LOG)
id_ = flow(EXAMPLE_FLOW_CFG)
schd: 'Scheduler' = scheduler(id_)
async with start(schd, level=logging.DEBUG):
yield schd
@pytest.fixture(scope='module')
async def mod_example_flow_2(
mod_flow: Callable, mod_scheduler: Callable, mod_run: Callable
) -> AsyncGenerator['Scheduler', None]:
"""Return a scheduler for interrogating its task pool.
This is module-scoped so faster than example_flow, but should only be used
where the test does not mutate the state of the scheduler or task pool.
"""
id_ = mod_flow(EXAMPLE_FLOW_2_CFG)
schd: 'Scheduler' = mod_scheduler(id_, paused_start=True)
async with mod_run(schd):
yield schd
@pytest.mark.parametrize(
'ids, expected_tasks_to_hold_ids',
[
param(
['1/foo', '3/asd'],
['1/foo', '3/asd'],
id="Active & inactive tasks",
),
param(
['1/FAM', '2/FAM', '6/FAM'],
['1/bar', '2/bar', '6/bar'],
id="Family names hold active and future tasks",
),
param(
['1/grogu', 'H/foo', '20/foo', '1/pub'],
[],
id="Non-existent task name or invalid cycle point",
),
param(
['1/foo:waiting', '1/foo:failed', '6/bar:waiting'],
['1/foo'],
id=(
"Specifying task state works for active tasks,"
" not inactive tasks"
),
),
],
)
async def test_hold_tasks(
ids: List[str],
expected_tasks_to_hold_ids: List[str],
example_flow: 'Scheduler',
caplog: pytest.LogCaptureFixture,
db_select: Callable
) -> None:
"""Test TaskPool.hold_tasks().
Also tests TaskPool_explicit_match_tasks_to_hold() in the process;
kills 2 birds with 1 stone.
Params:
items: Arg passed to hold_tasks().
expected_tasks_to_hold_ids: Expected IDs of the tasks that get put in
the TaskPool.tasks_to_hold set, of the form "{point}/{name}"/
expected_warnings: Expected to be logged.
"""
expected_tasks_to_hold_ids = sorted(expected_tasks_to_hold_ids)
caplog.set_level(logging.WARNING, CYLC_LOG)
task_pool = example_flow.pool
task_pool.hold_tasks(
{cast('TaskTokens', Tokens(id_, relative=True)) for id_ in ids}
)
for itask in task_pool.get_tasks():
hold_expected = itask.identity in expected_tasks_to_hold_ids
assert itask.state.is_held is hold_expected
assert get_task_ids(task_pool.tasks_to_hold) == expected_tasks_to_hold_ids
db_held_tasks = db_select(example_flow, True, 'tasks_to_hold')
assert get_task_ids(db_held_tasks) == expected_tasks_to_hold_ids
async def test_release_held_tasks(
example_flow: 'Scheduler', db_select: Callable
) -> None:
"""Test TaskPool.release_held_tasks().
For a workflow with held active tasks 1/foo & 1/bar, and held inactive task
3/asd.
We skip testing the matching logic here because it would be slow using the
function-scoped example_flow fixture, and it would repeat what is covered
in test_hold_tasks().
"""
# Setup
task_pool = example_flow.pool
expected_tasks_to_hold_ids = sorted(['1/foo', '1/bar', '3/asd'])
task_pool.hold_tasks(
{
TaskTokens('1', 'foo'),
TaskTokens('1', 'bar'),
TaskTokens('3', 'asd'),
}
)
for itask in task_pool.get_tasks():
hold_expected = itask.identity in expected_tasks_to_hold_ids
assert itask.state.is_held is hold_expected
assert get_task_ids(task_pool.tasks_to_hold) == expected_tasks_to_hold_ids
db_tasks_to_hold = db_select(example_flow, True, 'tasks_to_hold')
assert get_task_ids(db_tasks_to_hold) == expected_tasks_to_hold_ids
# Test
task_pool.release_held_tasks(
{TaskTokens('1', 'foo'), TaskTokens('3', 'asd')}
)
for itask in task_pool.get_tasks():
assert itask.state.is_held is (itask.identity == '1/bar')
expected_tasks_to_hold_ids = sorted(['1/bar'])
assert get_task_ids(task_pool.tasks_to_hold) == expected_tasks_to_hold_ids
db_tasks_to_hold = db_select(example_flow, True, 'tasks_to_hold')
assert get_task_ids(db_tasks_to_hold) == expected_tasks_to_hold_ids
@pytest.mark.parametrize(
'hold_after_point, expected_held_task_ids',
[
(
'0',
[
'1/foo',
'1/bar',
'2/foo',
'2/bar',
'2/pub',
'3/foo',
'3/bar',
'4/foo',
'4/bar',
'5/foo',
'5/bar',
],
),
(
'1',
[
'2/foo',
'2/bar',
'2/pub',
'3/foo',
'3/bar',
'4/foo',
'4/bar',
'5/foo',
'5/bar',
],
),
],
)
async def test_hold_point(
hold_after_point: str,
expected_held_task_ids: List[str],
example_flow: 'Scheduler', db_select: Callable
) -> None:
"""Test TaskPool.set_hold_point() and .release_hold_point()"""
expected_held_task_ids = sorted(expected_held_task_ids)
task_pool = example_flow.pool
# Test hold
task_pool.set_hold_point(IntegerPoint(hold_after_point))
assert ('holdcp', str(hold_after_point)) in db_select(
example_flow, True, 'workflow_params')
for itask in task_pool.get_tasks():
hold_expected = itask.identity in expected_held_task_ids
assert itask.state.is_held is hold_expected
assert get_task_ids(task_pool.tasks_to_hold) == expected_held_task_ids
db_tasks_to_hold = db_select(example_flow, True, 'tasks_to_hold')
assert get_task_ids(db_tasks_to_hold) == expected_held_task_ids
# Test release
task_pool.release_hold_point()
assert db_select(example_flow, True, 'workflow_params', key='holdcp') == [
('holdcp', None)
]
for itask in task_pool.get_tasks():
assert itask.state.is_held is False
assert task_pool.tasks_to_hold == set()
assert db_select(example_flow, True, 'tasks_to_hold') == []
@pytest.mark.parametrize(
'status,should_trigger',
[
(TASK_STATUS_WAITING, True),
(TASK_STATUS_PREPARING, False),
(TASK_STATUS_SUBMITTED, False),
(TASK_STATUS_RUNNING, False),
(TASK_STATUS_SUCCEEDED, True),
]
)
async def test_trigger_states(
status: str, should_trigger: bool, one: 'Scheduler', start: Callable
):
"""It should only trigger tasks in compatible states."""
async with start(one):
itask = one.pool.get_task(IntegerPoint('1'), 'one')
# reset task a to the provided state
itask.state.reset(status)
# try triggering the task
await commands.run_cmd(
commands.force_trigger_tasks(one, ['1/one'], []))
# retrieve the task again - the original may have been removed
itask = one.pool.get_task(IntegerPoint('1'), 'one')
# check whether the task triggered
assert itask.is_manual_submit == should_trigger
async def test_preparing_tasks_on_restart(one_conf, flow, scheduler, start):
"""Preparing tasks should be reset to waiting on restart.
This forces preparation to be re-done on restart so that it uses the
new configuration.
See discussion on: https://github.com/cylc/cylc-flow/pull/4668
"""
id_ = flow(one_conf)
# start the workflow, reset a task to preparing
one = scheduler(id_)
async with start(one):
itask = one.pool.get_tasks()[0]
itask.state.reset(TASK_STATUS_PREPARING)
# when we restart the task should have been reset to waiting
one = scheduler(id_)
async with start(one):
itask = one.pool.get_tasks()[0]
assert itask.state(TASK_STATUS_WAITING)
itask.state.reset(TASK_STATUS_SUCCEEDED)
# whereas if we reset the task to succeeded the state is not reset
one = scheduler(id_)
async with start(one):
itask = one.pool.get_tasks()[0]
assert itask.state(TASK_STATUS_SUCCEEDED)
async def test_reload_stopcp(
flow: Callable, scheduler: Callable, start: Callable
):
"""Test that the task pool stopping point does not revert to the final
cycle point on reload."""
cfg = {
'scheduler': {
'allow implicit tasks': True,
'cycle point format': 'CCYY',
},
'scheduling': {
'initial cycle point': 2010,
'stop after cycle point': 2020,
'final cycle point': 2030,
'graph': {
'P1Y': 'anakin'
}
}
}
schd: 'Scheduler' = scheduler(flow(cfg))
async with start(schd):
assert str(schd.pool.stop_point) == '2020'
await commands.run_cmd(commands.reload_workflow(schd))
assert str(schd.pool.stop_point) == '2020'
async def test_runahead_after_remove(
example_flow: 'Scheduler'
) -> None:
"""The runahead limit should be recomputed after tasks are removed.
"""
task_pool = example_flow.pool
assert int(task_pool.runahead_limit_point) == 4
# No change after removing an intermediate cycle.
await commands.run_cmd(commands.remove_tasks(example_flow, ['3/*'], ["1"]))
assert int(task_pool.runahead_limit_point) == 4
# Should update after removing the first point.
await commands.run_cmd(commands.remove_tasks(example_flow, ['1/*'], ["1"]))
assert int(task_pool.runahead_limit_point) == 5
async def test_load_db_bad_platform(
flow: Callable, scheduler: Callable, start: Callable, one_conf: Callable
):
"""Test that loading an unavailable platform from the database doesn't
cause calamitous failure."""
schd: 'Scheduler' = scheduler(flow(one_conf))
async with start(schd):
result = schd.pool.load_db_task_pool_for_restart(0, (
'1', 'one', '{"1": 1}', "0", False, False, "failed",
False, 1, '', 'culdee-fell-summit', '', '', '', '{}'
))
assert result == 'culdee-fell-summit'
def list_tasks(schd):
"""Return a sorted list of task pool tasks.
Returns a list in the format:
[
(cycle, task, state)
]
"""
return sorted(
(itask.tokens['cycle'], itask.tokens['task'], itask.state.status)
for itask in schd.pool.get_tasks()
)
@pytest.mark.parametrize(
'graph_1, graph_2, '
'expected_1, expected_2, expected_3, expected_4',
[
param( # Restart after adding a prerequisite to task z
'''a => z
b => z''',
'''a => z
b => z
c => z''',
[
('1', 'a', 'running'),
('1', 'b', 'running'),
],
[
('1', 'b', 'running'),
('1', 'z', 'waiting'),
],
[
('1', 'b', 'running'),
('1', 'z', 'waiting'),
],
[
{('1', 'a', 'succeeded'): 'satisfied naturally'},
{('1', 'b', 'succeeded'): False},
{('1', 'c', 'succeeded'): False},
],
id='added'
),
param( # Restart after removing a prerequisite from task z
'''a => z
b => z
c => z''',
'''a => z
b => z''',
[
('1', 'a', 'running'),
('1', 'b', 'running'),
('1', 'c', 'running'),
],
[
('1', 'b', 'running'),
('1', 'c', 'running'),
('1', 'z', 'waiting'),
],
[
('1', 'b', 'running'),
('1', 'c', 'running'),
('1', 'z', 'waiting'),
],
[
{('1', 'a', 'succeeded'): 'satisfied naturally'},
{('1', 'b', 'succeeded'): False},
],
id='removed'
)
]
)
async def test_restart_prereqs(
flow, scheduler, start,
graph_1, graph_2,
expected_1, expected_2, expected_3, expected_4
):
"""It should handle graph prerequisites change on restart.
Prerequisite changes must be applied to tasks already in the pool.
See https://github.com/cylc/cylc-flow/pull/5334
"""
conf = {
'scheduler': {'allow implicit tasks': 'True'},
'scheduling': {
'graph': {
'R1': graph_1
}
}
}
id_ = flow(conf)
schd: Scheduler = scheduler(id_, paused_start=False)
async with start(schd):
# Release tasks 1/a and 1/b
schd.pool.release_runahead_tasks()
schd.release_tasks_to_run()
assert list_tasks(schd) == expected_1
# Mark 1/a as succeeded and spawn 1/z
task_a = schd.pool.get_tasks()[0]
schd.pool.task_events_mgr.process_message(task_a, 1, 'succeeded')
assert list_tasks(schd) == expected_2
# Save our progress
schd.workflow_db_mgr.put_task_pool(schd.pool)
# Edit the workflow to add a new dependency on "z"
conf['scheduling']['graph']['R1'] = graph_2
id_ = flow(conf, workflow_id=id_)
# Restart it
schd = scheduler(id_, run_mode='simulation', paused_start=False)
async with start(schd):
# Load jobs from db
schd.workflow_db_mgr.pri_dao.select_jobs_for_restart(
schd.data_store_mgr.insert_db_job
)
assert list_tasks(schd) == expected_3
# To cover some code for loading prereqs from the DB at restart:
schd.data_store_mgr.update_data_structure()
# Check resulting dependencies of task z
task_z = [
t for t in schd.pool.get_tasks() if t.tdef.name == "z"
][0]
assert sorted(
(
p._satisfied
for p in task_z.state.prerequisites
),
key=lambda d: tuple(d.keys())[0],
) == expected_4
@pytest.mark.parametrize(
'graph_1, graph_2, '
'expected_1, expected_2, expected_3, expected_4',
[
param( # Reload after adding a prerequisite to task z
'''a => z
b => z''',
'''a => z
b => z
c => z''',
[
('1', 'a', 'running'),
('1', 'b', 'running'),
],
[
('1', 'b', 'running'),
('1', 'z', 'waiting'),
],
[
('1', 'b', 'running'),
('1', 'z', 'waiting'),
],
[
{('1', 'a', 'succeeded'): 'satisfied naturally'},
{('1', 'b', 'succeeded'): False},
{('1', 'c', 'succeeded'): False},
],
id='added'
),
param( # Reload after removing a prerequisite from task z
'''a => z
b => z
c => z''',
'''a => z
b => z''',
[
('1', 'a', 'running'),
('1', 'b', 'running'),
('1', 'c', 'running'),
],
[
('1', 'b', 'running'),
('1', 'c', 'running'),
('1', 'z', 'waiting'),
],
[
('1', 'b', 'running'),
('1', 'c', 'running'),
('1', 'z', 'waiting'),
],
[
{('1', 'a', 'succeeded'): 'satisfied naturally'},
{('1', 'b', 'succeeded'): False},
],
id='removed'
)
]
)
async def test_reload_prereqs(
flow, scheduler, start,
graph_1, graph_2,
expected_1, expected_2, expected_3, expected_4
):
"""It should handle graph prerequisites change on reload.
Prerequisite changes must be applied to tasks already in the pool.
See https://github.com/cylc/cylc-flow/pull/5334
"""
conf = {
'scheduler': {'allow implicit tasks': 'True'},
'scheduling': {
'graph': {
'R1': graph_1
}
}
}
id_ = flow(conf)
schd: Scheduler = scheduler(id_, paused_start=False)
async with start(schd):
# Release tasks 1/a and 1/b
schd.pool.release_runahead_tasks()
schd.release_tasks_to_run()
assert list_tasks(schd) == expected_1
# Mark 1/a as succeeded and spawn 1/z
task_a = schd.pool.get_tasks()[0]
schd.pool.task_events_mgr.process_message(task_a, 1, 'succeeded')
assert list_tasks(schd) == expected_2
# Modify flow.cylc to add a new dependency on "z"
conf['scheduling']['graph']['R1'] = graph_2
flow(conf, workflow_id=id_)
# Reload the workflow config
await commands.run_cmd(commands.reload_workflow(schd))
assert list_tasks(schd) == expected_3
# Check resulting dependencies of task z
task_z = [
t for t in schd.pool.get_tasks() if t.tdef.name == "z"
][0]
assert sorted(
(
p._satisfied
for p in task_z.state.prerequisites
),
key=lambda d: tuple(d.keys())[0],
) == expected_4
async def _test_restart_prereqs_sat():
schd: Scheduler
# YIELD: the workflow has now started...
schd = yield
await schd.update_data_structure()
# Release tasks 1/a and 1/b
schd.pool.release_runahead_tasks()
schd.release_tasks_to_run()
assert list_tasks(schd) == [
('1', 'a', 'running'),
('1', 'b', 'running')
]
# Mark both as succeeded and spawn 1/c
for itask in schd.pool.get_tasks():
schd.pool.task_events_mgr.process_message(itask, 1, 'succeeded')
schd.workflow_db_mgr.put_update_task_outputs(itask)
schd.pool.remove_if_complete(itask)
schd.workflow_db_mgr.process_queued_ops()
assert list_tasks(schd) == [
('1', 'c', 'waiting')
]
# YIELD: the workflow has now restarted or reloaded with the new config...
schd = yield
await schd.update_data_structure()
assert list_tasks(schd) == [
('1', 'c', 'waiting')
]
# Check resulting dependencies of task z
task_c = schd.pool.get_tasks()[0]
assert sorted(
(*key, satisfied)
for prereq in task_c.state.prerequisites
for key, satisfied in prereq.items()
) == [
('1', 'a', 'succeeded', 'satisfied naturally'),
('1', 'b', 'succeeded', 'satisfied from database')
]
# The prereqs in the data store should have been updated too
# await schd.update_data_structure()
tasks = (
schd.data_store_mgr.data[schd.data_store_mgr.workflow_id][TASK_PROXIES]
)
task_c_prereqs: List[PbPrerequisite] = tasks[
schd.data_store_mgr.id_.duplicate(cycle='1', task='c').id
].prerequisites
assert sorted(
(condition.task_proxy, condition.satisfied, condition.message)
for prereq in task_c_prereqs
for condition in prereq.conditions
) == [
('1/a', True, 'satisfied naturally'),
('1/b', True, 'satisfied from database'),
]
# and we're done, yield back control and return
yield
@pytest.mark.parametrize('do_restart', [True, False])
async def test_graph_change_prereq_satisfaction(
flow, scheduler, start, do_restart
):
"""It should handle graph prerequisites change on reload/restart.
If the graph is changed to add a dependency which has been previously
satisfied, then Cylc should perform a DB check and mark the prerequsite
as satisfied accordingly.
See https://github.com/cylc/cylc-flow/pull/5334
"""
conf = {
'scheduler': {'allow implicit tasks': 'True'},
'scheduling': {
'graph': {
'R1': '''
a => c
b
'''
}
}
}
id_ = flow(conf)
schd = scheduler(id_, run_mode='simulation', paused_start=False)
test = _test_restart_prereqs_sat()
await test.asend(None)
if do_restart:
async with start(schd):
# start the workflow and run part 1 of the tests
await test.asend(schd)
# shutdown and change the workflow definiton
conf['scheduling']['graph']['R1'] += '\nb => c'
flow(conf, workflow_id=id_)
schd = scheduler(id_, run_mode='simulation', paused_start=False)
async with start(schd):
# restart the workflow and run part 2 of the tests
await test.asend(schd)
else:
async with start(schd):
await test.asend(schd)
# Modify flow.cylc to add a new dependency on "b"
conf['scheduling']['graph']['R1'] += '\nb => c'
flow(conf, workflow_id=id_)
# Reload the workflow config
await commands.run_cmd(commands.reload_workflow(schd))
await test.asend(schd)
async def test_runahead_limit_for_sequence_before_start_cycle(
flow,
scheduler,
start,
):
"""It should obey the runahead limit.
Ensure the runahead limit is computed correctly for sequences before the
start cycle
See https://github.com/cylc/cylc-flow/issues/5603
"""
id_ = flow({
'scheduler': {'allow implicit tasks': 'True'},
'scheduling': {
'initial cycle point': '2000',
'runahead limit': 'P2Y',
'graph': {
'R1/2000': 'a',
'P1Y': 'b[-P1Y] => b',
},
}
})
schd = scheduler(id_, startcp='2005')
async with start(schd):
assert str(schd.pool.runahead_limit_point) == '20070101T0000Z'
def list_pool_from_db(schd):
"""Returns the task pool table as a sorted list."""
db_task_pool = []
schd.workflow_db_mgr.pri_dao.select_task_pool(
lambda _, row: db_task_pool.append(row)
)
return sorted(db_task_pool)
async def test_db_update_on_removal(
flow,
scheduler,
start,
):
"""It should updated the task_pool table when tasks complete.
There was a bug where the task_pool table was only being updated when tasks
in the pool were updated. This meant that if a task was removed the DB
would not reflect this change and would hold a record of the task in the
wrong state.
This test ensures that the DB is updated when a task is removed from the
pool.
See: https://github.com/cylc/cylc-flow/issues/5598
"""
id_ = flow({
'scheduler': {
'allow implicit tasks': 'true',
},
'scheduling': {
'graph': {
'R1': 'a',
},
},
})
schd = scheduler(id_)
async with start(schd):
task_a = schd.pool.get_tasks()[0]
# set the task to running
schd.pool.task_events_mgr.process_message(task_a, 1, 'started')
# update the db
await schd.update_data_structure()
schd.workflow_db_mgr.process_queued_ops()
# the task should appear in the DB
assert list_pool_from_db(schd) == [
['1', 'a', 'running', 0],
]
# mark the task as succeeded and allow it to be removed from the pool
schd.pool.task_events_mgr.process_message(task_a, 1, 'succeeded')
schd.pool.remove_if_complete(task_a)
# update the DB, note no new tasks have been added to the pool
await schd.update_data_structure()
schd.workflow_db_mgr.process_queued_ops()
# the task should be gone from the DB
assert list_pool_from_db(schd) == []
async def test_no_flow_tasks_dont_spawn(
flow,
scheduler,
start,
):
"""Ensure no-flow tasks don't spawn downstreams.
No-flow tasks (i.e `--flow=none`) are not attached to any "flow".
See https://github.com/cylc/cylc-flow/issues/5613
"""
id_ = flow({
'scheduling': {
'graph': {
'R1': 'a => b => c'
}
},
})
schd: Scheduler = scheduler(id_)
async with start(schd):
task_a = schd.pool.get_tasks()[0]
# set as no-flow:
task_a.flow_nums = set()
# Set as completed: should not spawn children.
schd.pool.set_prereqs_and_outputs(
{task_a.tokens}, [], [], [FLOW_NONE]
)
assert not schd.pool.get_tasks()
for flow_nums, expected_pool in (
# outputs yielded from a no-flow task should not spawn downstreams
(set(), []),
# outputs yielded from a task with flow numbers should spawn
# downstreams in the same flow
({1}, [('1/b', {1})]),
):
# set the flow-nums on 1/a
task_a.flow_nums = flow_nums
# spawn on the succeeded output
schd.pool.spawn_on_output(task_a, TASK_OUTPUT_SUCCEEDED)
schd.pool.spawn_on_all_outputs(task_a)
# ensure the pool is as expected
assert [
(itask.identity, itask.flow_nums)
for itask in schd.pool.get_tasks()