Debian Codegraph @

cylc/flow/task_outputs.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 """Task output message manager and constants."""
17
18 import ast
19 import re
20 from typing import (
21 TYPE_CHECKING,
22 Dict,
23 Iterable,
24 Iterator,
25 List,
26 Literal,
27 Optional,
28 Tuple,
29 Union,
30 )
31
32 from cylc.flow.exceptions import InvalidCompletionExpression
33 from cylc.flow.util import (
34 BOOL_SYMBOLS,
35 get_variable_names,
36 restricted_evaluator,
37 )
38
39
40 if TYPE_CHECKING:
41 from cylc.flow.taskdef import TaskDef
42
43
44 # Standard task output strings, used for triggering.
45 TASK_OUTPUT_EXPIRED = "expired"
46 TASK_OUTPUT_SUBMITTED = "submitted"
47 TASK_OUTPUT_SUBMIT_FAILED = "submit-failed"
48 TASK_OUTPUT_STARTED = "started"
49 TASK_OUTPUT_SUCCEEDED = "succeeded"
50 TASK_OUTPUT_FAILED = "failed"
51 TASK_OUTPUT_FINISHED = "finished"
52
53 SORT_ORDERS = (
54 TASK_OUTPUT_EXPIRED,
55 TASK_OUTPUT_SUBMITTED,
56 TASK_OUTPUT_SUBMIT_FAILED,
57 TASK_OUTPUT_STARTED,
58 TASK_OUTPUT_SUCCEEDED,
59 TASK_OUTPUT_FAILED,
60 )
61
62 TASK_OUTPUTS = (
63 TASK_OUTPUT_EXPIRED,
64 TASK_OUTPUT_SUBMITTED,
65 TASK_OUTPUT_SUBMIT_FAILED,
66 TASK_OUTPUT_STARTED,
67 TASK_OUTPUT_SUCCEEDED,
68 TASK_OUTPUT_FAILED,
69 TASK_OUTPUT_FINISHED,
70 )
71
72 # DB output message for forced completion
73 FORCED_COMPLETION_MSG = "(manually completed)"
74
75 # this evaluates task completion expressions
76 CompletionEvaluator = restricted_evaluator(
77 # expressions
78 ast.Expression,
79 # variables
80 ast.Name, ast.Load,
81 # operations
82 ast.BoolOp, ast.And, ast.Or, ast.BinOp,
83 error_class=InvalidCompletionExpression,
84 )
85
86 # regex for splitting expressions into individual parts for formatting
87 RE_EXPR_SPLIT = re.compile(r'([\(\) ])')
88
89
90 def trigger_to_completion_variable(output: str) -> str:
91 """Turn a trigger into something that can be used in an expression.
92
93 Examples:
94 >>> trigger_to_completion_variable('succeeded')
95 'succeeded'
96 >>> trigger_to_completion_variable('submit-failed')
97 'submit_failed'
98
99 """
100 return output.replace('-', '_')
101
102
103 def get_trigger_completion_variable_maps(triggers: Iterable[str]):
104 """Return a bi-map of trigger to completion variable.
105
106 Args:
107 triggers: All triggers for a task.
108
109 Returns:
110 (trigger_to_completion_variable, completion_variable_to_trigger)
111
112 Tuple of mappings for converting in either direction.
113
114 """
115 _trigger_to_completion_variable = {}
116 _completion_variable_to_trigger = {}
117 for trigger in triggers:
118 compvar = trigger_to_completion_variable(trigger)
119 _trigger_to_completion_variable[trigger] = compvar
120 _completion_variable_to_trigger[compvar] = trigger
121
122 return (
123 _trigger_to_completion_variable,
124 _completion_variable_to_trigger,
125 )
126
127
128 def get_completion_expression(tdef: 'TaskDef') -> str:
129 """Return a completion expression for this task definition.
130
131 If there is *not* a user provided completion statement:
132
133 1. Create a completion expression that ensures all required ouputs are
134 completed.
135 2. If success is optional add "or succeeded or failed" onto the end.
136 3. If submission is optional add "or submit-failed" onto the end of it.
137 4. If expiry is optional add "or expired" onto the end of it.
138 """
139 # check if there is a user-configured completion expression
140 completion = tdef.rtconfig.get('completion')
141 if completion:
142 # completion expression is defined in the runtime -> return it
143 return completion
144
145 # (1) start with an expression that ensures all required outputs are
146 # generated (if the task runs)
147 required = {
148 trigger_to_completion_variable(trigger)
149 for trigger, (_message, required) in tdef.outputs.items()
150 if required
151 }
152 parts = []
153 if required:
154 _part = ' and '.join(sorted(required))
155 if len(required) > 1:
156 # wrap the expression in brackets for clarity
157 parts.append(f'({_part})')
158 else:
159 parts.append(_part)
160
161 # (2) handle optional success
162 if (
163 tdef.outputs[TASK_OUTPUT_SUCCEEDED][1] is False
164 or tdef.outputs[TASK_OUTPUT_FAILED][1] is False
165 ):
166 # failure is tolerated -> ensure the task succeeds OR fails
167 if required:
168 # required outputs are required only if the task actually runs
169 parts = [
170 f'({parts[0]} and {TASK_OUTPUT_SUCCEEDED})'
171 f' or {TASK_OUTPUT_FAILED}'
172 ]
173 else:
174 parts.append(
175 f'{TASK_OUTPUT_SUCCEEDED} or {TASK_OUTPUT_FAILED}'
176 )
177
178 # (3) handle optional submission
179 if (
180 tdef.outputs[TASK_OUTPUT_SUBMITTED][1] is False
181 or tdef.outputs[TASK_OUTPUT_SUBMIT_FAILED][1] is False
182 ):
183 # submit-fail tolerated -> ensure the task executes OR submit-fails
184 parts.append(
185 trigger_to_completion_variable(TASK_OUTPUT_SUBMIT_FAILED)
186 )
187
188 # (4) handle optional expiry
189 if tdef.outputs[TASK_OUTPUT_EXPIRED][1] is False:
190 # expiry tolerated -> ensure the task executes OR expires
191 parts.append(TASK_OUTPUT_EXPIRED)
192
193 return ' or '.join(parts)
194
195
196 def get_optional_outputs(
197 expression: str,
198 outputs: Iterable[str],
199 disable: "Optional[str]" = None
200 ) -> Dict[str, Optional[bool]]:
201 """Determine which outputs in an expression are optional.
202
203 Args:
204 expression:
205 The completion expression.
206 outputs:
207 All outputs that apply to this task.
208 disable:
209 Disable this output and any others it is joined with by `and`
210 (which will mean they are necessarily optional).
211
212 Returns:
213 dict: compvar: is_optional
214
215 compvar:
216 The completion variable, i.e. the trigger as used in the completion
217 expression.
218 is_optional:
219 * True if var is optional.
220 * False if var is required.
221 * None if var is not referenced.
222
223 Examples:
224 >>> sorted(get_optional_outputs(
225 ... '(succeeded and (x or y)) or failed',
226 ... {'succeeded', 'x', 'y', 'failed', 'expired'}
227 ... ).items())
228 [('expired', None), ('failed', True), ('succeeded', True),
229 ('x', True), ('y', True)]
230
231 >>> sorted(get_optional_outputs(
232 ... '(succeeded and x and y) or expired',
233 ... {'succeeded', 'x', 'y', 'failed', 'expired'}
234 ... ).items())
235 [('expired', True), ('failed', None), ('succeeded', False),
236 ('x', False), ('y', False)]
237
238 >>> sorted(get_optional_outputs(
239 ... '(succeeded and towel) or (failed and bugblatter)',
240 ... {'succeeded', 'towel', 'failed', 'bugblatter'},
241 ... ).items())
242 [('bugblatter', True), ('failed', True),
243 ('succeeded', True), ('towel', True)]
244
245 >>> sorted(get_optional_outputs(
246 ... '(succeeded and towel) or (failed and bugblatter)',
247 ... {'succeeded', 'towel', 'failed', 'bugblatter'},
248 ... disable='failed'
249 ... ).items())
250 [('bugblatter', True), ('failed', True),
251 ('succeeded', False), ('towel', False)]
252
253 """
254 # determine which triggers are used in the expression
255 used_compvars = get_variable_names(expression)
256
257 # all completion variables which could appear in the expression
258 all_compvars = {trigger_to_completion_variable(out) for out in outputs}
259
260 # Allows exclusion of additional outcomes:
261 extra_excludes = {disable: False} if disable else {}
262
263 return { # output: is_optional
264 # the outputs that are used in the expression
265 **{
266 output: CompletionEvaluator(
267 expression,
268 **{
269 **{out: out != output for out in all_compvars},
270 # don't consider pre-execution conditions as optional
271 # (pre-conditions are considered separately)
272 'expired': False,
273 'submit_failed': False,
274 **extra_excludes
275 },
276 )
277 for output in used_compvars
278 },
279 **dict.fromkeys(all_compvars - used_compvars),
280 }
281
282
283 # a completion expression that considers the outputs complete if any final task
284 # output is received
285 FINAL_OUTPUT_COMPLETION = ' or '.join(
286 map(
287 trigger_to_completion_variable,
288 [
289 TASK_OUTPUT_SUCCEEDED,
290 TASK_OUTPUT_FAILED,
291 TASK_OUTPUT_SUBMIT_FAILED,
292 TASK_OUTPUT_EXPIRED,
293 ],
294 )
295 )
296
297
298 class TaskOutputs:
299 """Represents a collection of outputs for a task.
300
301 Task outputs have a trigger and a message:
302 * The trigger is used in the graph and with "cylc set".
303 * Messages map onto triggers and are used with "cylc message", they can
304 provide additional context to an output which will appear in the workflow
305 log.
306
307 [scheduling]
308 [[graph]]
309 R1 = t1:trigger1 => t2
310 [runtime]
311 [[t1]]
312 [[[outputs]]]
313 trigger1 = message 1
314
315 Args:
316 tdef:
317 The task definition for the task these outputs represent.
318
319 For use outside of the scheduler, this argument can be completion
320 expression string.
321
322 """
323 __slots__ = (
324 "_message_to_trigger",
325 "_message_to_compvar",
326 "_completed",
327 "_completion_expression",
328 "_forced",
329 )
330
331 _message_to_trigger: Dict[str, str] # message: trigger
332 _message_to_compvar: Dict[str, str] # message: completion variable
333 _completed: Dict[str, bool] # message: is_complete
334 _completion_expression: str
335 _forced: List[str] # list of messages of force-completed outputs
336
337 def __init__(self, tdef: 'Union[TaskDef, str]'):
338 self._message_to_trigger = {}
339 self._message_to_compvar = {}
340 self._completed = {}
341 self._forced = []
342
343 if isinstance(tdef, str):
344 # abnormal use e.g. from the "cylc show" command
345 self._completion_expression = tdef
346 else:
347 # normal use e.g. from within the scheduler
348 self._completion_expression = get_completion_expression(tdef)
349 for trigger, (message, _required) in tdef.outputs.items():
350 self.add(trigger, message)
351
352 def add(self, trigger: str, message: str) -> None:
353 """Register a new output.
354
355 Note, normally outputs are listed automatically from the provided
356 TaskDef so there is no need to call this interface. It exists for cases
357 where TaskOutputs are used outside of the scheduler where there is no
358 TaskDef object handy so outputs must be listed manually.
359 """
360 self._message_to_trigger[message] = trigger
361 self._message_to_compvar[message] = trigger_to_completion_variable(
362 trigger
363 )
364 self._completed[message] = False
365
366 def get_trigger(self, message: str) -> str:
367 """Return the trigger associated with this message."""
368 return self._message_to_trigger[message]
369
370 def set_trigger_complete(
371 self, trigger: str, forced=False
372 ) -> Optional[bool]:
373 """Set the provided output trigger as complete.
374
375 Args:
376 trigger:
377 The task output trigger to satisfy.
378
379 Returns:
380 True:
381 If the output was unset before.
382 False:
383 If the output was already set.
384 None
385 If the output does not apply.
386
387 """
388 trg_to_msg = {
389 v: k for k, v in self._message_to_trigger.items()
390 }
391 return self.set_message_complete(trg_to_msg[trigger], forced)
392
393 def set_message_complete(
394 self, message: str, forced=False
395 ) -> Optional[bool]:
396 """Set the provided task message as complete.
397
398 Args:
399 message:
400 The task output message to satisfy.
401
402 Returns:
403 True:
404 If the output was unset before.
405 False:
406 If the output was already set.
407 None
408 If the output does not apply.
409
410 """
411 if message not in self._completed:
412 # no matching output
413 return None
414
415 if self._completed[message] is False:
416 # output was incomplete
417 self._completed[message] = True
418 if forced:
419 self._forced.append(message)
420 return True
421
422 # output was already completed
423 return False
424
425 def is_message_complete(self, message: str) -> Optional[bool]:
426 """Return True if this message is complete.
427
428 Returns:
429 * True if the message is complete.
430 * False if the message is not complete.
431 * None if the message does not apply to these outputs.
432 """
433 if message in self._completed:
434 return self._completed[message]
435 return None
436
437 def get_completed_outputs(self) -> Dict[str, str]:
438 """Return a dict {trigger: message} of completed outputs.
439
440 Replace message with "forced" if the output was forced.
441
442 """
443 return {
444 self._message_to_trigger[message]: (
445 FORCED_COMPLETION_MSG if message in self._forced else message
446 )
447 for message, is_completed in self._completed.items()
448 if is_completed
449 }
450
451 def __iter__(self) -> Iterator[Tuple[str, str, bool]]:
452 """A generator that yields all outputs.
453
454 Yields:
455 (trigger, message, is_complete)
456
457 trigger:
458 The output trigger.
459 message:
460 The output message.
461 is_complete:
462 True if the output is complete, else False.
463
464 """
465 for message, is_complete in self._completed.items():
466 yield self._message_to_trigger[message], message, is_complete
467
468 def is_complete(self) -> bool:
469 """Return True if the outputs are complete."""
470 # NOTE: If a task has been removed from the workflow via restart /
471 # reload, then it is possible for the completion expression to be blank
472 # (empty string). In this case, we consider the task outputs to be
473 # complete when any final output has been generated.
474 # See https://github.com/cylc/cylc-flow/pull/5067
475 expr = self._completion_expression or FINAL_OUTPUT_COMPLETION
476 return CompletionEvaluator(
477 expr,
478 **{
479 self._message_to_compvar[message]: completed
480 for message, completed in self._completed.items()
481 },
482 )
483
484 def get_incomplete_implied(self, message: str) -> List[str]:
485 """Return an ordered list of incomplete implied messages.
486
487 Use to determined implied outputs to complete automatically.
488
489 Implied outputs are necessarily earlier outputs.
490
491 - started implies submitted
492 - succeeded and failed imply started
493 - custom outputs and expired do not imply other outputs
494
495 """
496 implied: List[str] = []
497
498 if message in [TASK_OUTPUT_SUCCEEDED, TASK_OUTPUT_FAILED]:
499 # Finished, so it must have submitted and started.
500 implied = [TASK_OUTPUT_SUBMITTED, TASK_OUTPUT_STARTED]
501 elif message == TASK_OUTPUT_STARTED:
502 # It must have submitted.
503 implied = [TASK_OUTPUT_SUBMITTED]
504
505 return [
506 message
507 for message in implied
508 if not self.is_message_complete(message)
509 ]
510
511 def format_completion_status(
512 self,
513 indent: int = 2,
514 gutter: int = 2,
515 ansimarkup: int = 0,
516 ) -> str:
517 """Return a text representation of the status of these outputs.
518
519 Returns a multiline string representing the status of each output used
520 in the expression within the context of the expression itself.
521
522 Args:
523 indent:
524 Number of spaces to indent each level of the expression.
525 gutter:
526 Number of spaces to pad the left column from the expression.
527 ansimarkup:
528 Turns on colour coding using ansimarkup tags. These will need
529 to be parsed before display. There are three options
530
531 0:
532 No colour coding.
533 1:
534 Only success colours will be used. This is easier to read
535 in colour coded logs.
536 2:
537 Both success and fail colours will be used.
538
539 Returns:
540 A multiline textural representation of the completion status.
541
542 """
543 indent_space: str = ' ' * indent
544 _gutter: str = ' ' * gutter
545
546 def color_wrap(string, is_complete):
547 if ansimarkup == 0:
548 return string
549 if is_complete:
550 return f'<green>{string}</green>'
551 if ansimarkup == 2:
552 return f'<red>{string}</red>'
553 return string
554
555 ret: List[str] = []
556 indent_level: int = 0
557 op: Optional[str] = None
558 fence = '┆' # U+2506 (Box Drawings Light Triple Dash Vertical)
559 for part in RE_EXPR_SPLIT.split(self._completion_expression):
560 if not part.strip():
561 continue
562
563 if part in {'and', 'or'}:
564 op = part
565 continue
566
567 elif part == '(':
568 if op:
569 ret.append(
570 f' {fence}{_gutter}{(indent_space * indent_level)}'
571 f'{op} {part}'
572 )
573 else:
574 ret.append(
575 f' {fence}{_gutter}'
576 f'{(indent_space * indent_level)}{part}'
577 )
578 indent_level += 1
579 elif part == ')':
580 indent_level -= 1
581 ret.append(
582 f' {fence}{_gutter}{(indent_space * indent_level)}{part}'
583 )
584
585 else:
586 _symbol = BOOL_SYMBOLS[bool(self._is_compvar_complete(part))]
587 is_complete = self._is_compvar_complete(part)
588 _pre = (
589 f'{color_wrap(_symbol, is_complete)} {fence}'
590 f'{_gutter}{(indent_space * indent_level)}'
591 )
592 if op:
593 ret.append(f'{_pre}{op} {color_wrap(part, is_complete)}')
594 else:
595 ret.append(f'{_pre}{color_wrap(part, is_complete)}')
596
597 op = None
598
599 return '\n'.join(ret)
600
601 @staticmethod
602 def is_valid_std_name(name: str) -> bool:
603 """Check name is a valid standard output name."""
604 return name in SORT_ORDERS
605
606 @staticmethod
607 def output_sort_key(item: Iterable[str]) -> float:
608 """Compare by output order.
609
610 Examples:
611 >>> this = TaskOutputs.output_sort_key
612 >>> sorted(['finished', 'started', 'custom'], key=this)
613 ['started', 'custom', 'finished']
614
615 """
616 if item in TASK_OUTPUTS:
617 return TASK_OUTPUTS.index(item)
618 # Sort custom outputs after started.
619 return TASK_OUTPUTS.index(TASK_OUTPUT_STARTED) + .5
620
621 def _is_compvar_complete(self, compvar: str) -> Optional[bool]:
622 """Return True if the completion variable is complete.
623
624 Returns:
625 * True if var is optional.
626 * False if var is required.
627 * None if var is not referenced.
628
629 """
630 for message, _compvar in self._message_to_compvar.items():
631 if _compvar == compvar:
632 return self.is_message_complete(message)
633 else:
634 raise KeyError(compvar)
635
636 def iter_required_messages(
637 self,
638 disable: 'Optional[Literal["succeeded", "failed"]]' = None
639 ) -> Iterator[str]:
640 """Yield task messages that are required for this task to be complete.
641
642 Note, in some cases tasks might not have any required messages,
643 e.g. "completion = succeeded or failed".
644
645 Args:
646 disable: Consider this output and any others it is joined with by
647 `and` to not exist. In skip mode we only want to check either
648 succeeded or failed, but not both.
649 """
650 for compvar, is_optional in get_optional_outputs(
651 self._completion_expression,
652 set(self._message_to_compvar.values()),
653 disable=disable
654 ).items():
655 if is_optional is False:
656 for message, _compvar in self._message_to_compvar.items():
657 if _compvar == compvar:
658 yield message