Debian Codegraph @

tests/i/test_remove.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 import logging
18
19 import pytest
20
21 from cylc.flow.commands import (
22 force_trigger_tasks,
23 reload_workflow,
24 remove_tasks,
25 run_cmd,
26 )
27 from cylc.flow.cycling.integer import IntegerPoint
28 from cylc.flow.id import TaskTokens
29 from cylc.flow.scheduler import Scheduler
30 from cylc.flow.task_outputs import TASK_OUTPUT_SUCCEEDED
31 from cylc.flow.task_proxy import TaskProxy
32 from cylc.flow.task_state import TASK_STATUS_FAILED
33
34
35 @pytest.fixture
36 async def cylc_show_prereqs(cylc_show):
37 """Fixture that returns the prereq info from `cylc show` in an
38 easy-to-use format."""
39 async def inner(schd: Scheduler, task: str):
40 prerequisites = (await cylc_show(schd, task))[task]['prerequisites']
41 return [
42 (
43 p['satisfied'],
44 {c['taskId']: c['satisfied'] for c in p['conditions']},
45 )
46 for p in prerequisites
47 ]
48
49 return inner
50
51
52 @pytest.fixture
53 def example_workflow(flow):
54 return flow({
55 'scheduling': {
56 'graph': {
57 # Note: test both `&` and separate arrows for combining
58 # dependencies
59 'R1': '''
60 a1 & a2 => b
61 a3 => b
62 ''',
63 },
64 },
65 })
66
67
68 def get_data_store_flow_nums(schd: Scheduler, itask: TaskProxy):
69 _, ds_tproxy = schd.data_store_mgr.store_node_fetcher(itask.tokens)
70 if ds_tproxy:
71 return ds_tproxy.flow_nums
72
73
74 async def test_basic(
75 example_workflow, scheduler, start, db_select
76 ):
77 """Test removing a task from all flows."""
78 schd: Scheduler = scheduler(example_workflow)
79 async with start(schd):
80 a1 = schd.pool._get_task_by_id('1/a1')
81 a3 = schd.pool._get_task_by_id('1/a3')
82 schd.pool.spawn_on_output(a1, TASK_OUTPUT_SUCCEEDED)
83 schd.pool.spawn_on_output(a3, TASK_OUTPUT_SUCCEEDED)
84 await schd.update_data_structure()
85
86 assert a1 in schd.pool.get_tasks()
87 for table in ('task_states', 'task_outputs'):
88 assert db_select(schd, True, table, 'flow_nums', name='a1') == [
89 ('[1]',),
90 ]
91 assert db_select(
92 schd, True, 'task_prerequisites', 'satisfied', prereq_name='a1'
93 ) == [
94 ('satisfied naturally',),
95 ]
96 assert get_data_store_flow_nums(schd, a1) == '[1]'
97
98 await run_cmd(remove_tasks(schd, ['1/a1'], []))
99 await schd.update_data_structure()
100
101 assert a1 not in schd.pool.get_tasks() # removed from pool
102 for table in ('task_states', 'task_outputs'):
103 assert db_select(schd, True, table, 'flow_nums', name='a1') == [
104 ('[]',), # removed from all flows
105 ]
106 assert db_select(
107 schd, True, 'task_prerequisites', 'satisfied', prereq_name='a1'
108 ) == [
109 ('0',), # prereq is now unsatisfied
110 ]
111 assert get_data_store_flow_nums(schd, a1) == '[]'
112
113
114 async def test_specific_flow(
115 example_workflow, scheduler, start, db_select
116 ):
117 """Test removing a task from a specific flow."""
118 schd: Scheduler = scheduler(example_workflow)
119
120 def select_prereqs():
121 return db_select(
122 schd,
123 True,
124 'task_prerequisites',
125 'flow_nums',
126 'satisfied',
127 prereq_name='a1',
128 )
129
130 async with start(schd):
131 a1 = schd.pool._get_task_by_id('1/a1')
132 await run_cmd(force_trigger_tasks(schd, ['1/a1'], ['1', '2']))
133 schd.pool.spawn_on_output(a1, TASK_OUTPUT_SUCCEEDED)
134 await schd.update_data_structure()
135
136 assert a1 in schd.pool.get_tasks()
137 assert a1.flow_nums == {1, 2}
138 for table in ('task_states', 'task_outputs'):
139 assert sorted(
140 db_select(schd, True, table, 'flow_nums', name='a1')
141 ) == [
142 ('[1, 2]',), # triggered task
143 ('[1]',), # original spawned task
144 ]
145 assert select_prereqs() == [
146 ('[1, 2]', 'satisfied naturally'),
147 ]
148 assert get_data_store_flow_nums(schd, a1) == '[1, 2]'
149
150 await run_cmd(remove_tasks(schd, ['1/a1'], ['1']))
151 await schd.update_data_structure()
152
153 assert a1 in schd.pool.get_tasks() # still in pool
154 assert a1.flow_nums == {2}
155 for table in ('task_states', 'task_outputs'):
156 assert sorted(
157 db_select(schd, True, table, 'flow_nums', name='a1')
158 ) == [
159 ('[2]',),
160 ('[]',),
161 ]
162 assert select_prereqs() == [
163 ('[1, 2]', '0'),
164 ]
165 assert get_data_store_flow_nums(schd, a1) == '[2]'
166
167
168 async def test_unset_prereq(example_workflow, scheduler, start):
169 """Test removing a task unsets any prerequisites it satisfied."""
170 schd: Scheduler = scheduler(example_workflow)
171 async with start(schd):
172 for task in ('a1', 'a2', 'a3'):
173 schd.pool.spawn_on_output(
174 schd.pool.get_task(IntegerPoint('1'), task),
175 TASK_OUTPUT_SUCCEEDED,
176 )
177 b = schd.pool.get_task(IntegerPoint('1'), 'b')
178 assert b.prereqs_are_satisfied()
179
180 await run_cmd(remove_tasks(schd, ['1/a1'], []))
181
182 assert not b.prereqs_are_satisfied()
183
184
185 async def test_not_unset_prereq(
186 example_workflow, scheduler, start, db_select
187 ):
188 """Test removing a task does not unset a force-satisfied prerequisite
189 (one that was satisfied by `cylc set --pre`)."""
190 schd: Scheduler = scheduler(example_workflow)
191 async with start(schd):
192 # This set prereq should not be unset by removing a1:
193 schd.pool.set_prereqs_and_outputs(
194 {TaskTokens('1', 'b')}, outputs=[], prereqs=['1/a1'], flow=[]
195 )
196 # Whereas the prereq satisfied by this set output *should* be unset
197 # by removing a2:
198 schd.pool.set_prereqs_and_outputs(
199 {TaskTokens('1', 'a2')}, outputs=['succeeded'], prereqs=[], flow=[]
200 )
201 await schd.update_data_structure()
202
203 assert sorted(
204 db_select(
205 schd, True, 'task_prerequisites', 'prereq_name', 'satisfied'
206 )
207 ) == [
208 ('a1', 'force satisfied'),
209 ('a2', 'satisfied naturally'),
210 ('a3', '0'),
211 ]
212
213 await run_cmd(remove_tasks(schd, ['1/a1', '1/a2'], []))
214 await schd.update_data_structure()
215
216 assert sorted(
217 db_select(
218 schd, True, 'task_prerequisites', 'prereq_name', 'satisfied'
219 )
220 ) == [
221 ('a1', 'force satisfied'),
222 ('a2', '0'),
223 ('a3', '0'),
224 ]
225
226
227 async def test_nothing_to_do(
228 example_workflow, scheduler, start, log_filter
229 ):
230 """Test removing an invalid task."""
231 schd: Scheduler = scheduler(example_workflow)
232 async with start(schd):
233 await run_cmd(remove_tasks(schd, ['1/doh'], []))
234 assert log_filter(logging.WARNING, 'No tasks match "1/doh"')
235
236
237 async def test_logging(
238 flow, scheduler, start, log_filter, caplog: pytest.LogCaptureFixture
239 ):
240 """Test logging of a mixture of valid and invalid task removals."""
241 schd: Scheduler = scheduler(
242 flow({
243 'scheduler': {
244 'cycle point format': 'CCYY',
245 },
246 'scheduling': {
247 'initial cycle point': '2000',
248 'graph': {
249 'R3//P1Y': 'b[-P1Y] => a & b',
250 },
251 },
252 })
253 )
254 tasks_to_remove = [
255 # Active, removable tasks:
256 '2000/*',
257 # Future, non-removable tasks:
258 '2001/a', '2001/b',
259 # Glob that doesn't match any active tasks:
260 '2002/*',
261 # Invalid tasks:
262 '2005/a', '2000/doh',
263 ]
264 async with start(schd):
265 await run_cmd(remove_tasks(schd, tasks_to_remove, []))
266
267 assert log_filter(
268 logging.INFO, "Removed tasks: 2000/a (flows=1), 2000/b (flows=1)"
269 )
270
271 assert log_filter(logging.WARNING, "Task(s) not removable: 2001/a, 2001/b")
272 assert log_filter(logging.WARNING, "Invalid cycle point for task: a, 2005")
273 assert log_filter(
274 logging.WARNING, "No tasks match the IDs:\n* 2000/doh\n* 2005/a"
275 )
276 # No tasks were submitted/running so none should have been killed:
277 assert "job killed" not in caplog.text
278
279
280 async def test_logging_flow_nums(
281 example_workflow, scheduler, start, log_filter
282 ):
283 """Test logging of task removals involving flow numbers."""
284 schd: Scheduler = scheduler(example_workflow)
285 async with start(schd):
286 await run_cmd(force_trigger_tasks(schd, ['1/a1'], ['1', '2']))
287 # Removing from flow that doesn't exist doesn't work:
288 await run_cmd(remove_tasks(schd, ['1/a1'], ['3']))
289 assert log_filter(
290 logging.WARNING, "Task(s) not removable: 1/a1 (flows=3)"
291 )
292
293 # But if a valid flow is included, it will be removed from that flow:
294 await run_cmd(remove_tasks(schd, ['1/a1'], ['2', '3']))
295 assert log_filter(logging.INFO, "Removed tasks: 1/a1 (flows=2)")
296 assert schd.pool._get_task_by_id('1/a1').flow_nums == {1}
297
298
299 async def test_retrigger(flow, scheduler, run, reflog, complete):
300 """Test prereqs & re-run behaviour when removing tasks."""
301 schd: Scheduler = scheduler(
302 flow('a => b => c'),
303 paused_start=False,
304 )
305 async with run(schd):
306 reflog_triggers: set = reflog(schd)
307 await complete(schd, '1/b')
308
309 await run_cmd(remove_tasks(schd, ['1/a', '1/b'], []))
310 schd.process_workflow_db_queue()
311 # Removing 1/b should un-queue 1/c:
312 assert len(schd.pool.task_queue_mgr.queues['default'].deque) == 0
313
314 assert reflog_triggers == {
315 ('1/a', None),
316 ('1/b', ('1/a',)),
317 }
318 reflog_triggers.clear()
319
320 await run_cmd(force_trigger_tasks(schd, ['1/a'], []))
321 await complete(schd)
322
323 assert reflog_triggers == {
324 ('1/a', None),
325 # 1/b should have run again after 1/a on the re-trigger in flow 1:
326 ('1/b', ('1/a',)),
327 ('1/c', ('1/b',)),
328 }
329
330
331 async def test_prereqs(
332 flow, scheduler, run, complete, cylc_show_prereqs, log_filter
333 ):
334 """Test prereqs & stall behaviour when removing tasks."""
335 schd: Scheduler = scheduler(
336 flow('(a1 | a2) & b => x'),
337 paused_start=False,
338 )
339 async with run(schd):
340 await complete(schd, '1/a1', '1/a2', '1/b')
341
342 await run_cmd(remove_tasks(schd, ['1/a1'], []))
343 assert not schd.pool.is_stalled()
344
345 # `cylc show` should reflect the now-unsatisfied condition:
346 assert await cylc_show_prereqs(schd, '1/x') == [
347 (True, {'1/a1': False, '1/a2': True, '1/b': True})
348 ]
349
350 await run_cmd(remove_tasks(schd, ['1/b'], []))
351 # Should cause stall now because 1/c prereq is unsatisfied:
352 assert schd.pool.is_stalled()
353 assert log_filter(
354 logging.WARNING,
355 "1/x is waiting on ['1/a1:succeeded', '1/b:succeeded']",
356 )
357 assert await cylc_show_prereqs(schd, '1/x') == [
358 (False, {'1/a1': False, '1/a2': True, '1/b': False})
359 ]
360
361 assert schd.pool._get_task_by_id('1/x')
362 await run_cmd(remove_tasks(schd, ['1/a2'], []))
363 # Should cause 1/x to be removed from the pool as it no longer has
364 # any satisfied prerequisite tasks:
365 assert not schd.pool._get_task_by_id('1/x')
366 assert log_filter(
367 logging.INFO,
368 regex=r"1/x.* removed .* prerequisite task\(s\) removed",
369 )
370
371
372 async def test_downstream_preparing(flow, scheduler, start):
373 """Downstream dependents should not be removed if they are already
374 preparing."""
375 schd: Scheduler = scheduler(
376 flow('''
377 a => x
378 a => y
379 '''),
380 )
381 async with start(schd):
382 a = schd.pool._get_task_by_id('1/a')
383 schd.pool.spawn_on_output(a, TASK_OUTPUT_SUCCEEDED)
384 assert schd.pool.get_task_ids() == {'1/a', '1/x', '1/y'}
385
386 schd.pool._get_task_by_id('1/y').state_reset('preparing')
387 await run_cmd(remove_tasks(schd, ['1/a'], []))
388 assert schd.pool.get_task_ids() == {'1/y'}
389
390
391 async def test_downstream_other_flows(flow, scheduler, run, complete):
392 """Downstream dependents should not be removed if they exist in other
393 flows."""
394 schd: Scheduler = scheduler(
395 flow('''
396 a => b => c => x
397 a => x
398 '''),
399 paused_start=False,
400 )
401 async with run(schd):
402 await complete(schd, '1/a')
403 await run_cmd(force_trigger_tasks(schd, ['1/c'], ['2']))
404 c = schd.pool._get_task_by_id('1/c')
405 schd.pool.spawn_on_output(c, TASK_OUTPUT_SUCCEEDED)
406 assert schd.pool._get_task_by_id('1/x').flow_nums == {1, 2}
407
408 await run_cmd(remove_tasks(schd, ['1/c'], ['2']))
409 assert schd.pool.get_task_ids() == {'1/b', '1/x'}
410 # Note: in future we might want to remove 1/x from flow 2 as well, to
411 # maintain flow continuity. However it is tricky at the moment because
412 # other prerequisite tasks could exist in flow 2 (we don't know as
413 # prereqs do not hold flow info other than in the DB).
414 assert schd.pool._get_task_by_id('1/x').flow_nums == {1, 2}
415
416
417 async def test_suicide(flow, scheduler, run, reflog, complete):
418 """Test that suicide prereqs are unset by `cylc remove`."""
419 schd: Scheduler = scheduler(
420 flow('''
421 a => b => c => d => x
422 a & c => !x
423 '''),
424 paused_start=False,
425 )
426 async with run(schd):
427 reflog_triggers: set = reflog(schd)
428 await complete(schd, '1/b')
429 await run_cmd(remove_tasks(schd, ['1/a'], []))
430 await complete(schd)
431
432 assert reflog_triggers == {
433 ('1/a', None),
434 ('1/b', ('1/a',)),
435 ('1/c', ('1/b',)),
436 ('1/d', ('1/c',)),
437 # 1/x not suicided as 1/a was removed:
438 ('1/x', ('1/d',)),
439 }
440
441
442 async def test_kill_running(flow, scheduler, run, complete, reflog):
443 """Test removing a running task should kill it.
444
445 Note this only tests simulation mode and a separate test for live mode
446 exists in tests/functional/cylc-remove.
447 """
448 schd: Scheduler = scheduler(
449 flow({
450 'scheduling': {
451 'graph': {
452 'R1': '''
453 a:started => b => c
454 a:failed => q
455 '''
456 },
457 },
458 'runtime': {
459 'a': {
460 'simulation': {
461 'default run length': 'PT30S'
462 },
463 },
464 },
465 }),
466 paused_start=False,
467 )
468 async with run(schd):
469 reflog_triggers = reflog(schd)
470 await complete(schd, '1/b')
471 a = schd.pool._get_task_by_id('1/a')
472 await run_cmd(remove_tasks(schd, ['1/a'], []))
473 assert a.state(TASK_STATUS_FAILED, is_held=True)
474 await complete(schd)
475
476 assert reflog_triggers == {
477 ('1/a', None),
478 ('1/b', ('1/a',)),
479 ('1/c', ('1/b',)),
480 # The a:failed output should not cause 1/q to run
481 }
482
483
484 async def test_reload_changed_config(flow, scheduler, run, complete):
485 """Test that a task is removed from the pool if its configuration changes
486 to make it no longer match the graph."""
487 wid = flow({
488 'scheduling': {
489 'graph': {
490 'R1': '''
491 a => b
492 a:started => s & b
493 ''',
494 },
495 },
496 'runtime': {
497 'a': {
498 'simulation': {
499 # Ensure 1/a still in pool during reload
500 'fail cycle points': 'all',
501 },
502 },
503 },
504 })
505 schd: Scheduler = scheduler(wid, paused_start=False)
506 async with run(schd):
507 await complete(schd, '1/s')
508 # Change graph then reload
509 flow('b', workflow_id=wid)
510 await run_cmd(reload_workflow(schd))
511 assert schd.config.cfg['scheduling']['graph']['R1'] == 'b'
512 assert schd.pool.get_task_ids() == {'1/a', '1/b'}
513
514 await run_cmd(remove_tasks(schd, ['1/a'], []))
515 await complete(schd, '1/b')
516
517
518 async def test_remove_triggered(flow, scheduler, start):
519 """It should remove tasks from pool and from to_trigger set."""
520 conf = {
521 'scheduling': {
522 'graph': {
523 'R1': 'a & b'
524 },
525 },
526 }
527 schd: Scheduler = scheduler(flow(conf))
528 async with start(schd):
529 foo, bar = schd.pool.get_tasks()
530 # trigger foo (now)
531 await run_cmd(
532 force_trigger_tasks(schd, [foo.identity], [])
533 )
534 assert foo in schd.pool.tasks_to_trigger_now
535
536 # trigger bar
537 await run_cmd(
538 force_trigger_tasks(schd, [bar.identity], [])
539 )
540 assert bar in schd.pool.tasks_to_trigger_now
541
542 await run_cmd(
543 remove_tasks(schd, [foo.identity, bar.identity], [])
544 )
545 assert not schd.pool.get_tasks()
546 assert not schd.pool.tasks_to_trigger_now