Debian Codegraph @

cylc/flow/task_pool.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 """Wrangle task proxies to manage the workflow."""
18
19 from collections import Counter
20 from contextlib import suppress
21 import json
22 import logging
23 from textwrap import indent
24 from typing import (
25 TYPE_CHECKING,
26 Dict,
27 Iterable,
28 List,
29 NamedTuple,
30 Optional,
31 Set,
32 Tuple,
33 Type,
34 Union,
35 )
36
37 from cylc.flow import LOG
38 from cylc.flow.cycling.loader import (
39 get_point,
40 standardise_point_string,
41 )
42 from cylc.flow.exceptions import (
43 PlatformLookupError,
44 PointParsingError,
45 WorkflowConfigError,
46 )
47 import cylc.flow.flags
48 from cylc.flow.flow_mgr import (
49 FLOW_NONE,
50 repr_flow_nums,
51 )
52 from cylc.flow.id import (
53 TaskTokens,
54 Tokens,
55 quick_relative_id,
56 )
57 from cylc.flow.id_match import id_match
58 from cylc.flow.platforms import get_platform
59 from cylc.flow.prerequisite import PrereqTuple
60 from cylc.flow.run_modes import RunMode
61 from cylc.flow.run_modes.skip import process_outputs as get_skip_mode_outputs
62 from cylc.flow.task_action_timer import (
63 TaskActionTimer,
64 TimerFlags,
65 )
66 from cylc.flow.task_events_mgr import (
67 CustomTaskEventHandlerContext,
68 EventKey,
69 TaskEventMailContext,
70 TaskJobLogsRetrieveContext,
71 )
72 from cylc.flow.task_id import TaskID
73 from cylc.flow.task_outputs import (
74 TASK_OUTPUT_EXPIRED,
75 TASK_OUTPUT_FAILED,
76 TASK_OUTPUT_SUBMIT_FAILED,
77 TASK_OUTPUT_SUCCEEDED,
78 )
79 from cylc.flow.task_proxy import TaskProxy
80 from cylc.flow.task_queues.independent import IndepQueueManager
81 from cylc.flow.task_state import (
82 TASK_STATUS_EXPIRED,
83 TASK_STATUS_FAILED,
84 TASK_STATUS_PREPARING,
85 TASK_STATUS_RUNNING,
86 TASK_STATUS_SUBMITTED,
87 TASK_STATUS_SUCCEEDED,
88 TASK_STATUS_WAITING,
89 TASK_STATUSES_ACTIVE,
90 TASK_STATUSES_FINAL,
91 status_geq,
92 )
93 from cylc.flow.task_trigger import TaskTrigger
94 from cylc.flow.util import deserialise_set
95 from cylc.flow.workflow_status import StopMode
96 from cylc.flow.scripts.set import XTRIGGER_PREREQ_PREFIX
97
98 if TYPE_CHECKING:
99 from cylc.flow.config import WorkflowConfig
100 from cylc.flow.cycling import (
101 IntervalBase,
102 PointBase,
103 )
104 from cylc.flow.data_store_mgr import DataStoreMgr
105 from cylc.flow.flow_mgr import (
106 FlowMgr,
107 FlowNums,
108 )
109 from cylc.flow.prerequisite import SatisfiedState
110 from cylc.flow.task_events_mgr import TaskEventsManager
111 from cylc.flow.taskdef import TaskDef
112 from cylc.flow.workflow_db_mgr import WorkflowDatabaseManager
113 from cylc.flow.xtrigger_mgr import XtriggerManager
114
115
116 Pool = Dict['PointBase', Dict[str, TaskProxy]]
117
118
119 def _get_xtrig_prereqs(
120 prereqs: 'Iterable[str]'
121 ) -> 'Dict[str, bool]':
122 """Extract xtriggers from user prerequisite input.
123
124 Weed out any task prerequisites.
125
126 Command validation has handled output suffixes and defaults.
127
128 Args:
129 prereqs: prerequisites and xtriggers in string form:
130 <cycle>/<task>:<output>
131 xtrigger/<xtrigger>[:succeeded]
132 xtrigger/all[:succeeded]
133
134 Returns: {<xtrigger> or "all": satisfied}
135
136 Examples:
137 >>> _get_xtrig_prereqs(["1/foo:started"])
138 {}
139
140 >>> _get_xtrig_prereqs({"1/foo:started", "xtrigger/x1:succeeded"})
141 {'x1': True}
142
143 (No need to test "all" - it just looks like an xtrigger label.)
144
145 """
146 _xtrigs = {}
147 for prereq in prereqs:
148 pre = Tokens(prereq, relative=True)
149
150 if pre['cycle'] != XTRIGGER_PREREQ_PREFIX:
151 # weed out task prerequisites
152 continue
153
154 # requested state to set:
155 _xtrigs[pre['task']] = (pre['task_sel'] == TASK_OUTPUT_SUCCEEDED)
156 return _xtrigs
157
158
159 class TaskPool:
160 """Task pool of a workflow."""
161
162 ERR_TMPL_NO_TASKID_MATCH = "No matching tasks found: {0}"
163 ERR_PREFIX_TASK_NOT_ON_SEQUENCE = "Invalid cycle point for task: {0}, {1}"
164 SUICIDE_MSG = "suicide trigger"
165 REMOVED_BY_PREREQ = "prerequisite task(s) removed"
166
167 def __init__(
168 self,
169 tokens: 'Tokens',
170 config: 'WorkflowConfig',
171 workflow_db_mgr: 'WorkflowDatabaseManager',
172 task_events_mgr: 'TaskEventsManager',
173 xtrigger_mgr: 'XtriggerManager',
174 data_store_mgr: 'DataStoreMgr',
175 flow_mgr: 'FlowMgr'
176 ) -> None:
177 self.tokens = tokens
178 self.config: 'WorkflowConfig' = config
179 self.stop_point = config.stop_point or config.final_point
180 self.workflow_db_mgr: 'WorkflowDatabaseManager' = workflow_db_mgr
181 self.task_events_mgr: 'TaskEventsManager' = task_events_mgr
182 self.task_events_mgr.spawn_func = self.spawn_on_output
183 self.xtrigger_mgr: 'XtriggerManager' = xtrigger_mgr
184 self.xtrigger_mgr.add_xtriggers(self.config.xtrigger_collator)
185 self.data_store_mgr: 'DataStoreMgr' = data_store_mgr
186 self.flow_mgr: 'FlowMgr' = flow_mgr
187
188 self.max_future_offset: Optional['IntervalBase'] = None
189 self._prev_runahead_base_point: Optional['PointBase'] = None
190 self._prev_runahead_sequence_points: Optional[Set['PointBase']] = None
191 self.runahead_limit_point: Optional['PointBase'] = None
192
193 # Tasks in the active window of the workflow.
194 self.active_tasks: Pool = {}
195 self._active_tasks_list: List[TaskProxy] = []
196 self.active_tasks_changed = False
197 self.tasks_removed = False
198
199 self.hold_point: Optional['PointBase'] = None
200 self.abs_outputs_done: Set[Tuple[str, str, str]] = set()
201
202 self.stop_task_id: Optional[str] = None
203 self.stop_task_finished = False
204 self.abort_task_failed = False
205 self.expected_failed_tasks = self.config.get_expected_failed_tasks()
206
207 self.task_name_list = self.config.get_task_name_list()
208 self.task_queue_mgr = IndepQueueManager(
209 self.config.cfg['scheduling']['queues'],
210 self.task_name_list,
211 self.config.runtime['descendants']
212 )
213
214 self.tasks_to_hold: set[tuple[str, 'PointBase']] = set()
215 self.tasks_to_trigger_now: set['TaskProxy'] = set()
216 self.pre_start_tasks_to_trigger: set[tuple[str, 'PointBase']] = set()
217
218 def set_stop_task(self, task_id):
219 """Set stop after a task."""
220 tokens = Tokens(task_id, relative=True)
221 name = tokens['task']
222 if name in self.config.taskdefs:
223 task_id = TaskID.get_standardised_taskid(task_id)
224 LOG.info("Setting stop task: " + task_id)
225 self.stop_task_id = task_id
226 self.stop_task_finished = False
227 self.workflow_db_mgr.put_workflow_stop_task(task_id)
228 else:
229 LOG.warning("Requested stop task name does not exist: %s" % name)
230
231 def stop_task_done(self):
232 """Return True if stop task has succeeded."""
233 if self.stop_task_id is not None and self.stop_task_finished:
234 LOG.info("Stop task %s finished" % self.stop_task_id)
235 self.stop_task_id = None
236 self.stop_task_finished = False
237 self.workflow_db_mgr.put_workflow_stop_task(None)
238 return True
239 return False
240
241 def _swap_out(self, itask):
242 """Swap old task for new, during reload."""
243 if itask.identity in self.active_tasks.get(itask.point, set()):
244 self.active_tasks[itask.point][itask.identity] = itask
245 self.active_tasks_changed = True
246
247 def queue_if_ready(self, itask: 'TaskProxy') -> None:
248 """Queue itask if it is ready to run.
249
250 Spawn next instance of sequential xtriggered tasks at this time too.
251
252 """
253 if (
254 not itask.state.is_queued
255 and not itask.state.is_runahead
256 and not itask.is_manual_submit
257 and itask.is_ready_to_run()
258 ):
259 self.queue_task(itask)
260
261 def spawn_psx_task(self, itask: 'TaskProxy') -> None:
262 """Spawn a parentless sequential xtriggered task.
263
264 Do it when all of its sequential xtriggers are satisfied.
265
266 """
267 if (
268 itask.is_xtrigger_sequential
269 and self.xtrigger_mgr.all_task_seq_xtriggers_satisfied(itask)
270 ):
271 self.spawn_next_parentless(itask)
272
273 def load_from_point(self):
274 """Load the task pool for the workflow start point.
275
276 Spawn the first parentless instance (if any) of every task.
277
278 """
279 flow_nums = {
280 self.flow_mgr.get_flow(
281 meta=f"original flow from {self.config.start_point}")
282 }
283 for name in self.task_name_list:
284 tdef = self.config.get_taskdef(name)
285 point = tdef.next_point_parentless(self.config.start_point)
286 if point:
287 ntask, _ = self.get_or_spawn_task(point, tdef, flow_nums)
288 if ntask is not None:
289 self.add_to_pool(ntask)
290
291 def db_add_new_flow_rows(self, itask: TaskProxy) -> None:
292 """Add new rows to DB task tables that record flow_nums.
293
294 Call when a new task is spawned or a flow merge occurs.
295 """
296 # Add row to task_states table.
297 self.workflow_db_mgr.put_insert_task_states(itask)
298 # Add row to task_outputs table:
299 self.workflow_db_mgr.put_insert_task_outputs(itask)
300
301 def add_to_pool(self, itask) -> None:
302 """Add a task to the pool."""
303
304 self.active_tasks.setdefault(itask.point, {})
305 if itask.identity in self.active_tasks[itask.point]:
306 # If logged, something has gone wrong.
307 LOG.debug(f"{itask.identity} not added to n=0: already exists")
308 return None
309 self.active_tasks[itask.point][itask.identity] = itask
310 self.active_tasks_changed = True
311 LOG.debug(f"[{itask}] added to the n=0 window")
312
313 self.create_data_store_elements(itask)
314
315 if itask.tdef.max_future_prereq_offset is not None:
316 # (Must do this once added to the pool).
317 self.set_max_future_offset()
318
319 def create_data_store_elements(self, itask):
320 """Create the node window elements about given task proxy."""
321 # Register pool node reference
322 self.data_store_mgr.add_pool_node(itask.tdef.name, itask.point)
323 # Create new data-store n-distance graph window about this task
324 self.data_store_mgr.increment_graph_window(
325 itask.tokens,
326 itask.point,
327 is_manual_submit=itask.is_manual_submit,
328 itask=itask
329 )
330 self.data_store_mgr.delta_task_state(itask)
331
332 def release_runahead_tasks(self):
333 """Release tasks below the runahead limit.
334
335 Return True if any tasks are released, else False.
336 Call when RH limit changes.
337 """
338 if not self.active_tasks or not self.runahead_limit_point:
339 # (At start-up task pool might not exist yet)
340 return False
341
342 released = False
343
344 # An intermediate list is needed here: auto-spawning of parentless
345 # tasks can cause the task pool to change size during iteration.
346 release_me = [
347 itask
348 for point, itask_id_map in self.active_tasks.items()
349 for itask in itask_id_map.values()
350 if point <= self.runahead_limit_point
351 if itask.state.is_runahead
352 ]
353
354 for itask in release_me:
355 # Release the task.
356 if itask.state_reset(is_runahead=False):
357 self.data_store_mgr.delta_task_state(itask)
358 # Spawn the next parentless instance (if there is one) on release.
359 if itask.flow_nums and not itask.is_xtrigger_sequential:
360 self.spawn_next_parentless(itask)
361 released = True
362
363 return released
364
365 def compute_runahead(self, force=False) -> bool:
366 """Compute the runahead limit; return True if it changed.
367
368 To be called if:
369 * The runahead base point might have changed:
370 - a task completed expected outputs, or expired
371 - (Cylc7 back compat: a task succeeded or failed)
372 * The max future offset might have changed.
373 * The runahead limit config or task pool might have changed (reload).
374
375 This is a collective task pool computation. Call it once at the end
376 of a group operation such as removal of multiple tasks (not after
377 every individual task operation).
378
379 Start from earliest point with unfinished tasks. Partially satisfied
380 and incomplete tasks count too because they still need to run.
381
382 The limit itself is limited by workflow stop point, if there is one,
383 and adjusted upward on the fly if tasks with future offsets appear.
384
385 With force=True we recompute the limit even if the base point has not
386 changed (needed if max_future_offset changed, or on reload).
387
388 """
389 limit = self.config.runahead_limit # e.g. P2 or P2D
390 count_cycles = False
391 with suppress(TypeError):
392 # Count cycles (integer cycling, and optional for datetime too).
393 ilimit = int(limit) # type: ignore
394 count_cycles = True
395
396 base_point: Optional['PointBase'] = None
397
398 # First get the runahead base point.
399 if not self.active_tasks:
400 # Find the earliest sequence point beyond the workflow start point.
401 base_point = min(
402 (
403 point
404 for point in {
405 seq.get_first_point(self.config.start_point)
406 for seq in self.config.sequences
407 }
408 if point is not None
409 ),
410 default=None,
411 )
412 else:
413 # Find the earliest point with incomplete tasks.
414 if cylc.flow.flags.cylc7_back_compat:
415 for point, itasks in sorted(self.get_tasks_by_point().items()):
416 # All n=0 tasks are incomplete by definition, but Cylc 7
417 # ignores failed ones (it does not ignore submit-failed!).
418 if all(
419 itask.state(TASK_STATUS_FAILED)
420 for itask in itasks
421 ):
422 continue
423 base_point = point
424 break
425 else:
426 base_point = min(self.active_tasks, default=None)
427
428 if base_point is None:
429 return False
430
431 if self._prev_runahead_base_point is None:
432 self._prev_runahead_base_point = base_point
433
434 if (
435 not force
436 and self.runahead_limit_point is not None
437 and (
438 base_point == self._prev_runahead_base_point
439 or self.runahead_limit_point == self.stop_point
440 )
441 ):
442 # No need to recompute the list of points if the base point did not
443 # change or the runahead limit is already at stop point.
444 return False
445
446 # Now generate all possible cycle points from the base point and stop
447 # at the runahead limit point. Note both cycle count and time interval
448 # limits involve all possible cycles, not just active cycles.
449 sequence_points: Set['PointBase'] = set()
450 if (
451 not force
452 and self._prev_runahead_sequence_points
453 and base_point == self._prev_runahead_base_point
454 ):
455 # Cache for speed.
456 sequence_points = self._prev_runahead_sequence_points
457 else:
458 # Recompute possible points.
459 for sequence in self.config.sequences:
460 seq_point = sequence.get_first_point(base_point)
461 count = 1
462 while seq_point is not None:
463 if count_cycles:
464 # P0 allows only the base cycle point to run.
465 if count > 1 + ilimit:
466 # this point may be beyond the runahead limit
467 break
468 else:
469 # PT0H allows only the base cycle point to run.
470 if seq_point > base_point + limit:
471 # this point can not be beyond the runahead limit
472 break
473 count += 1
474 sequence_points.add(seq_point)
475 seq_point = sequence.get_next_point(seq_point)
476 self._prev_runahead_sequence_points = sequence_points
477 self._prev_runahead_base_point = base_point
478
479 if not sequence_points:
480 limit_point = base_point
481 elif count_cycles:
482 # (len(list) may be less than ilimit due to sequence end)
483 limit_point = sorted(sequence_points)[:ilimit + 1][-1]
484 else:
485 limit_point = max(sequence_points)
486
487 # Adjust for future offset and stop point.
488 pre_adj_limit = limit_point
489 if self.max_future_offset is not None:
490 limit_point += self.max_future_offset
491 LOG.debug(
492 "Runahead (future trigger adjust):"
493 f" {pre_adj_limit} -> {limit_point}"
494 )
495 if self.stop_point and limit_point > self.stop_point:
496 limit_point = self.stop_point
497 LOG.debug(
498 "Runahead (stop point adjust):"
499 f" {pre_adj_limit} -> {limit_point} (stop point)"
500 )
501
502 LOG.debug(f"Runahead limit: {limit_point}")
503 self.runahead_limit_point = limit_point
504 return True
505
506 def update_flow_mgr(self):
507 flow_nums_seen = set()
508 for itask in self.get_tasks():
509 flow_nums_seen.update(itask.flow_nums)
510 self.flow_mgr.load_from_db(flow_nums_seen)
511
512 def load_abs_outputs_for_restart(self, row_idx, row):
513 cycle, name, output = row
514 self.abs_outputs_done.add((cycle, name, output))
515
516 def check_task_output(
517 self,
518 cycle: str,
519 task: str,
520 output_msg: str,
521 flow_nums: 'FlowNums',
522 ) -> 'SatisfiedState':
523 """Returns truthy if the specified output is satisfied in the DB.
524
525 Args:
526 cycle: Cycle point of the task whose output is being checked.
527 task: Name of the task whose output is being checked.
528 output_msg: The output message to check for.
529 flow_nums: Flow numbers of the task whose output is being
530 checked. If this is empty it means 'none'; will return False.
531 """
532 if not flow_nums:
533 return False
534
535 for task_outputs, task_flow_nums in (
536 self.workflow_db_mgr.pri_dao.select_task_outputs(task, cycle)
537 ).items():
538 # loop through matching tasks
539 # (if task_flow_nums is empty, it means the 'none' flow)
540 if flow_nums.intersection(task_flow_nums):
541 # BACK COMPAT: In Cylc >8.0.0,<8.3.0, only the task
542 # messages were stored in the DB as a list.
543 # from: 8.0.0
544 # to: 8.3.0
545 outputs: Union[
546 Dict[str, str], List[str]
547 ] = json.loads(task_outputs)
548 messages = (
549 outputs.values() if isinstance(outputs, dict)
550 else outputs
551 )
552 return (
553 'satisfied from database'
554 if output_msg in messages
555 else False
556 )
557 else:
558 # no matching entries
559 return False
560
561 def load_db_task_pool_for_restart(self, row_idx, row):
562 """Load tasks from DB task pool/states/jobs tables.
563
564 Output completion status is loaded from the DB, and tasks recorded
565 as submitted or running are polled to confirm their true status.
566 Tasks are added to queues again on release from runahead pool.
567
568 Returns:
569 Names of platform if attempting to look up that platform
570 has led to a PlatformNotFoundError.
571 """
572 if row_idx == 0:
573 LOG.info("LOADING task proxies")
574 # Create a task proxy corresponding to this DB entry.
575 (cycle, name, flow_nums, flow_wait, is_manual_submit, is_late, status,
576 is_held, submit_num, _, platform_name, time_submit, time_run, timeout,
577 outputs_str) = row
578 try:
579 itask = TaskProxy(
580 self.tokens,
581 self.config.get_taskdef(name),
582 get_point(cycle),
583 deserialise_set(flow_nums),
584 status=status,
585 is_held=is_held,
586 submit_num=submit_num,
587 is_late=bool(is_late),
588 flow_wait=bool(flow_wait),
589 is_manual_submit=bool(is_manual_submit),
590 sequential_xtrigger_labels=(
591 self.xtrigger_mgr.xtriggers.sequential_xtrigger_labels
592 ),
593 )
594
595 except WorkflowConfigError:
596 LOG.exception(
597 f'ignoring task {name} from the workflow run database\n'
598 '(its task definition has probably been deleted).')
599 except Exception:
600 LOG.exception(f'could not load task {name}')
601 else:
602 if status in (
603 TASK_STATUS_SUBMITTED,
604 TASK_STATUS_RUNNING,
605 TASK_STATUS_FAILED,
606 TASK_STATUS_SUCCEEDED
607 ):
608 # update the task proxy with platform
609 # If we get a failure from the platform selection function
610 # set task status to submit-failed.
611 try:
612 itask.platform = get_platform(platform_name)
613 except PlatformLookupError:
614 return platform_name
615
616 if time_submit:
617 itask.set_summary_time('submitted', time_submit)
618 if time_run:
619 itask.set_summary_time('started', time_run)
620 if timeout is not None:
621 itask.timeout = timeout
622 elif status == TASK_STATUS_PREPARING:
623 # put back to be readied again.
624 status = TASK_STATUS_WAITING
625 # Re-prepare same submit.
626 itask.submit_num -= 1
627
628 # Running or finished task can have completed custom outputs.
629 if itask.state(
630 TASK_STATUS_RUNNING,
631 TASK_STATUS_FAILED,
632 TASK_STATUS_SUCCEEDED
633 ):
634 for message in json.loads(outputs_str):
635 itask.state.outputs.set_message_complete(message)
636 self.data_store_mgr.delta_task_output(itask, message)
637
638 if platform_name and status != TASK_STATUS_WAITING:
639 itask.summary['platforms_used'][
640 int(submit_num)] = platform_name
641 LOG.info(
642 f"+ {cycle}/{name} {status}{' (held)' if is_held else ''}")
643
644 # Update prerequisite satisfaction status from DB
645 sat = {}
646 for prereq_name, prereq_cycle, prereq_output_msg, satisfied in (
647 self.workflow_db_mgr.pri_dao.select_task_prerequisites(
648 cycle, name, flow_nums,
649 )
650 ):
651 # Prereq satisfaction as recorded in the DB.
652 sat[
653 (prereq_cycle, prereq_name, prereq_output_msg)
654 ] = satisfied if satisfied != '0' else False
655
656 for itask_prereq in itask.state.prerequisites:
657 for key in itask_prereq:
658 if key in sat:
659 itask_prereq[key] = sat[key]
660 else:
661 # This prereq is not in the DB: new dependencies
662 # added to an already-spawned task before restart.
663 # Look through task outputs to see if is has been
664 # satisfied
665 prereq_cycle, prereq_task, prereq_output_msg = key
666 itask_prereq[key] = (
667 self.check_task_output(
668 prereq_cycle,
669 prereq_task,
670 prereq_output_msg,
671 itask.flow_nums,
672 )
673 )
674 for xtrigger_label in itask.state.xtriggers:
675 if ("xtrigger", xtrigger_label, TASK_OUTPUT_SUCCEEDED) in sat:
676 itask.state.xtriggers[xtrigger_label] = True
677
678 if itask.state_reset(status, is_runahead=True):
679 self.data_store_mgr.delta_task_state(itask)
680 self.add_to_pool(itask)
681
682 # All tasks load as runahead-limited, but finished and manually
683 # triggered tasks (incl. --start-task's) can be released now.
684 if (
685 itask.state(
686 TASK_STATUS_FAILED,
687 TASK_STATUS_SUCCEEDED,
688 TASK_STATUS_EXPIRED
689 )
690 or itask.is_manual_submit
691 ) and (
692 itask.state_reset(is_runahead=False)
693 ):
694 self.data_store_mgr.delta_task_state(itask)
695
696 def load_db_task_action_timers(self, row_idx: int, row: Iterable) -> None:
697 """Load a task action timer, e.g. event handlers, retry states."""
698 if row_idx == 0:
699 LOG.debug("LOADING task action timers")
700 (cycle, name, ctx_key_raw, ctx_raw, delays_raw, num, delay,
701 timeout) = row
702 tokens = Tokens(
703 cycle=cycle,
704 task=name,
705 )
706 id_ = tokens.relative_id
707 try:
708 # Extract type namedtuple variables from JSON strings
709 ctx_key = json.loads(str(ctx_key_raw))
710 ctx_data = json.loads(str(ctx_raw))
711 known_cls: Type[NamedTuple]
712 for known_cls in (
713 CustomTaskEventHandlerContext,
714 TaskEventMailContext,
715 TaskJobLogsRetrieveContext
716 ):
717 if ctx_data and ctx_data[0] == known_cls.__name__:
718 ctx_args: list = ctx_data[1]
719 if len(ctx_args) > len(known_cls._fields):
720 # BACK COMPAT: no-longer used ctx_type arg
721 # from: Cylc 7
722 # to: 8.3.0
723 ctx_args.pop(1)
724 ctx: tuple = known_cls(*ctx_args)
725 break
726 else: # no break
727 ctx = ctx_data
728 if ctx is not None:
729 ctx = tuple(ctx)
730 delays = json.loads(str(delays_raw))
731 except ValueError:
732 LOG.exception(
733 "%(id)s: skip action timer %(ctx_key)s" %
734 {"id": id_, "ctx_key": ctx_key_raw})
735 return
736 LOG.debug("+ %s/%s %s" % (cycle, name, ctx_key))
737 if ctx_key == "poll_timer":
738 itask = self._get_task_by_id(id_)
739 if itask is None:
740 return
741 itask.poll_timer = TaskActionTimer(
742 ctx, delays, num, delay, timeout)
743 elif ctx_key[0] == "try_timers":
744 itask = self._get_task_by_id(id_)
745 if itask is None:
746 return
747 if 'retrying' in ctx_key[1]:
748 if 'submit' in ctx_key[1]:
749 submit = True
750 ctx_key[1] = TimerFlags.SUBMISSION_RETRY
751 else:
752 submit = False
753 ctx_key[1] = TimerFlags.EXECUTION_RETRY
754
755 if timeout:
756 LOG.debug(
757 f' (upgrading retrying state for {itask.identity})')
758 self.task_events_mgr._retry_task(
759 itask,
760 float(timeout),
761 submit_retry=submit
762 )
763 itask.try_timers[ctx_key[1]] = TaskActionTimer(
764 ctx, delays, num, delay, timeout)
765 elif ctx:
766 (handler, event), submit_num = ctx_key
767 self.task_events_mgr.add_event_timer(
768 EventKey(
769 handler,
770 event,
771 # NOTE: the event "message" is not preserved in the DB so
772 # we use the event as a placeholder
773 event,
774 tokens.duplicate(job=submit_num),
775 ),
776 TaskActionTimer(
777 ctx, delays, num, delay, timeout
778 )
779 )
780 else:
781 LOG.exception(
782 "%(id)s: skip action timer %(ctx_key)s" %
783 {"id": id_, "ctx_key": ctx_key_raw})
784 return
785
786 def load_db_tasks_to_hold(self):
787 """Update the tasks_to_hold set with the tasks stored in the
788 database."""
789 self.tasks_to_hold.update(
790 (name, get_point(cycle)) for name, cycle in
791 self.workflow_db_mgr.pri_dao.select_tasks_to_hold()
792 )
793
794 def get_or_spawn_task(
795 self,
796 point: 'PointBase',
797 tdef: 'TaskDef',
798 flow_nums: 'FlowNums',
799 flow_wait: bool = False
800 ) -> 'Tuple[Optional[TaskProxy], bool]':
801 """Return new or existing task point/name with merged flow_nums.
802
803 Returns:
804 tuple - (itask, is_in_pool)
805
806 itask:
807 The requested task proxy, or None if task does not
808 exist or cannot spawn.
809 is_in_pool:
810 Was the task found in a pool.
811
812 It does not add a spawned task proxy to the pool.
813 """
814 ntask = self.get_task(point, tdef.name)
815 is_in_pool = False
816 if ntask is None:
817 # ntask does not exist: spawn it in the flow.
818 ntask = self.spawn_task(
819 tdef.name, point, flow_nums, flow_wait=flow_wait
820 )
821 # if the task was found set xtrigger checking type.
822 # otherwise find the xtrigger type if it can't spawn
823 # for whatever reason.
824 else:
825 # ntask already exists (n=0): merge flows.
826 is_in_pool = True
827 self.merge_flows(ntask, flow_nums)
828
829 # ntask may still be None
830 return ntask, is_in_pool
831
832 def spawn_next_parentless(self, itask: 'TaskProxy') -> None:
833 """Spawn next parentless instance of this task."""
834 if (
835 not itask.flow_nums # Force-triggered no-flow task
836 or itask.point < self.config.start_point # Warm start
837 ):
838 return
839 point = itask.tdef.next_point_parentless(
840 self.config.start_point, itask.point)
841 if point is not None:
842 ntask, is_in_pool = (
843 self.get_or_spawn_task(point, itask.tdef, itask.flow_nums)
844 )
845 if ntask is not None and not is_in_pool:
846 self.add_to_pool(ntask)
847
848 def remove(self, itask: 'TaskProxy', reason: Optional[str] = None) -> None:
849 """Remove a task from the pool."""
850 # the held state is no longer relevant -> remove it
851 self.release_held_active_task(itask)
852
853 # xtriggers are no longer relevant -> remove them
854 self.xtrigger_mgr.force_satisfy_all(itask, log=False)
855
856 if itask.flow_nums and (
857 itask.state.is_runahead or itask.is_xtrigger_sequential
858 ):
859 # If removing a parentless runahead-limited task
860 # auto-spawn its next instance first.
861 self.spawn_next_parentless(itask)
862
863 msg = f"removed from the n=0 window: {reason or 'completed'}"
864
865 # Mark as transient in case itask is still processed in other contexts.
866 itask.transient = True
867
868 try:
869 del self.active_tasks[itask.point][itask.identity]
870 except KeyError:
871 pass
872 else:
873 self.tasks_to_trigger_now.discard(itask)
874 self.pre_start_tasks_to_trigger.discard(
875 (itask.tdef.name, itask.point)
876 )
877 self.tasks_removed = True
878 self.active_tasks_changed = True
879 if not self.active_tasks[itask.point]:
880 del self.active_tasks[itask.point]
881 self.task_queue_mgr.remove_task(itask)
882 if itask.tdef.max_future_prereq_offset is not None:
883 self.set_max_future_offset()
884
885 # Notify the data-store manager of their removal
886 # (the manager uses window boundary tracking for pruning).
887 self.data_store_mgr.remove_pool_node(itask.tdef.name, itask.point)
888 # Event-driven final update of task_states table.
889 # TODO: same for datastore (still updated by scheduler loop)
890 self.workflow_db_mgr.put_update_task_state(itask)
891
892 level = logging.DEBUG
893 if itask.state(
894 TASK_STATUS_PREPARING,
895 TASK_STATUS_SUBMITTED,
896 TASK_STATUS_RUNNING,
897 ):
898 level = logging.WARNING
899 msg += " - active job orphaned"
900 elif reason == self.REMOVED_BY_PREREQ:
901 level = logging.INFO
902
903 LOG.log(level, f"[{itask}] {msg}")
904
905 # ensure this task is written to the DB before moving on
906 # https://github.com/cylc/cylc-flow/issues/6315
907 self.workflow_db_mgr.process_queued_ops()
908
909 del itask
910
911 def get_tasks(self) -> List[TaskProxy]:
912 """Return a list of task proxies in the task pool."""
913 # Cached list only for use internally in this method.
914 if self.active_tasks_changed:
915 self.active_tasks_changed = False
916 self._active_tasks_list = [
917 itask
918 for itask_id_map in self.active_tasks.values()
919 for itask in itask_id_map.values()
920 ]
921 return self._active_tasks_list
922
923 def get_task_ids(self) -> Set[str]:
924 """Return a list of task IDs in the task pool."""
925 return {itask.identity for itask in self.get_tasks()}
926
927 def get_tasks_by_point(self) -> 'Dict[PointBase, List[TaskProxy]]':
928 """Return a map of task proxies by cycle point."""
929 return {
930 point: list(itask_id_map.values())
931 for point, itask_id_map in self.active_tasks.items()
932 }
933
934 def get_task(self, point: 'PointBase', name: str) -> Optional[TaskProxy]:
935 """Retrieve a task from the pool."""
936 rel_id = f'{point}/{name}'
937 tasks = self.active_tasks.get(point)
938 if tasks:
939 return tasks.get(rel_id)
940 return None
941
942 def _get_task_by_id(self, id_: str) -> Optional[TaskProxy]:
943 """Return pool task by ID if it exists, or None."""
944 for itask_ids in self.active_tasks.values():
945 if id_ in itask_ids:
946 return itask_ids[id_]
947 return None
948
949 def get_itasks(self, ids: 'Iterable[Tokens]') -> List[TaskProxy]:
950 """Return a list of itasks matching the IDs provided.
951
952 Args:
953 ids: The exact IDs to match (no globs, families, etc supported).
954
955 Returns:
956 A list of an active tasks matching these IDs.
957
958 """
959 ids_ = {id_.relative_id for id_ in ids}
960 return [
961 itask
962 for itasks in self.active_tasks.values()
963 for id_, itask in itasks.items()
964 if id_ in ids_
965 ]
966
967 def queue_task(self, itask: TaskProxy) -> None:
968 """Queue a task that is ready to run.
969
970 If it is already queued, do nothing.
971 """
972 if itask.state_reset(is_queued=True):
973 self.data_store_mgr.delta_task_state(itask)
974 self.task_queue_mgr.push_task(itask)
975
976 def unqueue_task(self, itask: TaskProxy) -> None:
977 """Un-queue a task that is no longer ready to run.
978
979 If it is not queued, do nothing.
980 """
981 if itask.state_reset(is_queued=False):
982 self.data_store_mgr.delta_task_state(itask)
983 self.task_queue_mgr.remove_task(itask)
984
985 def count_active_tasks(self):
986 """Count active tasks and identify pre-prep tasks."""
987
988 # count active tasks by name
989 # {task_name: number_of_active_instances, ...}
990 active_task_counter = Counter()
991
992 # tasks which have entered the submission pipeline but have not yet
993 # entered the PREPARING state
994 pre_prep_tasks = []
995
996 for itask in self.get_tasks():
997 # populate active_task_counter and pre_prep_tasks together to
998 # avoid iterating the task pool twice
999 if itask.waiting_on_job_prep:
1000 # a task which has entered the submission pipeline
1001 # for the purposes of queue limiting this should be treated
1002 # the same as an active task
1003 active_task_counter.update([itask.tdef.name])
1004 pre_prep_tasks.append(itask)
1005 elif itask.state(
1006 TASK_STATUS_PREPARING,
1007 TASK_STATUS_SUBMITTED,
1008 TASK_STATUS_RUNNING,
1009 ):
1010 # an active task
1011 active_task_counter.update([itask.tdef.name])
1012
1013 return active_task_counter, pre_prep_tasks
1014
1015 def release_queued_tasks(self) -> set['TaskProxy']:
1016 """Return list of queue-released tasks awaiting job prep.
1017
1018 Note:
1019 Tasks can hang about for a while between being released and
1020 entering the PREPARING state for various reasons. This method
1021 returns tasks which are awaiting job prep irrespective of whether
1022 they have been previously returned.
1023
1024 """
1025 active_task_counter, pre_prep_tasks = self.count_active_tasks()
1026
1027 # release queued tasks
1028 released = self.task_queue_mgr.release_tasks(active_task_counter)
1029
1030 for itask in released:
1031 itask.state_reset(is_queued=False)
1032 self.data_store_mgr.delta_task_state(itask)
1033 itask.waiting_on_job_prep = True
1034
1035 if cylc.flow.flags.cylc7_back_compat:
1036 # Cylc 7 Back Compat: spawn downstream to cause Cylc 7 style
1037 # stalls - with unsatisfied waiting tasks - even with single
1038 # prerequisites (which result in incomplete tasks in Cylc 8).
1039 # We do it here (rather than at runhead release) to avoid
1040 # pre-spawning out to the runahead limit.
1041 self.spawn_on_all_outputs(itask)
1042
1043 # Note: released and pre_prep_tasks can overlap
1044 return set(released + pre_prep_tasks)
1045
1046 def get_min_point(self):
1047 """Return the minimum cycle point currently in the pool."""
1048 cycles = list(self.active_tasks)
1049 minc = None
1050 if cycles:
1051 minc = min(cycles)
1052 return minc
1053
1054 def set_max_future_offset(self):
1055 """Calculate the latest required future trigger offset."""
1056 orig = self.max_future_offset
1057 max_offset = None
1058 for itask in self.get_tasks():
1059 if (
1060 itask.tdef.max_future_prereq_offset is not None
1061 and (
1062 max_offset is None or
1063 itask.tdef.max_future_prereq_offset > max_offset
1064 )
1065 ):
1066 max_offset = itask.tdef.max_future_prereq_offset
1067 self.max_future_offset = max_offset
1068 if max_offset != orig:
1069 self.compute_runahead(force=True)
1070
1071 def reload(self, config: 'WorkflowConfig') -> None:
1072 self.config = config # store the updated config
1073 self.xtrigger_mgr.add_xtriggers(
1074 self.config.xtrigger_collator, reload=True)
1075 self._reload_taskdefs()
1076
1077 def _reload_taskdefs(self) -> None:
1078 """Reload the definitions of task proxies in the pool.
1079
1080 Orphaned tasks (whose definitions were removed from the workflow):
1081 - remove if not active yet
1082 - if active, leave them but prevent them from spawning children on
1083 subsequent outputs
1084
1085 Otherwise: replace task definitions but copy over existing outputs etc.
1086
1087 self.config should already be updated for the reload.
1088 """
1089 self.stop_point = self.config.stop_point or self.config.final_point
1090
1091 # find any old tasks that have been removed from the workflow
1092 old_task_name_list = self.task_name_list
1093 self.task_name_list = self.config.get_task_name_list()
1094 orphans = [
1095 task
1096 for task in old_task_name_list
1097 if task not in self.task_name_list
1098 ]
1099
1100 # adjust the new workflow config to handle the orphans
1101 self.config.adopt_orphans(orphans)
1102
1103 LOG.info("Reloading task definitions.")
1104 tasks = self.get_tasks()
1105 # Log tasks orphaned by a reload but not currently in the task pool.
1106 for name in orphans:
1107 if name not in (itask.tdef.name for itask in tasks):
1108 LOG.info("Removed task: '%s'", name)
1109 # Store lists of tasks which were active before reload.
1110 warn_tasks: List[str] = []
1111 _warn_tasks: List[str] = []
1112
1113 for itask in tasks:
1114 if itask.tdef.name in orphans:
1115 if (
1116 itask.state(TASK_STATUS_WAITING)
1117 or itask.state.is_held
1118 or itask.state.is_queued
1119 ):
1120 # Remove orphaned task if it hasn't started running yet.
1121 self.remove(itask, 'task definition removed')
1122 else:
1123 # Keep active orphaned task, but stop it from spawning.
1124 itask.graph_children = {}
1125 LOG.info(
1126 f"[{itask}] will not spawn children "
1127 "- task definition removed"
1128 )
1129 else:
1130 new_task = TaskProxy(
1131 self.tokens,
1132 self.config.get_taskdef(itask.tdef.name),
1133 itask.point,
1134 itask.flow_nums,
1135 itask.state.status,
1136 sequential_xtrigger_labels=(
1137 self.xtrigger_mgr.xtriggers.sequential_xtrigger_labels
1138 ),
1139 )
1140 itask.copy_to_reload_successor(
1141 new_task,
1142 self.check_task_output,
1143 )
1144 self._swap_out(new_task)
1145 self.data_store_mgr.delta_task_prerequisite(new_task)
1146 LOG.info(f"[{itask}] reloaded task definition")
1147
1148 if itask.state(*TASK_STATUSES_ACTIVE):
1149 warn_tasks.append(str(itask))
1150 elif itask.state(TASK_STATUS_PREPARING):
1151 # Job file might have been written at this point?
1152 _warn_tasks.append(str(itask))
1153
1154 for may, tasks in (('', warn_tasks), ('may be', _warn_tasks)):
1155 if tasks:
1156 _tasks = "\n * ".join(tasks)
1157 LOG.info(
1158 f"Tasks {may} active with pre-reload settings:\n{_tasks}")
1159
1160 # Reassign live tasks to the internal queue
1161 del self.task_queue_mgr
1162 self.task_queue_mgr = IndepQueueManager(
1163 self.config.cfg['scheduling']['queues'],
1164 self.task_name_list,
1165 self.config.runtime['descendants']
1166 )
1167
1168 # Now queue all tasks that are ready to run
1169 for itask in self.get_tasks():
1170 # Recreate data store elements from task pool.
1171 self.create_data_store_elements(itask)
1172
1173 def set_stop_point(self, stop_point: 'PointBase') -> bool:
1174 """Set the workflow stop cycle point.
1175
1176 And reset the runahead limit if less than the stop point.
1177 """
1178 if self.stop_point == stop_point:
1179 LOG.info(f"Stop point unchanged: {stop_point}")
1180 return False
1181
1182 LOG.info(f"Setting stop point: {stop_point}")
1183 self.stop_point = stop_point
1184
1185 if (
1186 self.runahead_limit_point is not None
1187 and self.runahead_limit_point > stop_point
1188 ):
1189 self.runahead_limit_point = stop_point
1190 # Now handle existing waiting tasks (e.g. xtriggered).
1191 for itask in self.get_tasks():
1192 if (
1193 itask.point > stop_point
1194 and itask.state(TASK_STATUS_WAITING)
1195 and itask.state_reset(is_runahead=True)
1196 ):
1197 self.data_store_mgr.delta_task_state(itask)
1198 return True
1199
1200 def can_stop(self, stop_mode):
1201 """Return True if workflow can stop.
1202
1203 A task is considered active if:
1204 * It is in the active state and not marked with a kill failure.
1205 * It has pending event handlers.
1206 """
1207 if stop_mode is None:
1208 return False
1209 if stop_mode == StopMode.REQUEST_NOW_NOW:
1210 return True
1211 if self.task_events_mgr._event_timers:
1212 return False
1213
1214 return not any(
1215 (
1216 stop_mode in [StopMode.REQUEST_CLEAN, StopMode.REQUEST_KILL]
1217 and itask.state(*TASK_STATUSES_ACTIVE)
1218 and not itask.state.kill_failed
1219 )
1220 # preparing tasks get reset to waiting on restart
1221 for itask in self.get_tasks()
1222 )
1223
1224 def warn_stop_orphans(self) -> None:
1225 """Log (warning) orphaned tasks on workflow stop."""
1226 orphans = []
1227 orphans_kill_failed = []
1228 for itask in self.get_tasks():
1229 if itask.state(*TASK_STATUSES_ACTIVE):
1230 if itask.state.kill_failed:
1231 orphans_kill_failed.append(itask)
1232 else:
1233 orphans.append(itask)
1234
1235 for orphanlist, extra_text in (
1236 (orphans_kill_failed, ' (kill failed)'),
1237 (orphans, '')
1238 ):
1239 if orphanlist:
1240 LOG.warning(
1241 f"Orphaned tasks{extra_text}:\n"
1242 + "\n".join(
1243 f"* {itask.identity} ({itask.state.status})"
1244 for itask in orphanlist)
1245 )
1246
1247 for id_key in self.task_events_mgr._event_timers:
1248 LOG.warning(
1249 f"{id_key.tokens.relative_id}:"
1250 " incomplete task event handler"
1251 f" {(id_key.handler, id_key.event)}"
1252 )
1253
1254 def log_incomplete_tasks(self) -> bool:
1255 """Log finished but incomplete tasks; return True if there any."""
1256 incomplete = []
1257 for itask in self.get_tasks():
1258 if not itask.state(*TASK_STATUSES_FINAL):
1259 continue
1260 if not itask.state.outputs.is_complete():
1261 incomplete.append(
1262 (
1263 itask.identity,
1264 itask.state.outputs.format_completion_status(
1265 ansimarkup=1
1266 ),
1267 )
1268 )
1269
1270 if incomplete:
1271 LOG.error(
1272 "Incomplete tasks:\n"
1273 + "\n".join(
1274 f"* {id_} did not complete the required outputs:"
1275 f"\n{indent(outputs, ' ')}"
1276 for id_, outputs in incomplete
1277 )
1278 )
1279 return True
1280 return False
1281
1282 def log_unsatisfied_prereqs(self) -> bool:
1283 """Log unsatisfied prerequisites in the pool.
1284
1285 Return True if any, ignoring:
1286 - prerequisites beyond the stop point
1287 - dependence on tasks beyond the stop point
1288 (can be caused by future triggers)
1289 """
1290 unsat: Dict[str, List[str]] = {}
1291 for itask in self.get_tasks():
1292 task_point = itask.point
1293 if self.stop_point and task_point > self.stop_point:
1294 continue
1295 for pr in itask.state.get_unsatisfied_prerequisites():
1296 if self.stop_point and get_point(pr.point) > self.stop_point:
1297 continue
1298 if itask.identity not in unsat:
1299 unsat[itask.identity] = []
1300 unsat[itask.identity].append(
1301 f"{pr.get_id()}:"
1302 f"{self.config.get_taskdef(pr.task).get_output(pr.output)}"
1303 )
1304 if unsat:
1305 LOG.warning(
1306 "Partially satisfied prerequisites:\n"
1307 + "\n".join(
1308 f" * {id_} is waiting on {sorted(others)}"
1309 for id_, others in unsat.items()
1310 )
1311 )
1312 return True
1313 return False
1314
1315 def is_stalled(self) -> bool:
1316 """Return whether the workflow is stalled.
1317
1318 Is stalled if not paused and contains only:
1319 - incomplete tasks
1320 - partially satisfied prerequisites (below stop point)
1321 - runahead-limited tasks (held back by the above)
1322 """
1323 if any(
1324 itask.state(
1325 *TASK_STATUSES_ACTIVE,
1326 TASK_STATUS_PREPARING
1327 ) or (
1328 itask.state(TASK_STATUS_WAITING)
1329 and not itask.state.is_runahead
1330 # (avoid waiting pre-spawned absolute-triggered tasks:)
1331 and itask.prereqs_are_satisfied()
1332 ) for itask in self.get_tasks()
1333 ):
1334 return False
1335
1336 incomplete = self.log_incomplete_tasks()
1337 unsatisfied = self.log_unsatisfied_prereqs()
1338 return (incomplete or unsatisfied)
1339
1340 def hold_active_task(self, itask: TaskProxy) -> None:
1341 if itask.state_reset(is_held=True):
1342 self.data_store_mgr.delta_task_state(itask)
1343 self.tasks_to_hold.add((itask.tdef.name, itask.point))
1344 self.workflow_db_mgr.put_tasks_to_hold(self.tasks_to_hold)
1345
1346 def release_held_active_task(self, itask: TaskProxy) -> None:
1347 if itask.state_reset(is_held=False):
1348 self.data_store_mgr.delta_task_state(itask)
1349 if (not itask.state.is_runahead) and itask.is_ready_to_run():
1350 self.queue_task(itask)
1351 self.tasks_to_hold.discard((itask.tdef.name, itask.point))
1352 self.workflow_db_mgr.put_tasks_to_hold(self.tasks_to_hold)
1353
1354 def set_hold_point(self, point: 'PointBase') -> None:
1355 """Set the point after which all tasks must be held."""
1356 self.hold_point = point
1357 for itask in self.get_tasks():
1358 if itask.point > point:
1359 self.hold_active_task(itask)
1360 self.workflow_db_mgr.put_workflow_hold_cycle_point(point)
1361
1362 def hold_tasks(self, items: Set[TaskTokens]) -> int:
1363 """Hold tasks with IDs matching the specified items."""
1364 matched, unmatched = self.id_match(items)
1365 for id_ in matched:
1366 itask = self._get_task_by_id(id_.relative_id)
1367 if itask:
1368 # hold active task
1369 self.hold_active_task(itask)
1370 else:
1371 # hold inactive task
1372 icycle = get_point(id_['cycle'])
1373 self.data_store_mgr.delta_task_held(id_['task'], icycle, True)
1374 self.tasks_to_hold.add((id_['task'], icycle))
1375
1376 self.workflow_db_mgr.put_tasks_to_hold(self.tasks_to_hold)
1377 LOG.debug(f"Tasks to hold: {self.tasks_to_hold}")
1378 return len(unmatched)
1379
1380 def release_held_tasks(self, items: Set[TaskTokens]) -> int:
1381 """Release held tasks with IDs matching any specified items."""
1382 matched, unmatched = id_match(
1383 self.config,
1384 {
1385 # only match held tasks
1386 TaskTokens(cycle=str(cycle), task=task)
1387 for task, cycle in self.tasks_to_hold
1388 },
1389 items,
1390 # only match tasks within the held task list
1391 only_match_pool=True,
1392 )
1393 for id_ in matched:
1394 itask = self._get_task_by_id(id_.relative_id)
1395 if itask:
1396 # release active task
1397 self.release_held_active_task(itask)
1398 else:
1399 # release inactive task
1400 self.data_store_mgr.delta_task_held(
1401 id_['task'], get_point(id_['cycle']), False
1402 )
1403 self.tasks_to_hold.discard(
1404 (id_['task'], get_point(id_['cycle']))
1405 )
1406 self.workflow_db_mgr.put_tasks_to_hold(self.tasks_to_hold)
1407 LOG.debug(f"Tasks to hold: {self.tasks_to_hold}")
1408 return len(unmatched)
1409
1410 def release_hold_point(self) -> None:
1411 """Unset the workflow hold point and release all held active tasks."""
1412 self.hold_point = None
1413 for itask in self.get_tasks():
1414 self.release_held_active_task(itask)
1415 self.tasks_to_hold.clear()
1416 self.workflow_db_mgr.put_tasks_to_hold(self.tasks_to_hold)
1417 self.workflow_db_mgr.put_workflow_hold_cycle_point(None)
1418
1419 def check_abort_on_task_fails(self):
1420 """Check whether workflow should abort on task failure.
1421
1422 Return True if a task failed and `--abort-if-any-task-fails` was given.
1423 """
1424 return self.abort_task_failed
1425
1426 def spawn_on_output(self, itask: TaskProxy, output: str) -> None:
1427 """Spawn child-tasks of given output, into the pool.
1428
1429 Remove the parent task from the pool if complete.
1430
1431 Called by task event manager on receiving output messages, and after
1432 forced setting of task outputs (in this case the parent task could
1433 be transient, i.e. not in the pool).
1434
1435 Also set the abort-on-task-failed flag if necessary.
1436
1437 If not flowing on, update existing children but don't spawn new ones
1438 (unless manually forced to spawn with no flow number).
1439
1440 If an absolute output is completed update the store of completed abs
1441 outputs, and update the prerequisites of every instance of the child
1442 in the pool. (The self.spawn method uses the store of completed abs
1443 outputs to satisfy any tasks with absolute prerequisites).
1444
1445 Args:
1446 output: output to spawn on.
1447
1448 """
1449 if (
1450 output == TASK_OUTPUT_FAILED
1451 and self.expected_failed_tasks is not None
1452 and itask.identity not in self.expected_failed_tasks
1453 ):
1454 self.abort_task_failed = True
1455
1456 children = []
1457 if itask.flow_nums:
1458 with suppress(KeyError):
1459 children = itask.graph_children[output]
1460
1461 if itask.flow_wait and children:
1462 LOG.warning(
1463 f"[{itask}] not spawning on {output}: flow wait requested")
1464 self.remove_if_complete(itask, output)
1465 return
1466
1467 if status_geq(itask.state.status, TASK_STATUS_PREPARING):
1468 # task has begun submission -> clear all xtriggers
1469 self.xtrigger_mgr.force_satisfy_all(itask, log=False)
1470
1471 suicide = []
1472 for c_name, c_point, is_abs in children:
1473 if is_abs:
1474 self.abs_outputs_done.add(
1475 (str(itask.point), itask.tdef.name, output))
1476 self.workflow_db_mgr.put_insert_abs_output(
1477 str(itask.point), itask.tdef.name, output)
1478 self.workflow_db_mgr.process_queued_ops()
1479
1480 c_task = self._get_task_by_id(quick_relative_id(c_point, c_name))
1481 in_pool = c_task is not None
1482
1483 if c_task is not None and c_task != itask:
1484 # (Avoid self-suicide: A => !A)
1485 self.merge_flows(c_task, itask.flow_nums)
1486 elif c_task is None and itask.flow_nums:
1487 # If child is not in the pool already, and parent belongs to a
1488 # flow (so it can spawn children), and parent is not waiting
1489 # for an upcoming flow merge before spawning ... then spawn it.
1490 c_task = self.spawn_task(c_name, c_point, itask.flow_nums)
1491
1492 tasks: List[TaskProxy]
1493 if c_task is not None:
1494 # Have child task, update its prerequisites.
1495 if is_abs:
1496 # NOTE: Absolute triggers can have an infinite number of
1497 # graph children, so only the first match is listed. We
1498 # satisfy the prerequisite for all other tasks of the same
1499 # name in the pool, future task instances have their
1500 # prereqs satisfied from the DB at spawn-time.
1501 matched, _unmatched = self.id_match(
1502 {TaskTokens(cycle='*', task=c_name)},
1503 only_match_pool=True,
1504 )
1505 tasks = self.get_itasks(matched)
1506 if c_task not in tasks:
1507 tasks.append(c_task)
1508 else:
1509 tasks = [c_task]
1510
1511 for t in tasks:
1512 t.satisfy_me(
1513 [itask.tokens.duplicate(task_sel=output)],
1514 mode=itask.run_mode
1515 )
1516 self.data_store_mgr.delta_task_prerequisite(t)
1517 if not in_pool:
1518 self.add_to_pool(t)
1519
1520 # Event-driven suicide.
1521 if (
1522 t.state.suicide_prerequisites and
1523 t.state.suicide_prerequisites_all_satisfied()
1524 ):
1525 suicide.append(t)
1526
1527 for c_task in suicide:
1528 if self.config.experimental.expire_triggers:
1529 self.task_queue_mgr.remove_task(c_task)
1530 self.task_events_mgr.process_message(
1531 c_task, logging.WARNING, TASK_OUTPUT_EXPIRED
1532 )
1533 else:
1534 self.remove(c_task, self.__class__.SUICIDE_MSG)
1535
1536 if suicide:
1537 # Update DB now in case of very quick respawn attempt.
1538 # See https://github.com/cylc/cylc-flow/issues/6066
1539 self.workflow_db_mgr.process_queued_ops()
1540
1541 self.remove_if_complete(itask, output)
1542
1543 def remove_if_complete(
1544 self, itask: TaskProxy, output: Optional[str] = None
1545 ) -> bool:
1546 """Remove a finished task if required outputs are complete.
1547
1548 Return True if removed else False.
1549
1550 Cylc 8:
1551 - if complete:
1552 - remove task and recompute runahead
1553 - else (incomplete):
1554 - retain
1555
1556 Cylc 7 back compat:
1557 - if succeeded:
1558 - remove task and recompute runahead
1559 else (failed):
1560 - retain and recompute runahead
1561 (C7 failed tasks don't count toward runahead limit)
1562
1563 """
1564 if not itask.state(*TASK_STATUSES_FINAL):
1565 # can't be complete
1566 return False
1567
1568 if itask.identity == self.stop_task_id:
1569 self.stop_task_finished = True
1570
1571 if cylc.flow.flags.cylc7_back_compat:
1572 ret = False
1573 if not itask.state(TASK_STATUS_FAILED, TASK_OUTPUT_SUBMIT_FAILED):
1574 self.remove(itask)
1575 ret = True
1576 return ret
1577
1578 if not itask.state.outputs.is_complete():
1579 # Keep incomplete tasks in the pool.
1580 if output in TASK_STATUSES_FINAL:
1581 # Log based on the output, not the state, to avoid warnings
1582 # due to use of "cylc set" to set internal outputs on an
1583 # already-finished task.
1584 LOG.warning(
1585 f"[{itask}] did not complete the required outputs:\n"
1586 + itask.state.outputs.format_completion_status(
1587 ansimarkup=1
1588 )
1589 )
1590 return False
1591
1592 self.remove(itask)
1593 return True
1594
1595 def spawn_on_all_outputs(
1596 self, itask: TaskProxy, completed_only: bool = False
1597 ) -> None:
1598 """Spawn on all (or all completed) task outputs.
1599
1600 If completed_only is False:
1601 Used in Cylc 7 Back Compat mode for pre-spawning waiting tasks. Do
1602 not set the associated prerequisites of spawned children satisfied.
1603
1604 If completed_only is True:
1605 Used to retroactively spawn on already-completed outputs when a flow
1606 merges into a force-triggered no-flow task. In this case, do set the
1607 associated prerequisites of spawned children to satisfied.
1608
1609 """
1610 if not itask.flow_nums:
1611 return
1612
1613 for _, message, is_completed in itask.state.outputs:
1614 if completed_only and not is_completed:
1615 continue
1616 try:
1617 children = itask.graph_children[message]
1618 except KeyError:
1619 continue
1620
1621 for c_name, c_point, _ in children:
1622 c_taskid = Tokens(
1623 cycle=str(c_point),
1624 task=c_name,
1625 ).relative_id
1626 c_task = self._get_task_by_id(c_taskid)
1627 if c_task is not None:
1628 # already spawned
1629 continue
1630
1631 c_task = self.spawn_task(c_name, c_point, itask.flow_nums)
1632 if c_task is None:
1633 # not spawnable
1634 continue
1635 if completed_only:
1636 c_task.satisfy_me(
1637 [itask.tokens.duplicate(task_sel=message)],
1638 mode=itask.run_mode
1639 )
1640 self.data_store_mgr.delta_task_prerequisite(c_task)
1641 self.add_to_pool(c_task)
1642
1643 def can_be_spawned(self, name: str, point: 'PointBase') -> bool:
1644 """Return True if a point/name is within graph bounds."""
1645
1646 if name not in self.config.taskdefs:
1647 LOG.debug('No task definition %s', name)
1648 return False
1649
1650 # Don't spawn outside of graph limits.
1651 # TODO: is it possible for initial_point to not be defined??
1652 # (see also the similar check + log message in scheduler.py)
1653 if self.config.initial_point and point < self.config.initial_point:
1654 # Attempted manual trigger prior to FCP
1655 # or future triggers like foo[+P1] => bar, with foo at ICP.
1656 LOG.debug(
1657 'Not spawning %s/%s: before initial cycle point', point, name)
1658 return False
1659
1660 if self.config.final_point and point > self.config.final_point:
1661 # Only happens on manual trigger beyond FCP
1662 LOG.debug(
1663 'Not spawning %s/%s: beyond final cycle point', point, name)
1664 return False
1665
1666 # Is it on-sequence and within recurrence bounds.
1667 if not self.config.get_taskdef(name).is_valid_point(point):
1668 LOG.warning(
1669 self.ERR_PREFIX_TASK_NOT_ON_SEQUENCE.format(
1670 name, point
1671 )
1672 )
1673 return False
1674
1675 return True
1676
1677 def _get_task_history(
1678 self, name: str, point: 'PointBase', flow_nums: 'FlowNums'
1679 ) -> tuple[int, str | None, bool]:
1680 """Get submit_num, status, flow_wait for point/name in flow_nums.
1681
1682 Args:
1683 name: task name
1684 point: task cycle point
1685 flow_nums: task flow numbers
1686
1687 Returns:
1688 (submit_num, status, flow_wait)
1689 If no matching history, status will be None
1690
1691 """
1692 submit_num: int = 0
1693 status: Optional[str] = None
1694 flow_wait = False
1695
1696 info = self.workflow_db_mgr.pri_dao.select_prev_instances(
1697 name, str(point)
1698 )
1699 with suppress(ValueError):
1700 submit_num = max(s[0] for s in info)
1701
1702 for _snum, f_wait, old_fnums, old_status in info:
1703 if set.intersection(flow_nums, old_fnums):
1704 # matching flows
1705 status = old_status
1706 flow_wait = f_wait
1707 if status in TASK_STATUSES_FINAL:
1708 # task finished
1709 break
1710 # Else continue: there may be multiple entries with flow
1711 # overlap due to merges (they'll have have same snum and
1712 # f_wait); keep going to find the finished one, if any.
1713
1714 return submit_num, status, flow_wait
1715
1716 def _load_historical_outputs(self, itask: 'TaskProxy') -> None:
1717 """Load a task's historical outputs from the DB.
1718
1719 NOTE this creates a task_states/task_outputs DB entry if not present.
1720 """
1721 info = self.workflow_db_mgr.pri_dao.select_task_outputs(
1722 itask.tdef.name, str(itask.point))
1723 if not info:
1724 # task never ran before
1725 self.db_add_new_flow_rows(itask)
1726 else:
1727 flow_seen = False
1728 for outputs_str, fnums in info.items():
1729 # (if fnums is empty, it means the 'none' flow)
1730 if itask.flow_nums.intersection(fnums):
1731 # DB row has overlap with itask's flows
1732 flow_seen = True
1733 # BACK COMPAT: In Cylc >8.0.0,<8.3.0, only the task
1734 # messages were stored in the DB as a list.
1735 # from: 8.0.0
1736 # to: 8.3.0
1737 outputs: Union[
1738 Dict[str, str], List[str]
1739 ] = json.loads(outputs_str)
1740 if isinstance(outputs, dict):
1741 # {trigger: message} - match triggers, not messages.
1742 # DB may record forced completion rather than message.
1743 for trigger in outputs.keys():
1744 itask.state.outputs.set_trigger_complete(trigger)
1745 else:
1746 # [message] - always the full task message
1747 for msg in outputs:
1748 itask.state.outputs.set_message_complete(msg)
1749 if not flow_seen:
1750 # itask never ran before in its assigned flows
1751 self.db_add_new_flow_rows(itask)
1752
1753 def spawn_task(
1754 self,
1755 name: str,
1756 point: 'PointBase',
1757 flow_nums: 'FlowNums',
1758 flow_wait: bool = False,
1759 ) -> TaskProxy | None:
1760 """Return a new task proxy for the given flow if possible.
1761
1762 We need to hit the DB for:
1763 - submit number
1764 - task status
1765 - flow-wait
1766 - completed outputs (e.g. via "cylc set")
1767
1768 If history records a final task status (for this flow):
1769 - if not flow wait, don't spawn (return None)
1770 - if flow wait, don't spawn (return None) but do spawn children
1771 - if outputs are incomplete, don't auto-rerun it (return None)
1772
1773 Otherwise, spawn the task and load any completed outputs.
1774
1775 """
1776 submit_num, prev_status, prev_flow_wait = (
1777 self._get_task_history(name, point, flow_nums)
1778 )
1779
1780 if (
1781 not prev_status
1782 and point < self.config.start_point
1783 and flow_nums.issuperset({1})
1784 # Warm start - treat pre-startcp tasks as already run in flow=1,
1785 # unless manually triggered:
1786 and (name, point) not in self.pre_start_tasks_to_trigger
1787 ):
1788 return None
1789
1790 # Create the task proxy with any completed outputs loaded.
1791 itask = self._load_db_task_proxy(
1792 point,
1793 self.config.get_taskdef(name),
1794 flow_nums,
1795 status=prev_status or TASK_STATUS_WAITING,
1796 submit_num=submit_num,
1797 flow_wait=flow_wait,
1798 )
1799 if itask is None:
1800 return None
1801
1802 if (
1803 prev_status is not None
1804 and not itask.state.outputs.get_completed_outputs()
1805 and not self.config.experimental.expire_triggers
1806 ):
1807 # If itask has any history but no completed outputs, it must have
1808 # been removed by suicide trigger (not by `cylc remove` which
1809 # erases task history).
1810 #
1811 # This was a bodge to prevent suicided tasks from respawning via
1812 # other dependencies, given that suicide leaves no DB record.
1813 # The bodge fails if any outputs were completed before suicide.
1814 #
1815 # The reimplementation of suicide triggers as expire triggers
1816 # renders this bodge obsolete. TODO: remove this code block on
1817 # migrating expire triggers from "experimental" to standard.
1818 LOG.info(f"Not respawning {point}/{name} - task was removed")
1819 return None
1820
1821 if prev_status in TASK_STATUSES_FINAL:
1822 # Task finished previously.
1823 if itask.is_complete():
1824 msg = "and completed"
1825 itask.transient = True
1826 else:
1827 # revive as incomplete.
1828 msg = "incomplete"
1829
1830 if LOG.level <= logging.DEBUG:
1831 # avoid unnecessary compute when we are not in debug mode
1832 id_ = itask.tokens.duplicate(
1833 task_sel=prev_status
1834 ).relative_id_with_selectors
1835 LOG.debug(
1836 f"[{id_}] already finished {msg}"
1837 f" {repr_flow_nums(flow_nums, full=True)})"
1838 )
1839 if prev_flow_wait:
1840 self._spawn_after_flow_wait(itask)
1841
1842 if itask.transient:
1843 return None
1844
1845 if not itask.transient:
1846 if (name, point) in self.tasks_to_hold:
1847 LOG.info(f"[{itask}] holding (as requested earlier)")
1848 self.hold_active_task(itask)
1849 elif self.hold_point and itask.point > self.hold_point:
1850 # Hold if beyond the workflow hold point
1851 LOG.info(
1852 f"[{itask}] holding (beyond workflow "
1853 f"hold point: {self.hold_point})"
1854 )
1855 self.hold_active_task(itask)
1856
1857 # Don't add to pool if it depends on a task beyond the stop point.
1858 # "foo; foo[+P1] & bar => baz"
1859 # Here, in the final cycle bar wants to spawn baz, but that would
1860 # stall because baz also depends on foo after the final point.
1861 if self.stop_point and itask.point <= self.stop_point:
1862 for pct in itask.state.prerequisites_get_target_points():
1863 if pct > self.stop_point:
1864 LOG.warning(
1865 f"[{itask}] not spawned: a prerequisite is beyond"
1866 f" the workflow stop point ({self.stop_point})"
1867 )
1868 return None
1869
1870 # Satisfy any absolute triggers.
1871 if (
1872 itask.tdef.has_abs_triggers
1873 and itask.state.prerequisites_are_not_all_satisfied()
1874 ):
1875 itask.satisfy_me([
1876 Tokens(cycle=cycle, task=task, task_sel=output)
1877 for cycle, task, output in self.abs_outputs_done
1878 ])
1879
1880 if prev_status is None:
1881 # only add new flow rows if this task has not run before
1882 # see https://github.com/cylc/cylc-flow/pull/6821
1883 self.db_add_new_flow_rows(itask)
1884
1885 return itask
1886
1887 def _spawn_after_flow_wait(self, itask: TaskProxy) -> None:
1888 LOG.info(f"[{itask}] spawning outputs after flow-wait")
1889 self.spawn_on_all_outputs(itask, completed_only=True)
1890 # update flow wait status in the DB
1891 itask.flow_wait = False
1892 # itask.flow_nums = orig_fnums
1893 self.workflow_db_mgr.put_update_task_flow_wait(itask)
1894 return None
1895
1896 def _load_db_task_proxy(
1897 self,
1898 point: 'PointBase',
1899 taskdef: 'TaskDef',
1900 flow_nums: 'FlowNums',
1901 status: str = TASK_STATUS_WAITING,
1902 flow_wait: bool = False,
1903 transient: bool = False,
1904 is_manual_submit: bool = False,
1905 submit_num: int = 0,
1906 ) -> 'TaskProxy | None':
1907 """Spawn a task, update outputs from DB.
1908
1909 NOTE this creates a task_states/task_outputs DB entry if not present.
1910 """
1911
1912 if not self.can_be_spawned(taskdef.name, point):
1913 return None
1914
1915 itask = TaskProxy(
1916 self.tokens,
1917 taskdef,
1918 point,
1919 flow_nums,
1920 status=status,
1921 flow_wait=flow_wait,
1922 submit_num=submit_num,
1923 transient=transient,
1924 is_manual_submit=is_manual_submit,
1925 sequential_xtrigger_labels=(
1926 self.xtrigger_mgr.xtriggers.sequential_xtrigger_labels
1927 ),
1928 )
1929 # Update it with outputs that were already completed.
1930 self._load_historical_outputs(itask)
1931 return itask
1932
1933 def _standardise_prereqs(
1934 self, prereqs: 'Iterable[str]'
1935 ) -> 'Set[PrereqTuple]':
1936 """Extract task prerequisites from user input and standardise.
1937
1938 Weed out any xtrigger prerequisites.
1939
1940 Command validation has handled output suffixes and defaults.
1941
1942 Args:
1943 prereqs: prerequisites and xtriggers in string form:
1944 <cycle>/<task>:<output>
1945 xtrigger/<xtrigger>[:succeeded]
1946 xtrigger/all[:succeeded]
1947
1948 Returns: {prerequisite-tokens}
1949
1950 """
1951 _prereqs = set()
1952 for prereq in prereqs:
1953 pre = Tokens(prereq, relative=True)
1954 if pre['cycle'] == XTRIGGER_PREREQ_PREFIX:
1955 # weed out xtrigger prerequisites
1956 continue
1957 output = TaskTrigger.standardise_name(
1958 pre['task_sel'] or TASK_OUTPUT_SUCCEEDED)
1959 # Convert outputs to task messages.
1960 try:
1961 msg = self.config.get_taskdef(
1962 str(pre['task'])
1963 ).outputs[output][0]
1964 cycle = standardise_point_string(pre['cycle'])
1965 except KeyError:
1966 LOG.warning(
1967 f"Output {pre.relative_id_with_selectors} not found")
1968 continue
1969 except WorkflowConfigError as exc:
1970 LOG.warning(
1971 f'Invalid prerequisite task name:\n{exc.args[0]}')
1972 except PointParsingError as exc:
1973 LOG.warning(
1974 f'Invalid prerequisite cycle point:\n{exc.args[0]}')
1975 else:
1976 _prereqs.add(PrereqTuple(str(cycle), str(pre['task']), msg))
1977 return _prereqs
1978
1979 def _standardise_outputs(
1980 self, point: 'PointBase', tdef: 'TaskDef', outputs: Iterable[str]
1981 ) -> List[str]:
1982 """Convert task output triggers to task messages."""
1983 _outputs = []
1984 for out in outputs:
1985 # convert "succeed" to "succeeded" etc.
1986 output = TaskTrigger.standardise_name(out)
1987 try:
1988 msg = tdef.outputs[output][0]
1989 except KeyError:
1990 LOG.warning(
1991 f"Output {point}/{tdef.name}:{output} not found")
1992 continue
1993 _outputs.append(msg)
1994 return _outputs
1995
1996 def set_prereqs_and_outputs(
1997 self,
1998 items: 'Set[TaskTokens]',
1999 outputs: List[str],
2000 prereqs: List[str],
2001 flow: List[str],
2002 flow_wait: bool = False,
2003 flow_descr: Optional[str] = None,
2004 ):
2005 """Complete outputs and satisfy prerequisites, via "cylc set" command.
2006
2007 Default to completing all required outputs.
2008
2009 On setting prerequisites:
2010 - spawn the task into n=0.
2011 - prerequisite validity is checked via the taskdef prior to spawning
2012 so we can back out it if no valid prerequisites are given
2013
2014 On setting outputs:
2015 - update task outputs in the DB
2016 - (implied outputs are handled by the event manager)
2017 - spawn children of the outputs, with those prerequisites satisfied
2018
2019 Transient task proxies are used to spawn the children of outputs. Even
2020 if the parent was previously spawned in this flow its children might
2021 not have been. ("Transient" just means not intended for the task pool,
2022 just a convient way to use TaskProxy methods).
2023
2024 A forced output cannot cause a state change to submitted or running,
2025 but it can complete a task so that it doesn't need to run.
2026
2027 Args:
2028 items: Parsed task ID patterns.
2029 prereqs: Prerequisites to satisfy.
2030 outputs: Outputs to complete.
2031 flow: Flow numbers for spawned or merged tasks.
2032 flow_wait: Wait for flows to catch up before continuing.
2033 flow_descr: Description of new flow.
2034
2035 """
2036 matched, _unmatched = self.id_match(set(items))
2037
2038 # Clean and separate requested prerequisite and xtrigger specs.
2039 if prereqs != ['all']:
2040 set_all = False
2041 clean_pre = self._standardise_prereqs(prereqs)
2042 clean_xtr = _get_xtrig_prereqs(prereqs)
2043 else:
2044 set_all = True
2045 clean_pre = set()
2046 clean_xtr = {}
2047
2048 if prereqs and not (set_all or clean_pre or clean_xtr):
2049 # Nothing to do!
2050 return
2051
2052 # Get integer flow numbers from CLI inputs.
2053 flow_nums = self.flow_mgr.cli_to_flow_nums(flow, flow_descr)
2054
2055 # Here, empty flow_nums means either no-flow or all active flows.
2056 if flow != [FLOW_NONE] and not flow_nums:
2057 flow_nums = self._get_active_flow_nums()
2058
2059 # Set active tasks.
2060 warnings_flow_none = []
2061 for id_ in matched:
2062 itask = self._get_task_by_id(id_.relative_id)
2063 if itask:
2064 # set active task
2065 if flow == [FLOW_NONE] and itask.flow_nums:
2066 # Exclude --flow=none for active tasks.
2067 warnings_flow_none.append(
2068 f"{itask.identity}: "
2069 f"{repr_flow_nums(itask.flow_nums, full=True)}"
2070 )
2071 continue
2072
2073 if prereqs:
2074 valid_prereqs = self._get_valid_prereqs(
2075 clean_pre, itask.tdef, itask.point)
2076 valid_xtrigs = self._get_valid_xtrigs(
2077 clean_xtr, itask.tdef, itask.point)
2078 if not (set_all or valid_prereqs or valid_xtrigs):
2079 continue
2080
2081 self.merge_flows(itask, flow_nums)
2082 self._set_prereqs_itask(
2083 itask, valid_prereqs, valid_xtrigs, set_all)
2084 else:
2085 # Outputs (may be empty list)
2086 # Spawn as if seq xtrig of parentless task was satisfied,
2087 # with associated task producing these outputs.
2088 self.merge_flows(itask, flow_nums)
2089 self._set_outputs_itask(itask, outputs)
2090
2091 else:
2092 # set inactive task
2093 tdef = self.config.taskdefs[id_['task']]
2094 icycle = get_point(id_['cycle'])
2095 if prereqs:
2096 valid_prereqs = self._get_valid_prereqs(
2097 clean_pre, tdef, icycle)
2098 valid_xtrigs = self._get_valid_xtrigs(
2099 clean_xtr, tdef, icycle)
2100 if not (set_all or valid_prereqs or valid_xtrigs):
2101 continue
2102
2103 self._set_prereqs_tdef(
2104 icycle, tdef, valid_prereqs, valid_xtrigs, flow_nums,
2105 flow_wait, set_all)
2106 else:
2107 # Outputs (may be empty list)
2108 trans = self._load_db_task_proxy(
2109 icycle, tdef, flow_nums,
2110 flow_wait=flow_wait, transient=True
2111 )
2112 if trans:
2113 self._set_outputs_itask(trans, outputs)
2114
2115 if warnings_flow_none:
2116 msg = '\n * '.join(warnings_flow_none)
2117 LOG.warning(f"Already active - ignoring no-flow set: \n * {msg}")
2118
2119 def _get_valid_prereqs(
2120 self, prereqs: Set[PrereqTuple], tdef: 'TaskDef', point: 'PointBase'
2121 ) -> 'Set[PrereqTuple]':
2122 """Weed out prerequisites not valid for this task.
2123
2124 And convert outputs to messages, for satisfying task prerequisites.
2125
2126 """
2127 # Valid prerequisites as tokens (outputs as task messages).
2128 valid_pre = {
2129 PrereqTuple(key.point, key.task, key.output)
2130 for pre in tdef.get_prereqs(point)
2131 for key in pre.keys()
2132 }
2133
2134 # standardise and weed out xtrigger prerequisites
2135 invalid = prereqs - valid_pre
2136
2137 if invalid:
2138 task = quick_relative_id(point, tdef.name)
2139 for prereq in invalid:
2140 # But log bad ones with triggers, not messages.
2141 trg = self.config.get_taskdef(
2142 prereq.task
2143 ).get_output(prereq.output)
2144 LOG.warning(
2145 f'{task} does not depend on'
2146 f' "{quick_relative_id(prereq.point, prereq.task, trg)}"'
2147 )
2148
2149 return valid_pre & prereqs
2150
2151 def _get_valid_xtrigs(
2152 self, xtrigs: Dict[str, bool], tdef: 'TaskDef', point: 'PointBase'
2153 ) -> 'Dict[str, bool]':
2154 """Weed out xtriggers not valid for this task."""
2155
2156 valid_x_labels = tdef.get_xtrigs(point)
2157
2158 # And allow any dynamically xtriggers, such as retries.
2159 itask = self.get_task(point, tdef.name)
2160 if itask is not None:
2161 valid_x_labels.update(itask.state.xtriggers.keys())
2162
2163 invalid = set(xtrigs.keys()) - valid_x_labels
2164
2165 if invalid:
2166 task = quick_relative_id(point, tdef.name)
2167 for xtrig in invalid:
2168 if xtrig != "all":
2169 LOG.warning(
2170 f'{task} does not depend on xtrigger "{xtrig}"')
2171
2172 return {
2173 k: v for k, v in xtrigs.items()
2174 if k in valid_x_labels or k == "all"
2175 }
2176
2177 def _set_outputs_itask(
2178 self,
2179 itask: 'TaskProxy',
2180 outputs: Iterable[str],
2181 ) -> bool:
2182 """Manually set requested outputs on a task proxy and spawn children.
2183
2184 If no outputs were specified and the task has no required outputs to
2185 set, set the "success pathway" outputs in the same way that skip mode
2186 does.
2187
2188 Designated flows should already be merged to the task proxy.
2189
2190 Returns:
2191 True if any outputs were set, else False.
2192
2193 """
2194 no_op = True
2195 outputs = set(outputs)
2196
2197 if not outputs:
2198 outputs = set(
2199 # Set required outputs by default
2200 itask.state.outputs.iter_required_messages()
2201 ) or (
2202 # Set success pathway outputs
2203 get_skip_mode_outputs(itask)
2204 )
2205 else:
2206 # --out=skip sets all the outputs that skip mode would.
2207 skips: Set[str] = set()
2208 if RunMode.SKIP.value in outputs:
2209 # Check for broadcasts to task:
2210 outputs.remove(RunMode.SKIP.value)
2211 bc_mgr = self.task_events_mgr.broadcast_mgr
2212 rtconfig = bc_mgr.get_updated_rtconfig(itask)
2213 skips = get_skip_mode_outputs(itask, rtconfig)
2214 itask.run_mode = RunMode.SKIP
2215 outputs = set(
2216 self._standardise_outputs(itask.point, itask.tdef, outputs)
2217 ).union(skips)
2218
2219 for output in sorted(outputs, key=itask.state.outputs.output_sort_key):
2220 if itask.state.outputs.is_message_complete(output):
2221 LOG.info(f"output {itask.identity}:{output} completed already")
2222 continue
2223 self.task_events_mgr.process_message(
2224 itask, logging.INFO, output, forced=True
2225 )
2226 no_op = False
2227
2228 if not itask.state(TASK_STATUS_WAITING):
2229 # Can't be runahead limited or queued.
2230 itask.state_reset(is_runahead=False, is_queued=False)
2231 self.task_queue_mgr.remove_task(itask)
2232
2233 if no_op:
2234 return False
2235
2236 self.data_store_mgr.delta_task_state(itask)
2237 self.data_store_mgr.delta_task_outputs(itask)
2238 self.workflow_db_mgr.put_update_task_state(itask)
2239 self.workflow_db_mgr.put_update_task_outputs(itask)
2240 self.workflow_db_mgr.process_queued_ops()
2241 return True
2242
2243 def _set_prereqs_itask(
2244 self,
2245 itask: 'TaskProxy',
2246 prereqs: 'Iterable[PrereqTuple]',
2247 xtrigs: 'Dict[str, bool]',
2248 set_all: bool
2249 ) -> None:
2250 """Set prerequisites on a task proxy.
2251
2252 Designated flows should already be merged to the task proxy.
2253 """
2254 # task prerequisites
2255 itask.force_satisfy(prereqs, set_all)
2256 # xtriggers, including "all"
2257 self.xtrigger_mgr.force_satisfy(itask, xtrigs)
2258
2259 def _set_prereqs_tdef(
2260 self,
2261 point: 'PointBase',
2262 taskdef: 'TaskDef',
2263 prereqs: 'Iterable[PrereqTuple]',
2264 xtrigs: 'Dict[str, bool]',
2265 flow_nums: 'FlowNums',
2266 flow_wait: bool,
2267 set_all: bool
2268 ) -> Optional[TaskProxy]:
2269 """Spawn an inactive task and set prerequisites on it."""
2270 itask = self.spawn_task(
2271 taskdef.name, point, flow_nums, flow_wait=flow_wait
2272 )
2273 if itask is None:
2274 return None
2275
2276 self.db_add_new_flow_rows(itask)
2277 self._set_prereqs_itask(itask, prereqs, xtrigs, set_all)
2278 self.add_to_pool(itask)
2279 return itask
2280
2281 def _get_active_flow_nums(self) -> 'FlowNums':
2282 """Return all active flow numbers.
2283
2284 If there are no active flows (e.g. on restarting a completed workflow)
2285 return the most recent active flows.
2286 Or, if there are no flows in the workflow history (e.g. after
2287 `cylc remove`), return flow=1.
2288
2289 """
2290 return (
2291 set().union(*(itask.flow_nums for itask in self.get_tasks()))
2292 or self.workflow_db_mgr.pri_dao.select_latest_flow_nums()
2293 or {1}
2294 )
2295
2296 def queue_or_trigger(self, itask: 'TaskProxy'):
2297 """Handle state, queues, and runahead for a manually triggered task.
2298
2299 Triggering a non-queued task:
2300 - queue it, if the queue is full
2301 - run it, if the queue is not full
2302
2303 Triggering a queued task:
2304 - run it, regardless of the queue limit
2305
2306 If ready, add itask to the tasks_to_trigger_now list.
2307
2308 Assumes the task is in the pool.
2309
2310 Note manual trigger now works by satisfying prerequisites so
2311 this method should only be called for fully satisfied tasks.
2312
2313 """
2314 itask.is_manual_submit = True
2315 itask.reset_try_timers()
2316 self.data_store_mgr.delta_task_prerequisite(itask)
2317
2318 if itask.state_reset(TASK_STATUS_WAITING):
2319 # (could also be unhandled failed)
2320 self.data_store_mgr.delta_task_state(itask)
2321
2322 if not itask.state.is_queued:
2323 # queue it if limiting
2324 active, _ = self.count_active_tasks()
2325 if self.task_queue_mgr.push_task_if_limited(itask, active):
2326 itask.state_reset(is_queued=True)
2327 self.data_store_mgr.delta_task_state(itask)
2328
2329 elif self.task_queue_mgr.remove_task(itask):
2330 # else release it from the queue to run now
2331 itask.state_reset(is_queued=False)
2332 self.data_store_mgr.delta_task_state(itask)
2333
2334 if not itask.state.is_queued:
2335 # If not queued now, record the task as ready to run.
2336 itask.waiting_on_job_prep = True
2337 self.tasks_to_trigger_now.add(itask)
2338
2339 def clock_expire_tasks(self):
2340 """Expire any tasks past their clock-expiry time."""
2341 for itask in self.get_tasks():
2342 if (
2343 # force triggered tasks can not clock-expire
2344 # see proposal point 10:
2345 # https://cylc.github.io/cylc-admin/proposal-optional-output-extension.html#proposal
2346 not itask.is_manual_submit
2347
2348 # only waiting tasks can clock-expire
2349 # see https://github.com/cylc/cylc-flow/issues/6025
2350 # (note retrying tasks will be in the waiting state)
2351 and itask.state(TASK_STATUS_WAITING)
2352
2353 # check if this task is clock expired
2354 and itask.clock_expire()
2355 ):
2356 self.task_queue_mgr.remove_task(itask)
2357 self.task_events_mgr.process_message(
2358 itask,
2359 logging.WARNING,
2360 TASK_OUTPUT_EXPIRED,
2361 )
2362
2363 def task_succeeded(self, id_):
2364 """Return True if task with id_ is in the succeeded state."""
2365 return any(
2366 (
2367 itask.identity == id_
2368 and itask.state(TASK_STATUS_SUCCEEDED)
2369 )
2370 for itask in self.get_tasks()
2371 )
2372
2373 def stop_flow(self, flow_num):
2374 """Stop a given flow from spawning any further.
2375
2376 Remove the flow number from every task in the pool, and remove any task
2377 with no remaining flow numbers if it is not already active.
2378 """
2379 for itask in self.get_tasks():
2380 try:
2381 itask.flow_nums.remove(flow_num)
2382 except KeyError:
2383 continue
2384 else:
2385 if (
2386 not itask.state(
2387 *TASK_STATUSES_ACTIVE, TASK_STATUS_PREPARING)
2388 and not itask.flow_nums
2389 ):
2390 # Don't spawn successor if the task is parentless.
2391 self.remove(itask, "flow stopped")
2392
2393 def log_task_pool(self, log_lvl=logging.DEBUG):
2394 """Log content of task pool, for debugging."""
2395 LOG.log(
2396 log_lvl,
2397 "\n".join(
2398 f"* {itask}" for itask in self.get_tasks()
2399 )
2400 )
2401
2402 def id_match(
2403 self,
2404 ids: Set[TaskTokens],
2405 only_match_pool: bool = False,
2406 ) -> Tuple[Set[TaskTokens], Set[TaskTokens]]:
2407 """Match IDs against active tasks in the pool."""
2408 active_task_ids: Set[TaskTokens] = {
2409 TaskTokens(
2410 cycle=itask.tokens['cycle'],
2411 task=itask.tokens['task'],
2412 task_sel=itask.state.status,
2413 )
2414 for itasks in self.active_tasks.values()
2415 for itask in itasks.values()
2416 }
2417
2418 return id_match(
2419 self.config,
2420 active_task_ids,
2421 ids,
2422 only_match_pool=only_match_pool,
2423 )
2424
2425 def merge_flows(self, itask: TaskProxy, flow_nums: 'FlowNums') -> None:
2426 """Merge flow_nums into itask.flow_nums, for existing itask.
2427
2428 This is required when we try to spawn a task instance that already
2429 exists in the pool (i.e., with the same name and cycle point).
2430
2431 This also performs required spawning / state changing for edge cases.
2432 """
2433 if not flow_nums or (flow_nums == itask.flow_nums):
2434 # Don't do anything if:
2435 # 1. merging from a no-flow task, or
2436 # 2. same flow (no merge needed); can arise
2437 # downstream of an AND trigger (if "A & B => C"
2438 # and A spawns C first, B will find C is already in the pool),
2439 # and via suicide triggers ("A =>!A": A tries to spawn itself).
2440 return
2441
2442 merge_with_no_flow = not itask.flow_nums
2443
2444 itask.merge_flows(flow_nums)
2445 self.data_store_mgr.delta_task_flow_nums(itask)
2446
2447 # Merged tasks get a new row in the db task_states table.
2448 self.db_add_new_flow_rows(itask)
2449
2450 if (
2451 itask.state(*TASK_STATUSES_FINAL)
2452 and not itask.state.outputs.is_complete()
2453 ):
2454 # Re-queue incomplete task to run again in the merged flow.
2455 LOG.info(f"[{itask}] incomplete task absorbed by new flow.")
2456 itask.state_reset(TASK_STATUS_WAITING)
2457 self.queue_task(itask)
2458 self.data_store_mgr.delta_task_state(itask)
2459
2460 elif merge_with_no_flow or itask.flow_wait:
2461 # 2. Retro-spawn on completed outputs and continue as merged flow.
2462 LOG.info(f"[{itask}] spawning on pre-merge outputs")
2463 itask.flow_wait = False
2464 self.spawn_on_all_outputs(itask, completed_only=True)