Debian Codegraph @

tests/i/test_data_store_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
17 import logging
18 from logging import INFO
19 from typing import (
20 Iterable,
21 List,
22 cast,
23 )
24 from unittest.mock import Mock
25
26 import pytest
27
28 from cylc.flow import LOG
29 from cylc.flow.commands import (
30 force_trigger_tasks,
31 run_cmd,
32 )
33 from cylc.flow.data_messages_pb2 import (
34 PbJob,
35 PbPrerequisite,
36 PbTaskProxy,
37 )
38 from cylc.flow.data_store_mgr import (
39 EDGES,
40 FAMILY_PROXIES,
41 JOBS,
42 TASK_PROXIES,
43 TASKS,
44 WORKFLOW,
45 )
46 from cylc.flow.id import (
47 TaskTokens,
48 Tokens,
49 )
50 from cylc.flow.network.log_stream_handler import ProtobufStreamHandler
51 from cylc.flow.scheduler import Scheduler
52 from cylc.flow.task_events_mgr import TaskEventsManager
53 from cylc.flow.task_outputs import (
54 TASK_OUTPUT_FAILED,
55 TASK_OUTPUT_STARTED,
56 TASK_OUTPUT_SUBMITTED,
57 TASK_OUTPUT_SUCCEEDED,
58 )
59 from cylc.flow.task_proxy import TaskProxy
60 from cylc.flow.task_state import (
61 TASK_STATUS_FAILED,
62 TASK_STATUS_PREPARING,
63 TASK_STATUS_RUNNING,
64 TASK_STATUS_SUCCEEDED,
65 TASK_STATUS_WAITING,
66 )
67 from cylc.flow.wallclock import get_current_time_string
68
69
70 # NOTE: Some of these tests mutate the data store, so running them in
71 # isolation may see failures when they actually pass if you run the
72 # whole file
73
74
75 def job_config(schd):
76 return {
77 'owner': schd.owner,
78 'submit_num': 3,
79 'task_id': '1/foo',
80 'job_runner_name': 'background',
81 'env-script': None,
82 'err-script': None,
83 'exit-script': None,
84 'execution_time_limit': None,
85 'init-script': None,
86 'post-script': None,
87 'pre-script': None,
88 'script': 'sleep 5; echo "I come in peace"',
89 'work_d': None,
90 'directives': {},
91 'environment': {"FOO": "foo"},
92 'param_var': {},
93 'platform': {'name': 'platform'},
94 'execution retry delays': [10.0, 20.0],
95 'execution time limit': 30.0,
96 }
97
98
99 @pytest.fixture
100 def job_db_row():
101 return [
102 '1',
103 'foo',
104 4,
105 '2020-04-03T13:40:18+13:00',
106 0,
107 '2020-04-03T13:40:20+13:00',
108 None,
109 None,
110 'background',
111 '20542',
112 'localhost',
113 ]
114
115
116 def int_id(_):
117 return '1/foo/03'
118
119
120 def ext_id(schd):
121 return f'~{schd.owner}/{schd.workflow}//{int_id(None)}'
122
123
124 def get_pb_prereqs(schd: 'Scheduler') -> 'List[PbPrerequisite]':
125 """Get all protobuf prerequisites from the data store task proxies."""
126 return [
127 p
128 for t in cast(
129 'Iterable[PbTaskProxy]',
130 schd.data_store_mgr.updated[TASK_PROXIES].values()
131 )
132 for p in t.prerequisites
133 ]
134
135
136 def get_pb_job(schd: Scheduler, itask: TaskProxy) -> PbJob:
137 """Get the protobuf job for a given task from the data store."""
138 return schd.data_store_mgr.data[schd.id][JOBS][itask.job_tokens.id]
139
140
141 @pytest.fixture(scope='module')
142 async def mod_harness(mod_flow, mod_scheduler, mod_start):
143 flow_def = {
144 'scheduler': {
145 'allow implicit tasks': True
146 },
147 'scheduling': {
148 'graph': {
149 'R1': 'foo => bar'
150 }
151 }
152 }
153 id_: str = mod_flow(flow_def)
154 schd: 'Scheduler' = mod_scheduler(id_)
155 async with mod_start(schd):
156 await schd.update_data_structure()
157 data = schd.data_store_mgr.data[schd.data_store_mgr.workflow_id]
158 yield schd, data
159
160
161 @pytest.fixture(scope='module')
162 async def edgeharness(mod_flow, mod_scheduler, mod_start):
163 """Graph with > n in window edge at n=1."""
164 flow_def = {
165 'scheduler': {
166 'allow implicit tasks': True
167 },
168 'scheduling': {
169 'graph': {
170 'R1': """
171 b1 & b2 => c1 & c2
172 c1 => c2
173 """
174 }
175 }
176 }
177 id_: str = mod_flow(flow_def)
178 schd: 'Scheduler' = mod_scheduler(id_)
179 async with mod_start(schd):
180 await schd.update_data_structure()
181 data = schd.data_store_mgr.data[schd.data_store_mgr.workflow_id]
182 yield schd, data
183
184
185 @pytest.fixture(scope='module')
186 async def xharness(mod_flow, mod_scheduler, mod_start):
187 """Like harness, but add xtriggers."""
188 flow_def = {
189 'scheduler': {
190 'allow implicit tasks': True
191 },
192 'scheduling': {
193 'xtriggers': {
194 'x': 'xrandom(0)',
195 'x2': 'xrandom(0)',
196 'y': 'xrandom(0, _=1)'
197 },
198 'graph': {
199 'R1': """
200 @x => foo
201 @x2 => foo
202 @y => foo
203 @x => bar
204 """
205 }
206 }
207 }
208 id_: str = mod_flow(flow_def)
209 schd: 'Scheduler' = mod_scheduler(id_)
210 async with mod_start(schd):
211 await schd.update_data_structure()
212 data = schd.data_store_mgr.data[schd.data_store_mgr.workflow_id]
213 yield schd, data
214
215
216 def collect_states(data, node_type):
217 return [
218 t.state
219 for t in data[node_type].values()
220 if t.state != ''
221 ]
222
223
224 def test_generate_definition_elements(mod_harness):
225 """Test method that generates all definition elements."""
226 schd, data = mod_harness
227 task_defs = schd.config.taskdefs.keys()
228 assert len(data[TASKS]) == len(task_defs)
229 assert len(data[TASK_PROXIES]) == len(task_defs)
230
231
232 def test_generate_graph_elements(mod_harness):
233 schd, data = mod_harness
234 task_defs = schd.config.taskdefs.keys()
235 assert len(data[TASK_PROXIES]) == len(task_defs)
236
237
238 def test_get_data_elements(mod_harness):
239 schd, data = mod_harness
240 flow_msg = schd.data_store_mgr.get_data_elements(TASK_PROXIES)
241 assert len(flow_msg.added) == len(data[TASK_PROXIES])
242
243 flow_msg = schd.data_store_mgr.get_data_elements(WORKFLOW)
244 assert flow_msg.added.last_updated == data[WORKFLOW].last_updated
245
246 none_msg = schd.data_store_mgr.get_data_elements('fraggle')
247 assert len(none_msg.ListFields()) == 0
248
249
250 def test_get_entire_workflow(mod_harness):
251 """Test method that populates the entire workflow protobuf message."""
252 schd, data = mod_harness
253 flow_msg = schd.data_store_mgr.get_entire_workflow()
254 assert len(flow_msg.task_proxies) == len(data[TASK_PROXIES])
255
256
257 def test_increment_graph_window(mod_harness):
258 """Test method that adds and removes elements window boundary."""
259 schd, data = mod_harness
260 assert schd.data_store_mgr.prune_trigger_nodes
261 assert len(data[TASK_PROXIES]) == 2
262
263
264 def test_in_window_extra_edges(edgeharness):
265 """Test edges beyond walk but within window are generated."""
266 schd, data = edgeharness
267 w_id = schd.data_store_mgr.workflow_id
268 assert f'{w_id}//$edge|1/c1|1/c2' in data[EDGES]
269
270
271 def test_initiate_data_model(mod_harness):
272 """Test method that generates all data elements in order."""
273 schd: Scheduler
274 schd, data = mod_harness
275 assert len(data[WORKFLOW].task_proxies) == 2
276 schd.data_store_mgr.initiate_data_model(reloaded=True)
277 assert len(data[WORKFLOW].task_proxies) == 2
278 # Check n-window preserved on reload:
279 schd.data_store_mgr.set_graph_window_extent(2)
280 schd.data_store_mgr.update_data_structure()
281 assert schd.data_store_mgr.n_edge_distance == 2
282 schd.data_store_mgr.initiate_data_model(reloaded=True)
283 assert schd.data_store_mgr.n_edge_distance == 2
284
285
286 async def test_delta_task_state(mod_harness):
287 """Test update_data_structure. This method will generate and
288 apply adeltas/updates given."""
289 schd, data = mod_harness
290 # follow only needs to happen once .. tests working on the same object?
291 w_id = schd.data_store_mgr.workflow_id
292 schd.data_store_mgr.data[w_id] = data
293 assert TASK_STATUS_FAILED not in set(collect_states(data, TASK_PROXIES))
294 for itask in schd.pool.get_tasks():
295 itask.state.reset(TASK_STATUS_FAILED)
296 schd.data_store_mgr.delta_task_state(itask)
297 assert TASK_STATUS_FAILED in set(collect_states(
298 schd.data_store_mgr.updated, TASK_PROXIES))
299
300 # put things back the way we found them
301 for itask in schd.pool.get_tasks():
302 itask.state.reset(TASK_STATUS_WAITING)
303 schd.data_store_mgr.delta_task_state(itask)
304 await schd.update_data_structure()
305
306
307 async def test_delta_task_held(mod_harness):
308 """Test update_data_structure. This method will generate and
309 apply adeltas/updates given."""
310 schd: Scheduler
311 schd, data = mod_harness
312 schd.pool.hold_tasks({TaskTokens('*', 'root')})
313 await schd.update_data_structure()
314 assert True in {t.is_held for t in data[TASK_PROXIES].values()}
315 for itask in schd.pool.get_tasks():
316 itask.state.reset(is_held=False)
317 schd.data_store_mgr.delta_task_held(
318 itask.tdef.name, itask.point, False
319 )
320 assert True not in {
321 t.is_held
322 for t in schd.data_store_mgr.updated[TASK_PROXIES].values()
323 }
324
325 # put things back the way we found them
326 schd.pool.release_held_tasks({TaskTokens('*', 'root')})
327 await schd.update_data_structure()
328
329
330 def test_insert_job(mod_harness):
331 """Test method that adds a new job to the store."""
332 schd: Scheduler
333 schd, data = mod_harness
334 assert len(schd.data_store_mgr.added[JOBS]) == 0
335 itask = schd.pool.get_tasks()[0]
336 schd.data_store_mgr.insert_job(itask, 'submitted', job_config(schd))
337 assert len(schd.data_store_mgr.added[JOBS]) == 1
338 assert ext_id(schd) in schd.data_store_mgr.added[JOBS]
339
340
341 def test_insert_db_job(mod_harness, job_db_row):
342 """Test method that adds a new job from the db to the store."""
343 schd: Scheduler
344 schd, data = mod_harness
345 assert len(schd.data_store_mgr.added[JOBS]) == 1
346 schd.data_store_mgr.insert_db_job(0, job_db_row)
347 assert len(schd.data_store_mgr.added[JOBS]) == 2
348 assert ext_id(schd) in schd.data_store_mgr.added[JOBS]
349
350
351 def test_delta_job_msg(mod_harness):
352 """Test method adding messages to job element."""
353 schd: Scheduler
354 schd, data = mod_harness
355 j_id = ext_id(schd)
356 tokens = Tokens(j_id)
357 # First update creation
358 assert schd.data_store_mgr.updated[JOBS].get('j_id') is None
359 schd.data_store_mgr.delta_job_msg(tokens, 'The Atomic Age')
360 assert schd.data_store_mgr.updated[JOBS][j_id].messages
361
362
363 def test_delta_job_attr(mod_harness):
364 """Test method modifying job fields to job element."""
365 schd: Scheduler
366 schd, data = mod_harness
367 schd.data_store_mgr.delta_job_attr(
368 Mock(job_tokens=Tokens(ext_id(schd))), 'job_runner_name', 'at'
369 )
370 assert schd.data_store_mgr.updated[JOBS][ext_id(schd)].messages != (
371 schd.data_store_mgr.added[JOBS][ext_id(schd)].job_runner_name
372 )
373
374
375 def test_delta_job_time(mod_harness):
376 """Test method setting job state change time."""
377 schd: Scheduler
378 schd, data = mod_harness
379 event_time = get_current_time_string()
380 schd.data_store_mgr.delta_job_time(
381 Mock(job_tokens=Tokens(ext_id(schd))), 'submitted', event_time
382 )
383 job_updated = schd.data_store_mgr.updated[JOBS][ext_id(schd)]
384 with pytest.raises(ValueError):
385 job_updated.HasField('jumped_time')
386 assert job_updated.submitted_time != (
387 schd.data_store_mgr.added[JOBS][ext_id(schd)].submitted_time
388 )
389
390
391 async def test_update_data_structure(mod_harness):
392 """Test update_data_structure. This method will generate and
393 apply adeltas/updates given."""
394 schd, data = mod_harness
395 w_id = schd.data_store_mgr.workflow_id
396 schd.data_store_mgr.data[w_id] = data
397 schd.pool.hold_tasks({TaskTokens('*', 'root')})
398 await schd.update_data_structure()
399 assert TASK_STATUS_FAILED not in set(collect_states(data, TASK_PROXIES))
400 assert TASK_STATUS_FAILED not in set(collect_states(data, FAMILY_PROXIES))
401 assert TASK_STATUS_FAILED not in data[WORKFLOW].state_totals
402 assert len({t.id for t in data[TASK_PROXIES].values() if t.is_held}) == 2
403 for itask in schd.pool.get_tasks():
404 itask.state.reset(TASK_STATUS_FAILED)
405 schd.data_store_mgr.delta_task_state(itask)
406 schd.data_store_mgr.update_data_structure()
407 # State change applied
408 assert TASK_STATUS_FAILED in set(collect_states(data, TASK_PROXIES))
409 # family state changed and applied
410 assert TASK_STATUS_FAILED in set(collect_states(data, FAMILY_PROXIES))
411
412
413 async def test_prune_data_store(flow, scheduler, start):
414 """Test prune_data_store. This method will expand and reduce the data-store
415 to invoke pruning.
416
417 Also test rapid addition and removal of families (as happens with suicide
418 triggers):
419 https://github.com/cylc/cylc-ui/issues/1999
420
421 """
422 id_ = flow({
423 'scheduling': {
424 'graph': {
425 'R1': 'foo => bar'
426 }
427 },
428 'runtime': {
429 'FOOBAR': {},
430 'FOO': {
431 'inherit': 'FOOBAR'
432 },
433 'foo': {
434 'inherit': 'FOO'
435 },
436 'BAR': {
437 'inherit': 'FOOBAR'
438 },
439 'bar': {
440 'inherit': 'BAR'
441 }
442 }
443 })
444 schd = scheduler(id_)
445 async with start(schd):
446 # initialise the data store
447 await schd.update_data_structure()
448 w_id = schd.data_store_mgr.workflow_id
449 data = schd.data_store_mgr.data[w_id]
450 schd.pool.hold_tasks({TaskTokens('*', 'root')})
451 await schd.update_data_structure()
452 assert (
453 len({t.id for t in data[TASK_PROXIES].values() if t.is_held}) == 2
454 )
455
456 # Window size reduction to invoke pruning
457 schd.data_store_mgr.set_graph_window_extent(0)
458 schd.data_store_mgr.update_data_structure()
459 assert (
460 len({t.id for t in data[TASK_PROXIES].values() if t.is_held}) == 1
461 )
462
463 # Test rapid addition and removal
464 # bar/BAR task/family proxies not in .added
465 assert len({
466 t.name
467 for t in schd.data_store_mgr.added[TASK_PROXIES].values()
468 if t.name == 'bar'
469 }) == 0
470 assert len({
471 f.name
472 for f in schd.data_store_mgr.added[FAMILY_PROXIES].values()
473 if f.name == 'BAR'
474 }) == 0
475 # Add bar/BAR on set output of foo
476 for itask in schd.pool.get_tasks():
477 schd.pool.spawn_on_output(itask, TASK_OUTPUT_SUCCEEDED)
478 # bar/BAR now found.
479 assert len({
480 t.name
481 for t in schd.data_store_mgr.added[TASK_PROXIES].values()
482 if t.name == 'bar'
483 }) == 1
484 assert len({
485 f.name
486 for f in schd.data_store_mgr.added[FAMILY_PROXIES].values()
487 if f.name == 'BAR'
488 }) == 1
489 # Before updating the data-store, remove bar/BAR.
490 schd.pool.remove(schd.pool._get_task_by_id('1/bar'), 'Test removal')
491 schd.data_store_mgr.update_data_structure()
492 # bar/BAR not found in data or added stores.
493 assert len({
494 t.name
495 for t in data[TASK_PROXIES].values()
496 if t.name == 'bar'
497 }) == 0
498 assert len({
499 t.name
500 for t in schd.data_store_mgr.added[TASK_PROXIES].values()
501 if t.name == 'bar'
502 }) == 0
503 assert len({
504 f.name
505 for f in data[FAMILY_PROXIES].values()
506 if f.name == 'BAR'
507 }) == 0
508 assert len({
509 f.name
510 for f in schd.data_store_mgr.added[FAMILY_PROXIES].values()
511 if f.name == 'BAR'
512 }) == 0
513
514
515 async def test_family_ascent_point_prune(mod_harness):
516 """Test _family_ascent_point_prune. This method tries to remove
517 non-existent family."""
518 schd, data = mod_harness
519 fp_id = 'NotAFamilyProxy'
520 parent_ids = {fp_id}
521 checked_ids = set()
522 node_ids = set()
523 schd.data_store_mgr._family_ascent_point_prune(
524 next(iter(parent_ids)),
525 node_ids,
526 parent_ids,
527 checked_ids,
528 schd.data_store_mgr.family_pruned_ids
529 )
530 assert len(checked_ids) == 1
531 assert len(parent_ids) == 0
532
533
534 def test_delta_task_prerequisite(mod_harness):
535 """Test delta_task_prerequisites."""
536 schd: Scheduler
537 schd, data = mod_harness
538 schd.pool.set_prereqs_and_outputs(
539 {itask.tokens for itask in schd.pool.get_tasks()},
540 [TASK_STATUS_SUCCEEDED],
541 [],
542 flow=[]
543 )
544 assert all(p.satisfied for p in get_pb_prereqs(schd))
545 for itask in schd.pool.get_tasks():
546 # set prereqs as not-satisfied
547 for prereq in itask.state.prerequisites:
548 for key in prereq:
549 prereq[key] = False
550 schd.data_store_mgr.delta_task_prerequisite(itask)
551 assert not any(p.satisfied for p in get_pb_prereqs(schd))
552
553
554 def test_delta_task_xtrigger(xharness):
555 """Test delta_task_xtrigger."""
556 schd: Scheduler
557 schd, _ = xharness
558 foo = schd.pool._get_task_by_id('1/foo')
559 bar = schd.pool._get_task_by_id('1/bar')
560
561 assert not foo.state.xtriggers['x'] # not satisfied
562 assert not foo.state.xtriggers['x2'] # not satisfied
563 assert not foo.state.xtriggers['y'] # not satisfied
564 assert not bar.state.xtriggers['x'] # not satisfied
565
566 # satisfy foo's dependence on x
567 schd.pool.set_prereqs_and_outputs(
568 {TaskTokens('1', 'foo')},
569 [],
570 ['xtrigger/x:succeeded'],
571 flow=[]
572 )
573
574 # check the task pool
575 assert foo.state.xtriggers['x'] # satisfied
576 assert not foo.state.xtriggers['y'] # satisfied
577 assert not bar.state.xtriggers['x'] # not satisfied
578
579 # data store should have one updated task proxy with satisfied xtrigger x
580 [pbfoo] = schd.data_store_mgr.updated[TASK_PROXIES].values()
581 assert pbfoo.id.endswith('foo')
582 xtrig = pbfoo.xtriggers['x=xrandom(0)']
583 assert xtrig.label == 'x'
584 assert xtrig.satisfied
585
586 # unsatisfy it again
587 schd.pool.set_prereqs_and_outputs(
588 {TaskTokens('1', 'foo')},
589 [],
590 ['xtrigger/x:unsatisfied'],
591 flow=[]
592 )
593
594 # check the task pool
595 assert not foo.state.xtriggers['x'] # not satisfied
596
597 # data store should have one updated task proxy with unsatisfied xtrigger x
598 [pbfoo] = schd.data_store_mgr.updated[TASK_PROXIES].values()
599 assert pbfoo.id.endswith('foo')
600 xtrig = pbfoo.xtriggers['x=xrandom(0)']
601 assert xtrig.label == 'x'
602 assert not xtrig.satisfied
603
604 # satisfy both of foo's xtriggers at once
605 schd.pool.set_prereqs_and_outputs(
606 {TaskTokens('1', 'foo')},
607 [],
608 ['xtrigger/all:succeeded'],
609 flow=[]
610 )
611
612 # check the task pool
613 assert foo.state.xtriggers['x'] # satisfied
614 assert foo.state.xtriggers['y'] # satisfied
615
616 # data store should have one updated task proxy with satisfied xtrigger x
617 [pbfoo] = schd.data_store_mgr.updated[TASK_PROXIES].values()
618 assert pbfoo.id.endswith('foo')
619
620 xtrig_x = pbfoo.xtriggers['x=xrandom(0)']
621 assert xtrig_x.label == 'x'
622 assert xtrig_x.satisfied
623
624 # updated task proxy should also contain duplicate xtrigger labels
625 xtrig_x2 = pbfoo.xtriggers['x2=xrandom(0)']
626 assert xtrig_x2.label == 'x2'
627 assert xtrig_x2.satisfied
628
629 xtrig_y = pbfoo.xtriggers['y=xrandom(0, _=1)']
630 assert xtrig_y.label == 'y'
631 assert xtrig_y.satisfied
632
633
634 async def test_absolute_graph_edges(flow, scheduler, start):
635 """It should add absolute graph edges to the store.
636
637 See: https://github.com/cylc/cylc-flow/issues/5845
638 """
639 runahead_cycles = 1
640 id_ = flow({
641 'scheduling': {
642 'initial cycle point': '1',
643 'cycling mode': 'integer',
644 'runahead limit': f'P{runahead_cycles}',
645 'graph': {
646 'R1': 'build',
647 'P1': 'build[^] => run',
648 },
649 },
650 })
651 schd = scheduler(id_)
652
653 async with start(schd):
654 await schd.update_data_structure()
655
656 assert {
657 (Tokens(edge.source).relative_id, Tokens(edge.target).relative_id)
658 for edge in schd.data_store_mgr.data[schd.id][EDGES].values()
659 } == {
660 ('1/build', f'{cycle}/run')
661 # +1 for Python's range()
662 # +2 for Cylc's runahead
663 for cycle in range(1, runahead_cycles + 3)
664 }
665
666
667 async def test_group_state_on_window_resize(flow, scheduler, start):
668 """Test group state change on n-window resize. This method will expand
669 and reduce the data-store to change the family/root states.
670
671 See: https://github.com/cylc/cylc-flow/issues/7115
672 """
673 id_ = flow({
674 'scheduling': {
675 'graph': {
676 'R1': 'foo:failed => bar'
677 }
678 },
679 'runtime': {
680 'FOOBAR': {},
681 'FOO': {
682 'inherit': 'FOOBAR'
683 },
684 'foo': {
685 'inherit': 'FOO',
686 },
687 'BAR': {
688 'inherit': 'FOOBAR'
689 },
690 'bar': {
691 'inherit': 'BAR'
692 }
693 }
694 })
695 schd = scheduler(id_)
696 async with start(schd):
697 # initialise the data store
698 await schd.update_data_structure()
699 w_id = schd.data_store_mgr.workflow_id
700 data = schd.data_store_mgr.data[w_id]
701 schd.pool.hold_tasks({TaskTokens('1', 'bar')})
702 await schd.update_data_structure()
703 # At startup foo/FOO/FOOBAR/root should be waiting
704 assert {
705 t.state
706 for t in data[TASK_PROXIES].values()
707 } == {TASK_STATUS_WAITING}
708 assert {
709 data[FAMILY_PROXIES][f_id].state
710 for f_id in [
711 schd.data_store_mgr.id_.duplicate(cycle='1', task=t).id
712 for t in ['FOO', 'FOOBAR', 'root']
713 ]
714 } == {TASK_STATUS_WAITING}
715
716 # Set foo to failed, spawn in bar, remove foo
717 itask = schd.pool._get_task_by_id('1/foo')
718 itask.state.reset(TASK_STATUS_FAILED)
719 schd.pool.spawn_on_output(itask, TASK_OUTPUT_FAILED)
720 schd.data_store_mgr.delta_task_state(itask)
721 schd.pool.remove(itask, 'Test removal')
722 schd.data_store_mgr.update_data_structure()
723 # With both tasks there should be a mix failed and waiting
724 assert {
725 t.state
726 for t in data[TASK_PROXIES].values()
727 } == {TASK_STATUS_FAILED, TASK_STATUS_WAITING}
728 assert [
729 data[FAMILY_PROXIES][f_id].state
730 for f_id in [
731 schd.data_store_mgr.id_.duplicate(cycle='1', task=t).id
732 for t in ['FOO', 'BAR', 'FOOBAR', 'root']
733 ]
734 ] == [
735 TASK_STATUS_FAILED,
736 TASK_STATUS_WAITING,
737 TASK_STATUS_FAILED,
738 TASK_STATUS_FAILED,
739 ]
740
741 # Window size reduction to remove failed state task
742 schd.data_store_mgr.set_graph_window_extent(0)
743 schd.data_store_mgr.update_data_structure()
744 # Now bar/BAR/FOOBAR/root should be waiting
745 assert {
746 t.state
747 for t in data[TASK_PROXIES].values()
748 } == {TASK_STATUS_WAITING}
749 assert {
750 data[FAMILY_PROXIES][f_id].state
751 for f_id in [
752 schd.data_store_mgr.id_.duplicate(cycle='1', task=t).id
753 for t in ['BAR', 'FOOBAR', 'root']
754 ]
755 } == {TASK_STATUS_WAITING}
756
757 # Window size increase to add failed state task again
758 schd.data_store_mgr.set_graph_window_extent(1)
759 schd.data_store_mgr.update_data_structure()
760 # Again there should be a mix failed and waiting states
761 assert {
762 t.state
763 for t in data[TASK_PROXIES].values()
764 } == {TASK_STATUS_FAILED, TASK_STATUS_WAITING}
765 assert [
766 data[FAMILY_PROXIES][f_id].state
767 for f_id in [
768 schd.data_store_mgr.id_.duplicate(cycle='1', task=t).id
769 for t in ['FOO', 'BAR', 'FOOBAR', 'root']
770 ]
771 ] == [
772 TASK_STATUS_FAILED,
773 TASK_STATUS_WAITING,
774 TASK_STATUS_FAILED,
775 TASK_STATUS_FAILED,
776 ]
777
778
779 async def test_flow_numbers(flow, scheduler, start):
780 """It should update flow numbers when a task is triggered.
781
782 See https://github.com/cylc/cylc-flow/issues/6114
783 """
784 id_ = flow({
785 'scheduling': {
786 'graph': {
787 'R1': 'a => b'
788 }
789 }
790 })
791 schd = scheduler(id_)
792 async with start(schd):
793 # initialise the data store
794 await schd.update_data_structure()
795
796 # the task should not have a flow number as it is n>0
797 ds_task = schd.data_store_mgr.get_data_elements(TASK_PROXIES).added[1]
798 assert ds_task.name == 'b'
799 assert ds_task.flow_nums == '[]'
800
801 # force trigger the task in a new flow
802 await run_cmd(force_trigger_tasks(schd, ['1/b'], ['2']))
803
804 # update the data store
805 await schd.update_data_structure()
806
807 # the task should now exist in the new flow
808 ds_task = schd.data_store_mgr.get_data_elements(TASK_PROXIES).added[1]
809 assert ds_task.name == 'b'
810 assert ds_task.flow_nums == '[2]'
811
812
813 async def test_delta_task_outputs(one: 'Scheduler', start):
814 """Ensure task outputs are inserted into the store.
815
816 Note: Task outputs should *not* be updated incrementally until we have
817 a protocol for doing so, see https://github.com/cylc/cylc-flow/pull/6403
818 """
819
820 def get_data_outputs():
821 """Return satisfied outputs from the *data* store."""
822 return {
823 output.label
824 for output in one.data_store_mgr.data[one.id][TASK_PROXIES][
825 itask.tokens.id
826 ].outputs.values()
827 if output.satisfied
828 }
829
830 def get_delta_outputs():
831 """Return satisfied outputs from the *delta* store.
832
833 Or return None if there's nothing there.
834 """
835 try:
836 return {
837 output.label
838 for output in one.data_store_mgr.updated[TASK_PROXIES][
839 itask.tokens.id
840 ].outputs.values()
841 if output.satisfied
842 }
843 except KeyError:
844 return None
845
846 def _patch_remove(*args, **kwargs):
847 """Prevent the task/workflow from completing."""
848 pass
849
850 async with start(one):
851 one.pool.remove = _patch_remove
852
853 # create a job submission
854 itask = one.pool.get_tasks()[0]
855 assert itask
856 itask.submit_num += 1
857 one.data_store_mgr.insert_job(
858 itask, itask.state.status, {'submit_num': 1}
859 )
860 await one.update_data_structure()
861
862 # satisfy the submitted & started outputs
863 # (note started implies submitted)
864 one.task_events_mgr.process_message(
865 itask, 'INFO', TaskEventsManager.EVENT_STARTED
866 )
867
868 # the delta should be populated with the newly satisfied outputs
869 assert get_data_outputs() == set()
870 assert get_delta_outputs() == {
871 TASK_OUTPUT_SUBMITTED,
872 TASK_OUTPUT_STARTED,
873 }
874
875 # the delta should be applied to the store
876 await one.update_data_structure()
877 assert get_data_outputs() == {
878 TASK_OUTPUT_SUBMITTED,
879 TASK_OUTPUT_STARTED,
880 }
881 assert get_delta_outputs() is None
882
883 # satisfy the succeeded output
884 one.task_events_mgr.process_message(
885 itask, 'INFO', TaskEventsManager.EVENT_SUCCEEDED
886 )
887
888 # the delta should be populated with ALL satisfied outputs
889 # (not just the newly satisfied output)
890 assert get_data_outputs() == {
891 TASK_OUTPUT_SUBMITTED,
892 TASK_OUTPUT_STARTED,
893 }
894 assert get_delta_outputs() == {
895 TASK_OUTPUT_SUBMITTED,
896 TASK_OUTPUT_STARTED,
897 TASK_OUTPUT_SUCCEEDED,
898 }
899
900 # the delta should be applied to the store
901 await one.update_data_structure()
902 assert get_data_outputs() == {
903 TASK_OUTPUT_SUBMITTED,
904 TASK_OUTPUT_STARTED,
905 TASK_OUTPUT_SUCCEEDED,
906 }
907 assert get_delta_outputs() is None
908
909
910 async def test_remove_added_jobs_of_pruned_task(one: Scheduler, start):
911 """When a task is pruned, any of its jobs added in the same batch
912 must be removed from the batch.
913
914 See https://github.com/cylc/cylc-flow/pull/6656
915 """
916 async with start(one):
917 itask = one.pool.get_tasks()[0]
918 itask.state_reset(TASK_STATUS_PREPARING)
919 one.task_events_mgr.process_message(itask, INFO, TASK_OUTPUT_SUCCEEDED)
920 assert not one.data_store_mgr.data[one.id][JOBS]
921 assert len(one.data_store_mgr.added[JOBS]) == 1
922 one.data_store_mgr.update_data_structure()
923 assert not one.data_store_mgr.data[one.id][JOBS]
924 assert not one.data_store_mgr.added[JOBS]
925
926
927 async def test_log_events(one: Scheduler, start):
928 """It should record log events and strip and ANSI formatting."""
929 async with start(one):
930 handler = ProtobufStreamHandler(
931 one,
932 level=logging.INFO,
933 )
934 LOG.addHandler(handler)
935
936 try:
937 # log a message with some ANSIMARKUP formatting
938 LOG.warning(
939 '<bold>here</bold> <red>hare</red> <yellow>here</yellow>'
940 )
941
942 await one.update_data_structure()
943 log_records = one.data_store_mgr.data[one.id][WORKFLOW].log_records
944
945 assert len(log_records) == 1
946 log_record = log_records[0]
947
948 # the message should be in the store, the ANSI formatting should be
949 # stripped
950 assert log_record.level == 'WARNING'
951 assert log_record.message == 'here hare here'
952 finally:
953 LOG.removeHandler(handler)
954
955
956 async def test_no_backwards_job_state_change(one: Scheduler, start):
957 """It should not allow backwards job state changes."""
958 async with start(one):
959 itask = one.pool.get_tasks()[0]
960 itask.state_reset(TASK_STATUS_PREPARING)
961 itask.submit_num += 1
962 await one.update_data_structure()
963
964 one.task_events_mgr.process_message(itask, INFO, TASK_OUTPUT_STARTED)
965 await one.update_data_structure()
966 assert get_pb_job(one, itask).state == TASK_STATUS_RUNNING
967
968 # Simulate late arrival of "submitted" message
969 one.task_events_mgr.process_message(itask, INFO, TASK_OUTPUT_SUBMITTED)
970 await one.update_data_structure()
971 assert get_pb_job(one, itask).state == TASK_STATUS_RUNNING
972
973
974 async def test_job_estimated_finish_time(one_conf, flow, scheduler, start):
975 """It should set estimated_finish_time on job elements along with
976 started_time."""
977 wid = flow({
978 **one_conf,
979 'scheduler': {'UTC mode': True},
980 'runtime': {
981 'one': {'execution time limit': 'PT2M'},
982 },
983 })
984 schd: Scheduler = scheduler(wid)
985 date = '2081-07-02T'
986
987 async def start_job(itask: TaskProxy, start_time: str):
988 if not schd.pool.get_task(itask.point, itask.tdef.name):
989 schd.pool.add_to_pool(itask)
990 await schd.update_data_structure()
991 itask.state_reset(TASK_STATUS_PREPARING)
992 itask.submit_num += 1
993 itask.jobs = []
994 schd.task_events_mgr.process_message(
995 itask, INFO, TASK_OUTPUT_SUBMITTED # submit time irrelevant
996 )
997 await schd.update_data_structure()
998 schd.task_events_mgr.process_message(
999 itask, INFO, TASK_OUTPUT_STARTED, f'{date}{start_time}'
1000 )
1001 await schd.update_data_structure()
1002
1003 async with start(schd):
1004 itask = schd.pool.get_tasks()[0]
1005 await start_job(itask, '06:00:00Z')
1006 # 1st job: estimate based on execution time limit:
1007 assert (
1008 get_pb_job(schd, itask).estimated_finish_time
1009 == f'{date}06:02:00Z'
1010 )
1011
1012 # Finish this job and start a new one:
1013 schd.task_events_mgr.process_message(
1014 itask, INFO, TASK_OUTPUT_SUCCEEDED, f'{date}06:00:40Z'
1015 )
1016 await start_job(itask, '06:01:00Z')
1017 # >=2nd job: estimate based on mean of previous jobs:
1018 assert (
1019 get_pb_job(schd, itask).estimated_finish_time
1020 == f'{date}06:01:40Z'
1021 )
1022
1023
1024 async def test__family_ascent_point_update(flow, scheduler, run, validate):
1025 """Check that task states are cascaded up the family tree
1026 to the root family and the workflow "containsRetry" flag.
1027
1028 https://github.com/cylc/cylc-flow/issues/7174
1029 """
1030 wid = flow({
1031 'scheduling': {
1032 'initial cycle point': '3333',
1033 'graph': {
1034 'R1': (
1035 'FAM'
1036 '\n@wallclock => is_wallclock'
1037 '\n@echo_false => is_xt'
1038 )
1039 },
1040 'xtriggers': {
1041 'wallclock': 'wall_clock()',
1042 'echo_false': 'echo(succeed=False)'
1043 }
1044 },
1045 'runtime': {
1046 'FAM': {},
1047 'is_retry': {
1048 'inherit': 'FAM',
1049 'execution retry delays': 'PT10M',
1050 'simulation': {
1051 'fail cycle points': 'all',
1052 'default run length': 'PT0S'
1053 }
1054 },
1055 'normal': {'inherit': 'FAM'},
1056 'is_wallclock': {'inherit': 'FAM'},
1057 'is_xt': {'inherit': 'FAM'},
1058 }
1059 })
1060 is_flags = ['is_retry', 'is_wallclock', 'is_xtriggered']
1061 validate(wid)
1062 schd = scheduler(wid, paused_start=False)
1063 async with run(schd):
1064 data = schd.data_store_mgr.data
1065
1066 assert data[schd.id]['workflow'].contains_retry is False
1067
1068 await schd._main_loop()
1069
1070 assert data[schd.id]['workflow'].contains_retry is True
1071 for family_proxy in data[schd.id]['family_proxies'].values():
1072 for attribute in is_flags:
1073 assert getattr(family_proxy, attribute) is True