Debian Codegraph @

tests/integration/test_task_pool.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 from json import loads
18 import logging
19 import re
20 from typing import (
21 TYPE_CHECKING,
22 AsyncGenerator,
23 Callable,
24 Iterable,
25 List,
26 Tuple,
27 Union,
28 cast,
29 )
30
31 import pytest
32 from pytest import param
33
34 from cylc.flow import (
35 CYLC_LOG,
36 commands,
37 )
38 from cylc.flow.cycling.integer import IntegerPoint
39 from cylc.flow.cycling.iso8601 import ISO8601Point
40 from cylc.flow.data_messages_pb2 import PbPrerequisite
41 from cylc.flow.data_store_mgr import TASK_PROXIES
42 from cylc.flow.exceptions import WorkflowConfigError
43 from cylc.flow.flow_mgr import FLOW_NONE
44 from cylc.flow.id import (
45 TaskTokens,
46 Tokens,
47 )
48 from cylc.flow.run_modes import RunMode
49 from cylc.flow.task_events_mgr import TaskEventsManager
50 from cylc.flow.task_outputs import (
51 TASK_OUTPUT_FAILED,
52 TASK_OUTPUT_SUCCEEDED,
53 )
54 from cylc.flow.task_pool import TaskPool
55 from cylc.flow.task_state import (
56 TASK_STATUS_EXPIRED,
57 TASK_STATUS_FAILED,
58 TASK_STATUS_PREPARING,
59 TASK_STATUS_RUNNING,
60 TASK_STATUS_SUBMIT_FAILED,
61 TASK_STATUS_SUBMITTED,
62 TASK_STATUS_SUCCEEDED,
63 TASK_STATUS_WAITING,
64 )
65
66
67 if TYPE_CHECKING:
68 from cylc.flow.cycling import PointBase
69 from cylc.flow.scheduler import Scheduler
70
71
72 # NOTE: foo and bar have no parents so at start-up (even with the workflow
73 # paused) they get spawned out to the runahead limit. 2/pub spawns
74 # immediately too, because we spawn autospawn absolute-triggered tasks as
75 # well as parentless tasks. 3/asd does not spawn at start, however.
76 EXAMPLE_FLOW_CFG = {
77 'scheduling': {
78 'cycling mode': 'integer',
79 'initial cycle point': 1,
80 'final cycle point': 10,
81 'runahead limit': 'P3',
82 'graph': {
83 'P1': 'foo & bar',
84 'R1/2': 'foo[1] => pub',
85 'R1/3': 'foo[-P1] => asd'
86 }
87 },
88 'runtime': {
89 'FAM': {},
90 'bar': {'inherit': 'FAM'}
91 }
92 }
93
94
95 EXAMPLE_FLOW_2_CFG = {
96 'scheduler': {
97 'UTC mode': True
98 },
99 'scheduling': {
100 'initial cycle point': '2001',
101 'runahead limit': 'P3Y',
102 'graph': {
103 'P1Y': 'foo',
104 'R/2025/P1Y': 'foo => bar',
105 }
106 },
107 }
108
109
110 def get_task_ids(
111 name_point_list: Iterable[Tuple[str, Union['PointBase', str, int]]]
112 ) -> List[str]:
113 """Helper function to return sorted task identities
114 from a list of (name, point) tuples."""
115 return sorted(f'{point}/{name}' for name, point in name_point_list)
116
117
118 def assert_expected_log(
119 caplog_instance: pytest.LogCaptureFixture,
120 expected_log_substrings: List[str]
121 ) -> List[str]:
122 """Helper function to check that expected (substrings of) log messages
123 are actually in the log.
124
125 Returns the list of actual logged messages.
126
127 Args:
128 caplog_instance: The instance of the caplog fixture for the particular
129 test.
130 expected_log_substrings: The expected, possibly partial, log messages.
131 """
132 logged_messages = [i[2] for i in caplog_instance.record_tuples]
133 assert len(logged_messages) == len(expected_log_substrings)
134 for actual, expected in zip(
135 sorted(logged_messages), sorted(expected_log_substrings)):
136 assert expected in actual
137 return logged_messages
138
139
140 @pytest.fixture(scope='module')
141 async def mod_example_flow(
142 mod_flow: Callable, mod_scheduler: Callable, mod_run: Callable
143 ) -> AsyncGenerator['Scheduler', None]:
144 """Return a scheduler for interrogating its task pool.
145
146 This is module-scoped so faster than example_flow, but should only be used
147 where the test does not mutate the state of the scheduler or task pool.
148 """
149 id_ = mod_flow(EXAMPLE_FLOW_CFG)
150 schd: 'Scheduler' = mod_scheduler(id_, paused_start=True)
151 async with mod_run(schd, level=logging.DEBUG):
152 yield schd
153
154
155 @pytest.fixture
156 async def example_flow(
157 flow: Callable,
158 scheduler: Callable,
159 start,
160 caplog: pytest.LogCaptureFixture,
161 ) -> AsyncGenerator['Scheduler', None]:
162 """Return a scheduler for interrogating its task pool.
163
164 This is function-scoped so slower than mod_example_flow; only use this
165 when the test mutates the scheduler or task pool.
166 """
167 # The run(schd) fixture doesn't work for modifying the DB, so have to
168 # set up caplog and do schd.install()/.initialise()/.configure() instead
169 caplog.set_level(logging.INFO, CYLC_LOG)
170 id_ = flow(EXAMPLE_FLOW_CFG)
171 schd: 'Scheduler' = scheduler(id_)
172 async with start(schd, level=logging.DEBUG):
173 yield schd
174
175
176 @pytest.fixture(scope='module')
177 async def mod_example_flow_2(
178 mod_flow: Callable, mod_scheduler: Callable, mod_run: Callable
179 ) -> AsyncGenerator['Scheduler', None]:
180 """Return a scheduler for interrogating its task pool.
181
182 This is module-scoped so faster than example_flow, but should only be used
183 where the test does not mutate the state of the scheduler or task pool.
184 """
185 id_ = mod_flow(EXAMPLE_FLOW_2_CFG)
186 schd: 'Scheduler' = mod_scheduler(id_, paused_start=True)
187 async with mod_run(schd):
188 yield schd
189
190
191 @pytest.mark.parametrize(
192 'ids, expected_tasks_to_hold_ids',
193 [
194 param(
195 ['1/foo', '3/asd'],
196 ['1/foo', '3/asd'],
197 id="Active & inactive tasks",
198 ),
199 param(
200 ['1/FAM', '2/FAM', '6/FAM'],
201 ['1/bar', '2/bar', '6/bar'],
202 id="Family names hold active and future tasks",
203 ),
204 param(
205 ['1/grogu', 'H/foo', '20/foo', '1/pub'],
206 [],
207 id="Non-existent task name or invalid cycle point",
208 ),
209 param(
210 ['1/foo:waiting', '1/foo:failed', '6/bar:waiting'],
211 ['1/foo'],
212 id=(
213 "Specifying task state works for active tasks,"
214 " not inactive tasks"
215 ),
216 ),
217 ],
218 )
219 async def test_hold_tasks(
220 ids: List[str],
221 expected_tasks_to_hold_ids: List[str],
222 example_flow: 'Scheduler',
223 caplog: pytest.LogCaptureFixture,
224 db_select: Callable
225 ) -> None:
226 """Test TaskPool.hold_tasks().
227
228 Also tests TaskPool_explicit_match_tasks_to_hold() in the process;
229 kills 2 birds with 1 stone.
230
231 Params:
232 items: Arg passed to hold_tasks().
233 expected_tasks_to_hold_ids: Expected IDs of the tasks that get put in
234 the TaskPool.tasks_to_hold set, of the form "{point}/{name}"/
235 expected_warnings: Expected to be logged.
236 """
237 expected_tasks_to_hold_ids = sorted(expected_tasks_to_hold_ids)
238 caplog.set_level(logging.WARNING, CYLC_LOG)
239 task_pool = example_flow.pool
240 task_pool.hold_tasks(
241 {cast('TaskTokens', Tokens(id_, relative=True)) for id_ in ids}
242 )
243
244 for itask in task_pool.get_tasks():
245 hold_expected = itask.identity in expected_tasks_to_hold_ids
246 assert itask.state.is_held is hold_expected
247
248 assert get_task_ids(task_pool.tasks_to_hold) == expected_tasks_to_hold_ids
249
250 db_held_tasks = db_select(example_flow, True, 'tasks_to_hold')
251 assert get_task_ids(db_held_tasks) == expected_tasks_to_hold_ids
252
253
254 async def test_release_held_tasks(
255 example_flow: 'Scheduler', db_select: Callable
256 ) -> None:
257 """Test TaskPool.release_held_tasks().
258
259 For a workflow with held active tasks 1/foo & 1/bar, and held inactive task
260 3/asd.
261
262 We skip testing the matching logic here because it would be slow using the
263 function-scoped example_flow fixture, and it would repeat what is covered
264 in test_hold_tasks().
265 """
266 # Setup
267 task_pool = example_flow.pool
268 expected_tasks_to_hold_ids = sorted(['1/foo', '1/bar', '3/asd'])
269 task_pool.hold_tasks(
270 {
271 TaskTokens('1', 'foo'),
272 TaskTokens('1', 'bar'),
273 TaskTokens('3', 'asd'),
274 }
275 )
276 for itask in task_pool.get_tasks():
277 hold_expected = itask.identity in expected_tasks_to_hold_ids
278 assert itask.state.is_held is hold_expected
279 assert get_task_ids(task_pool.tasks_to_hold) == expected_tasks_to_hold_ids
280 db_tasks_to_hold = db_select(example_flow, True, 'tasks_to_hold')
281 assert get_task_ids(db_tasks_to_hold) == expected_tasks_to_hold_ids
282
283 # Test
284 task_pool.release_held_tasks(
285 {TaskTokens('1', 'foo'), TaskTokens('3', 'asd')}
286 )
287 for itask in task_pool.get_tasks():
288 assert itask.state.is_held is (itask.identity == '1/bar')
289
290 expected_tasks_to_hold_ids = sorted(['1/bar'])
291 assert get_task_ids(task_pool.tasks_to_hold) == expected_tasks_to_hold_ids
292
293 db_tasks_to_hold = db_select(example_flow, True, 'tasks_to_hold')
294 assert get_task_ids(db_tasks_to_hold) == expected_tasks_to_hold_ids
295
296
297 @pytest.mark.parametrize(
298 'hold_after_point, expected_held_task_ids',
299 [
300 (
301 '0',
302 [
303 '1/foo',
304 '1/bar',
305 '2/foo',
306 '2/bar',
307 '2/pub',
308 '3/foo',
309 '3/bar',
310 '4/foo',
311 '4/bar',
312 '5/foo',
313 '5/bar',
314 ],
315 ),
316 (
317 '1',
318 [
319 '2/foo',
320 '2/bar',
321 '2/pub',
322 '3/foo',
323 '3/bar',
324 '4/foo',
325 '4/bar',
326 '5/foo',
327 '5/bar',
328 ],
329 ),
330 ],
331 )
332 async def test_hold_point(
333 hold_after_point: str,
334 expected_held_task_ids: List[str],
335 example_flow: 'Scheduler', db_select: Callable
336 ) -> None:
337 """Test TaskPool.set_hold_point() and .release_hold_point()"""
338 expected_held_task_ids = sorted(expected_held_task_ids)
339 task_pool = example_flow.pool
340
341 # Test hold
342 task_pool.set_hold_point(IntegerPoint(hold_after_point))
343
344 assert ('holdcp', str(hold_after_point)) in db_select(
345 example_flow, True, 'workflow_params')
346
347 for itask in task_pool.get_tasks():
348 hold_expected = itask.identity in expected_held_task_ids
349 assert itask.state.is_held is hold_expected
350
351 assert get_task_ids(task_pool.tasks_to_hold) == expected_held_task_ids
352 db_tasks_to_hold = db_select(example_flow, True, 'tasks_to_hold')
353 assert get_task_ids(db_tasks_to_hold) == expected_held_task_ids
354
355 # Test release
356 task_pool.release_hold_point()
357
358 assert db_select(example_flow, True, 'workflow_params', key='holdcp') == [
359 ('holdcp', None)
360 ]
361
362 for itask in task_pool.get_tasks():
363 assert itask.state.is_held is False
364
365 assert task_pool.tasks_to_hold == set()
366 assert db_select(example_flow, True, 'tasks_to_hold') == []
367
368
369 @pytest.mark.parametrize(
370 'status,should_trigger',
371 [
372 (TASK_STATUS_WAITING, True),
373 (TASK_STATUS_PREPARING, False),
374 (TASK_STATUS_SUBMITTED, False),
375 (TASK_STATUS_RUNNING, False),
376 (TASK_STATUS_SUCCEEDED, True),
377 ]
378 )
379 async def test_trigger_states(
380 status: str, should_trigger: bool, one: 'Scheduler', start: Callable
381 ):
382 """It should only trigger tasks in compatible states."""
383 async with start(one):
384 itask = one.pool.get_task(IntegerPoint('1'), 'one')
385
386 # reset task a to the provided state
387 itask.state.reset(status)
388
389 # try triggering the task
390 await commands.run_cmd(
391 commands.force_trigger_tasks(one, ['1/one'], []))
392
393 # retrieve the task again - the original may have been removed
394 itask = one.pool.get_task(IntegerPoint('1'), 'one')
395
396 # check whether the task triggered
397 assert itask.is_manual_submit == should_trigger
398
399
400 async def test_preparing_tasks_on_restart(one_conf, flow, scheduler, start):
401 """Preparing tasks should be reset to waiting on restart.
402
403 This forces preparation to be re-done on restart so that it uses the
404 new configuration.
405
406 See discussion on: https://github.com/cylc/cylc-flow/pull/4668
407
408 """
409 id_ = flow(one_conf)
410
411 # start the workflow, reset a task to preparing
412 one = scheduler(id_)
413 async with start(one):
414 itask = one.pool.get_tasks()[0]
415 itask.state.reset(TASK_STATUS_PREPARING)
416
417 # when we restart the task should have been reset to waiting
418 one = scheduler(id_)
419 async with start(one):
420 itask = one.pool.get_tasks()[0]
421 assert itask.state(TASK_STATUS_WAITING)
422 itask.state.reset(TASK_STATUS_SUCCEEDED)
423
424 # whereas if we reset the task to succeeded the state is not reset
425 one = scheduler(id_)
426 async with start(one):
427 itask = one.pool.get_tasks()[0]
428 assert itask.state(TASK_STATUS_SUCCEEDED)
429
430
431 async def test_reload_stopcp(
432 flow: Callable, scheduler: Callable, start: Callable
433 ):
434 """Test that the task pool stopping point does not revert to the final
435 cycle point on reload."""
436 cfg = {
437 'scheduler': {
438 'allow implicit tasks': True,
439 'cycle point format': 'CCYY',
440 },
441 'scheduling': {
442 'initial cycle point': 2010,
443 'stop after cycle point': 2020,
444 'final cycle point': 2030,
445 'graph': {
446 'P1Y': 'anakin'
447 }
448 }
449 }
450 schd: 'Scheduler' = scheduler(flow(cfg))
451 async with start(schd):
452 assert str(schd.pool.stop_point) == '2020'
453 await commands.run_cmd(commands.reload_workflow(schd))
454 assert str(schd.pool.stop_point) == '2020'
455
456
457 async def test_runahead_after_remove(
458 example_flow: 'Scheduler'
459 ) -> None:
460 """The runahead limit should be recomputed after tasks are removed.
461
462 """
463 task_pool = example_flow.pool
464 assert int(task_pool.runahead_limit_point) == 4
465
466 # No change after removing an intermediate cycle.
467 await commands.run_cmd(commands.remove_tasks(example_flow, ['3/*'], ["1"]))
468 assert int(task_pool.runahead_limit_point) == 4
469
470 # Should update after removing the first point.
471 await commands.run_cmd(commands.remove_tasks(example_flow, ['1/*'], ["1"]))
472 assert int(task_pool.runahead_limit_point) == 5
473
474
475 async def test_load_db_bad_platform(
476 flow: Callable, scheduler: Callable, start: Callable, one_conf: Callable
477 ):
478 """Test that loading an unavailable platform from the database doesn't
479 cause calamitous failure."""
480 schd: 'Scheduler' = scheduler(flow(one_conf))
481
482 async with start(schd):
483 result = schd.pool.load_db_task_pool_for_restart(0, (
484 '1', 'one', '{"1": 1}', "0", False, False, "failed",
485 False, 1, '', 'culdee-fell-summit', '', '', '', '{}'
486 ))
487 assert result == 'culdee-fell-summit'
488
489
490 def list_tasks(schd):
491 """Return a sorted list of task pool tasks.
492
493 Returns a list in the format:
494 [
495 (cycle, task, state)
496 ]
497
498 """
499 return sorted(
500 (itask.tokens['cycle'], itask.tokens['task'], itask.state.status)
501 for itask in schd.pool.get_tasks()
502 )
503
504
505 @pytest.mark.parametrize(
506 'graph_1, graph_2, '
507 'expected_1, expected_2, expected_3, expected_4',
508 [
509 param( # Restart after adding a prerequisite to task z
510 '''a => z
511 b => z''',
512 '''a => z
513 b => z
514 c => z''',
515 [
516 ('1', 'a', 'running'),
517 ('1', 'b', 'running'),
518 ],
519 [
520 ('1', 'b', 'running'),
521 ('1', 'z', 'waiting'),
522 ],
523 [
524 ('1', 'b', 'running'),
525 ('1', 'z', 'waiting'),
526 ],
527 [
528 {('1', 'a', 'succeeded'): 'satisfied naturally'},
529 {('1', 'b', 'succeeded'): False},
530 {('1', 'c', 'succeeded'): False},
531 ],
532 id='added'
533 ),
534 param( # Restart after removing a prerequisite from task z
535 '''a => z
536 b => z
537 c => z''',
538 '''a => z
539 b => z''',
540 [
541 ('1', 'a', 'running'),
542 ('1', 'b', 'running'),
543 ('1', 'c', 'running'),
544 ],
545 [
546 ('1', 'b', 'running'),
547 ('1', 'c', 'running'),
548 ('1', 'z', 'waiting'),
549 ],
550 [
551 ('1', 'b', 'running'),
552 ('1', 'c', 'running'),
553 ('1', 'z', 'waiting'),
554 ],
555 [
556 {('1', 'a', 'succeeded'): 'satisfied naturally'},
557 {('1', 'b', 'succeeded'): False},
558 ],
559 id='removed'
560 )
561 ]
562 )
563 async def test_restart_prereqs(
564 flow, scheduler, start,
565 graph_1, graph_2,
566 expected_1, expected_2, expected_3, expected_4
567 ):
568 """It should handle graph prerequisites change on restart.
569
570 Prerequisite changes must be applied to tasks already in the pool.
571 See https://github.com/cylc/cylc-flow/pull/5334
572
573 """
574 conf = {
575 'scheduler': {'allow implicit tasks': 'True'},
576 'scheduling': {
577 'graph': {
578 'R1': graph_1
579 }
580 }
581 }
582 id_ = flow(conf)
583 schd: Scheduler = scheduler(id_, paused_start=False)
584
585 async with start(schd):
586 # Release tasks 1/a and 1/b
587 schd.pool.release_runahead_tasks()
588 schd.release_tasks_to_run()
589 assert list_tasks(schd) == expected_1
590
591 # Mark 1/a as succeeded and spawn 1/z
592 task_a = schd.pool.get_tasks()[0]
593 schd.pool.task_events_mgr.process_message(task_a, 1, 'succeeded')
594 assert list_tasks(schd) == expected_2
595
596 # Save our progress
597 schd.workflow_db_mgr.put_task_pool(schd.pool)
598
599 # Edit the workflow to add a new dependency on "z"
600 conf['scheduling']['graph']['R1'] = graph_2
601 id_ = flow(conf, workflow_id=id_)
602
603 # Restart it
604 schd = scheduler(id_, run_mode='simulation', paused_start=False)
605 async with start(schd):
606 # Load jobs from db
607 schd.workflow_db_mgr.pri_dao.select_jobs_for_restart(
608 schd.data_store_mgr.insert_db_job
609 )
610 assert list_tasks(schd) == expected_3
611
612 # To cover some code for loading prereqs from the DB at restart:
613 schd.data_store_mgr.update_data_structure()
614
615 # Check resulting dependencies of task z
616 task_z = [
617 t for t in schd.pool.get_tasks() if t.tdef.name == "z"
618 ][0]
619 assert sorted(
620 (
621 p._satisfied
622 for p in task_z.state.prerequisites
623 ),
624 key=lambda d: tuple(d.keys())[0],
625 ) == expected_4
626
627
628 @pytest.mark.parametrize(
629 'graph_1, graph_2, '
630 'expected_1, expected_2, expected_3, expected_4',
631 [
632 param( # Reload after adding a prerequisite to task z
633 '''a => z
634 b => z''',
635 '''a => z
636 b => z
637 c => z''',
638 [
639 ('1', 'a', 'running'),
640 ('1', 'b', 'running'),
641 ],
642 [
643 ('1', 'b', 'running'),
644 ('1', 'z', 'waiting'),
645 ],
646 [
647 ('1', 'b', 'running'),
648 ('1', 'z', 'waiting'),
649 ],
650 [
651 {('1', 'a', 'succeeded'): 'satisfied naturally'},
652 {('1', 'b', 'succeeded'): False},
653 {('1', 'c', 'succeeded'): False},
654 ],
655 id='added'
656 ),
657 param( # Reload after removing a prerequisite from task z
658 '''a => z
659 b => z
660 c => z''',
661 '''a => z
662 b => z''',
663 [
664 ('1', 'a', 'running'),
665 ('1', 'b', 'running'),
666 ('1', 'c', 'running'),
667 ],
668 [
669 ('1', 'b', 'running'),
670 ('1', 'c', 'running'),
671 ('1', 'z', 'waiting'),
672 ],
673 [
674 ('1', 'b', 'running'),
675 ('1', 'c', 'running'),
676 ('1', 'z', 'waiting'),
677 ],
678 [
679 {('1', 'a', 'succeeded'): 'satisfied naturally'},
680 {('1', 'b', 'succeeded'): False},
681 ],
682 id='removed'
683 )
684 ]
685 )
686 async def test_reload_prereqs(
687 flow, scheduler, start,
688 graph_1, graph_2,
689 expected_1, expected_2, expected_3, expected_4
690 ):
691 """It should handle graph prerequisites change on reload.
692
693 Prerequisite changes must be applied to tasks already in the pool.
694 See https://github.com/cylc/cylc-flow/pull/5334
695
696 """
697 conf = {
698 'scheduler': {'allow implicit tasks': 'True'},
699 'scheduling': {
700 'graph': {
701 'R1': graph_1
702 }
703 }
704 }
705 id_ = flow(conf)
706 schd: Scheduler = scheduler(id_, paused_start=False)
707
708 async with start(schd):
709 # Release tasks 1/a and 1/b
710 schd.pool.release_runahead_tasks()
711 schd.release_tasks_to_run()
712 assert list_tasks(schd) == expected_1
713
714 # Mark 1/a as succeeded and spawn 1/z
715 task_a = schd.pool.get_tasks()[0]
716 schd.pool.task_events_mgr.process_message(task_a, 1, 'succeeded')
717 assert list_tasks(schd) == expected_2
718
719 # Modify flow.cylc to add a new dependency on "z"
720 conf['scheduling']['graph']['R1'] = graph_2
721 flow(conf, workflow_id=id_)
722
723 # Reload the workflow config
724 await commands.run_cmd(commands.reload_workflow(schd))
725 assert list_tasks(schd) == expected_3
726
727 # Check resulting dependencies of task z
728 task_z = [
729 t for t in schd.pool.get_tasks() if t.tdef.name == "z"
730 ][0]
731 assert sorted(
732 (
733 p._satisfied
734 for p in task_z.state.prerequisites
735 ),
736 key=lambda d: tuple(d.keys())[0],
737 ) == expected_4
738
739
740 async def _test_restart_prereqs_sat():
741 schd: Scheduler
742 # YIELD: the workflow has now started...
743 schd = yield
744 await schd.update_data_structure()
745
746 # Release tasks 1/a and 1/b
747 schd.pool.release_runahead_tasks()
748 schd.release_tasks_to_run()
749 assert list_tasks(schd) == [
750 ('1', 'a', 'running'),
751 ('1', 'b', 'running')
752 ]
753
754 # Mark both as succeeded and spawn 1/c
755 for itask in schd.pool.get_tasks():
756 schd.pool.task_events_mgr.process_message(itask, 1, 'succeeded')
757 schd.workflow_db_mgr.put_update_task_outputs(itask)
758 schd.pool.remove_if_complete(itask)
759 schd.workflow_db_mgr.process_queued_ops()
760 assert list_tasks(schd) == [
761 ('1', 'c', 'waiting')
762 ]
763
764 # YIELD: the workflow has now restarted or reloaded with the new config...
765 schd = yield
766 await schd.update_data_structure()
767 assert list_tasks(schd) == [
768 ('1', 'c', 'waiting')
769 ]
770
771 # Check resulting dependencies of task z
772 task_c = schd.pool.get_tasks()[0]
773 assert sorted(
774 (*key, satisfied)
775 for prereq in task_c.state.prerequisites
776 for key, satisfied in prereq.items()
777 ) == [
778 ('1', 'a', 'succeeded', 'satisfied naturally'),
779 ('1', 'b', 'succeeded', 'satisfied from database')
780 ]
781
782 # The prereqs in the data store should have been updated too
783 # await schd.update_data_structure()
784 tasks = (
785 schd.data_store_mgr.data[schd.data_store_mgr.workflow_id][TASK_PROXIES]
786 )
787 task_c_prereqs: List[PbPrerequisite] = tasks[
788 schd.data_store_mgr.id_.duplicate(cycle='1', task='c').id
789 ].prerequisites
790 assert sorted(
791 (condition.task_proxy, condition.satisfied, condition.message)
792 for prereq in task_c_prereqs
793 for condition in prereq.conditions
794 ) == [
795 ('1/a', True, 'satisfied naturally'),
796 ('1/b', True, 'satisfied from database'),
797 ]
798
799 # and we're done, yield back control and return
800 yield
801
802
803 @pytest.mark.parametrize('do_restart', [True, False])
804 async def test_graph_change_prereq_satisfaction(
805 flow, scheduler, start, do_restart
806 ):
807 """It should handle graph prerequisites change on reload/restart.
808
809 If the graph is changed to add a dependency which has been previously
810 satisfied, then Cylc should perform a DB check and mark the prerequsite
811 as satisfied accordingly.
812
813 See https://github.com/cylc/cylc-flow/pull/5334
814
815 """
816 conf = {
817 'scheduler': {'allow implicit tasks': 'True'},
818 'scheduling': {
819 'graph': {
820 'R1': '''
821 a => c
822 b
823 '''
824 }
825 }
826 }
827 id_ = flow(conf)
828 schd = scheduler(id_, run_mode='simulation', paused_start=False)
829
830 test = _test_restart_prereqs_sat()
831 await test.asend(None)
832
833 if do_restart:
834 async with start(schd):
835 # start the workflow and run part 1 of the tests
836 await test.asend(schd)
837
838 # shutdown and change the workflow definiton
839 conf['scheduling']['graph']['R1'] += '\nb => c'
840 flow(conf, workflow_id=id_)
841 schd = scheduler(id_, run_mode='simulation', paused_start=False)
842
843 async with start(schd):
844 # restart the workflow and run part 2 of the tests
845 await test.asend(schd)
846
847 else:
848 async with start(schd):
849 await test.asend(schd)
850
851 # Modify flow.cylc to add a new dependency on "b"
852 conf['scheduling']['graph']['R1'] += '\nb => c'
853 flow(conf, workflow_id=id_)
854
855 # Reload the workflow config
856 await commands.run_cmd(commands.reload_workflow(schd))
857
858 await test.asend(schd)
859
860
861 async def test_runahead_limit_for_sequence_before_start_cycle(
862 flow,
863 scheduler,
864 start,
865 ):
866 """It should obey the runahead limit.
867
868 Ensure the runahead limit is computed correctly for sequences before the
869 start cycle
870
871 See https://github.com/cylc/cylc-flow/issues/5603
872 """
873 id_ = flow({
874 'scheduler': {'allow implicit tasks': 'True'},
875 'scheduling': {
876 'initial cycle point': '2000',
877 'runahead limit': 'P2Y',
878 'graph': {
879 'R1/2000': 'a',
880 'P1Y': 'b[-P1Y] => b',
881 },
882 }
883 })
884 schd = scheduler(id_, startcp='2005')
885 async with start(schd):
886 assert str(schd.pool.runahead_limit_point) == '20070101T0000Z'
887
888
889 def list_pool_from_db(schd):
890 """Returns the task pool table as a sorted list."""
891 db_task_pool = []
892 schd.workflow_db_mgr.pri_dao.select_task_pool(
893 lambda _, row: db_task_pool.append(row)
894 )
895 return sorted(db_task_pool)
896
897
898 async def test_db_update_on_removal(
899 flow,
900 scheduler,
901 start,
902 ):
903 """It should updated the task_pool table when tasks complete.
904
905 There was a bug where the task_pool table was only being updated when tasks
906 in the pool were updated. This meant that if a task was removed the DB
907 would not reflect this change and would hold a record of the task in the
908 wrong state.
909
910 This test ensures that the DB is updated when a task is removed from the
911 pool.
912
913 See: https://github.com/cylc/cylc-flow/issues/5598
914 """
915 id_ = flow({
916 'scheduling': {
917 'graph': {
918 'R1': 'a',
919 },
920 },
921 'runtime': {
922 'root': {
923 'simulation': {
924 # Avoid instant task success for this test
925 'default run length': 'PT2S',
926 },
927 },
928 },
929 })
930 schd: Scheduler = scheduler(id_)
931 async with start(schd):
932 task_a = schd.pool.get_tasks()[0]
933
934 # set the task to running
935 schd.pool.task_events_mgr.process_message(task_a, 1, 'started')
936
937 await schd._main_loop()
938
939 # the task should appear in the DB
940 assert list_pool_from_db(schd) == [
941 ['1', 'a', 'running', 0],
942 ]
943
944 # mark the task as succeeded and allow it to be removed from the pool
945 schd.pool.task_events_mgr.process_message(task_a, 1, 'succeeded')
946 schd.pool.remove_if_complete(task_a)
947
948 await schd._main_loop()
949
950 # the task should be gone from the DB
951 assert list_pool_from_db(schd) == []
952
953
954 async def test_no_flow_tasks_dont_spawn(
955 flow,
956 scheduler,
957 start,
958 ):
959 """Ensure no-flow tasks don't spawn downstreams.
960
961 No-flow tasks (i.e `--flow=none`) are not attached to any "flow".
962
963 See https://github.com/cylc/cylc-flow/issues/5613
964 """
965 id_ = flow({
966 'scheduling': {
967 'graph': {
968 'R1': 'a => b => c'
969 }
970 },
971 })
972
973 schd: Scheduler = scheduler(id_)
974 async with start(schd):
975 task_a = schd.pool.get_tasks()[0]
976
977 # set as no-flow:
978 task_a.flow_nums = set()
979
980 # Set as completed: should not spawn children.
981 schd.pool.set_prereqs_and_outputs(
982 {task_a.tokens}, [], [], [FLOW_NONE]
983 )
984 assert not schd.pool.get_tasks()
985
986 for flow_nums, expected_pool in (
987 # outputs yielded from a no-flow task should not spawn downstreams
988 (set(), []),
989 # outputs yielded from a task with flow numbers should spawn
990 # downstreams in the same flow
991 ({1}, [('1/b', {1})]),
992 ):
993 # set the flow-nums on 1/a
994 task_a.flow_nums = flow_nums
995
996 # spawn on the succeeded output
997 schd.pool.spawn_on_output(task_a, TASK_OUTPUT_SUCCEEDED)
998
999 schd.pool.spawn_on_all_outputs(task_a)
1000
1001 # ensure the pool is as expected
1002 assert [
1003 (itask.identity, itask.flow_nums)
1004 for itask in schd.pool.get_tasks()
1005 ] == expected_pool
1006
1007
1008 async def test_task_proxy_remove_from_queues(
1009 flow, one_conf, scheduler, start,
1010 ):
1011 """TaskPool.remove should delete task proxies from queues.
1012
1013 See https://github.com/cylc/cylc-flow/pull/5573
1014 """
1015 # Set up a scheduler with a non-default queue:
1016 one_conf['scheduling'] = {
1017 'queues': {'queue_two': {'members': 'one, control'}},
1018 'graph': {'R1': 'two & one & control'},
1019 }
1020 schd = scheduler(flow(one_conf))
1021 async with start(schd):
1022 # Get a list of itasks:
1023 itasks = schd.pool.get_tasks()
1024
1025 for itask in itasks:
1026 id_ = itask.identity
1027
1028 # The meat of the test - remove itask from pool if it
1029 # doesn't have "control" in the name:
1030 if 'control' not in id_:
1031 schd.pool.remove(itask)
1032
1033 # Look at the queues afterwards:
1034 queues_after = {
1035 name: [itask.identity for itask in queue.deque]
1036 for name, queue in schd.pool.task_queue_mgr.queues.items()}
1037
1038 assert queues_after['queue_two'] == ['1/control']
1039
1040
1041 async def test_runahead_offset_start(
1042 mod_example_flow_2: 'Scheduler'
1043 ) -> None:
1044 """Late-start recurrences should not break the runahead limit at start-up.
1045
1046 See GitHub #5708
1047 """
1048 task_pool = mod_example_flow_2.pool
1049 assert task_pool.runahead_limit_point == ISO8601Point('2004')
1050
1051
1052 async def test_detect_incomplete_tasks(
1053 flow,
1054 scheduler,
1055 start,
1056 log_filter,
1057 ):
1058 """Finished but incomplete tasks should be retained as incomplete."""
1059 incomplete_final_task_states = {
1060 # final task states that would leave a task with
1061 # completion=succeeded incomplete
1062 TASK_STATUS_FAILED: TaskEventsManager.EVENT_FAILED,
1063 TASK_STATUS_EXPIRED: TaskEventsManager.EVENT_EXPIRED,
1064 TASK_STATUS_SUBMIT_FAILED: TaskEventsManager.EVENT_SUBMIT_FAILED
1065 }
1066 id_ = flow({
1067 'scheduling': {
1068 'graph': {
1069 # a workflow with one task for each of the final task states
1070 'R1': '\n'.join(incomplete_final_task_states.keys())
1071 }
1072 }
1073 })
1074 schd = scheduler(id_)
1075 async with start(schd, level=logging.DEBUG):
1076 itasks = schd.pool.get_tasks()
1077 for itask in itasks:
1078 itask.state_reset(is_queued=False)
1079 # spawn the output corresponding to the task
1080 schd.pool.task_events_mgr.process_message(
1081 itask, 1,
1082 incomplete_final_task_states[itask.tdef.name]
1083 )
1084 # ensure that it is correctly identified as incomplete
1085 assert not itask.state.outputs.is_complete()
1086 assert log_filter(
1087 contains=(
1088 f"[{itask}] did not complete the required outputs:"
1089 ),
1090 )
1091 # the task should not have been removed
1092 assert itask in schd.pool.get_tasks()
1093
1094
1095 async def test_trigger_icp_fcp_syntax(
1096 flow,
1097 scheduler,
1098 start,
1099 log_filter,
1100 ):
1101 """It should support the ^/$ syntax for referencing the initial/final cp.
1102
1103 See https://github.com/cylc/cylc-flow/issues/6537
1104 """
1105 cfg = {
1106 'scheduling': {
1107 'cycling mode': 'integer',
1108 'initial cycle point': 1,
1109 'final cycle point': 2,
1110 'graph': {
1111 'R1/^': 'start',
1112 'R1/$': 'end',
1113 },
1114 },
1115 }
1116
1117 # trigger tasks at both the initial and final cycle points
1118 id_ = flow(cfg)
1119 schd = scheduler(id_)
1120 async with start(schd) as log:
1121 await commands.run_cmd(
1122 commands.force_trigger_tasks(schd, ['^/start', '$/end'], ['1'])
1123 )
1124 assert log_filter(contains='[1/start:waiting(queued)] => waiting')
1125 assert log_filter(contains='[2/end:waiting(queued)] => waiting')
1126 log.clear()
1127
1128 # clear the final cycle point
1129 del cfg['scheduling']['final cycle point']
1130 del cfg['scheduling']['graph']['R1/$']
1131
1132 # try triggering a task at the (non existent) final cycle point
1133 id_ = flow(cfg)
1134 schd = scheduler(id_)
1135 async with start(schd):
1136 await commands.run_cmd(
1137 commands.force_trigger_tasks(schd, ['^/start', '$/end'], ['1'])
1138 )
1139 assert log_filter(contains='[1/start:waiting(queued)] => waiting')
1140 assert not log_filter(contains='[2/end:waiting(queued)] => waiting')
1141 assert log_filter(
1142 contains='ID references final cycle point, but none is set: $/end'
1143 )
1144
1145
1146 async def test_future_trigger_final_point(
1147 flow,
1148 scheduler,
1149 start,
1150 log_filter,
1151 ):
1152 """Check spawning of future-triggered tasks: foo[+P1] => bar.
1153
1154 Don't spawn if a prerequisite reaches beyond the final cycle point.
1155
1156 """
1157 id_ = flow(
1158 {
1159 'scheduling': {
1160 'cycling mode': 'integer',
1161 'initial cycle point': 1,
1162 'final cycle point': 1,
1163 'graph': {
1164 'P1': "foo\n foo[+P1] & bar => baz"
1165 }
1166 }
1167 }
1168 )
1169 schd = scheduler(id_)
1170 async with start(schd):
1171 for itask in schd.pool.get_tasks():
1172 schd.pool.spawn_on_output(itask, "succeeded")
1173 await schd._main_loop()
1174 assert log_filter(
1175 regex=(
1176 ".*1/baz.*not spawned: a prerequisite is beyond"
1177 r" the workflow stop point \(1\)"
1178 )
1179 )
1180
1181
1182 async def test_set_failed_complete(
1183 flow,
1184 scheduler,
1185 start,
1186 one_conf,
1187 log_filter,
1188 db_select: Callable
1189 ):
1190 """Test manual completion of an incomplete failed task."""
1191 id_ = flow(one_conf)
1192 schd: Scheduler = scheduler(id_)
1193 async with start(schd, level=logging.DEBUG):
1194 one = schd.pool.get_tasks()[0]
1195 one.state_reset(is_queued=False)
1196
1197 schd.pool.task_events_mgr.process_message(one, 1, "failed")
1198 assert log_filter(
1199 regex="1/one.* setting implied output: submitted")
1200 assert log_filter(
1201 regex="1/one.* setting implied output: started")
1202 assert log_filter(
1203 regex="failed.* did not complete the required outputs")
1204
1205 # Set failed task complete via default "set" args.
1206 schd.pool.set_prereqs_and_outputs({one.tokens}, [], [], [])
1207
1208 assert log_filter(
1209 contains=f'[{one}] removed from the n=0 window: completed')
1210
1211 db_outputs = db_select(
1212 schd, True, 'task_outputs', 'outputs',
1213 **{'name': 'one'}
1214 )
1215 assert (
1216 sorted(loads((db_outputs[0])[0])) == [
1217 "failed", "started", "submitted", "succeeded"
1218 ]
1219 )
1220
1221
1222 async def test_set_prereqs(
1223 flow,
1224 scheduler,
1225 start,
1226 log_filter,
1227 ):
1228 """Check manual setting of prerequisites (task and xtrigger).
1229
1230 """
1231 id_ = flow(
1232 {
1233 'scheduling': {
1234 'initial cycle point': '2040',
1235 'xtriggers': {
1236 'x': 'xrandom(0)'
1237 },
1238 'graph': {
1239 'R1': """
1240 foo & bar & baz => qux",
1241 @x => bar
1242 """
1243 }
1244 },
1245 'runtime': {
1246 'foo': {
1247 'outputs': {
1248 'a': 'drugs and money',
1249 }
1250 }
1251 }
1252 }
1253 )
1254 schd: Scheduler = scheduler(id_)
1255
1256 async with start(schd):
1257
1258 # it should start up with foo, bar, baz
1259 assert schd.pool.get_task_ids() == {
1260 "20400101T0000Z/bar",
1261 "20400101T0000Z/baz",
1262 "20400101T0000Z/foo",
1263 }
1264
1265 # try to set an invalid prereq of qux
1266 schd.pool.set_prereqs_and_outputs(
1267 {TaskTokens('20400101T0000Z', 'qux')},
1268 [],
1269 ["20400101T0000Z/foo:a", "xtrigger/x"],
1270 [],
1271 )
1272 assert log_filter(
1273 contains=(
1274 '20400101T0000Z/qux does not depend on "20400101T0000Z/foo:a"'
1275 )
1276 )
1277 assert log_filter(
1278 contains=(
1279 '20400101T0000Z/qux does not depend on xtrigger "x"'
1280 )
1281 )
1282
1283 # it should not add 20400101T0000Z/qux to the pool
1284 assert schd.pool.get_task_ids() == {
1285 "20400101T0000Z/bar",
1286 "20400101T0000Z/baz",
1287 "20400101T0000Z/foo",
1288 }
1289
1290 # set an xtrigger (see also test_xtrigger_mgr, and test_data_store_mgr)
1291 bar = schd.pool._get_task_by_id('20400101T0000Z/bar')
1292 assert bar.state.prerequisites_all_satisfied()
1293 assert not bar.state.xtriggers_all_satisfied()
1294 schd.pool.set_prereqs_and_outputs(
1295 {TaskTokens('20400101T0000Z', 'bar')},
1296 [],
1297 ["xtrigger/x:succeeded"],
1298 [],
1299 )
1300 assert bar.state.xtriggers_all_satisfied()
1301 assert log_filter(
1302 contains=('prerequisite force-satisfied: x = xrandom(0)'))
1303
1304 # set xtrigger in the wrong task
1305 schd.pool.set_prereqs_and_outputs(
1306 {TaskTokens('20400101T0000Z', 'baz')},
1307 [],
1308 ["xtrigger/x:succeeded"],
1309 [],
1310 )
1311 assert log_filter(
1312 contains='20400101T0000Z/baz does not depend on xtrigger "x"')
1313
1314 # set one prereq of inactive task 20400101T0000Z/qux
1315 schd.pool.set_prereqs_and_outputs(
1316 {TaskTokens('20400101T0000Z', 'qux')},
1317 [],
1318 ["20400101T0000Z/foo:succeeded"],
1319 [])
1320
1321 # it should add 20400101T0000Z/qux to the pool
1322 assert schd.pool.get_task_ids() == {
1323 "20400101T0000Z/bar",
1324 "20400101T0000Z/baz",
1325 "20400101T0000Z/foo",
1326 "20400101T0000Z/qux",
1327 }
1328
1329 # get the 20400101T0000Z/qux task proxy
1330 qux = schd.pool.get_task(ISO8601Point("20400101T0000Z"), "qux")
1331 assert not qux.state.prerequisites_all_satisfied()
1332
1333 # set its other prereqs (test implicit "succeeded" and "succeed")
1334 # and truncated cycle point
1335 schd.pool.set_prereqs_and_outputs(
1336 {TaskTokens('20400101T0000Z', 'qux')},
1337 [],
1338 ["2040/bar", "2040/baz:succeed"],
1339 [],
1340 )
1341
1342 assert log_filter(
1343 contains=('prerequisite force-satisfied: 20400101T0000Z/bar'))
1344 assert log_filter(
1345 contains=('prerequisite force-satisfied: 20400101T0000Z/baz'))
1346
1347 # it should now be fully satisfied
1348 assert qux.state.prerequisites_all_satisfied()
1349
1350 # set one again
1351 schd.pool.set_prereqs_and_outputs(
1352 {TaskTokens('20400101T0000Z', 'qux')}, [], ["2040/bar"], [])
1353
1354 assert log_filter(
1355 contains=('prerequisite already satisfied: 20400101T0000Z/bar'))
1356
1357
1358 async def test_set_bad_prereqs(
1359 flow,
1360 scheduler,
1361 start,
1362 log_filter,
1363 ):
1364 """Check manual setting of prerequisites.
1365
1366 """
1367 id_ = flow({
1368 'scheduler': {
1369 'cycle point format': '%Y'},
1370 'scheduling': {
1371 'initial cycle point': '2040',
1372 'graph': {'R1': "foo => bar"}},
1373 })
1374 schd: Scheduler = scheduler(id_)
1375
1376 def set_prereqs(prereqs):
1377 """Shorthand so only variable under test given as arg"""
1378 schd.pool.set_prereqs_and_outputs(
1379 {TaskTokens('2040', 'bar')}, [], prereqs, [])
1380
1381 async with start(schd):
1382 # Invalid: task name wildcard:
1383 set_prereqs(["2040/*"])
1384 assert log_filter(contains='Invalid prerequisite task name')
1385
1386 # Invalid: cycle point wildcard.
1387 set_prereqs(["*/foo"])
1388 assert log_filter(contains='Invalid prerequisite cycle point')
1389
1390
1391 async def test_set_outputs_live(
1392 flow,
1393 scheduler,
1394 start,
1395 log_filter,
1396 ):
1397 """Check manual set outputs in an active (spawned) task.
1398
1399 """
1400 id_ = flow(
1401 {
1402 'scheduling': {
1403 'graph': {
1404 'R1': """
1405 foo:x => bar
1406 foo => baz
1407 foo:y
1408 """
1409 }
1410 },
1411 'runtime': {
1412 'foo': {
1413 'outputs': {
1414 'x': 'xylophone',
1415 'y': 'yacht'
1416 }
1417 }
1418 }
1419 }
1420 )
1421 schd: Scheduler = scheduler(id_)
1422
1423 async with start(schd):
1424
1425 # it should start up with just 1/foo
1426 assert schd.pool.get_task_ids() == {"1/foo"}
1427
1428 # fake failed
1429 foo = schd.pool.get_task(IntegerPoint("1"), "foo")
1430 foo.state_reset(is_queued=False)
1431 schd.pool.task_events_mgr.process_message(foo, 1, 'failed')
1432
1433 # set foo:x: it should spawn bar but not baz
1434 schd.pool.set_prereqs_and_outputs(
1435 {TaskTokens('1', 'foo')}, ["x"], [], []
1436 )
1437 assert schd.pool.get_task_ids() == {"1/bar", "1/foo"}
1438 # Foo should have been removed from the queue:
1439 assert '1/foo' not in [
1440 i.identity for i
1441 in schd.pool.task_queue_mgr.queues['default'].deque
1442 ]
1443 # set foo:succeed: it should spawn baz but foo remains incomplete.
1444 schd.pool.set_prereqs_and_outputs(
1445 {TaskTokens('1', 'foo')}, ["succeeded"], [], []
1446 )
1447 assert schd.pool.get_task_ids() == {"1/bar", "1/baz", "1/foo"}
1448
1449 # it should complete implied outputs (submitted, started) too
1450 assert log_filter(contains="setting implied output: submitted")
1451 assert log_filter(contains="setting implied output: started")
1452
1453 # set foo (default: all required outputs) to complete y.
1454 schd.pool.set_prereqs_and_outputs({TaskTokens('1', 'foo')}, [], [], [])
1455 assert log_filter(contains="output 1/foo:succeeded completed")
1456 assert schd.pool.get_task_ids() == {"1/bar", "1/baz"}
1457
1458
1459 async def test_set_outputs_live2(
1460 flow,
1461 scheduler,
1462 start,
1463 log_filter,
1464 ):
1465 """Assert that optional outputs are satisfied before completion
1466 outputs to prevent incomplete task warnings.
1467 """
1468 id_ = flow(
1469 {
1470 'scheduling': {'graph': {
1471 'R1': """
1472 foo:a => apple
1473 foo:b => boat
1474 """}},
1475 'runtime': {'foo': {'outputs': {
1476 'a': 'xylophone',
1477 'b': 'yacht'}}}
1478 }
1479 )
1480 schd: Scheduler = scheduler(id_)
1481
1482 async with start(schd):
1483 schd.pool.set_prereqs_and_outputs({TaskTokens('1', 'foo')}, [], [], [])
1484 assert not log_filter(
1485 contains="did not complete required outputs: ['a', 'b']"
1486 )
1487
1488
1489 async def test_set_outputs_future(
1490 flow,
1491 scheduler,
1492 start,
1493 log_filter,
1494 ):
1495 """Check manual setting of inactive task outputs.
1496
1497 """
1498 id_ = flow(
1499 {
1500 'scheduling': {
1501 'graph': {
1502 'R1': "a:x & a:y => b => c"
1503 }
1504 },
1505 'runtime': {
1506 'a': {
1507 'outputs': {
1508 'x': 'xylophone',
1509 'y': 'yacht'
1510 }
1511 }
1512 }
1513 }
1514 )
1515 schd: Scheduler = scheduler(id_)
1516
1517 async with start(schd):
1518
1519 # it should start up with just 1/a
1520 assert schd.pool.get_task_ids() == {"1/a"}
1521
1522 # setting inactive task b succeeded should spawn c but not b
1523 schd.pool.set_prereqs_and_outputs(
1524 {TaskTokens('1', 'b')}, ["succeeded"], [], [])
1525 assert schd.pool.get_task_ids() == {"1/a", "1/c"}
1526
1527 schd.pool.set_prereqs_and_outputs(
1528 items={TaskTokens('1', 'a')},
1529 outputs=["x", "y", "cheese"],
1530 prereqs=[],
1531 flow=[]
1532 )
1533 assert log_filter(contains="Output 1/a:cheese not found")
1534 assert log_filter(contains="completed output x")
1535 assert log_filter(contains="completed output y")
1536
1537
1538 async def test_set_outputs_from_skip_settings(
1539 flow,
1540 scheduler,
1541 start,
1542 log_filter,
1543 validate
1544 ):
1545 """Check working of ``cylc set --out=skip``:
1546
1547 1. --out=skip can be used to set all required outputs.
1548 2. --out=skip,other_output can be used to set other outputs.
1549
1550 """
1551 id_ = flow(
1552 {
1553 'scheduling': {
1554 'cycling mode': 'integer',
1555 'initial cycle point': 1,
1556 'final cycle point': 2,
1557 'graph': {
1558 'P1': """
1559 a => after_asucceeded
1560 a:x => after_ax
1561 a:y? => after_ay
1562 """
1563 }
1564 },
1565 'runtime': {
1566 'a': {
1567 'outputs': {
1568 'x': 'xebec',
1569 'y': 'yacht'
1570 },
1571 'skip': {'outputs': 'x'}
1572 }
1573 }
1574 }
1575 )
1576 validate(id_)
1577 schd: Scheduler = scheduler(id_)
1578
1579 async with start(schd):
1580 # it should start up with just tasks a:
1581 assert schd.pool.get_task_ids() == {'1/a', '2/a'}
1582
1583 # setting 1/a output to skip should set output x, but not
1584 # y (because y is optional).
1585 schd.pool.set_prereqs_and_outputs(
1586 {TaskTokens('1', 'a')}, ['skip'], [], [])
1587 assert schd.pool.get_task_ids() == {
1588 '1/after_asucceeded',
1589 '1/after_ax',
1590 '2/a',
1591 }
1592
1593 # Check that the presence of "skip" in outputs doesn't
1594 # trigger a warning:
1595 assert not log_filter(level=30)
1596
1597 # You should be able to set skip as part of a list of outputs:
1598 schd.pool.set_prereqs_and_outputs(
1599 {TaskTokens('2', 'a')}, ['skip', 'y'], [], [])
1600 assert schd.pool.get_task_ids() == {
1601 '1/after_asucceeded',
1602 '1/after_ax',
1603 '2/after_asucceeded',
1604 '2/after_ax',
1605 '2/after_ay',
1606 }
1607
1608
1609 async def test_prereq_satisfaction(
1610 flow,
1611 scheduler,
1612 start,
1613 log_filter,
1614 ):
1615 """Check manual setting of task prerequisites.
1616
1617 """
1618 id_ = flow(
1619 {
1620 'scheduling': {
1621 'graph': {
1622 'R1': "a:x & a:y => b"
1623 }
1624 },
1625 'runtime': {
1626 'a': {
1627 'outputs': {
1628 'x': 'xylophone',
1629 'y': 'yacht'
1630 }
1631 }
1632 }
1633 }
1634 )
1635 schd: Scheduler = scheduler(id_)
1636 async with start(schd):
1637 # it should start up with just 1/a
1638 assert schd.pool.get_task_ids() == {"1/a"}
1639 # spawn b
1640 schd.pool.set_prereqs_and_outputs(
1641 {TaskTokens('1', 'a')}, ["x"], [], []
1642 )
1643 assert schd.pool.get_task_ids() == {"1/a", "1/b"}
1644
1645 b = schd.pool.get_task(IntegerPoint("1"), "b")
1646
1647 assert not b.prereqs_are_satisfied()
1648
1649 # set valid and invalid prerequisites, by label and message.
1650 schd.pool.set_prereqs_and_outputs(
1651 prereqs=["1/a:xylophone", "1/a:y", "1/a:w", "1/a:z"],
1652 items={TaskTokens('1', 'b')},
1653 outputs=[],
1654 flow=[],
1655 )
1656 assert log_filter(contains="1/a:z not found")
1657 assert log_filter(contains="1/a:w not found")
1658 # FIXME: testing that something is *not* logged is extremely fragile:
1659 assert not log_filter(regex='.*does not depend on.*')
1660
1661 assert b.prereqs_are_satisfied()
1662
1663
1664 @pytest.mark.parametrize('compat_mode', ['compat-mode', 'normal-mode'])
1665 @pytest.mark.parametrize('cycling_mode', ['integer', 'datetime'])
1666 @pytest.mark.parametrize('runahead_format', ['P3Y', 'P3'])
1667 async def test_compute_runahead(
1668 cycling_mode,
1669 compat_mode,
1670 runahead_format,
1671 flow,
1672 scheduler,
1673 start,
1674 monkeypatch,
1675 ):
1676 """Test the calculation of the runahead limit.
1677
1678 This test ensures that:
1679 * Runahead tasks are excluded from computations
1680 see https://github.com/cylc/cylc-flow/issues/5825
1681 * Tasks are initiated with the correct is_runahead status on startup.
1682 * Behaviour in compat/regular modes is same unless failed tasks are present
1683 * Behaviour is the same for integer/datetime cycling modes.
1684
1685 """
1686 if cycling_mode == 'integer':
1687
1688 config = {
1689 'scheduler': {
1690 'allow implicit tasks': 'True',
1691 },
1692 'scheduling': {
1693 'initial cycle point': '1',
1694 'cycling mode': 'integer',
1695 'runahead limit': 'P3',
1696 'graph': {
1697 'P1': 'a'
1698 },
1699 }
1700 }
1701 point = lambda point: IntegerPoint(str(int(point)))
1702 else:
1703 config = {
1704 'scheduler': {
1705 'allow implicit tasks': 'True',
1706 'cycle point format': 'CCYY',
1707 },
1708 'scheduling': {
1709 'initial cycle point': '0001',
1710 'runahead limit': runahead_format,
1711 'graph': {
1712 'P1Y': 'a'
1713 },
1714 }
1715 }
1716 point = ISO8601Point
1717
1718 monkeypatch.setattr(
1719 'cylc.flow.flags.cylc7_back_compat',
1720 compat_mode == 'compat-mode',
1721 )
1722
1723 id_ = flow(config)
1724 schd = scheduler(id_)
1725 async with start(schd):
1726 schd.pool.compute_runahead(force=True)
1727 assert int(str(schd.pool.runahead_limit_point)) == 4
1728
1729 # ensure task states are initiated with is_runahead status
1730 assert schd.pool.get_task(point('0001'), 'a').state(is_runahead=False)
1731 assert schd.pool.get_task(point('0005'), 'a').state(is_runahead=True)
1732
1733 # mark the first three cycles as running
1734 for cycle in range(1, 4):
1735 schd.pool.get_task(point(f'{cycle:04}'), 'a').state.reset(
1736 TASK_STATUS_RUNNING
1737 )
1738
1739 schd.pool.compute_runahead(force=True)
1740 assert int(str(schd.pool.runahead_limit_point)) == 4 # no change
1741
1742 # In Cylc 8 all incomplete tasks hold back runahead.
1743
1744 # In Cylc 7, submit-failed tasks hold back runahead..
1745 schd.pool.get_task(point('0001'), 'a').state.reset(
1746 TASK_STATUS_SUBMIT_FAILED
1747 )
1748 schd.pool.compute_runahead(force=True)
1749 assert int(str(schd.pool.runahead_limit_point)) == 4
1750
1751 # ... but failed ones don't. Go figure.
1752 schd.pool.get_task(point('0001'), 'a').state.reset(
1753 TASK_STATUS_FAILED
1754 )
1755 schd.pool.compute_runahead(force=True)
1756 if compat_mode == 'compat-mode':
1757 assert int(str(schd.pool.runahead_limit_point)) == 5
1758 else:
1759 assert int(str(schd.pool.runahead_limit_point)) == 4 # no change
1760
1761 # mark cycle 1 as complete
1762 # (via task message so the task gets removed before runahead compute)
1763 schd.task_events_mgr.process_message(
1764 schd.pool.get_task(point('0001'), 'a'),
1765 logging.INFO,
1766 TASK_OUTPUT_SUCCEEDED
1767 )
1768 schd.pool.compute_runahead(force=True)
1769 assert int(str(schd.pool.runahead_limit_point)) == 5 # +1
1770
1771
1772 async def test_compute_runahead_with_no_tasks(flow, scheduler, run):
1773 """It should handle the case of an empty workflow.
1774
1775 See https://github.com/cylc/cylc-flow/issues/6225
1776 """
1777 id_ = flow(
1778 {
1779 'scheduling': {
1780 'initial cycle point': '2000',
1781 'graph': {'R1': 'foo'},
1782 },
1783 }
1784 )
1785 schd = scheduler(id_, startcp='2002', paused_start=False)
1786 async with run(schd):
1787 assert schd.pool.compute_runahead() is False
1788 assert schd.pool.runahead_limit_point is None
1789 assert schd.pool.get_tasks() == []
1790
1791
1792 async def test_compute_runahead_with_no_sequences(
1793 flow, scheduler, start, run, complete
1794 ):
1795 """It should handle no sequences within the start-stop cycle range.
1796
1797 See https://github.com/cylc/cylc-flow/issues/6154
1798 """
1799 cfg = {
1800 'scheduling': {
1801 'cycling mode': 'integer',
1802 'initial cycle point': '1',
1803 'graph': {
1804 'P1': 'foo[-P1] => foo',
1805 },
1806 },
1807 }
1808 id_ = flow(cfg)
1809 schd = scheduler(id_, paused_start=False)
1810 async with run(schd):
1811 await complete(schd, '2/foo')
1812
1813 cfg['scheduling']['graph']['R1'] = cfg['scheduling']['graph']['P1']
1814 cfg['scheduling']['graph'].pop('P1')
1815 flow(cfg, workflow_id=id_)
1816
1817 schd = scheduler(id_, paused_start=False)
1818 async with start(schd):
1819 schd.pool.compute_runahead()
1820 assert schd.pool.runahead_limit_point == IntegerPoint('3')
1821
1822
1823 @pytest.mark.parametrize('rhlimit', ['P2D', 'P2'])
1824 @pytest.mark.parametrize('compat_mode', ['compat-mode', 'normal-mode'])
1825 async def test_runahead_future_trigger(
1826 flow,
1827 scheduler,
1828 start,
1829 monkeypatch,
1830 rhlimit,
1831 compat_mode,
1832 ):
1833 """Equivalent time interval and cycle count runahead limits should yield
1834 the same limit point, even if there is a future trigger.
1835
1836 See https://github.com/cylc/cylc-flow/pull/5893
1837 """
1838 id_ = flow({
1839 'scheduler': {
1840 'allow implicit tasks': 'True',
1841 'cycle point format': 'CCYYMMDD',
1842 },
1843 'scheduling': {
1844 'initial cycle point': '2001',
1845 'runahead limit': rhlimit,
1846 'graph': {
1847 'P1D': '''
1848 a
1849 a[+P1D] => b
1850 ''',
1851 },
1852 }
1853 })
1854
1855 monkeypatch.setattr(
1856 'cylc.flow.flags.cylc7_back_compat',
1857 compat_mode == 'compat-mode',
1858 )
1859 schd = scheduler(id_,)
1860 async with start(schd, level=logging.DEBUG):
1861 assert str(schd.pool.runahead_limit_point) == '20010103'
1862 schd.pool.release_runahead_tasks()
1863 for itask in schd.pool.get_tasks():
1864 schd.pool.spawn_on_output(itask, 'succeeded')
1865 # future trigger raises the limit by one cycle point
1866 assert str(schd.pool.runahead_limit_point) == '20010104'
1867
1868
1869 @pytest.fixture(scope='module')
1870 async def mod_blah(
1871 mod_flow: Callable, mod_scheduler: Callable, mod_run: Callable
1872 ) -> 'Scheduler':
1873 """Return a scheduler for interrogating its task pool.
1874
1875 This is module-scoped so faster than example_flow, but should only be used
1876 where the test does not mutate the state of the scheduler or task pool.
1877 """
1878
1879 config = {
1880 'scheduler': {
1881 'allow implicit tasks': 'True',
1882 'cycle point format': '%Y',
1883 },
1884 'scheduling': {
1885 'initial cycle point': '0001',
1886 'runahead limit': 'P1Y',
1887 'graph': {
1888 'P1Y': 'a'
1889 },
1890 }
1891 }
1892 id_ = mod_flow(config)
1893 schd: 'Scheduler' = mod_scheduler(id_, paused_start=True)
1894 async with mod_run(schd):
1895 yield schd
1896
1897
1898 @pytest.mark.parametrize(
1899 'status, expected',
1900 [
1901 # (Status, Are we expecting an update?)
1902 (TASK_STATUS_WAITING, False),
1903 (TASK_STATUS_EXPIRED, False),
1904 (TASK_STATUS_PREPARING, False),
1905 (TASK_STATUS_SUBMIT_FAILED, False),
1906 (TASK_STATUS_SUBMITTED, False),
1907 (TASK_STATUS_RUNNING, False),
1908 (TASK_STATUS_FAILED, True),
1909 (TASK_STATUS_SUCCEEDED, True)
1910 ]
1911 )
1912 async def test_runahead_c7_compat_task_state(
1913 status,
1914 expected,
1915 mod_blah,
1916 monkeypatch,
1917 ):
1918 """For each task status check whether changing the oldest task
1919 to that status will cause compute_runahead to make a change.
1920
1921 Compat mode: Cylc 7 ignored failed tasks but not submit-failed!
1922
1923 """
1924
1925 def max_cycle(tasks):
1926 return max([int(t.tokens.get("cycle")) for t in tasks])
1927
1928 monkeypatch.setattr(
1929 'cylc.flow.flags.cylc7_back_compat', True)
1930 monkeypatch.setattr(
1931 'cylc.flow.task_events_mgr.TaskEventsManager._insert_task_job',
1932 lambda *_: True)
1933
1934 mod_blah.pool.compute_runahead()
1935 before_pt = max_cycle(mod_blah.pool.get_tasks())
1936 before = mod_blah.pool.runahead_limit_point
1937 itask = mod_blah.pool.get_task(ISO8601Point(f'{before_pt - 2:04}'), 'a')
1938 itask.state_reset(status, is_queued=False)
1939 mod_blah.pool.compute_runahead()
1940 after = mod_blah.pool.runahead_limit_point
1941 assert bool(before != after) == expected
1942
1943
1944 async def test_fast_respawn(
1945 example_flow: 'Scheduler',
1946 caplog: pytest.LogCaptureFixture,
1947 ) -> None:
1948 """Immediate re-spawn of removed tasks is not allowed.
1949
1950 An immediate DB update is required to stop the respawn.
1951 https://github.com/cylc/cylc-flow/pull/6067
1952
1953 """
1954 task_pool = example_flow.pool
1955
1956 # find task 1/foo in the pool
1957 foo = task_pool.get_task(IntegerPoint("1"), "foo")
1958
1959 # remove it from the pool
1960 task_pool.remove(foo)
1961 assert foo not in task_pool.get_tasks()
1962
1963 # attempt to spawn it again
1964 itask = task_pool.spawn_task("foo", IntegerPoint("1"), {1})
1965 assert itask is None
1966 assert "Not respawning 1/foo - task was removed" in caplog.text
1967
1968
1969 async def test_remove_active_task(
1970 example_flow: 'Scheduler',
1971 log_filter: Callable,
1972 ) -> None:
1973 """Test warning on removing an active task."""
1974
1975 task_pool = example_flow.pool
1976
1977 # find task 1/foo in the pool
1978 foo = task_pool.get_task(IntegerPoint("1"), "foo")
1979
1980 foo.state_reset(TASK_STATUS_RUNNING)
1981 task_pool.remove(foo, "request")
1982 assert foo not in task_pool.get_tasks()
1983
1984 assert log_filter(
1985 regex=(
1986 "1/foo.*removed from the n=0 window:"
1987 " request - active job orphaned"
1988 ),
1989 level=logging.WARNING
1990 )
1991
1992
1993 async def test_remove_by_expire_trigger(
1994 flow,
1995 validate,
1996 scheduler,
1997 start,
1998 log_filter
1999 ):
2000 """Test task removal by suicide trigger.
2001
2002 * Suicide triggers should remove tasks from the pool.
2003 * It should be possible to bring them back by manually triggering them.
2004 * Removing a task manually (cylc remove) should work the same.
2005 """
2006 def _get_id(b_completion: str = "succeeded"):
2007 return flow({
2008 'scheduler': {
2009 'experimental': {
2010 'expire triggers': 'True',
2011 }
2012 },
2013 'scheduling': {
2014 'graph': {
2015 'R1': '''
2016 a? => b
2017 a:failed? => !b
2018 '''
2019 },
2020 },
2021 'runtime': {
2022 'b': {
2023 'completion': b_completion
2024 }
2025 }
2026 })
2027 with pytest.raises(
2028 WorkflowConfigError,
2029 match=re.escape(
2030 "This may be due to use of an expire (formerly suicide) trigger"
2031 )
2032 ):
2033 validate(_get_id())
2034
2035 id_ = _get_id("succeeded or expired")
2036 validate(id_)
2037 schd: 'Scheduler' = scheduler(id_, paused_start=False)
2038
2039 async with start(schd, level=logging.DEBUG) as log:
2040 # it should start up with 1/a
2041 assert schd.pool.get_task_ids() == {"1/a"}
2042 a = schd.pool.get_task(IntegerPoint("1"), "a")
2043
2044 # mark 1/a as failed and check that 1/b expires
2045 schd.pool.spawn_on_output(a, TASK_OUTPUT_FAILED)
2046 assert log_filter(regex="1/b.*=> expired")
2047 assert schd.pool.get_task_ids() == {"1/a"}
2048
2049 # 1/b should not be resurrected if it becomes ready
2050 schd.pool.set_prereqs_and_outputs(
2051 {TaskTokens('1', 'b')}, [], ["1/a"], ["1"],
2052 )
2053 assert log_filter(regex="1/b:expired.* already finished and completed")
2054
2055 # but we can still resurrect 1/b by triggering it
2056 log.clear()
2057 await commands.run_cmd(
2058 commands.force_trigger_tasks(schd, ['1/b'], ['1']))
2059 assert log_filter(regex='1/b.*added to the n=0 window')
2060
2061 # remove 1/b with "cylc remove""
2062 await commands.run_cmd(
2063 commands.remove_tasks(schd, ['1/b'], [])
2064 )
2065 assert log_filter(
2066 regex='1/b.*removed from the n=0 window: request',
2067 )
2068
2069 # and bring 1/b back again by triggering it again
2070 log.clear()
2071 await commands.run_cmd(
2072 commands.force_trigger_tasks(schd, ['1/b'], ['1']))
2073 assert log_filter(regex='1/b.*added to the n=0 window',)
2074
2075
2076 async def test_remove_by_suicide(
2077 flow,
2078 scheduler,
2079 start,
2080 log_filter
2081 ):
2082 """Test task removal by suicide trigger.
2083
2084 * Suicide triggers should remove tasks from the pool.
2085 * It should be possible to bring them back by manually triggering them.
2086 * Removing a task manually (cylc remove) should work the same.
2087 """
2088 id_ = flow({
2089 'scheduling': {
2090 'graph': {
2091 'R1': '''
2092 a? & b
2093 a:failed? => !b
2094 '''
2095 },
2096 }
2097 })
2098 schd: 'Scheduler' = scheduler(id_)
2099 async with start(schd, level=logging.DEBUG) as log:
2100 # it should start up with 1/a and 1/b
2101 assert schd.pool.get_task_ids() == {"1/a", "1/b"}
2102 a = schd.pool.get_task(IntegerPoint("1"), "a")
2103
2104 # mark 1/a as failed and ensure 1/b is removed by suicide trigger
2105 schd.pool.spawn_on_output(a, TASK_OUTPUT_FAILED)
2106 assert log_filter(
2107 regex="1/b.*removed from the n=0 window: suicide trigger"
2108 )
2109 assert schd.pool.get_task_ids() == {"1/a"}
2110
2111 # ensure that we are able to bring 1/b back by triggering it
2112 log.clear()
2113 await commands.run_cmd(
2114 commands.force_trigger_tasks(schd, ['1/b'], ['1']))
2115 assert log_filter(
2116 regex='1/b.*added to the n=0 window',
2117 )
2118
2119 # remove 1/b by request (cylc remove)
2120 await commands.run_cmd(
2121 commands.remove_tasks(schd, ['1/b'], [])
2122 )
2123 assert log_filter(
2124 regex='1/b.*removed from the n=0 window: request',
2125 )
2126
2127 # ensure that we are able to bring 1/b back by triggering it
2128 log.clear()
2129 await commands.run_cmd(
2130 commands.force_trigger_tasks(schd, ['1/b'], ['1']))
2131 assert log_filter(regex='1/b.*added to the n=0 window',)
2132
2133
2134 async def test_set_future_flow(flow, scheduler, start, log_filter):
2135 """Manually-set outputs for new flow num must be recorded in the DB.
2136
2137 See https://github.com/cylc/cylc-flow/pull/6186
2138
2139 To trigger the bug, the flow must be new but the task must have been
2140 spawned before in an earlier flow.
2141
2142 """
2143 # Scenario: after flow 1, set c1:succeeded in a future flow so
2144 # when b succeeds in the new flow it will spawn c2 but not c1.
2145 id_ = flow({
2146 'scheduler': {
2147 'allow implicit tasks': True
2148 },
2149 'scheduling': {
2150 'cycling mode': 'integer',
2151 'graph': {
2152 'R1': 'b => c1 & c2',
2153 },
2154 },
2155 })
2156 schd: 'Scheduler' = scheduler(id_)
2157 async with start(schd, level=logging.DEBUG):
2158 assert schd.pool.get_task(IntegerPoint("1"), "b") is not None, (
2159 '1/b should be spawned on startup'
2160 )
2161
2162 # set b, c1, c2 succeeded in flow 1
2163 schd.pool.set_prereqs_and_outputs(
2164 {
2165 TaskTokens('1', 'b'),
2166 TaskTokens('1', 'c1'),
2167 TaskTokens('1', 'c2'),
2168 },
2169 prereqs=[],
2170 outputs=[],
2171 flow=['1'],
2172 )
2173 schd.workflow_db_mgr.process_queued_ops()
2174
2175 # set task c1:succeeded in flow 2
2176 schd.pool.set_prereqs_and_outputs(
2177 {TaskTokens('1', 'c1')}, prereqs=[], outputs=[], flow=['2']
2178 )
2179 schd.workflow_db_mgr.process_queued_ops()
2180
2181 # set b:succeeded in flow 2 and check downstream spawning
2182 schd.pool.set_prereqs_and_outputs(
2183 {TaskTokens('1', 'b')}, prereqs=[], outputs=[], flow=['2']
2184 )
2185 assert schd.pool.get_task(IntegerPoint("1"), "c1") is None, (
2186 '1/c1 (flow 2) should not be spawned after 1/b:succeeded'
2187 )
2188 assert schd.pool.get_task(IntegerPoint("1"), "c2") is not None, (
2189 '1/c2 (flow 2) should be spawned after 1/b:succeeded'
2190 )
2191
2192
2193 async def test_trigger_queue(one, run, db_select, complete):
2194 """It should handle triggering tasks in the queued state.
2195
2196 Triggering a queued task with a new flow number should result in the
2197 task running with merged flow numbers.
2198
2199 See https://github.com/cylc/cylc-flow/pull/6241
2200 """
2201 async with run(one):
2202 # the workflow should start up with one task in the original flow
2203 task = one.pool.get_tasks()[0]
2204 assert task.state(TASK_STATUS_WAITING, is_queued=True)
2205 assert task.flow_nums == {1}
2206
2207 # trigger this task even though is already queued in flow 1
2208 await commands.run_cmd(
2209 commands.force_trigger_tasks(one, [task.identity], ['2']))
2210
2211 # the merged flow should continue
2212 one.resume_workflow()
2213 await complete(one, timeout=2)
2214 assert db_select(one, False, 'task_outputs', 'flow_nums') == [
2215 ('[1, 2]',),
2216 ('[1]',),
2217 ]
2218
2219
2220 async def test_reload_xtriggers(flow, scheduler, start):
2221 """It should rebuild xtriggers when the workflow is reloaded.
2222
2223 See https://github.com/cylc/cylc-flow/pull/6263
2224 """
2225 config = {
2226 'scheduling': {
2227 'initial cycle point': '2000',
2228 'graph': {
2229 'R1': '''
2230 @a => foo
2231 @b => foo
2232 '''
2233 },
2234 'xtriggers': {
2235 'a': 'wall_clock(offset="P0D")',
2236 'b': 'wall_clock(offset="P5D")',
2237 },
2238 }
2239 }
2240 id_ = flow(config)
2241 schd: Scheduler = scheduler(id_)
2242
2243 def list_xtrig_mgr():
2244 """List xtrigs from the xtrigger_mgr."""
2245 return {
2246 key: repr(value)
2247 for key, value in schd.xtrigger_mgr.xtriggers.functx_map.items()
2248 }
2249
2250 async def list_data_store():
2251 """List xtrigs from the data_store_mgr."""
2252 await schd.update_data_structure()
2253 return {
2254 value.label: value.id
2255 for key, value in schd.data_store_mgr.data[schd.tokens.id][
2256 TASK_PROXIES
2257 ][
2258 schd.tokens.duplicate(cycle='20000101T0000Z', task='foo').id
2259 ].xtriggers.items()
2260 }
2261
2262 async with start(schd):
2263 # check xtrigs on startup
2264 assert list_xtrig_mgr() == {
2265 'a': '<SubFuncContext wall_clock(offset=P0D):10.0>',
2266 'b': '<SubFuncContext wall_clock(offset=P5D):10.0>',
2267 }
2268 assert await list_data_store() == {
2269 'a': 'wall_clock(trigger_time=946684800)',
2270 'b': 'wall_clock(trigger_time=947116800)',
2271 }
2272
2273 # remove @a
2274 config['scheduling']['xtriggers'].pop('a')
2275 # modify @b
2276 config['scheduling']['xtriggers']['b'] = 'wall_clock(offset="PT12H")'
2277 # add @c
2278 config['scheduling']['xtriggers']['c'] = 'wall_clock(offset="PT1H")'
2279 config['scheduling']['graph']['R1'] = config['scheduling']['graph'][
2280 'R1'
2281 ].replace('@a', '@c')
2282
2283 # reload
2284 flow(config, workflow_id=id_)
2285 await commands.run_cmd(commands.reload_workflow(schd))
2286
2287 # check xtrigs post-reload
2288 assert list_xtrig_mgr() == {
2289 'b': '<SubFuncContext wall_clock(offset=PT12H):10.0>',
2290 'c': '<SubFuncContext wall_clock(offset=PT1H):10.0>',
2291 }
2292 assert await list_data_store() == {
2293 'b': 'wall_clock(trigger_time=946728000)',
2294 'c': 'wall_clock(trigger_time=946688400)',
2295 }
2296
2297
2298 @pytest.mark.parametrize(
2299 'expire_type', ['clock-expire', 'manual-expire', 'expire-trigger']
2300 )
2301 async def test_expire_dequeue_with_retries(
2302 flow, scheduler, start, expire_type
2303 ):
2304 """An expired waiting task should be removed from any queues.
2305
2306 See https://github.com/cylc/cylc-flow/issues/6284
2307 """
2308 conf = {
2309 'scheduler': {
2310 'experimental': {
2311 'expire triggers': True,
2312 },
2313 },
2314 'scheduling': {
2315 'initial cycle point': '2000',
2316 'graph': {
2317 'R1': 'foo'
2318 },
2319 },
2320 'runtime': {
2321 'foo': {
2322 'execution retry delays': 'PT0S',
2323 'outputs': {
2324 'x': 'xxx',
2325 },
2326 },
2327 },
2328 }
2329
2330 if expire_type == 'clock-expire':
2331 # configure foo to clock-expire
2332 conf['scheduling']['special tasks'] = {'clock-expire': 'foo(PT0S)'}
2333
2334 # run the clock-expire logic
2335 def method(schd):
2336 schd.pool.clock_expire_tasks()
2337
2338 elif expire_type == 'manual-expire':
2339 # run the "cylc set" command to expire "foo"
2340 def method(schd):
2341 schd.pool.set_prereqs_and_outputs(
2342 {TaskTokens('20000101T0000Z', 'foo')},
2343 prereqs=[],
2344 outputs=['expired'],
2345 flow=['1'],
2346 )
2347
2348 else:
2349 # configure the task to be expire-triggered once "bar" succeeds
2350 conf['scheduling']['graph']['R1'] = '''
2351 foo:x => bar
2352 foo:x & bar => !foo
2353 '''
2354
2355 # run the "cylc set" command to succeed "bar"
2356 def method(schd):
2357 schd.pool.set_prereqs_and_outputs(
2358 {TaskTokens('20000101T0000Z', 'bar')},
2359 prereqs=[],
2360 outputs=['succeeded'],
2361 flow=['1'],
2362 )
2363
2364 id_ = flow(conf)
2365 schd = scheduler(id_, run_mode='live')
2366 schd: Scheduler
2367 async with start(schd):
2368 foo = schd.pool._get_task_by_id('20000101T0000Z/foo')
2369 assert foo
2370
2371 # fake a real submission failure
2372 # NOTE: yes, all of these things are needed for a valid test!
2373 # Try removing the "force=True" added in this commit and ensure the
2374 # "clock-expire" test fails before changing anything here!
2375 foo.submit_num += 1
2376 foo.run_mode = RunMode.LIVE
2377 schd.task_job_mgr._set_retry_timers(foo, foo.tdef.rtconfig)
2378 schd.task_events_mgr.process_message(foo, 0, 'started')
2379 schd.task_events_mgr.process_message(foo, 0, 'xxx')
2380 schd.task_events_mgr.process_message(foo, 0, 'failed')
2381 schd.task_events_mgr._retry_task(foo, 0)
2382
2383 # the task should start as "waiting(queued)"
2384 assert foo.state(TASK_STATUS_WAITING, is_queued=True)
2385
2386 # expire the task via whichever method we are testing
2387 method(schd)
2388
2389 # the task should enter the "expired" state
2390 assert foo.state(TASK_STATUS_EXPIRED, is_queued=False)
2391
2392 # the task should also have been removed from the queue
2393 assert not schd.pool.task_queue_mgr.remove_task(foo)
2394
2395
2396 async def test_clock_expire_with_sequential_xtriggers(
2397 flow,
2398 scheduler,
2399 run,
2400 complete,
2401 log_filter,
2402 ):
2403 """Clock expire should play nicely with sequential xtriggers.
2404
2405 See https://github.com/cylc/cylc-flow/issues/7103
2406 """
2407 id_ = flow({
2408 'scheduler': {
2409 'cycle point format': 'CCYY',
2410 },
2411 'scheduling': {
2412 'initial cycle point': '2000',
2413 # v prevent this test passing if sequential spawning gets broken
2414 'runahead limit': 'P2',
2415 'special tasks': {
2416 'clock-expire': 'a',
2417 },
2418 'graph': {
2419 'P1Y': '@wall_clock => a => b => c'
2420 },
2421 },
2422 'runtime': {
2423 'a': {
2424 'completion': 'succeeded or expired',
2425 },
2426 },
2427 })
2428 schd = scheduler(id_, paused_start=False)
2429 async with run(schd):
2430 # each cycle should expire and spawn in turn
2431 await complete(schd, '2005/a')
2432 for cycle in range(2000, 2006):
2433 assert log_filter(regex=rf'{cycle}/a:waiting.*expired')
2434
2435 # * the next instance should have been spawned
2436 # * it should be the only task in the pool
2437 assert {
2438 itask.tokens.relative_id for itask in schd.pool.get_tasks()
2439 } == {'2006/a'}
2440
2441
2442 async def test_downstream_complete_before_upstream(
2443 flow, scheduler, start, db_select
2444 ):
2445 """A downstream task that completes - in the same main loop iteration as
2446 its upstream task - does not get re-spawned.
2447
2448 See https://github.com/cylc/cylc-flow/issues/6315
2449 """
2450 id_ = flow('a => b')
2451 schd: Scheduler = scheduler(id_)
2452 async with start(schd):
2453 # 1/a should be pre-spawned (parentless)
2454 a_1 = schd.pool.get_task(IntegerPoint('1'), 'a')
2455 assert a_1
2456
2457 # spawn 1/b (this can happens as the result of request e.g. trigger)
2458 b_1 = schd.pool.spawn_task('b', IntegerPoint('1'), {1})
2459 schd.pool.add_to_pool(b_1)
2460 assert b_1
2461
2462 # mark 1/b as succeeded
2463 schd.task_events_mgr.process_message(b_1, 'INFO', 'succeeded')
2464
2465 # 1/b should be removed from the pool (completed)
2466 assert schd.pool.get_tasks() == [a_1]
2467
2468 # as a side effect the DB should have been updated (not waiting for
2469 # the main loop to do it)
2470 assert (
2471 TASK_OUTPUT_SUCCEEDED
2472 in db_select(
2473 schd,
2474 # "False" means "do not run the DB update before checking it"
2475 False, # do not change this to "True"
2476 'task_outputs',
2477 'outputs',
2478 name='b',
2479 cycle='1',
2480 )[0][0]
2481 )
2482
2483 # mark 1/a as succeeded
2484 schd.task_events_mgr.process_message(a_1, 'INFO', 'succeeded')
2485
2486 # 1/a should be removed from the pool (completed)
2487 # 1/b should not be re-spawned by the success of 1/a
2488 assert schd.pool.get_tasks() == []
2489
2490
2491 async def test_job_insert_on_crash(one_conf, flow, scheduler, start):
2492 """Ensure that a job can be inserted if its config is not known.
2493
2494 It is possible, though very difficult, to create the circumstances where
2495 the configuration for the latest job is not held in `itask.jobs`.
2496
2497 This should not happen under normal circumstances, but should be handled
2498 elegantly if it does occur.
2499
2500 See https://github.com/cylc/cylc-flow/issues/6314
2501 """
2502 id_ = flow(one_conf)
2503 schd: Scheduler = scheduler(id_, run_mode='live')
2504 async with start(schd):
2505 task_1 = schd.pool.get_tasks()[0]
2506
2507 # make it look like the task submitted but without storing the job
2508 # config in TaskProxy.jobs
2509 task_1.submit_num += 1
2510 task_1.state.reset('preparing')
2511 schd.task_events_mgr.process_message(
2512 task_1,
2513 'INFO',
2514 'submitted',
2515 )
2516
2517 # the task state should be updated correctly
2518 assert task_1.state.status == 'submitted'
2519
2520 # and a job entry should be added
2521 assert len(task_1.jobs) == 1
2522
2523
2524 async def test_start_tasks(
2525 flow,
2526 scheduler,
2527 start,
2528 capture_submission,
2529 ):
2530 """Check starting from "start-tasks" with and without clock-triggers.
2531
2532 """
2533 id_ = flow(
2534 {
2535 'scheduler': {
2536 'cycle point format': '%Y',
2537 },
2538 'scheduling': {
2539 'initial cycle point': '2040',
2540 'runahead limit': 'P0Y',
2541 'xtriggers': {
2542 'wall_clock_satisfied': "wall_clock(offset='-P100Y')"
2543 },
2544 'graph': {
2545 'P1Y': """
2546 foo
2547 @wall_clock => bar
2548 @wall_clock_satisfied => baz
2549 qux
2550 """
2551 }
2552 }
2553 }
2554 )
2555 schd: Scheduler = scheduler(
2556 id_,
2557 starttask=['2050/foo', '2050/bar', '2050/baz'],
2558 paused_start=False
2559 )
2560
2561 async with start(schd):
2562 # capture any job submissions
2563 submitted_tasks = capture_submission(schd)
2564 assert submitted_tasks == set()
2565
2566 # It should start up with:
2567 # - 2050/foo and 2051/foo (spawned to runahead limit)
2568 # - 2050/bar waiting on its (unsatisfied) clock-trigger
2569 # - 2050/baz waiting on its (satisfied) clock-trigger
2570 # - no qux instances (not listed as a start-task)
2571 itasks = schd.pool.get_tasks()
2572 assert (
2573 set(itask.identity for itask in itasks) == {
2574 "2050/foo",
2575 "2051/foo",
2576 "2050/bar",
2577 "2050/baz",
2578 }
2579 )
2580
2581 await schd._main_loop()
2582
2583 # It should submit 2050/foo, 2050/baz
2584 # It should not submit 2050/bar (waiting on clock trigger)
2585 # It should not submit 2051/foo (runahead limited)
2586 assert (
2587 set(itask.identity for itask in submitted_tasks) == {
2588 "2050/foo",
2589 "2050/baz",
2590 }
2591 )
2592
2593
2594 async def test_add_new_flow_rows_on_spawn(
2595 flow,
2596 scheduler,
2597 run,
2598 complete,
2599 db_select,
2600 capcall,
2601 ) -> None:
2602 """Task suicide should not override previously completed outputs.
2603
2604 See https://github.com/cylc/cylc-flow/pull/6821
2605 """
2606 # capture all TaskPool.spawn_task() calls
2607 spawn_task_calls = capcall(
2608 'cylc.flow.task_pool.TaskPool.spawn_task', TaskPool.spawn_task
2609 )
2610
2611 def list_spawn_task_calls():
2612 """Return a list of the names of tasks which have been run through the
2613 "spawn_tasks" function so far."""
2614 return [
2615 args[1] for args, _kwargs in spawn_task_calls
2616 ]
2617
2618 id_ = flow({
2619 'scheduling': {
2620 'graph': {
2621 'R1': '''
2622 slow:fail? => foo
2623 slow? => !foo
2624 foo:x => x
2625 ''',
2626 },
2627 },
2628 'runtime': {
2629 'foo': {
2630 'outputs': {'x': 'xxx'}
2631 },
2632 },
2633 })
2634
2635 schd = scheduler(id_, paused_start=False)
2636 async with run(schd):
2637 # 1/slow should spawn on startup
2638 assert list_spawn_task_calls() == ['slow']
2639
2640 # set foo:x
2641 await commands.run_cmd(
2642 commands.set_prereqs_and_outputs(
2643 schd, ['1/foo'], ['1'], ['x'], None
2644 )
2645 )
2646 # 1/foo:x should be recorded in the DB:
2647 assert db_select(
2648 schd, True, 'task_outputs', 'outputs', cycle='1', name='foo'
2649 ) == [('{"x": "(manually completed)"}',)]
2650 # and 1/x should spawn:
2651 assert list_spawn_task_calls() == ['slow', 'x']
2652
2653 # run the workflow until completion
2654 await complete(schd, timeout=5)
2655
2656 # 1/foo should spawn as a result of the suicide trigger
2657 assert list_spawn_task_calls() == ['slow', 'x', 'foo']
2658
2659 # the manually completed output should not have been overwritten by the
2660 # suicide trigger
2661 assert db_select(
2662 schd, True, 'task_outputs', 'outputs', cycle='1', name='foo'
2663 ) == [('{"x": "(manually completed)"}',)]
2664
2665
2666 async def test_add_to_pool(
2667 flow, scheduler, start, caplog
2668 ):
2669 """It should log attempts to add the same task again."""
2670 id_ = flow('a')
2671 schd = scheduler(id_)
2672
2673 async with start(schd):
2674 caplog.set_level(logging.DEBUG, CYLC_LOG)
2675
2676 # 1/a should be pre-spawned (parentless)
2677 a_1 = schd.pool.get_task(IntegerPoint('1'), 'a')
2678 assert a_1
2679
2680 # add it again
2681 schd.pool.add_to_pool(a_1)
2682
2683 assert "1/a not added to n=0: already exists" in caplog.text
2684
2685
2686 async def test_parentless_spawning(flow, scheduler, run, complete):
2687 """Check that parentless spawning works even if parented in some cycles.
2688
2689 Parentless spawning could be blocked if a parented cycle ended up at
2690 the runahead limit. See https://github.com/cylc/cylc-flow/pull/7237.
2691
2692 """
2693 cfg = {
2694 'scheduling': {
2695 'cycling mode': 'integer',
2696 'initial cycle point': '1',
2697 'runahead limit': 'P0',
2698 'graph': {
2699 'P1': 'b',
2700 'R1/2/P0': 'a => b',
2701 }
2702 },
2703 }
2704 id_ = flow(cfg)
2705 schd = scheduler(id_, paused_start=False)
2706 async with run(schd):
2707 await complete(schd, "2/b")
2708 # The task pool should not be empty now.
2709 assert len(schd.pool.get_tasks())