Debian Codegraph @

cylc/flow/prerequisite.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 """Functionality for expressing and evaluating logical triggers."""
18
19 import re
20 from typing import (
21 TYPE_CHECKING,
22 Dict,
23 ItemsView,
24 Iterable,
25 Iterator,
26 KeysView,
27 Literal,
28 NamedTuple,
29 Optional,
30 Tuple,
31 Union,
32 )
33
34 from cylc.flow.cycling.loader import get_point
35 from cylc.flow.data_messages_pb2 import (
36 PbCondition,
37 PbPrerequisite,
38 )
39 from cylc.flow.exceptions import TriggerExpressionError
40 from cylc.flow.id import quick_relative_id
41 from cylc.flow.run_modes import RunMode
42
43
44 if TYPE_CHECKING:
45 from cylc.flow.cycling import PointBase
46 from cylc.flow.id import Tokens
47
48
49 AnyPrereqTuple = Tuple[Union['PointBase', str, int], str, str]
50
51
52 class PrereqTuple(NamedTuple):
53 """A task output in a Prerequisite."""
54 point: str
55 task: str
56 output: str
57
58 def get_id(self, show_output=False) -> str:
59 """Get the relative ID of the task in this prereq output."""
60 if show_output:
61 return quick_relative_id(self.point, self.task, self.output)
62 else:
63 return quick_relative_id(self.point, self.task)
64
65 @staticmethod
66 def coerce(tuple_: AnyPrereqTuple) -> 'PrereqTuple':
67 """Coerce a tuple to a PrereqTuple."""
68 if isinstance(tuple_, PrereqTuple):
69 return tuple_
70 point, task, output = tuple_
71 return PrereqTuple(point=str(point), task=task, output=output)
72
73
74 SatisfiedState = Literal[
75 'satisfied naturally',
76 'satisfied from database',
77 'satisfied by skip mode',
78 'force satisfied',
79 False
80 ]
81
82
83 class Prerequisite:
84 """The concrete result of an abstract logical trigger expression.
85
86 A Prerequisite object represents the left-hand side of a single graph
87 arrow.
88
89 A single TaskProxy can have multiple Prerequisites, all of which require
90 satisfying. This corresponds to multiple graph arrow dependencies
91 (e.g. `a => c`, `b => c`). But a single Prerequisite object
92 can also have multiple dependencies from operator-joined left-hand side
93 expressions in the graph (e.g. `a & (b | c) => d`).
94 """
95
96 # Memory optimization - constrain possible attributes to this list.
97 __slots__ = (
98 "_satisfied",
99 "_cached_satisfied",
100 "conditional_expression",
101 "point",
102 )
103
104 # Extracts T from "foo.T succeeded" etc.
105 SATISFIED_TEMPLATE = 'bool(self._satisfied[("%s", "%s", "%s")])'
106 MESSAGE_TEMPLATE = r'%s/%s %s'
107
108 def __init__(self, point: 'PointBase'):
109 # The cycle point to which this prerequisite belongs.
110 # cylc.flow.cycling.PointBase
111 self.point = point
112
113 # Dictionary of task outputs pertaining to this prerequisite
114 # (i.e. all the outputs on the LHS of the graph arrow).
115 # {('point string', 'task name', 'output'): DEP_STATE_X, ...}
116 self._satisfied: Dict[PrereqTuple, SatisfiedState] = {}
117
118 # Expression present only when the OR operator is used.
119 # '1/foo failed | 1/bar succeeded'
120 self.conditional_expression: Optional[str] = None
121
122 # The cached state of this prerequisite:
123 # * `None` (no cached state)
124 # * `True` (prerequisite satisfied)
125 # * `False` (prerequisite unsatisfied).
126 self._cached_satisfied: Optional[bool] = None
127
128 def instantaneous_hash(self) -> int:
129 """Generate a hash of this prerequisite in its current state.
130
131 NOTE: Is not affected by any change in satisfaction state.
132
133 (Not defining `self.__hash__()` because Prerequisite objects
134 are mutable.)
135 """
136 return hash((
137 self.point,
138 self.conditional_expression,
139 tuple(self._satisfied.keys()),
140 ))
141
142 def __getitem__(self, key: AnyPrereqTuple) -> SatisfiedState:
143 """Return the satisfaction state of a dependency.
144
145 Args:
146 key: Tuple of (point, name, output) for a task.
147 """
148 return self._satisfied[PrereqTuple.coerce(key)]
149
150 def __setitem__(
151 self,
152 key: AnyPrereqTuple,
153 value: Union[SatisfiedState, bool] = False,
154 ) -> None:
155 """Register an output with this prerequisite.
156
157 Args:
158 key: Tuple of (point, name, output) for a prerequisite task.
159 value: Dependency satisfaction state (for pre-initial dependencies
160 this should be True).
161
162 """
163 key = PrereqTuple.coerce(key)
164 if value is True:
165 value = 'satisfied naturally'
166 self._satisfied[key] = value
167 if not (self._cached_satisfied and value):
168 # Force later recalculation of cached satisfaction state:
169 self._cached_satisfied = None
170
171 def __iter__(self) -> Iterator[PrereqTuple]:
172 return iter(self._satisfied)
173
174 def items(self) -> ItemsView[PrereqTuple, SatisfiedState]:
175 return self._satisfied.items()
176
177 def keys(self) -> KeysView[PrereqTuple]:
178 return self._satisfied.keys()
179
180 def get_raw_conditional_expression(self):
181 """Return a representation of this prereq as a string.
182
183 Returns None if this prerequisite does not involve an OR operator.
184
185 """
186 expr = self.conditional_expression
187 if not expr:
188 return None
189 for task_output in self._satisfied:
190 expr = expr.replace(self.SATISFIED_TEMPLATE % task_output,
191 self.MESSAGE_TEMPLATE % task_output)
192 return expr
193
194 def set_conditional_expr(self, expr):
195 """Set the conditional expression for this prerequisite.
196 Resets the cached state (self._cached_satisfied).
197
198 Examples:
199 # GH #3644 construct conditional expression when one task name
200 # is a substring of another: 11/foo | 1/foo => bar.
201 >>> preq = Prerequisite(1)
202 >>> preq[(1, 'foo', 'succeeded')] = False
203 >>> preq[(11, 'foo', 'succeeded')] = False
204 >>> preq.set_conditional_expr("11/foo succeeded|1/foo succeeded")
205 >>> expr = preq.conditional_expression
206 >>> expr.split('|') # doctest: +NORMALIZE_WHITESPACE
207 ['bool(self._satisfied[("11", "foo", "succeeded")])',
208 'bool(self._satisfied[("1", "foo", "succeeded")])']
209
210 # GH #6588 integer offset "x[-P2] | a" gives a negative cycle point
211 # during validation, for evaluation at the initial cycle point 1.
212 >>> preq = Prerequisite(1)
213 >>> preq[(-1, 'x', 'succeeded')] = False
214 >>> preq[(1, 'a', 'succeeded')] = False
215 >>> preq.set_conditional_expr("-1/x succeeded|1/a succeeded")
216 >>> expr = preq.conditional_expression
217 >>> expr.split('|') # doctest: +NORMALIZE_WHITESPACE
218 ['bool(self._satisfied[("-1", "x", "succeeded")])',
219 'bool(self._satisfied[("1", "a", "succeeded")])']
220 """
221 self._cached_satisfied = None
222 if '|' in expr:
223 # Make a Python expression so we can eval() the logic.
224 for t_output in self._satisfied:
225 # Use '\b' in case one task name is a substring of another
226 # and escape special chars ('.', timezone '+') in task IDs.
227 msg = self.MESSAGE_TEMPLATE % t_output
228 if msg[0] == '-':
229 # -ve cycles: \b needs to be to the right of the `-` char.
230 pattern = fr"-\b{re.escape(msg[1:])}\b"
231 else:
232 pattern = fr"\b{re.escape(msg)}\b"
233 expr = re.sub(
234 pattern,
235 self.SATISFIED_TEMPLATE % t_output,
236 expr
237 )
238
239 self.conditional_expression = expr
240
241 def is_satisfied(self):
242 """Return True if prerequisite is satisfied.
243
244 Return cached state if present, else evaluate the prerequisite.
245
246 """
247 if self._cached_satisfied is not None:
248 # Cached value.
249 return self._cached_satisfied
250 if self._satisfied == {}:
251 # No prerequisites left after pre-initial simplification.
252 return True
253 self._cached_satisfied = self._eval_satisfied()
254 return self._cached_satisfied
255
256 def _eval_satisfied(self) -> bool:
257 """Evaluate the prerequisite's condition expression.
258
259 Does not cache the result.
260
261 """
262 if not self.conditional_expression:
263 return all(self._satisfied.values())
264
265 try:
266 res = eval(self.conditional_expression) # nosec
267 # * the expression is constructed internally
268 # * https://github.com/cylc/cylc-flow/issues/4403
269 except (SyntaxError, ValueError) as exc:
270 raise TriggerExpressionError(
271 f'"{self.get_raw_conditional_expression}":\n{str(exc)}'
272 ) from None
273 return res
274
275 def satisfy_me(
276 self,
277 outputs: Iterable['Tokens'],
278 mode: Optional[RunMode] = None,
279 forced: bool = False,
280 ) -> None:
281 """Set the given outputs as satisfied (if they are not already).
282
283 Args:
284 outputs: List of outputs to satisfy.
285 mode: Task run mode.
286 forced: If True, records that this should not be undone by
287 `cylc remove`.
288 """
289 for output in outputs:
290 output_tuple = PrereqTuple(
291 output['cycle'], output['task'], output['task_sel']
292 )
293 if output_tuple not in self._satisfied:
294 continue
295 if not self._satisfied[output_tuple]:
296 self[output_tuple] = (
297 'force satisfied' if forced
298 else 'satisfied by skip mode' if mode == RunMode.SKIP
299 else 'satisfied naturally'
300 )
301
302 def api_dump(self) -> Optional[PbPrerequisite]:
303 """Return list of populated Protobuf data objects."""
304 if not self._satisfied:
305 return None
306 if self.conditional_expression:
307 expr = (
308 self.get_raw_conditional_expression()
309 ).replace('|', ' | ').replace('&', ' & ')
310 else:
311 expr = ' & '.join(
312 self.MESSAGE_TEMPLATE % task_output
313 for task_output in self._satisfied
314 )
315 conds = []
316 num_length = len(str(len(self._satisfied)))
317 for ind, output_tuple in enumerate(sorted(self._satisfied)):
318 t_id = output_tuple.get_id()
319 char = str(ind).zfill(num_length)
320 c_msg = self.MESSAGE_TEMPLATE % output_tuple
321 c_val = self._satisfied[output_tuple]
322 conds.append(
323 PbCondition(
324 task_proxy=t_id,
325 expr_alias=char,
326 req_state=output_tuple.output,
327 satisfied=bool(c_val),
328 message=(c_val or 'unsatisfied'),
329 )
330 )
331 expr = expr.replace(c_msg, char)
332 return PbPrerequisite(
333 expression=expr,
334 satisfied=self.is_satisfied(),
335 conditions=conds,
336 cycle_points=sorted(self.iter_target_point_strings()),
337 )
338
339 def set_satisfied(self) -> None:
340 """Force this prerequisite into the satisfied state.
341
342 Sets all of the outputs in this prerequisite to satisfied if not
343 already.
344 """
345 for task_output in self._satisfied:
346 if not self._satisfied[task_output]:
347 self._satisfied[task_output] = 'force satisfied'
348 if self.conditional_expression:
349 self._cached_satisfied = self._eval_satisfied()
350 else:
351 self._cached_satisfied = True
352
353 def iter_target_point_strings(self):
354 yield from {
355 task_output.point for task_output in self._satisfied
356 }
357
358 def get_target_points(self):
359 """Return a list of cycle points target by each prerequisite,
360 including each component of conditionals."""
361 return [
362 get_point(p) for p in self.iter_target_point_strings()
363 ]
364
365 def unset_naturally_satisfied(self, id_: str) -> bool:
366 """Set the dependencies with matching task IDs to unsatisfied only if
367 they were naturally satisfied.
368
369 Returns True if any dependencies were changed.
370 """
371 changed = False
372 for t_output, sat in self._satisfied.items():
373 if t_output.get_id() == id_ and sat and sat != 'force satisfied':
374 self[t_output] = False
375 changed = True
376 return changed