Debian Codegraph @

tests/i/test_xtrigger_mgr.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 """Tests for the behaviour of xtrigger manager."""
17
18 import asyncio
19 from pathlib import Path
20 from textwrap import dedent
21 from typing import cast, Iterable
22
23 from cylc.flow import commands
24 from cylc.flow.data_messages_pb2 import PbTaskProxy
25 from cylc.flow.data_store_mgr import FAMILY_PROXIES, TASK_PROXIES
26 from cylc.flow.id import TaskTokens
27 from cylc.flow.pathutil import get_workflow_run_dir
28 from cylc.flow.scheduler import Scheduler
29 from cylc.flow.subprocctx import SubFuncContext
30 from cylc.flow.task_outputs import TASK_OUTPUT_SUCCEEDED
31
32
33 async def test_2_xtriggers(flow, start, scheduler, monkeypatch):
34 """Test that if an itask has 4 wall_clock triggers with different
35 offsets that xtrigger manager gets all of them.
36
37 https://github.com/cylc/cylc-flow/issues/5783
38
39 n.b. Clock 3 exists to check the memoization path is followed,
40 and causing this test to give greater coverage.
41 Clock 4 & 5 test higher precision offsets than the CPF.
42 """
43 task_point = 1588636800 # 2020-05-05
44 ten_years_ahead = 1904169600 # 2030-05-05
45 PT2H35M31S_ahead = 1588646131 # 2020-05-05 02:35:31
46 PT2H35M31S_behind = 1588627469 # 2020-05-04 21:24:29
47 monkeypatch.setattr(
48 'cylc.flow.xtriggers.wall_clock.time',
49 lambda: ten_years_ahead - 1
50 )
51 id_ = flow({
52 'scheduler': {
53 'cycle point format': 'CCYY-MM-DD',
54 },
55 'scheduling': {
56 'initial cycle point': '2020-05-05',
57 'xtriggers': {
58 'clock_1': 'wall_clock()',
59 'clock_2': 'wall_clock(offset=P10Y)',
60 'clock_3': 'wall_clock(offset=P10Y)',
61 'clock_4': 'wall_clock(offset=PT2H35M31S)',
62 'clock_5': 'wall_clock(offset=-PT2H35M31S)',
63 },
64 'graph': {
65 'R1': (
66 '@clock_1 & @clock_2 & @clock_3 & @clock_4 & @clock_5'
67 ' => foo'
68 )
69 }
70 }
71 })
72 schd = scheduler(id_)
73 async with start(schd):
74 foo_proxy = schd.pool.get_tasks()[0]
75 clock_1_ctx = schd.xtrigger_mgr.get_xtrig_ctx(foo_proxy, 'clock_1')
76 clock_2_ctx = schd.xtrigger_mgr.get_xtrig_ctx(foo_proxy, 'clock_2')
77 clock_3_ctx = schd.xtrigger_mgr.get_xtrig_ctx(foo_proxy, 'clock_2')
78 clock_4_ctx = schd.xtrigger_mgr.get_xtrig_ctx(foo_proxy, 'clock_4')
79 clock_5_ctx = schd.xtrigger_mgr.get_xtrig_ctx(foo_proxy, 'clock_5')
80
81 assert clock_1_ctx.func_kwargs['trigger_time'] == task_point
82 assert clock_2_ctx.func_kwargs['trigger_time'] == ten_years_ahead
83 assert clock_3_ctx.func_kwargs['trigger_time'] == ten_years_ahead
84 assert clock_4_ctx.func_kwargs['trigger_time'] == PT2H35M31S_ahead
85 assert clock_5_ctx.func_kwargs['trigger_time'] == PT2H35M31S_behind
86
87 schd.xtrigger_mgr.call_xtriggers_async(foo_proxy)
88 assert foo_proxy.state.xtriggers == {
89 'clock_1': True,
90 'clock_2': False,
91 'clock_3': False,
92 'clock_4': True,
93 'clock_5': True,
94 }
95
96
97 async def test_1_xtrigger_2_tasks(flow, start, scheduler, mocker):
98 """
99 If two tasks depend on the same satisfied xtrigger, put_xtriggers should
100 only be called once - when the xtrigger gets satisfied.
101 - https://github.com/cylc/cylc-flow/pull/5908
102
103 So long as both tasks are active at once:
104 - https://github.com/cylc/cylc-flow/issues/7027
105
106 """
107 id_ = flow({
108 'scheduling': {
109 'initial cycle point': '2020',
110 'graph': {
111 'R1': '@wall_clock => foo & bar'
112 }
113 }
114 })
115
116 schd = scheduler(id_)
117 spy = mocker.spy(schd.workflow_db_mgr, 'put_xtriggers')
118
119 async with start(schd):
120
121 # Call the clock trigger via its dependent tasks, to get it satisfied.
122 for task in schd.pool.get_tasks():
123 # (For clock triggers this is synchronous)
124 schd.xtrigger_mgr.call_xtriggers_async(task)
125
126 # It should now be satisfied.
127 assert task.state.xtriggers == {'wall_clock': True}
128
129 # Check one put_xtriggers call only, not two.
130 assert spy.call_count == 1
131
132 # Note on master prior to GH #5908 the call is made from the
133 # scheduler main loop when the two tasks become satisfied,
134 # resulting in two calls to put_xtriggers. This test fails
135 # on master, but with call count 0 (not 2) because the main
136 # loop doesn't run in this test.
137
138
139 async def test_1_xtrigger_2_tasks_async(
140 flow, start, scheduler, mocker, caplog
141 ):
142 """
143 Like test_1_xtrigger_2_tasks but for async (not clock) xtriggers.
144
145 If two tasks depend on the same satisfied xtrigger, put_xtriggers should
146 only be called once - when the xtrigger gets satisfied (so long as both
147 are active at once - https://github.com/cylc/cylc-flow/issues/7027
148
149 """
150 id_ = flow({
151 'scheduling': {
152 'cycling mode': 'integer',
153 'xtriggers': {
154 'echo': 'echo("whatever", succeed=False)',
155 },
156 'graph': {
157 'R1': '''
158 @echo => foo & bar
159 '''
160 },
161 },
162 })
163
164 schd = scheduler(id_)
165 spy = mocker.spy(schd.workflow_db_mgr, 'put_xtriggers')
166
167 async with start(schd):
168
169 foo = schd.pool._get_task_by_id('1/foo')
170 bar = schd.pool._get_task_by_id('1/bar')
171
172 schd.xtrigger_mgr.call_xtriggers_async(foo)
173 assert "Commencing xtrigger" in caplog.text
174 caplog.clear()
175
176 schd.xtrigger_mgr.call_xtriggers_async(bar)
177 assert "Commencing xtrigger" not in caplog.text
178 caplog.clear()
179
180 satisfy_xtrigger_functions(schd) # mock results
181 assert "xtrigger succeeded" in caplog.text
182 caplog.clear()
183
184 schd.xtrigger_mgr.call_xtriggers_async(foo) # process callbacks
185 assert "satisfying xtrigger" in caplog.text
186 caplog.clear()
187
188 schd.xtrigger_mgr.call_xtriggers_async(bar) # process callbacks
189 assert "satisfying xtrigger" in caplog.text
190 caplog.clear()
191
192 # It should now be satisfied.
193 assert foo.state.xtriggers == {'echo': True}
194 assert bar.state.xtriggers == {'echo': True}
195
196 # Check put_xtriggers called once, not twice.
197 assert spy.call_count == 1
198
199
200 async def test_1_xtrigger_2_tasks_later(
201 flow, start, scheduler, mocker, caplog
202 ):
203 """
204 If two tasks depend on the same satisfied xtrigger, but are not
205 both active at the same time, the xtrigger will need to be
206 satisfied twice - https://github.com/cylc/cylc-flow/issues/7027
207
208 """
209 id_ = flow({
210 'scheduling': {
211 'cycling mode': 'integer',
212 'xtriggers': {
213 'echo': 'echo("whatever", succeed=False)',
214 },
215 'graph': {
216 'R1': '''
217 @echo => foo & bar
218 # spawn bar after @echo is housekept post satisfying foo
219 foo => bar
220 '''
221 },
222 },
223 })
224
225 schd = scheduler(id_)
226 spy = mocker.spy(schd.workflow_db_mgr, 'put_xtriggers')
227
228 async with start(schd):
229
230 # Get foo at startup
231 foo = schd.pool._get_task_by_id('1/foo')
232
233 # call the xtrigger
234 schd.xtrigger_mgr.call_xtriggers_async(foo)
235 assert "Commencing xtrigger" in caplog.text
236 caplog.clear()
237
238 # satisfy it
239 satisfy_xtrigger_functions(schd) # mock results
240 assert "xtrigger succeeded" in caplog.text
241 caplog.clear()
242
243 # process callback
244 schd.xtrigger_mgr.call_xtriggers_async(foo)
245 assert "satisfying xtrigger" in caplog.text
246 caplog.clear()
247
248 # foo should now be satisfied.
249 assert foo.state.xtriggers == {'echo': True}
250
251 # this will delete the xtrigger - nothing else depends on it
252 schd.xtrigger_mgr.housekeep([foo])
253
254 # Spawn bar and remove foo
255 schd.pool.spawn_on_output(foo, TASK_OUTPUT_SUCCEEDED)
256
257 bar = schd.pool._get_task_by_id('1/bar')
258
259 # the xtrigger should be called again for bar
260 schd.xtrigger_mgr.call_xtriggers_async(bar)
261 assert "Commencing xtrigger" in caplog.text
262 caplog.clear()
263
264 # satisfy it
265 satisfy_xtrigger_functions(schd) # mock results
266 assert "xtrigger succeeded" in caplog.text
267 caplog.clear()
268
269 # process callback
270 schd.xtrigger_mgr.call_xtriggers_async(bar)
271 assert "satisfying xtrigger" in caplog.text
272 caplog.clear()
273
274 # bar should now be satisfied.
275 assert bar.state.xtriggers == {'echo': True}
276
277 # Check put_xtriggers called twice, not once.
278 assert spy.call_count == 2
279
280
281 async def test_xtriggers_restart(flow, start, scheduler, db_select):
282 """It should write satisfied xtriggers to the DB and load on restart.
283
284 This checks persistence of xtrigger function results across restarts.
285
286 See also test_set_xtriggers_restart for task dependence on xtriggers.
287
288 """
289 id_ = flow({
290 'scheduling': {
291 'xtriggers': {
292 'x100': 'xrandom(100)', # always succeeds
293 'x0': 'xrandom(0)' # never succeeds
294 },
295 'graph': {
296 'R1': '''
297 @x100 => foo
298 @x0 = > bar
299 '''
300 },
301 }
302 })
303 # start the workflow & run the xtrigger
304 schd = scheduler(id_)
305 async with start(schd):
306 # run all xtriggers
307 for task in schd.pool.get_tasks():
308 schd.xtrigger_mgr.call_xtriggers_async(task)
309 # two xtriggers should have been scheduled to run
310 # and x100 should succeed
311 assert len(schd.proc_pool.queuings) + len(schd.proc_pool.runnings) == 2
312 # wait for it to return
313 for _ in range(50):
314 await asyncio.sleep(0.1)
315 schd.proc_pool.process()
316 if len(schd.proc_pool.runnings) == 0:
317 break
318 else:
319 raise Exception('Process pool did not clear')
320
321 # the satisfied x100 should be written to the DB
322 db_xtriggers = db_select(schd, True, 'xtriggers')
323 assert len(db_xtriggers) == 1
324 assert db_xtriggers[0][0] == 'xrandom(100)'
325 assert db_xtriggers[0][1].startswith('{"COLOR":') # (xrandom result dict)
326
327 # restart the workflow, the xtrigger should *not* run again
328 schd = scheduler(id_)
329 async with start(schd):
330 # run all xtriggers
331 for task in schd.pool.get_tasks():
332 schd.xtrigger_mgr.call_xtriggers_async(task)
333
334 # satisfied x100 should have been loaded from the DB
335 # so only one xtrigger should be scheduled to run now
336 assert len(schd.proc_pool.queuings) + len(schd.proc_pool.runnings) == 1
337
338 # x0 should not be satisfied
339 bar = schd.pool._get_task_by_id('1/bar')
340 assert not bar.state.xtriggers["x0"]
341
342 # x100 should now be satisfied in the task pool and the datastore
343 foo = schd.pool._get_task_by_id('1/foo')
344 assert foo.state.xtriggers["x100"]
345
346 await schd.update_data_structure()
347 [xtrig] = [
348 p
349 for t in cast(
350 'Iterable[PbTaskProxy]',
351 schd.data_store_mgr.data[
352 schd.data_store_mgr.workflow_id
353 ][
354 TASK_PROXIES
355 ].values()
356 )
357 for p in t.xtriggers.values()
358 if p.label == "x100"
359 ]
360 assert xtrig.id == "xrandom(100)"
361 assert xtrig.satisfied
362
363 # check the DB to ensure no additional entries have been created
364 assert db_select(schd, True, 'xtriggers') == db_xtriggers
365
366
367 async def test_set_xtrig_prereq_restart(flow, start, scheduler, db_select):
368 """Satisfied xtrigger prerequisites should persist across restart.
369
370 (Task prerequisites can be artificially satisfied by "cylc set").
371
372 See also test_xtriggers_restart, for persistence of xtrigger results.
373
374 """
375 id_ = flow({
376 'scheduling': {
377 'xtriggers': {
378 'x0': 'xrandom(0)' # never succeeds naturally
379 },
380 'graph': {
381 'R1': '''
382 @x0 = > foo & bar
383 '''
384 },
385 }
386 })
387 schd = scheduler(id_)
388 async with start(schd):
389 # artificially set dependence of foo on x0
390 schd.pool.set_prereqs_and_outputs(
391 {TaskTokens('1', 'foo')}, [], ['xtrigger/x0:succeeded'], []
392 )
393
394 # the satisfied x0 prerequisite should be written to the DB
395 [db_pre] = db_select(schd, True, 'task_prerequisites')
396 assert db_pre == ('1', 'foo', '[1]', 'x0', 'xtrigger', 'succeeded', '1')
397
398 # restart the workflow
399 schd = scheduler(id_)
400 async with start(schd):
401 # run all xtriggers
402 for task in schd.pool.get_tasks():
403 schd.xtrigger_mgr.call_xtriggers_async(task)
404
405 # foo's dependence on x0 should be satisfied from the DB
406 # but bar still depends on it so the scheduler should still call it.
407 assert len(schd.proc_pool.queuings) + len(schd.proc_pool.runnings) == 1
408
409 # "@x0 => bar" should not be satisfied
410 bar = schd.pool._get_task_by_id('1/bar')
411 assert not bar.state.xtriggers["x0"]
412
413 # but "x0 => foo" should be, in the task pool and the datastore
414 foo = schd.pool._get_task_by_id('1/foo')
415 assert foo.state.xtriggers["x0"]
416
417 await schd.update_data_structure()
418 xtrigs = [
419 (t.id, p)
420 for t in cast(
421 'Iterable[PbTaskProxy]',
422 schd.data_store_mgr.data[
423 schd.data_store_mgr.workflow_id
424 ][
425 TASK_PROXIES
426 ].values()
427 )
428 for p in t.xtriggers.values()
429 ]
430 assert len(xtrigs) == 2
431 for (id, xtrig) in xtrigs:
432 if id.endswith('foo'):
433 assert xtrig.id == "xrandom(0)"
434 assert xtrig.satisfied
435 elif id.endswith('bar'):
436 assert xtrig.id == "xrandom(0)"
437 assert not xtrig.satisfied
438 else:
439 assert False
440
441
442 async def test_error_in_xtrigger(flow, start, scheduler):
443 """Failure in an xtrigger is handled nicely.
444 """
445 id_ = flow({
446 'scheduling': {
447 'xtriggers': {
448 'mytrig': 'mytrig()'
449 },
450 'graph': {
451 'R1': '@mytrig => foo'
452 },
453 }
454 })
455
456 # add a custom xtrigger to the workflow
457 run_dir = Path(get_workflow_run_dir(id_))
458 xtrig_dir = run_dir / 'lib/python'
459 xtrig_dir.mkdir(parents=True)
460 (xtrig_dir / 'mytrig.py').write_text(dedent('''
461 def mytrig(*args, **kwargs):
462 raise Exception('This Xtrigger is broken')
463 '''))
464
465 schd = scheduler(id_)
466 async with start(schd) as log:
467 foo = schd.pool.get_tasks()[0]
468 schd.xtrigger_mgr.call_xtriggers_async(foo)
469 for _ in range(50):
470 await asyncio.sleep(0.1)
471 schd.proc_pool.process()
472 if len(schd.proc_pool.runnings) == 0:
473 break
474 else:
475 raise Exception('Process pool did not clear')
476
477 error = log.messages[-1].split('\n')
478 assert error[-2] == 'Exception: This Xtrigger is broken'
479 assert error[0] == 'ERROR in xtrigger mytrig()'
480
481
482 async def test_1_seq_clock_trigger_2_tasks(flow, start, scheduler):
483 """Test that all tasks dependent on a sequential clock trigger continue to
484 spawn after the first cycle.
485
486 See https://github.com/cylc/cylc-flow/issues/6204
487 """
488 id_ = flow({
489 'scheduler': {
490 'cycle point format': 'CCYY',
491 },
492 'scheduling': {
493 'initial cycle point': '1990',
494 'graph': {
495 'P1Y': '@wall_clock => foo & bar',
496 },
497 },
498 })
499 schd: Scheduler = scheduler(id_)
500
501 async with start(schd):
502 start_task_pool = schd.pool.get_task_ids()
503 assert start_task_pool == {'1990/foo', '1990/bar'}
504
505 for _ in range(3):
506 await schd._main_loop()
507
508 assert schd.pool.get_task_ids() == start_task_pool.union(
509 f'{year}/{name}'
510 for year in range(1991, 1994)
511 for name in ('foo', 'bar')
512 )
513
514
515 async def test_set_xtrig_prereq_reload(flow, start, scheduler, db_select):
516 """Satisfied xtrigger prerequisites should persist across reload.
517
518 (Task prerequisites can be artificially satisfied by "cylc set").
519
520 """
521 id_ = flow({
522 'scheduling': {
523 'xtriggers': {
524 'x0': 'xrandom(0)' # never succeeds naturally
525 },
526 'graph': {
527 'R1': '''
528 @x0 = > foo & bar
529 '''
530 },
531 }
532 })
533 schd = scheduler(id_)
534 async with start(schd):
535 # artificially set dependence of foo on x0
536 schd.pool.set_prereqs_and_outputs(
537 {TaskTokens('1', 'foo')}, [], ['xtrigger/x0:succeeded'], []
538 )
539
540 # reload the workflow
541 await commands.run_cmd(commands.reload_workflow(schd))
542
543 # run all xtriggers
544 for task in schd.pool.get_tasks():
545 schd.xtrigger_mgr.call_xtriggers_async(task)
546
547 # foo's dependence on x0 should remain satisfied, but bar still depends
548 # on it so the function should still be called by the scheduler.
549 assert len(schd.proc_pool.queuings) + len(schd.proc_pool.runnings) == 1
550
551 # "@x0 => bar" should not be satisfied
552 bar = schd.pool._get_task_by_id('1/bar')
553 assert not bar.state.xtriggers["x0"]
554
555 # but "x0 => foo" should be, in the task pool and the datastore
556 foo = schd.pool._get_task_by_id('1/foo')
557 assert foo.state.xtriggers["x0"]
558
559 await schd.update_data_structure()
560 xtrigs = [
561 (t.id, p)
562 for t in cast(
563 'Iterable[PbTaskProxy]',
564 schd.data_store_mgr.data[
565 schd.data_store_mgr.workflow_id
566 ][
567 TASK_PROXIES
568 ].values()
569 )
570 for p in t.xtriggers.values()
571 ]
572 assert len(xtrigs) == 2
573 for (id, xtrig) in xtrigs:
574 if id.endswith('foo'):
575 assert xtrig.id == "xrandom(0)"
576 assert xtrig.satisfied
577 elif id.endswith('bar'):
578 assert xtrig.id == "xrandom(0)"
579 assert not xtrig.satisfied
580 else:
581 assert False
582
583
584 async def test_force_satisfy(flow, start, scheduler, log_filter):
585 """It should satisfy valid xtriggers and ignore invalid ones."""
586 id_ = flow({
587 'scheduling': {
588 'xtriggers': {
589 'x': 'xrandom(0)'
590 },
591 'graph': {
592 'R1': '@x => foo'
593 },
594 }
595 })
596 schd = scheduler(id_)
597 async with start(schd):
598 foo = schd.pool.get_tasks()[0]
599
600 # check x not satisfied yet
601 assert not foo.state.xtriggers['x'] # not satisfied
602
603 # force satisfy it
604 xtrigs = {
605 "x": True, # it should satisfy this one
606 "y": True # it should just ignore this one
607 }
608 schd.xtrigger_mgr.force_satisfy(foo, xtrigs)
609
610 assert foo.state.xtriggers['x'] # satisfied
611 assert log_filter(
612 contains=('prerequisite force-satisfied: x = xrandom(0)'))
613
614 # force satisfy it again
615 schd.xtrigger_mgr.force_satisfy(foo, xtrigs)
616 assert foo.state.xtriggers['x'] # satisfied
617 assert log_filter(
618 contains=('prerequisite already satisfied: x = xrandom(0)'))
619
620 # force unsatisfy it
621 schd.xtrigger_mgr.force_satisfy(foo, {"x": False})
622 assert not foo.state.xtriggers['x'] # not satisfied
623 assert log_filter(
624 contains=('prerequisite force-unsatisfied: x = xrandom(0)'))
625
626 # force unsatisfy it again
627 schd.xtrigger_mgr.force_satisfy(foo, {"x": False})
628 assert not foo.state.xtriggers['x'] # not satisfied
629 assert log_filter(
630 contains=('prerequisite already unsatisfied: x = xrandom(0)')
631 )
632
633
634 async def test_data_store(flow, start, scheduler):
635 """It should update the data store with xtrigger state."""
636 id_ = flow({
637 'scheduling': {
638 'initial cycle point': 'previous(T00)',
639 'xtriggers': {
640 'clock1': 'wall_clock()',
641 'clock2': 'wall_clock(offset="P1Y")',
642 },
643 'graph': {
644 'R1': '''
645 @clock1 => foo
646 @clock2 => foo
647 '''
648 }
649 }
650 })
651 schd: Scheduler = scheduler(id_)
652 async with start(schd):
653 await schd.update_data_structure()
654 itask = schd.pool.get_tasks()[0]
655
656 # extract xtrigger entry from the data store
657 xtriggers = schd.data_store_mgr.data[
658 schd.tokens.id
659 ][TASK_PROXIES][itask.tokens.id].xtriggers
660 clock1, clock2 = sorted(x for x in xtriggers if 'wall_clock' in x)
661
662 # it should not be satisfied (yet)
663 assert xtriggers[clock1].label == 'clock1'
664 assert xtriggers[clock1].satisfied is False
665
666 # execute the xtrigger
667 schd.xtrigger_mgr.call_xtriggers_async(itask)
668
669 # an update delta should be produced
670 # NOTE: both xtriggers should be present in the update
671 # (see https://github.com/cylc/cylc-flow/issues/6307)
672 task_delta = schd.data_store_mgr.updated[TASK_PROXIES][itask.tokens.id]
673 assert task_delta.xtriggers[clock1].satisfied is True
674 assert task_delta.xtriggers[clock2].satisfied is False
675
676 # the xtrigger should be satisfied in the data store
677 await schd.update_data_structure()
678 assert xtriggers[clock1].label == 'clock1'
679 assert xtriggers[clock1].satisfied is True
680
681
682 def satisfy_xtrigger_functions(schd, stdout='[true, {}]', ret_code=0):
683 """Satisfy and dequeue any xtrigger subprocesses."""
684 for item in list(schd.proc_pool.queuings):
685 ctx, _, callback, *_ = item
686 if isinstance(schd.proc_pool.queuings[0][0], SubFuncContext):
687 # dequeue from the proc pool
688 schd.proc_pool.queuings.remove(item)
689
690 # mock the xtrigger output
691 ctx.ret_code = ret_code
692 ctx.out = stdout
693
694 # run the callback
695 callback(ctx)
696
697
698 async def test_xtrigger_modifiers(flow, scheduler, start):
699 """It should update xtrigger derived task modifiers."""
700 id_ = flow({
701 'scheduling': {
702 'initial cycle point': 'previous(T00)',
703 'xtriggers': {
704 'echo': 'echo("whatever", succeed=True)',
705 },
706 'graph': {
707 'R1': '''
708 @wall_clock => foo
709 @echo => foo
710 '''
711 },
712 },
713 'runtime': {
714 'foo': {
715 'execution retry delays': 'PT0S',
716 },
717 },
718 })
719 schd = scheduler(id_)
720 async with start(schd):
721 # configure the task to retry
722 itask = schd.pool.get_tasks()[0]
723 schd.task_events_mgr._retry_task(itask, 0)
724 await schd.update_data_structure()
725
726 # the task proxy object in the data store
727 ds_tproxy = schd.data_store_mgr.data[schd.tokens.id][TASK_PROXIES][
728 itask.tokens.id
729 ]
730
731 # the "root" family proxy object in the data store
732 ds_fproxy = schd.data_store_mgr.data[schd.tokens.id][FAMILY_PROXIES][
733 itask.tokens.duplicate(task='root').id
734 ]
735
736 # the task modifiers should be initialised on task creation
737 assert len(itask.state.xtriggers) == 3
738 assert ds_tproxy.is_retry is True
739 assert ds_tproxy.is_wallclock is True
740 assert ds_tproxy.is_xtriggered is True
741
742 # the modifiers should bubble up the family tree
743 assert ds_fproxy.is_retry is True
744 assert ds_fproxy.is_wallclock is True
745 assert ds_fproxy.is_xtriggered is True
746
747 # run the xtriggers
748 schd.xtrigger_mgr.call_xtriggers_async(itask) # run xtrigs
749 satisfy_xtrigger_functions(schd) # mock results
750 schd.xtrigger_mgr.call_xtriggers_async(itask) # process callbacks
751
752 await schd.update_data_structure()
753
754 # the task modifiers should have been updated
755 assert ds_tproxy.is_retry is False
756 assert ds_tproxy.is_wallclock is False
757 assert ds_tproxy.is_xtriggered is False
758
759 # the modifiers should bubble up the family tree
760 assert ds_fproxy.is_retry is False
761 assert ds_fproxy.is_wallclock is False
762 assert ds_fproxy.is_xtriggered is False
763
764
765 async def test_orphaned_task_with_xtrigger_on_reload(
766 flow, start, scheduler, log_filter
767 ):
768 """Removing a task with an xtrigger dependency and reloading should not
769 crash.
770 """
771 conf = {
772 'scheduling': {
773 'xtriggers': {
774 'my_xtrig': 'xrandom(0)',
775 },
776 'graph': {
777 'R1': '''
778 @my_xtrig => foo
779 bar
780 '''
781 },
782 },
783 }
784 id_ = flow(conf)
785 schd: Scheduler = scheduler(id_)
786 async with start(schd):
787 # confirm the task with the xtrigger is in the pool
788 assert schd.pool._get_task_by_id('1/foo') is not None
789
790 # remove task with xtrigger dependency (no foo in R1)
791 conf['scheduling']['graph']['R1'] = 'bar'
792 flow(conf, workflow_id=id_)
793
794 # reload should not crash
795 await commands.run_cmd(commands.reload_workflow(schd))
796
797 # the orphaned task should have been removed
798 assert schd.pool._get_task_by_id('1/foo') is None
799
800 # the reload should have completed successfully
801 assert log_filter(contains='Reload completed')