Debian Codegraph @

cylc/flow/graph_parser.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 """Module for parsing cylc graph strings."""
17
18 import re
19 import contextlib
20
21 from typing import (
22 Dict,
23 Iterable,
24 List,
25 Optional,
26 Set,
27 Tuple,
28 Union
29 )
30
31 import cylc.flow.flags
32 from cylc.flow.exceptions import GraphParseError
33 from cylc.flow.param_expand import GraphExpander
34 from cylc.flow.task_id import TaskID
35 from cylc.flow.task_trigger import TaskTrigger
36 from cylc.flow.task_outputs import (
37 TASK_OUTPUT_EXPIRED,
38 TASK_OUTPUT_SUCCEEDED,
39 TASK_OUTPUT_STARTED,
40 TASK_OUTPUT_FAILED,
41 TASK_OUTPUT_FINISHED,
42 TASK_OUTPUT_SUBMITTED,
43 TASK_OUTPUT_SUBMIT_FAILED
44 )
45 from cylc.flow.task_qualifiers import (
46 QUAL_FAM_EXPIRE_ALL,
47 QUAL_FAM_EXPIRE_ANY,
48 QUAL_FAM_SUCCEED_ALL,
49 QUAL_FAM_SUCCEED_ANY,
50 QUAL_FAM_FAIL_ALL,
51 QUAL_FAM_FAIL_ANY,
52 QUAL_FAM_FINISH_ALL,
53 QUAL_FAM_FINISH_ANY,
54 QUAL_FAM_START_ALL,
55 QUAL_FAM_START_ANY,
56 QUAL_FAM_SUBMIT_ALL,
57 QUAL_FAM_SUBMIT_ANY,
58 QUAL_FAM_SUBMIT_FAIL_ALL,
59 QUAL_FAM_SUBMIT_FAIL_ANY,
60 )
61
62
63 class Replacement:
64 """A class to remember match group information in re.sub() calls"""
65 def __init__(self, replacement):
66 self.replacement = replacement
67 self.substitutions = []
68 self.match_groups = []
69
70 def __call__(self, match):
71 matched = match.group(0)
72 replaced = match.expand(self.replacement)
73 self.substitutions.append((matched, replaced))
74 self.match_groups.append(match.groups())
75 return replaced
76
77
78 class GraphParser:
79 """Class for extracting dependency information from cylc graph strings.
80
81 For each task in the graph string, results are stored as:
82 self.triggers[task_name][expression] = ([expr_task_names], suicide)
83 self.original[task_name][expression] = original_expression
84
85 (original_expression is separated out to allow comparison of triggers
86 from different equivalent expressions, e.g. family vs member).
87
88 This is currently intended to process a single multi-line graph string
89 (i.e. the content of a single graph section). But it could be extended to
90 store dependencies for the whole workflow (call parse_graph multiple times
91 and key results by graph section).
92
93 The general form of a dependency is "LHS => RHS", where:
94 * On the left, an EXPRESSION of nodes involving parentheses, and
95 logical operators '&' (AND), and '|' (OR).
96 * On the right, an EXPRESSION of nodes NOT involving '|'
97 * Node names may be parameterized (any number of parameters):
98 NODE<i,j,k>
99 NODE<i=0,j,k> # specific parameter value
100 NODE<i-1,j,k> # offset parameter value
101 * A parameterized qualified node name looks like this:
102 NODE(<PARAMS>)([CYCLE-POINT-OFFSET])(:QUALIFIER)
103 * The default trigger type is ':succeeded'.
104 * A remote workflow qualified node name looks like this:
105 NODE(<REMOTE-WORKFLOW-QUALIFIER>)(:QUALIFIER)
106 * Outputs (boo:x) are ignored as triggers on the RHS to allow chaining:
107 "foo => bar:x => baz & qux"
108
109 Chained triggers get decomposed into pairs for processing, e.g.:
110 x # lone node
111 a | b => c & d => e
112 becomes:
113 [None, x],
114 [None, a],
115 [None, b],
116 [a|b, c&d], --> [a|b, c], [a|b, d]
117 [c&d, e], --> [c, e], [d, e]
118 (Lone nodes and left-side nodes make [None, left] for auto-triggering.)
119
120 LEFT sides are TASK OUTPUTS (a plain name is short for "task:succeeded"):
121 a:x & b? & c => d
122 means:
123 a:x & b:succeeded? & c:succeeded => d
124
125 RIGHT sides are just TASKS to trigger when the left side outputs complete:
126 [left] => d # does NOT imply d:succeeded is required
127
128 But output optionality can be *explicitly* set on the right, if you like:
129 [left] => d?
130 [left] => e:x
131 means
132 [left] => d # AND d:succeeded is optional
133 [left] => e # AND e:x is required
134
135 How the graph parser determines output optionality:
136 In chained triggers every node appears on the right of a pair, so we
137 only need rights to set (and check consitency of) optional outputs.
138 x # [None, x] ... x is end-of-chain
139 a => b => c # [None, a], [a, b], [b, c] ... c is end-of-chain
140
141 But note we infer :succeeded (for plain task names) except at the end
142 of a chain that is not a lone node (i.e. for x, but not c).
143 i.e.: if NOT end-of-chain OR left is None.
144
145 """
146 CYLC7_COMPAT = "CYLC 7 BACK-COMPAT"
147
148 OP_AND = '&'
149 OP_OR = '|'
150 OP_AND_ERR = '&&'
151 OP_OR_ERR = '||'
152 SUICIDE = '!'
153 OPTIONAL = '?'
154 QUALIFIER = ':'
155 ARROW = '=>'
156 XTRIG = '@'
157 CONTINUATION_STRS = (ARROW, OP_AND, OP_OR)
158 BAD_STRS = (OP_AND_ERR, OP_OR_ERR)
159
160 # Map family trigger type to (member-trigger, any/all), for use in
161 # expanding family trigger expressions to member trigger expressions.
162 # - "FAM:succeed-all => g" means "f1:succeed & f2:succeed => g"
163 # - "FAM:fail-any => g" means "f1:fail | f2:fail => g".
164 # E.g. QUAL_FAM_START_ALL: (TASK_OUTPUT_STARTED, True) simply maps
165 # "FAM:start-all" to "MEMBER:started" and "-all" (all members).
166 fam_to_mem_trigger_map: Dict[str, Tuple[str, bool]] = {
167 QUAL_FAM_EXPIRE_ALL: (TASK_OUTPUT_EXPIRED, True),
168 QUAL_FAM_EXPIRE_ANY: (TASK_OUTPUT_EXPIRED, False),
169 QUAL_FAM_START_ALL: (TASK_OUTPUT_STARTED, True),
170 QUAL_FAM_START_ANY: (TASK_OUTPUT_STARTED, False),
171 QUAL_FAM_SUCCEED_ALL: (TASK_OUTPUT_SUCCEEDED, True),
172 QUAL_FAM_SUCCEED_ANY: (TASK_OUTPUT_SUCCEEDED, False),
173 QUAL_FAM_FAIL_ALL: (TASK_OUTPUT_FAILED, True),
174 QUAL_FAM_FAIL_ANY: (TASK_OUTPUT_FAILED, False),
175 QUAL_FAM_SUBMIT_ALL: (TASK_OUTPUT_SUBMITTED, True),
176 QUAL_FAM_SUBMIT_ANY: (TASK_OUTPUT_SUBMITTED, False),
177 QUAL_FAM_SUBMIT_FAIL_ALL: (TASK_OUTPUT_SUBMIT_FAILED, True),
178 QUAL_FAM_SUBMIT_FAIL_ANY: (TASK_OUTPUT_SUBMITTED, False),
179 QUAL_FAM_FINISH_ALL: (TASK_OUTPUT_FINISHED, True),
180 QUAL_FAM_FINISH_ANY: (TASK_OUTPUT_FINISHED, False),
181 }
182
183 # Map family pseudo triggers to affected member outputs.
184 fam_to_mem_output_map: Dict[str, List[str]] = {
185 QUAL_FAM_EXPIRE_ANY: [TASK_OUTPUT_EXPIRED],
186 QUAL_FAM_EXPIRE_ALL: [TASK_OUTPUT_EXPIRED],
187 QUAL_FAM_START_ANY: [TASK_OUTPUT_STARTED],
188 QUAL_FAM_START_ALL: [TASK_OUTPUT_STARTED],
189 QUAL_FAM_SUCCEED_ANY: [TASK_OUTPUT_SUCCEEDED],
190 QUAL_FAM_SUCCEED_ALL: [TASK_OUTPUT_SUCCEEDED],
191 QUAL_FAM_FAIL_ANY: [TASK_OUTPUT_FAILED],
192 QUAL_FAM_FAIL_ALL: [TASK_OUTPUT_FAILED],
193 QUAL_FAM_SUBMIT_ANY: [TASK_OUTPUT_SUBMITTED],
194 QUAL_FAM_SUBMIT_ALL: [TASK_OUTPUT_SUBMITTED],
195 QUAL_FAM_SUBMIT_FAIL_ANY: [TASK_OUTPUT_SUBMIT_FAILED],
196 QUAL_FAM_SUBMIT_FAIL_ALL: [TASK_OUTPUT_SUBMIT_FAILED],
197 QUAL_FAM_FINISH_ANY: [TASK_OUTPUT_SUCCEEDED, TASK_OUTPUT_FAILED],
198 QUAL_FAM_FINISH_ALL: [TASK_OUTPUT_SUCCEEDED, TASK_OUTPUT_FAILED]
199 }
200
201 _RE_SUICIDE = r'(?:!)?'
202 _RE_NODE = _RE_SUICIDE + TaskID.NAME_RE
203 _RE_NODE_OR_XTRIG = r'(?:[!@])?' + TaskID.NAME_RE
204 _RE_PARAMS = r'<[\w,=\-+]+>'
205 _RE_OFFSET = r'\[[\w\-\+\^:]+\]'
206 _RE_QUAL = QUALIFIER + r'[\w\-]+' # task or fam trigger
207 _RE_OPT = r'\??' # optional output indicator
208 _RE_ANDOR = re.compile(r'\s*[&|]\s*')
209
210 REC_QUAL = re.compile(_RE_QUAL)
211
212 # Match if there are any spaces which could lead to graph problems
213 REC_GRAPH_BAD_SPACES_LINE = re.compile(
214 TaskID.NAME_RE +
215 rf"""
216 (?<![\-+](?=\s*[0-9])) # allow spaces after -+ if numbers follow
217 (?!\s*[\-+]\s*[0-9]) # allow spaces before/after -+ if nums follow
218 \s+ # do not allow 'task<space>task'
219 {TaskID.NAME_SUFFIX_RE}
220 """,
221 re.X
222 )
223
224 # Match @xtriggers.
225 REC_XTRIG = re.compile(r'@[\w\-+%]+')
226
227 # Match fully qualified parameterized single nodes.
228 REC_NODE_FULL = re.compile(
229 rf"""
230 {_RE_SUICIDE}
231 (?:(?:{TaskID.NAME_RE} # node name
232 (?:{_RE_PARAMS})?|{_RE_PARAMS}))+ # allow task<param> to repeat
233 (?:{_RE_OFFSET})? # cycle point offset
234 (?:{_RE_QUAL})? # qualifier
235 (?:{_RE_OPT})? # optional output indicator
236 """,
237 re.X
238 )
239
240 # Extract node or xtrigger from LHS expressions after param expansion.
241 REC_NODES = re.compile(
242 rf"""
243 ({_RE_NODE_OR_XTRIG}) # node name
244 ({_RE_OFFSET})? # cycle point offset
245 ({_RE_QUAL})? # trigger qualifier
246 ({_RE_OPT})? # optional output indicator
247 """,
248 re.X
249 )
250
251 REC_COMMENT = re.compile('#.*$')
252
253 # Detect presence of expansion parameters in a graph line.
254 REC_PARAMS = re.compile(_RE_PARAMS)
255
256 # Detect and extract workflow state polling task info.
257 REC_WORKFLOW_STATE = re.compile(
258 rf"""
259 ({TaskID.NAME_RE})
260 (<([\w.\-/]+)::({TaskID.NAME_RE})
261 ({_RE_QUAL})?>)
262 """,
263 re.X
264 )
265
266 # Remove out-of-range nodes
267 # <TASK_NAME_PART> : [^\s&\|] # i.e. sequence of not <AND|OR|SPACE>
268 # <REMOVE_TOKEN> : <TASK_NAME_PART> <_REMOVE>
269 # <TASK_NAME_PART>?
270 _TASK_NAME_PART = rf'[^\s{OP_AND}{OP_OR}]'
271 _REMOVE_TOKEN = (
272 rf"{_TASK_NAME_PART}+{str(GraphExpander._REMOVE)}?{_TASK_NAME_PART}+"
273 )
274
275 REC_NODE_OUT_OF_RANGE = re.compile(
276 rf"""
277 ( #
278 ^{_REMOVE_TOKEN}[{OP_AND}{OP_OR}] # ^<REMOVE> <AND|OR>
279 | #
280 [{OP_AND}{OP_OR}]{_REMOVE_TOKEN} # <AND|OR> <REMOVE>
281 | #
282 ^{_REMOVE_TOKEN}$ # ^<REMOVE>$
283 ) #
284 """,
285 re.X
286 )
287
288 REC_RHS_NODE = re.compile(
289 rf"""
290 (!)? # suicide mark
291 ({_RE_NODE}) # node name
292 ({_RE_OFFSET})? # cycle point offset
293 ({_RE_QUAL})? # trigger qualifier
294 ({_RE_OPT})? # optional output indicator
295 """,
296 re.X
297 )
298
299 def __init__(
300 self,
301 family_map: Optional[Dict[str, List[str]]] = None,
302 parameters: Optional[Dict] = None,
303 task_output_opt:
304 Optional[Dict[Tuple[str, str], Tuple[bool, bool, bool]]] = None,
305 expire_triggers: bool = False,
306 ) -> None:
307 """Initialize the graph string parser.
308
309 Args:
310 family_map:
311 {family_name: [family member task names]}
312 parameters:
313 task parameters for expansion here
314 task_output_opt:
315 {(name, output): (is-optional, is-opt-default, is-fixed)}
316 passed in to allow checking across multiple graph strings
317
318 """
319 self.family_map = family_map or {}
320 self.parameters = parameters
321 self.triggers: Dict = {}
322 self.original: Dict = {}
323 self.workflow_state_polling_tasks: Dict = {}
324 self.expire_triggers = expire_triggers
325 self.end_of_chain_nodes: set[str] = set()
326
327 # Record task outputs as optional or required:
328 # {(name, output): (is_optional, is_member)}
329 # (Need to compare across separately-parsed graph strings.)
330 if task_output_opt:
331 self.task_output_opt = task_output_opt
332 else:
333 self.task_output_opt = {}
334
335 def parse_graph(self, graph_string: str) -> None:
336 """Parse the graph string for a single graph section.
337
338 (Assumes any general line-continuation markers have been processed).
339 1. Strip comments, whitespace, and blank lines.
340 (all whitespace is removed up front so we don't have to consider
341 it in regexes and strip it from matched elements)
342 2. Join incomplete lines starting or ending with '=>'.
343 3. Replicate and expand any parameterized lines.
344 4. Split and process by pairs "left-expression => right-node":
345 i. Replace families with members (any or all semantics).
346 ii. Record parsed dependency information for each right-side node.
347 """
348 # Strip comments, whitespace, and blank lines.
349 non_blank_lines = []
350 bad_lines = []
351 for line in graph_string.split('\n'):
352 modified_line = self.__class__.REC_COMMENT.sub('', line)
353
354 # Ignore empty lines
355 if not modified_line or modified_line.isspace():
356 continue
357
358 # Catch simple bad lines that would be accepted once
359 # spaces are removed, e.g. 'foo bar => baz'
360 if self.REC_GRAPH_BAD_SPACES_LINE.search(modified_line):
361 bad_lines.append(line)
362 continue
363
364 # Apparently this is the fastest way to strip all whitespace!:
365 modified_line = "".join(modified_line.split())
366 non_blank_lines.append(modified_line)
367
368 # Check if there were problem lines and abort
369 if bad_lines:
370 self._report_invalid_lines(bad_lines)
371
372 # Join incomplete lines (beginning or ending with an arrow).
373 full_lines = []
374 part_lines = []
375 for i, _ in enumerate(non_blank_lines):
376 this_line = non_blank_lines[i]
377 for seq in self.CONTINUATION_STRS:
378 if i == 0 and this_line.startswith(seq):
379 # First line can't start with an arrow.
380 raise GraphParseError(f"Leading {seq}: {this_line}")
381 try:
382 next_line = non_blank_lines[i + 1]
383 except IndexError:
384 next_line = ''
385 for seq in self.CONTINUATION_STRS:
386 if this_line.endswith(seq):
387 # Last line can't end with an arrow, & or |.
388 raise GraphParseError(
389 f"Dangling {seq}:"
390 f"{this_line}"
391 ) from None
392 part_lines.append(this_line)
393
394 # Check that a continuation sequence doesn't end this line and
395 # begin the next:
396 if (
397 this_line.endswith(self.CONTINUATION_STRS) and
398 next_line.startswith(self.CONTINUATION_STRS)
399 ):
400 raise GraphParseError(
401 'Consecutive lines end and start with continuation '
402 'characters:\n'
403 f'{this_line}\n'
404 f'{next_line}'
405 )
406
407 # Check that line ends with a valid continuation sequence:
408 if (any(
409 this_line.endswith(seq) or next_line.startswith(seq) for
410 seq in self.CONTINUATION_STRS
411 ) and not (any(
412 this_line.endswith(seq) or next_line.startswith(seq) for
413 seq in self.BAD_STRS
414 ))):
415 continue
416
417 full_line = ''.join(part_lines)
418
419 # Record inter-workflow dependence and remove the marker notation.
420 # ("foo<WORKFLOW::TASK:fail> => bar" becomes:fail "foo => bar").
421 repl = Replacement('\\1')
422 full_line = self.__class__.REC_WORKFLOW_STATE.sub(repl, full_line)
423 for item in repl.match_groups:
424 l_task, r_all, r_workflow, r_task, r_status = item
425 if r_status is not None:
426 r_status = TaskTrigger.standardise_name(
427 r_status.strip(self.__class__.QUALIFIER)
428 )
429 self.workflow_state_polling_tasks[l_task] = (
430 r_workflow, r_task, r_status, r_all
431 )
432
433 full_lines.append(full_line)
434 part_lines = []
435
436 # Check for double-char conditional operators (a common mistake),
437 # and bad node syntax (order of qualifiers).
438 bad_lines = []
439 for line in full_lines:
440 if self.__class__.OP_AND_ERR in line:
441 raise GraphParseError(
442 "The graph AND operator is "
443 f"'{self.__class__.OP_AND}': {line}")
444 if self.__class__.OP_OR_ERR in line:
445 raise GraphParseError(
446 "The graph OR operator is "
447 f"'{self.__class__.OP_OR}': {line}")
448 # Check node syntax. First drop all non-node characters.
449 node_str = line
450 for spec in [
451 self.__class__.ARROW,
452 self.__class__.OP_OR,
453 self.__class__.OP_AND,
454 self.__class__.SUICIDE,
455 '(',
456 ')',
457 ]:
458 node_str = node_str.replace(spec, ' ')
459 # Drop all valid @xtriggers, longest first to avoid sub-strings.
460 nodes = self.__class__.REC_XTRIG.findall(node_str)
461 nodes.sort(key=len, reverse=True)
462 for node in nodes:
463 node_str = node_str.replace(node, '')
464 # Then drop all valid nodes, longest first to avoid sub-strings.
465 bad_lines = [node_str for node in node_str.split()
466 if self.__class__.REC_NODE_FULL.sub('', node, 1)]
467 if bad_lines:
468 self._report_invalid_lines(bad_lines)
469
470 # Expand parameterized lines (or detect undefined parameters).
471 line_set = set()
472 graph_expander = GraphExpander(self.parameters)
473 for line in full_lines:
474 if not self.__class__.REC_PARAMS.search(line):
475 line_set.add(line)
476 continue
477 for line_ in graph_expander.expand(line):
478 line_set.add(line_)
479
480 # Process chains of dependencies as pairs: left => right.
481 # Parameterization can duplicate some dependencies, so use a set.
482 pairs: Set[Tuple[Optional[str], str]] = set()
483 for line in line_set:
484 chain = []
485 # "foo => bar => baz" becomes [foo, bar, baz]
486 # "foo => bar_-32768 => baz" becomes [foo]
487 # "foo_-32768 => bar" becomes []
488 for node in line.split(self.__class__.ARROW):
489 # This can happen, e.g. "foo => => bar" produces
490 # "foo, '', bar", so we add so that later it raises
491 # an error
492 if node == '':
493 chain.append(node)
494 continue
495 node = self.REC_NODE_OUT_OF_RANGE.sub('', node)
496 if node == '':
497 # For "foo => bar<err> => baz", stop at "bar<err>"
498 break
499 else:
500 chain.append(node)
501
502 if not chain:
503 continue
504
505 for item in self.__class__.REC_NODES.findall(chain[0]):
506 # Auto-trigger lone nodes and initial nodes in a chain.
507 if not item[0].startswith(self.__class__.XTRIG):
508 pairs.add((None, ''.join(item)))
509
510 for i in range(0, len(chain) - 1):
511 pairs.add((chain[i], chain[i + 1]))
512
513 # Record end of chain nodes (can be multiple with &)
514 self.end_of_chain_nodes.update(
515 chain[-1].split(self.__class__.OP_AND)
516 )
517
518 # Get a set of RH nodes which are not at the LH of another pair:
519 # terminals = {p[1] for p in pairs}.difference({p[0] for p in pairs})
520
521 check_terminals: Dict[str, str] = {}
522 lefts: Set[str] = set()
523 rights: Set[str] = set()
524
525 for pair in sorted(pairs, key=lambda p: str(p[0])):
526 self._proc_dep_pair(pair, check_terminals, lefts, rights)
527
528 self.terminals = rights.difference(lefts)
529 for right in self.terminals:
530 left = check_terminals.get(right)
531 if left:
532 raise GraphParseError(
533 'Invalid cycle point offsets only on right hand'
534 ' side of dependency (must be on left hand side):'
535 f'{left} => {right}'
536 )
537
538 @classmethod
539 def _report_invalid_lines(cls, lines: List[str]) -> None:
540 """Raise GraphParseError in a consistent format when there are
541 lines with bad syntax.
542
543 The list of bad lines are inserted into the error message to show
544 exactly what lines have problems. The correct syntax of graph lines
545 is displayed to direct people on the correct path.
546
547 Keyword Arguments:
548 lines -- a list of bad graph lines to be reported
549
550 Raises:
551 GraphParseError -- always. This is the sole purpose of this method
552 """
553 raise GraphParseError(
554 "Bad graph node format:\n"
555 " " + "\n ".join(lines) + "\n"
556 "Correct format is:\n"
557 " @XTRIG or "
558 " NAME(<PARAMS>)([CYCLE-POINT-OFFSET])(:QUALIFIER)(?)\n"
559 " {NAME(<PARAMS>) can also be: "
560 "<PARAMS>NAME or NAME<PARAMS>NAME_CONTINUED}\n"
561 " or\n"
562 " NAME(<REMOTE-WORKFLOW-QUALIFIER>)(:QUALIFIER)")
563
564 def _proc_dep_pair(
565 self,
566 pair: Tuple[Optional[str], str],
567 check_terminals: Dict[str, str],
568 _lefts: Set[str],
569 _rights: Set[str],
570 ) -> None:
571 """Process a single dependency pair 'left => right'.
572
573 A node is an xtrigger, or a task or a family name.
574 A qualified name is NAME([CYCLE-POINT-OFFSET])(:QUALIFIER).
575
576 Args:
577 pair:
578 'left' can be a logical expression of qualified node names.
579 'left' can be None, when triggering a left-side or lone node.
580 'left' can be "", if null task name in graph error (a => => b).
581 'right' can be one or more node names joined by AND.
582 'right' can't be None or "".
583 terminals:
584 Nodes which are _only_ on the RH end of chains.
585 """
586 left, right = pair
587 # Raise error for right-hand-side OR operators.
588 if self.__class__.OP_OR in right:
589 raise GraphParseError(f"Illegal OR on right side: {right}")
590
591 # Raise error if suicide triggers on the left of the trigger.
592 if left and self.__class__.SUICIDE in left:
593 raise GraphParseError(
594 "Suicide markers must be"
595 f" on the right of a trigger: {left}")
596
597 # Check that parentheses match.
598 mismatch_msg = 'Mismatched parentheses in: "{}"'
599 if left and left.count("(") != left.count(")"):
600 raise GraphParseError(mismatch_msg.format(left))
601 if right.count("(") != right.count(")"):
602 raise GraphParseError(mismatch_msg.format(right))
603
604 # Raise error for cycle point offsets at the end of chains
605 if '[' in right and left:
606 check_terminals[right] = left
607
608 # Split right side on AND.
609 rights = right.split(self.__class__.OP_AND)
610 if '' in rights or right and not all(rights):
611 raise GraphParseError(
612 f"Null task name in graph: {left} => {right}")
613
614 lefts: Union[List[str], List[Optional[str]]]
615 if not left or (self.__class__.OP_OR in left or '(' in left):
616 # Treat conditional or parenthesised expressions as a single entity
617 # Can get [None] or [""] here
618 lefts = [left]
619 else:
620 # Split non-conditional left-side expressions on AND.
621 # Can get [""] here too
622 lefts = left.split(self.__class__.OP_AND)
623 if '' in lefts or left and not all(lefts):
624 raise GraphParseError(
625 f"Null task name in graph: {left} => {right}")
626
627 _rights.update(*([rights] or []))
628
629 for left in lefts:
630 # Extract information about all nodes on the left.
631 if left:
632 info: list[Iterable[str]] = self.__class__.REC_NODES.findall(
633 left
634 )
635 expr = left
636 for _left in info:
637 _lefts.add(''.join(_left))
638
639 else:
640 # There is no left-hand-side task.
641 info = []
642 expr = ''
643
644 n_info: List[Tuple[str, str, str, bool]] = []
645 for name, offset, trig, opt_char in info:
646 opt = opt_char == self.__class__.OPTIONAL
647 if name.startswith(self.__class__.XTRIG):
648 n_info.append((name, offset, trig, opt))
649 continue
650 if trig:
651 # Replace with standard trigger name if necessary
652 trig = trig.strip(self.__class__.QUALIFIER)
653 n_trig = TaskTrigger.standardise_name(trig)
654 if n_trig != trig:
655 if offset:
656 this = r'\b%s\b%s:%s(?!:)' % (
657 re.escape(name),
658 re.escape(offset),
659 re.escape(trig)
660 )
661 else:
662 this = r'\b%s:%s\b(?![\[:])' % (
663 re.escape(name),
664 re.escape(trig)
665 )
666 that = f"{name}{offset}:{n_trig}"
667 expr = re.sub(this, that, expr)
668 else:
669 # Make success triggers explicit.
670 if name in self.family_map:
671 raise GraphParseError(
672 f"Family trigger required: {left} => {right}"
673 )
674 n_trig = TASK_OUTPUT_SUCCEEDED
675 if offset:
676 this = r'\b%s\b%s(?!:)' % (
677 re.escape(name),
678 re.escape(offset)
679 )
680 else:
681 this = r'\b%s\b(?![\[:])' % re.escape(name)
682 that = f"{name}{offset}:{n_trig}"
683 expr = re.sub(this, that, expr)
684
685 n_info.append((name, offset, n_trig, opt))
686
687 # Determine semantics of all family triggers present.
688 family_trig_map = {}
689 for name, _, trig, _ in n_info:
690 if name.startswith(self.__class__.XTRIG):
691 # Avoid @xtrigger nodes.
692 continue
693 if name in self.family_map:
694 # Family; deal with members.
695 try:
696 family_trig_map[(name, trig)] = (
697 self.__class__.fam_to_mem_trigger_map[trig]
698 )
699 except KeyError:
700 # "FAM:bad => foo" in LHS (includes "FAM => bar" too).
701 raise GraphParseError(
702 f"Illegal family trigger in {expr}"
703 ) from None
704 else:
705 # Not a family.
706 if trig in self.__class__.fam_to_mem_trigger_map:
707 raise GraphParseError(
708 f"family trigger on non-family namespace {expr}")
709
710 # remove '?' from expr (not needed in logical trigger evaluation)
711 expr = re.sub(self.__class__._RE_OPT, '', expr)
712 self._families_all_to_all(expr, rights, n_info, family_trig_map)
713
714 def _families_all_to_all(
715 self,
716 expr: str,
717 rights: List[str],
718 info: List[Tuple[str, str, str, bool]],
719 family_trig_map: Dict[Tuple[str, str], Tuple[str, bool]]
720 ) -> None:
721 """Replace all family names with member names, for all/any semantics.
722
723 Args:
724 expr: the associated graph expression
725 rights: list of right-side nodes
726 trigs: parsed trigger info
727 info: [(name, offset, trigger-name, optional)] for each node
728 expr: the associated graph expression for this graph line
729
730 """
731 # Process left-side expression for defining triggers.
732 n_info = []
733 n_expr = expr
734 for name, offset, trig, _ in info:
735 if (name, trig) in family_trig_map:
736 ttype, mem_all = family_trig_map[(name, trig)]
737 m_info = []
738 m_expr = []
739 for mem in self.family_map[name]:
740 m_info.append((mem, offset, ttype))
741 m_expr.append(f"{mem}{offset}:{ttype}")
742 this = r'\b%s%s:%s\b' % (
743 name,
744 re.escape(offset),
745 trig
746 )
747 if mem_all:
748 that = '(%s)' % '&'.join(m_expr)
749 else:
750 that = '(%s)' % '|'.join(m_expr)
751 n_expr = re.sub(this, that, n_expr)
752 n_info += m_info
753 else:
754 n_info += [(name, offset, trig)]
755
756 self._compute_triggers(expr, rights, n_expr, n_info)
757
758 def _set_triggers(
759 self,
760 name: str,
761 suicide: bool,
762 trigs: List[str],
763 expr: str,
764 orig_expr: str
765 ) -> None:
766 """Record parsed triggers.
767
768 Args:
769 name: task name
770 suicide: whether this is a suicide trigger or not
771 trigs: parsed trigger info
772 expr: the associated graph expression
773 orig_expr: the original associated graph expression
774 """
775
776 # Check suicide triggers
777 with contextlib.suppress(KeyError):
778 osuicide = self.triggers[name][expr][1]
779 # This trigger already exists, so we must have both
780 # "expr => member" and "expr => !member" in the graph,
781 # or simply a duplicate trigger not recognized earlier
782 # because of parameter offsets.
783 if not expr:
784 pass
785 elif suicide is not osuicide:
786 oexp = re.sub(r'(&|\|)', r' \1 ', orig_expr)
787 oexp = re.sub(r':succeeded', '', oexp)
788 raise GraphParseError(
789 f"{oexp} can't trigger both {name} and !{name}")
790
791 # Record triggers
792 self.triggers.setdefault(name, {})
793 self.triggers[name][expr] = (trigs, suicide)
794 self.original.setdefault(name, {})
795 self.original[name][expr] = orig_expr
796
797 if suicide and self.expire_triggers:
798 # Make expiry optional for suicide triggered tasks.
799 self._set_output_opt(name, TASK_OUTPUT_EXPIRED, True, False, False)
800
801 def _set_output_opt(
802 self,
803 name: str,
804 output: str,
805 optional: bool,
806 suicide: bool,
807 fam_member: bool = False
808 ) -> None:
809 """Set or check consistency of optional/required output.
810
811 Args:
812 name: task name
813 output: task output name
814 optional: is the output optional?
815 suicide: is this from a suicide trigger?
816 fam_member: is this from an expanded family trigger?
817
818 """
819 if cylc.flow.flags.cylc7_back_compat:
820 # Set all outputs optional (set :succeed required elsewhere).
821 self.task_output_opt[(name, output)] = (True, True, True)
822 return
823
824 # Do not infer output optionality from suicide triggers:
825 if suicide:
826 return
827
828 if (
829 output in {TASK_OUTPUT_EXPIRED, TASK_OUTPUT_SUBMIT_FAILED}
830 and not optional
831 ):
832 # ":expire" and ":submit-fail" cannot be required
833 # proposal point 4:
834 # https://cylc.github.io/cylc-admin/proposal-optional-output-extension.html#proposal
835 raise GraphParseError(f"{name}:{output} must be optional")
836
837 if output == TASK_OUTPUT_FINISHED:
838 # Interpret :finish pseudo-output
839 if optional:
840 raise GraphParseError(
841 f"Pseudo-output {name}:{output} can't be optional")
842 # But implicit optional for the real succeed/fail outputs.
843 optional = True
844 for outp in [TASK_OUTPUT_SUCCEEDED, TASK_OUTPUT_FAILED]:
845 self._set_output_opt(
846 name, outp, optional, suicide, fam_member)
847 return
848
849 try:
850 prev_optional, prev_default, prev_fixed = (
851 self.task_output_opt[(name, output)])
852 except KeyError:
853 # Not already set; set it. Fix it if not fam_member.
854 self.task_output_opt[(name, output)] = (
855 optional, optional, not fam_member)
856 else:
857 # Already set; check consistency with previous.
858 if prev_fixed:
859 # optionality fixed already
860 if fam_member:
861 pass
862 else:
863 if optional != prev_optional:
864 raise GraphParseError(
865 f"Output {name}:{output} can't be both required"
866 " and optional")
867 else:
868 # optionality not fixed yet (only family default)
869 if fam_member:
870 # family defaults must be consistent
871 if optional != prev_default:
872 raise GraphParseError(
873 f"Output {name}:{output} can't default to both"
874 " optional and required (via family trigger"
875 " defaults)")
876 else:
877 # fix the optionality now
878 self.task_output_opt[(name, output)] = (
879 optional, prev_default, True)
880
881 # Check opposite output where appropriate.
882 for opposites in [
883 (TASK_OUTPUT_SUCCEEDED, TASK_OUTPUT_FAILED),
884 (TASK_OUTPUT_SUBMITTED, TASK_OUTPUT_SUBMIT_FAILED)
885 ]:
886 if output not in opposites:
887 continue
888 succeed, fail = opposites
889 opposite = fail if output == succeed else succeed
890 try:
891 opp_optional, opp_default, opp_fixed = (
892 self.task_output_opt[(name, opposite)]
893 )
894 except KeyError:
895 # opposite not set, no need to check
896 continue
897 else:
898 # opposite already set; check consistency
899 optional, default, oset = (
900 self.task_output_opt[(name, output)]
901 )
902 msg = (f"Opposite outputs {name}:{output} and {name}:"
903 f"{opposite} must both be optional if both are used")
904 if fam_member or not opp_fixed:
905 if not optional or not opp_default:
906 raise GraphParseError(
907 msg + " (via family trigger defaults)")
908 elif not optional or not opp_optional:
909 raise GraphParseError(
910 msg + " (via family trigger)")
911 elif not optional or not opp_optional:
912 raise GraphParseError(msg)
913
914 def _compute_triggers(
915 self,
916 orig_expr: str,
917 rights: List[str],
918 expr: str,
919 info: List[Tuple[str, str, str]]
920 ) -> None:
921 """Store trigger info from "expr => right".
922
923 Args:
924 orig_expr: the original associated graph expression
925 rights: list of right-side nodes including qualifiers like :fail?
926 expr: the associated graph expression
927 info: [(name, offset, trigger-name)] for each name in expr.
928
929 """
930 trigs = []
931 for name, offset, trigger in info:
932 # Replace finish triggers (must be done after member substn).
933 if name.startswith(self.__class__.XTRIG):
934 trigs += [name]
935 elif trigger == TASK_OUTPUT_FINISHED:
936 this = f"{name}{offset}:{trigger}"
937 that = "(%s%s:%s%s%s%s:%s)" % (
938 name, offset, TASK_OUTPUT_SUCCEEDED,
939 self.__class__.OP_OR,
940 name, offset, TASK_OUTPUT_FAILED)
941 expr = expr.replace(this, that)
942 trigs += [
943 "%s%s:%s" % (name, offset, TASK_OUTPUT_SUCCEEDED),
944 "%s%s:%s" % (name, offset, TASK_OUTPUT_FAILED)]
945 else:
946 trigs += [f"{name}{offset}:{trigger}"]
947
948 for right in rights:
949 right = right.strip('()') # parentheses don't matter
950 m = self.__class__.REC_RHS_NODE.match(right)
951 if not m:
952 # Bad nodes should have been detected earlier; fail loudly
953 raise ValueError( # pragma: no cover
954 f"Unexpected graph expression: '{right}'"
955 )
956 suicide_char, name, offset, output, opt_char = m.groups()
957 suicide = (suicide_char == self.__class__.SUICIDE)
958 optional = (opt_char == self.__class__.OPTIONAL)
959 if output:
960 output = output.strip(self.__class__.QUALIFIER)
961
962 if name in self.family_map:
963 fam = True
964 rhs_members = self.family_map[name]
965 if not output and not expr:
966 # Infer :succeed-all for lone family nodes, e.g. for
967 # "R1 = FAM": members default to success required, or
968 # for "FAM:succeed-all?" they default to success optional.
969 output = QUAL_FAM_SUCCEED_ALL
970 elif output and output.startswith("finish"):
971 if optional:
972 raise GraphParseError(
973 f"Family pseudo-output {name}:{output} can't be"
974 " optional")
975 else:
976 # Implicit optional for the real succeed/fail outputs.
977 optional = True
978 if output:
979 try:
980 outputs = self.__class__.fam_to_mem_output_map[output]
981 except KeyError:
982 # Illegal family trigger on RHS of a pair.
983 raise GraphParseError(
984 f"Illegal family trigger: {name}:{output}"
985 ) from None
986 else:
987 outputs = ['']
988 else:
989 fam = False
990 rhs_members = [name]
991 if output:
992 # Convert to standard output names if necessary.
993 output = TaskTrigger.standardise_name(output)
994 elif optional or (
995 right not in self.end_of_chain_nodes
996 or not expr
997 ):
998 # Infer "name:succeeded?" for explicit "name?"
999 # Infer "name:succeeded" for plain "name"
1000 # if not (end-of-chain and left is not None)
1001 output = TASK_OUTPUT_SUCCEEDED
1002 outputs = [output] # may be [None]
1003
1004 for mem in rhs_members:
1005 if not offset:
1006 # Nodes with offsets on the RHS do not define triggers.
1007 self._set_triggers(mem, suicide, trigs, expr, orig_expr)
1008 for output in outputs:
1009 if output:
1010 # Infer optionality for explicit outputs on RHS.
1011 self._set_output_opt(
1012 mem, output, optional, suicide, fam)