Skip to content

radical.asyncflow.workflow_manager

WorkflowEngine

WorkflowEngine(backend: Any = None, dry_run: bool = False, implicit_data: bool = True, uid: Optional[str] = None, work_dir: Optional[str] = None)

An asynchronous workflow manager that uses asyncio event loops and coroutines to manage and execute workflow components (blocks and/or tasks) within Directed Acyclic Graph (DAG) or Chain Graph (CG) structures.

This class provides async/await operations and handles task dependencies, input/output data staging, and execution.

Attributes:

Name Type Description
loop AbstractEventLoop

The asyncio event loop (current running loop).

backend

The execution backend used for task execution.

dry_run bool

Indicates whether the engine is in dry-run mode.

Initialize the WorkflowEngine (sync part only).

Note: This is a private constructor. Use WorkflowEngine.create() instead.

Parameters:

Name Type Description Default
backend Any

Execution backend (required, pre-validated)

None
dry_run bool

Whether to run in dry-run mode

False
implicit_data bool

Whether to enable implicit data dependency linking

True
uid Optional[str]

Optional unique identifier for this engine. Defaults to asyncflow.session.{hex8} (UUID-based).

None
work_dir Optional[str]

Working directory for output files (default: cwd)

None
Source code in doc_env/lib/python3.15/site-packages/radical/asyncflow/workflow_manager.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
@typeguard.typechecked
def __init__(
    self,
    backend: Any = None,
    dry_run: bool = False,
    implicit_data: bool = True,
    uid: Optional[str] = None,
    work_dir: Optional[str] = None,
) -> None:
    """Initialize the WorkflowEngine (sync part only).

    Note: This is a private constructor. Use WorkflowEngine.create() instead.

    Args:
        backend: Execution backend (required, pre-validated)
        dry_run: Whether to run in dry-run mode
        implicit_data: Whether to enable implicit data dependency linking
        uid: Optional unique identifier for this engine. Defaults to
            ``asyncflow.session.{hex8}`` (UUID-based).
        work_dir: Working directory for output files (default: cwd)
    """
    # Get the current running loop - assume it exists
    self.loop = get_event_loop_or_raise("WorkflowEngine")

    self.uid = uid or f"asyncflow.session.{uuid.uuid4().hex[:8]}"
    self.work_dir = work_dir or os.getcwd()
    # Per-engine ContextVar avoids cross-engine context leakage in shared coroutines,
    # while asyncio still propagates it across create_task/gather branches.
    self._workflow_id_ctx: ContextVar[str | None] = ContextVar(
        f"asyncflow_workflow_id.{self.uid}", default=None
    )

    # Normalize backend: accept a single backend or a list of backends
    if not isinstance(backend, list):
        backend = [backend]
    self._backends: dict = {}
    # backend name -> (supports implicit, supports explicit) data linking
    self._data_linking: dict[str, tuple[bool, bool]] = {}
    for b in backend:
        self._attach_backend(b)
    self._default_backend_name: str = backend[0].name
    # The data-linking hooks are called on the default backend, so gate them
    # by its capabilities. Read once here, not per task.
    self._links_implicit_data, self._links_explicit_data = self._data_linking[
        self._default_backend_name
    ]

    # Initialize core attributes
    self.running: set[str] = set()
    self.components = {}
    self.resolved = set()
    self.dependencies = {}
    self.dry_run = dry_run
    self.queue = asyncio.Queue()
    self.implicit_data_mode = implicit_data

    # Optimization: Track component state changes
    self._ready_queue = deque()
    # Components whose futures are done, in the order they finished, for the run
    # loop's next pass (see _record_finished), and when it last checked them all
    self._finished: deque[str] = deque()
    self._next_sweep = 0.0
    self._dependents_map = defaultdict(set)
    self._dependency_count = {}
    self._component_change_event = asyncio.Event()

    # Block task registry: uid -> asyncio.Task for running execute_block coroutines
    self._block_asyncio_tasks: dict[str, asyncio.Task] = {}
    # Block member registry: block_uid -> set of component UIDs registered within it
    self._block_members: dict[str, set[str]] = {}
    # Futures of components whose registration task has not finished, which
    # self.components does not hold yet; shutdown cancels them
    self._pending_registrations: set[asyncio.Future] = set()
    # Futures of tasks cancelled while submit was in flight, whose backends are
    # told when it returns
    self._pending_cancels: set[_ComponentFuture] = set()

    self.task_states_map = self.backend.get_task_states_map()

    # Define decorators
    self.block = self._register_decorator(comp_type=BLOCK)
    self.function_task = self._register_decorator(
        comp_type=TASK, task_type=FUNCTION
    )
    self.executable_task = self._register_decorator(
        comp_type=TASK, task_type=EXECUTABLE
    )
    self.prompt_task = self._register_decorator(comp_type=TASK, task_type=PROMPT)

    # Initialize async task references (will be set in _start_async_components)
    self._run_task = None
    self._shutdown_event = asyncio.Event()  # Added shutdown signal
    # The one shutdown every shutdown() call joins, and its first call's argument
    self._shutdown_task: asyncio.Task | None = None
    self._shutdown_skips_backends = False

    # Telemetry (opt-in via start_telemetry(), None = disabled, zero cost)
    self._telemetry = None
    self._tel_make_event = None  # cached to avoid per-call import lookup
    self._tel_events: dict = {}  # cached event classes: name -> class
    self._task_submit_times: dict[str, float] = {}
    self._task_start_times: dict[str, float] = {}

    self._setup_signal_handlers()

backend property

backend

Return the default execution backend.

is_shutting_down property

is_shutting_down: bool

True once shutdown() has been called (by the caller, a signal or an engine error).

It stays True after the shutdown has finished: an engine is never restarted.

telemetry property

telemetry: TelemetryManager | None

The TelemetryManager from the latest start_telemetry() call, or None.

This is the manager the engine emits its events into.

start_telemetry async

start_telemetry(resource_poll_interval: float = 5.0, checkpoint_interval: float | None = None, checkpoint_path: str | None = None, span_processors: list | None = None, metric_readers: list | None = None, resource: object | None = None) -> Any

Create and start a RHAPSODY TelemetryManager for this workflow engine.

Mirrors Session.start_telemetry(): creates the manager, wires all registered backends (silently skipping LocalExecutionBackend and NoopExecutionBackend which have no adapter), starts the async dispatch loop, and returns the manager.

Parameters:

Name Type Description Default
resource_poll_interval float

Seconds between resource metric polls (default: 5.0).

5.0
checkpoint_interval float | None

Seconds between periodic metric+span flushes to disk. None = no periodic flush (file still written at stop).

None
checkpoint_path str | None

Directory for the JSONL checkpoint file. None = no file output.

None
span_processors list | None

Optional list of OTel SpanProcessor instances added to RHAPSODY's TracerProvider alongside the internal SpanBuffer. Callers own exporter construction.

None
metric_readers list | None

Optional list of OTel MetricReader instances added to RHAPSODY's MeterProvider alongside InMemoryMetricReader.

None
resource object | None

Optional opentelemetry.sdk.resources.Resource. When None, Resource.create() reads OTEL_SERVICE_NAME from the environment automatically.

None

Returns:

Type Description
Any

The active TelemetryManager instance.

Source code in doc_env/lib/python3.15/site-packages/radical/asyncflow/workflow_manager.py
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
async def start_telemetry(
    self,
    resource_poll_interval: float = 5.0,
    checkpoint_interval: float | None = None,
    checkpoint_path: str | None = None,
    span_processors: list | None = None,
    metric_readers: list | None = None,
    resource: object | None = None,
) -> Any:
    """Create and start a RHAPSODY TelemetryManager for this workflow engine.

    Mirrors Session.start_telemetry(): creates the manager, wires all
    registered backends (silently skipping LocalExecutionBackend and
    NoopExecutionBackend which have no adapter), starts the async dispatch
    loop, and returns the manager.

    Args:
        resource_poll_interval: Seconds between resource metric polls (default: 5.0).
        checkpoint_interval:    Seconds between periodic metric+span flushes to disk.
                                None = no periodic flush (file still written at stop).
        checkpoint_path:        Directory for the JSONL checkpoint file.
                                None = no file output.
        span_processors:        Optional list of OTel SpanProcessor instances added to
                                RHAPSODY's TracerProvider alongside the internal
                                SpanBuffer. Callers own exporter construction.
        metric_readers:         Optional list of OTel MetricReader instances added to
                                RHAPSODY's MeterProvider alongside InMemoryMetricReader.
        resource:               Optional ``opentelemetry.sdk.resources.Resource``.
                                When None, ``Resource.create()`` reads
                                ``OTEL_SERVICE_NAME`` from the environment automatically.

    Returns:
        The active TelemetryManager instance.
    """
    from rhapsody.telemetry.manager import TelemetryManager  # noqa: PLC0415

    self._telemetry = TelemetryManager(
        session_id=self.uid,
        checkpoint_interval=checkpoint_interval,
        checkpoint_path=checkpoint_path,
        span_processors=span_processors,
        metric_readers=metric_readers,
        resource=resource,
    )

    for backend in self._backends.values():
        self._telemetry.attach_backend(
            backend,
            session_id=self.uid,
            backend_name=backend.name,
            interval=resource_poll_interval,
        )

    await self._telemetry.start()

    self._telemetry.register_span_enricher(
        lambda event: (
            {"asyncflow.workflow_id": event.attributes["asyncflow.workflow_id"]}
            if isinstance(event.attributes, dict)
            and "asyncflow.workflow_id" in event.attributes
            else {}
        )
    )

    from rhapsody.telemetry.events import (  # noqa: PLC0415
        TaskCanceled,
        TaskCompleted,
        TaskCreated,
        TaskFailed,
        TaskQueued,
        TaskStarted,
        TaskSubmitted,
        define_event,
        make_event,
    )

    # asyncflow.TaskResolved is DAG-specific — not a RHAPSODY core event.
    # Defined here with define_event so RHAPSODY stays unaware of DAG semantics.
    TaskResolved = define_event("asyncflow.TaskResolved")

    self._tel_make_event = make_event
    self._tel_events = {
        "TaskCreated": TaskCreated,
        "TaskQueued": TaskQueued,
        "asyncflow.TaskResolved": TaskResolved,
        "TaskSubmitted": TaskSubmitted,
        "TaskStarted": TaskStarted,
        "TaskCompleted": TaskCompleted,
        "TaskFailed": TaskFailed,
        "TaskCanceled": TaskCanceled,
    }

    return self._telemetry

workflow_scope async

workflow_scope(workflow_id: str | None = None) -> AsyncIterator[str]

Tag all tasks registered inside this scope with a shared workflow_id.

Also creates an OTel workflow span (when telemetry is active) so that task spans registered inside become structural children in the trace hierarchy.

Parameters:

Name Type Description Default
workflow_id str | None

Explicit id for this workflow instance. If omitted, a short UUID is generated automatically.

None

Yields:

Type Description
AsyncIterator[str]

The workflow_id string in use.

Source code in doc_env/lib/python3.15/site-packages/radical/asyncflow/workflow_manager.py
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
@asynccontextmanager
async def workflow_scope(
    self, workflow_id: str | None = None
) -> AsyncIterator[str]:
    """Tag all tasks registered inside this scope with a shared workflow_id.

    Also creates an OTel workflow span (when telemetry is active) so that task spans
    registered inside become structural children in the trace hierarchy.

    Args:
        workflow_id: Explicit id for this workflow instance.
            If omitted, a short UUID is generated automatically.

    Yields:
        The workflow_id string in use.
    """
    wid = workflow_id or f"wf-{uuid.uuid4().hex[:8]}"
    token = self._workflow_id_ctx.set(wid)
    try:
        scope = (
            self._telemetry.span_scope("workflow", {"asyncflow.workflow_id": wid})
            if self._telemetry is not None
            else nullcontext()
        )
        with scope:
            yield wid
    finally:
        self._workflow_id_ctx.reset(token)

create async classmethod

create(backend: Any = None, dry_run: bool = False, implicit_data: bool = True, uid: Optional[str] = None, work_dir: Optional[str] = None) -> 'WorkflowEngine'

Factory method to create and initialize a WorkflowEngine.

Parameters:

Name Type Description Default
backend Any

Execution backend. If None and dry_run=True, uses NoopExecutionBackend

None
dry_run bool

Whether to run in dry-run mode

False
implicit_data bool

Whether to enable implicit data dependency linking

True
uid Optional[str]

Optional unique identifier for this engine. Defaults to asyncflow.session.{hex8} (UUID-based).

None
work_dir Optional[str]

Working directory for output files (default: cwd)

None

Returns:

Name Type Description
WorkflowEngine 'WorkflowEngine'

Fully initialized workflow engine

Example

engine = await WorkflowEngine.create(dry_run=True)

Source code in doc_env/lib/python3.15/site-packages/radical/asyncflow/workflow_manager.py
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
@classmethod
async def create(
    cls,
    backend: Any = None,
    dry_run: bool = False,
    implicit_data: bool = True,
    uid: Optional[str] = None,
    work_dir: Optional[str] = None,
) -> "WorkflowEngine":
    """Factory method to create and initialize a WorkflowEngine.

    Args:
        backend: Execution backend. If None and dry_run=True,
                 uses NoopExecutionBackend
        dry_run: Whether to run in dry-run mode
        implicit_data: Whether to enable implicit data dependency linking
        uid: Optional unique identifier for this engine. Defaults to
            ``asyncflow.session.{hex8}`` (UUID-based).
        work_dir: Working directory for output files (default: cwd)

    Returns:
        WorkflowEngine: Fully initialized workflow engine

    Example:
        engine = await WorkflowEngine.create(dry_run=True)
    """
    # Setup and validate backend first
    validated_backend = await cls._setup_execution_backend(backend, dry_run)

    # Create instance with validated backend
    instance = cls(
        backend=validated_backend,
        dry_run=dry_run,
        implicit_data=implicit_data,
        uid=uid,
        work_dir=work_dir,
    )

    # Initialize async components
    await instance._start_async_components()

    return instance

run async

run()

Manages asynchronous execution of workflow components.

Continuously monitors and manages workflow components, handling their dependencies and execution states. Performs dependency resolution and prepares components for execution when their dependencies are satisfied.

Workflow Process
  1. Monitors unresolved components
  2. Checks dependency resolution status
  3. Prepares resolved components for execution
  4. Handles data staging between components
  5. Submits ready components to execution

Raises:

Type Description
CancelledError

If the coroutine is cancelled during execution

State Management
  • unresolved (set): Component UIDs with pending dependencies
  • resolved (set): Component UIDs with satisfied dependencies
  • running (list): Currently executing component UIDs
  • dependencies (dict): Maps component UIDs to dependency info
  • components (dict): Maps UIDs to component descriptions and futures
  • queue (asyncio.Queue): Execution queue for ready components
Note
  • Runs indefinitely until cancelled or shutdown is signaled
  • Uses sleep intervals to prevent busy-waiting
  • Handles both implicit and explicit data dependencies
  • Trigger internal shutdown on loop failure
Source code in doc_env/lib/python3.15/site-packages/radical/asyncflow/workflow_manager.py
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
async def run(self):
    """Manages asynchronous execution of workflow components.

    Continuously monitors and manages workflow components, handling their
    dependencies and execution states. Performs dependency resolution and
    prepares components for execution when their dependencies are satisfied.

    Workflow Process:
        1. Monitors unresolved components
        2. Checks dependency resolution status
        3. Prepares resolved components for execution
        4. Handles data staging between components
        5. Submits ready components to execution

    Raises:
        asyncio.CancelledError: If the coroutine is cancelled during execution

    State Management:
        - unresolved (set): Component UIDs with pending dependencies
        - resolved (set): Component UIDs with satisfied dependencies
        - running (list): Currently executing component UIDs
        - dependencies (dict): Maps component UIDs to dependency info
        - components (dict): Maps UIDs to component descriptions and futures
        - queue (asyncio.Queue): Execution queue for ready components

    Note:
        - Runs indefinitely until cancelled or shutdown is signaled
        - Uses sleep intervals to prevent busy-waiting
        - Handles both implicit and explicit data dependencies
        - Trigger internal shutdown on loop failure
    """
    while not self._shutdown_event.is_set():
        try:
            to_submit = []

            # Process ready components, for _PREPARE_SLICE at most: the rest goes
            # in the next pass, after this slice is submitted. Every component
            # counts, also one that fails or is cancelled here (a cascade)
            slice_end = time.monotonic() + _PREPARE_SLICE
            prepared = 0
            sliced = False
            while self._ready_queue and not self._shutdown_event.is_set():
                if prepared and time.monotonic() >= slice_end:
                    sliced = True
                    break
                prepared += 1
                comp_uid = self._ready_queue.popleft()

                # Skip if already processed
                if comp_uid in self.resolved or comp_uid in self.running:
                    continue

                # Check if future is already done (could be cancelled/failed)
                if self.components[comp_uid]["future"].done():
                    self.resolved.add(comp_uid)
                    self._notify_dependents(comp_uid)
                    continue

                # Verify dependencies are still met
                dependencies = self.dependencies[comp_uid]
                dep_futures = [
                    self.components[dep["uid"]]["future"] for dep in dependencies
                ]

                failed_deps = []
                cancelled_deps = []

                for fut in dep_futures:
                    if fut.cancelled():
                        cancelled_deps.append(fut)
                    elif fut.exception() is not None:
                        failed_deps.append(fut.exception())

                # Handle dependency issues
                if cancelled_deps or failed_deps:
                    comp_desc = self.components[comp_uid]["description"]

                    if cancelled_deps:
                        logger.info(
                            f"Cancelling {comp_desc['name']} "
                            "due to cancelled dependencies"
                        )
                        self.handle_component_cancellation(
                            comp_desc, self.components[comp_uid]["future"]
                        )
                    else:  # failed_deps
                        chained_exception = (
                            self._create_dependency_failure_exception(
                                comp_desc, failed_deps
                            )
                        )
                        self.handle_component_failure(
                            comp_desc,
                            self.components[comp_uid]["future"],
                            chained_exception,
                        )

                    # Common cleanup
                    self.resolved.add(comp_uid)
                    self._notify_dependents(comp_uid)
                    continue

                # Handle data dependencies for tasks
                comp_desc = self.components[comp_uid]["description"]
                if self.components[comp_uid]["type"] == TASK:
                    # Data linking runs only on backends that declare it;
                    # implicit and explicit linking are independent.
                    if self._links_implicit_data and self.implicit_data_mode:
                        for dep in dependencies:
                            dep_desc = self.components[dep["uid"]]["description"]

                            # Link implicit data dependencies
                            if not dep_desc["metadata"].get("output_files"):
                                logger.debug(
                                    "Linking implicit file(s): from "
                                    f"{dep_desc['name']} to {comp_desc['name']}"
                                )
                                self.backend.link_implicit_data_deps(
                                    dep_desc, comp_desc
                                )

                    if self._links_explicit_data:
                        explicit_files_to_stage = []

                        for dep in dependencies:
                            dep_desc = self.components[dep["uid"]]["description"]

                            # Link explicit data dependencies
                            for output_file in dep_desc["metadata"]["output_files"]:
                                if (
                                    output_file
                                    in comp_desc["metadata"]["input_files"]
                                ):
                                    logger.debug(
                                        f"Linking explicit file ({output_file}) "
                                        f"from {dep_desc['name']} "
                                        f"to {comp_desc['name']}"
                                    )
                                    data_dep = self.backend.link_explicit_data_deps(
                                        src_task=dep_desc,
                                        dst_task=comp_desc,
                                        file_name=output_file,
                                    )
                                    explicit_files_to_stage.append(data_dep)

                        # Input staging data dependencies
                        dependency_output_files = self._get_dependency_output_files(
                            dependencies
                        )
                        staged_targets = {
                            Path(item["target"]).name
                            for item in explicit_files_to_stage
                        }

                        for input_file in comp_desc["metadata"]["input_files"]:
                            input_basename = Path(input_file).name
                            if (
                                input_basename not in staged_targets
                                and input_basename not in dependency_output_files
                            ):
                                logger.debug(
                                    f"Staging {input_file} "
                                    f"to {comp_desc['name']} work dir"
                                )
                                data_dep = self.backend.link_explicit_data_deps(
                                    src_task=None,
                                    dst_task=comp_desc,
                                    file_name=input_basename,
                                    file_path=input_file,
                                )
                                explicit_files_to_stage.append(data_dep)

                try:
                    # Update the component description with resolved values
                    (
                        comp_desc["args"],
                        comp_desc["kwargs"],
                    ) = await self._extract_dependency_values(comp_desc)
                except Exception as e:
                    logger.error(
                        f"Failed to resolve future for {comp_desc['name']}: {e}"
                    )
                    self.handle_component_failure(
                        comp_desc, self.components[comp_uid]["future"], e
                    )
                    self.resolved.add(comp_uid)
                    self._notify_dependents(comp_uid)
                    continue
                except asyncio.CancelledError:
                    # Only a cancelled future can raise this here:
                    # _extract_dependency_values never suspends, so the run
                    # task itself cannot be cancelled inside it. Cancel the
                    # dependent instead of letting it stop the run loop.
                    logger.info(f"Cancelling {comp_desc['name']}")
                    self.handle_component_cancellation(
                        comp_desc, self.components[comp_uid]["future"]
                    )
                    self.resolved.add(comp_uid)
                    self._notify_dependents(comp_uid)
                    continue

                to_submit.append(comp_desc)
                # Now, not after submit: it tells cancel() that submit has this
                # task, which is not in running until submit returns.
                self.resolved.add(comp_uid)
                res_deps = [dep["name"] for dep in dependencies]
                msg = f"Ready to submit: {comp_desc['name']}"
                msg += f" with resolved dependencies: {res_deps}"
                logger.debug(msg)

                if self.components[comp_uid]["type"] == TASK:
                    self._emit(
                        "TaskQueued",
                        task_id=comp_uid,
                        workflow_id=comp_desc.get("workflow_id"),
                        attributes={
                            "executable": comp_desc["_tel_executable"],
                            "task_type": comp_desc["_tel_task_type"],
                        },
                    )

            # Submit ready components
            if to_submit:
                await self.submit(to_submit)
                for comp_desc in to_submit:
                    comp_uid = comp_desc["uid"]
                    self.running.add(comp_uid)
                    self._watch_running(comp_uid)
                # Every backend knows these tasks now
                while self._pending_cancels:
                    self._pending_cancels.pop()._cancel_on_backend()

            # The running components that finished since the last pass, in the
            # order they finished: not a check of every running one, except once
            # in a while (_sweep_running)
            if time.monotonic() >= self._next_sweep:
                self._sweep_running()
            completed_components = []
            finished = self._finished
            while finished:
                comp_uid = finished.popleft()
                if comp_uid in self.running:
                    self.running.discard(comp_uid)
                    completed_components.append(comp_uid)

            # Notify dependents of completed components
            for comp_uid in completed_components:
                self._notify_dependents(comp_uid)

            # If nothing is ready/running, wait for changes or shutdown
            if not self._ready_queue and not to_submit and not completed_components:
                try:
                    # Create tasks for event waiting
                    event_task = asyncio.create_task(
                        self._component_change_event.wait(),
                        name="component-event-task",
                    )
                    shutdown_task = asyncio.create_task(
                        self._shutdown_event.wait(), name="shutdown-event-task"
                    )

                    done, pending = await asyncio.wait(
                        [event_task, shutdown_task],
                        return_when=asyncio.FIRST_COMPLETED,
                        timeout=1.0,
                    )
                    # Cancel any pending tasks to clean up
                    for task in pending:
                        task.cancel()
                    # Clear component change event if it was set
                    if event_task in done:
                        self._component_change_event.clear()
                except asyncio.CancelledError:
                    # If we get cancelled, make sure to clean up our tasks
                    for task in [event_task, shutdown_task]:
                        if not task.done():
                            task.cancel()
                    raise
            elif sliced:
                # The slice ended with more to prepare: let the others run first
                await asyncio.sleep(0)
            else:
                # As before: completions in the meantime join the next batch
                await asyncio.sleep(0.01)

        except asyncio.CancelledError:
            logger.debug("Run component stopped")
            break
        except Exception as e:
            logger.exception(f"Error in run loop: {e}")
            await self._handle_shutdown_signal(signal.SIGUSR1, source="internal")
            break

submit async

submit(objects: list) -> None

Manages asynchronous submission of tasks/blocks to the execution backend.

Retrieves and submit ready tasks and blocks for execution. Separates incoming objects into tasks and blocks based on their UID pattern, and dispatches each to the appropriate backend method.

Submission Process
  1. Receive batch of objects
  2. Filters objects into tasks and blocks
  3. Submits tasks via backend.submit_tasks
  4. Submits blocks via _submit_blocks asynchronously

Parameters:

Name Type Description Default
objects list

Tasks and blocks are identified by uid field content

required

Returns:

Type Description
None

None

Raises:

Type Description
Exception

If an unexpected error occurs during submission

Source code in doc_env/lib/python3.15/site-packages/radical/asyncflow/workflow_manager.py
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
async def submit(self, objects: list) -> None:
    """Manages asynchronous submission of tasks/blocks to the execution backend.

    Retrieves and submit ready tasks and blocks for execution. Separates incoming
    objects into tasks and blocks based on their UID pattern, and dispatches each
    to the appropriate backend method.

    Submission Process:
        1. Receive batch of objects
        2. Filters objects into tasks and blocks
        3. Submits tasks via `backend.submit_tasks`
        4. Submits blocks via `_submit_blocks` asynchronously

    Args:
        objects: Tasks and blocks are identified by `uid` field content

    Returns:
        None

    Raises:
        Exception: If an unexpected error occurs during submission
    """
    try:
        # Separate tasks and blocks
        tasks = [t for t in objects if t and BLOCK not in t["uid"]]
        blocks = [b for b in objects if b and TASK not in b["uid"]]

        logger.info(f"Submitting {len(objects)} tasks/blocks for execution")
        logger.debug(f"Submitting: {[b['name'] for b in objects]}")

        if tasks:
            if self._telemetry is not None:
                now = time.time()
                for t in tasks:
                    self._task_submit_times[t["uid"]] = now
                    self._emit(
                        "TaskSubmitted",
                        task_id=t["uid"],
                        workflow_id=t.get("workflow_id"),
                        event_time=now,
                        attributes={
                            "executable": t["_tel_executable"],
                            "task_type": t["_tel_task_type"],
                        },
                    )

            if not any(t.get("target_backend") for t in tasks):
                # Fast path: all tasks go to the default backend
                await self.backend.submit_tasks(tasks)
            else:
                by_backend: dict = {}
                for t in tasks:
                    by_backend.setdefault(
                        t.get("target_backend") or self._default_backend_name, []
                    ).append(t)
                # Submit to all target backends in parallel
                await asyncio.gather(
                    *(
                        self._backends[b_name].submit_tasks(b_tasks)
                        for b_name, b_tasks in by_backend.items()
                    )
                )
        if blocks:
            await self._submit_blocks(blocks)
    except Exception as e:
        logger.exception(f"Error in submit component: {e}")
        raise

execute_block async

execute_block(block_fut: Future, func: Callable, *args: Any, **kwargs: Any) -> None

Executes a block function and sets its result on the associated future.

Calls the given function with provided args, awaiting it if it's a coroutine, or running it in the executor otherwise. On completion, updates the block_fut with the result or exception. Does not call the function if block_fut is already done.

Parameters:

Name Type Description Default
block_fut Future

Future to store the result or exception.

required
func Callable

Function or coroutine function to execute.

required
*args Any

Positional arguments to pass to the function.

()
**kwargs Any

Keyword arguments to pass to the function.

{}

Returns:

Type Description
None

None

Source code in doc_env/lib/python3.15/site-packages/radical/asyncflow/workflow_manager.py
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
async def execute_block(
    self, block_fut: asyncio.Future, func: Callable, *args: Any, **kwargs: Any
) -> None:
    """Executes a block function and sets its result on the associated future.

    Calls the given function with provided args, awaiting it if it's a coroutine,
    or running it in the executor otherwise. On completion, updates the `block_fut`
    with the result or exception. Does not call the function if `block_fut` is
    already done.

    Args:
        block_fut (asyncio.Future): Future to store the result or exception.
        func (Callable): Function or coroutine function to execute.
        *args: Positional arguments to pass to the function.
        **kwargs: Keyword arguments to pass to the function.

    Returns:
        None
    """

    # Done before this first step: cancelled while submit was suspended on the
    # tasks of the batch, or after create_task. The done callback that cancels
    # this task runs too late to stop the body from starting.
    if block_fut.done():
        return

    block_uid = block_fut.block["uid"]
    token = self._workflow_id_ctx.set(block_uid)
    try:
        scope = (
            self._telemetry.span_scope(
                "block", {"asyncflow.workflow_id": block_uid}
            )
            if self._telemetry is not None
            else nullcontext()
        )
        with scope:
            result = await func(*args, **kwargs)
        if not block_fut.done():
            self.handle_component_success(
                {"uid": block_uid, "return_value": result}, block_fut
            )
    except Exception as e:
        if not block_fut.done():
            self.handle_component_failure(block_fut.block, block_fut, e)
    except asyncio.CancelledError:
        # The block body raised CancelledError, e.g. by awaiting a member task
        # that was cancelled. Cancel the block so it and its dependents don't
        # hang. When the engine itself cancelled the block (block_fut.cancel()
        # or shutdown), block_fut is already done and this is a no-op.
        self.handle_component_cancellation(block_fut.block, block_fut)
        raise
    finally:
        self._workflow_id_ctx.reset(token)

handle_component_success

handle_component_success(component: dict, component_fut: Future) -> None

Handles successful completion of a component (task or block).

Sets the result of the component's future: the function's return value for function tasks and blocks, or stdout for executable and prompt tasks. Logs a warning if the future is already resolved.

Parameters:

Name Type Description Default
component dict

Completed component descriptor containing - 'uid' (str): Unique component identifier - 'return_value' / 'stdout': Result of the execution

required
component_fut Future

Future to set the result on.

required
Source code in doc_env/lib/python3.15/site-packages/radical/asyncflow/workflow_manager.py
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
def handle_component_success(
    self, component: dict, component_fut: asyncio.Future
) -> None:
    """Handles successful completion of a component (task or block).

    Sets the result of the component's future: the function's return value for
    function tasks and blocks, or stdout for executable and prompt tasks. Logs a
    warning if the future is already resolved.

    Args:
        component (dict): Completed component descriptor containing
            - 'uid' (str): Unique component identifier
            - 'return_value' / 'stdout': Result of the execution
        component_fut (asyncio.Future): Future to set the result on.
    """
    internal_component = self.components[component["uid"]]["description"]

    if not component_fut.done():
        if internal_component[FUNCTION]:
            component_fut.set_result(component["return_value"])
        else:
            component_fut.set_result(component["stdout"])
        component_fut.state = "DONE"
        self._record_finished(component["uid"])
    else:
        logger.warning(
            "Attempted to handle an already finished component "
            f'"{component["uid"]}"'
        )
        # Set outside the engine: the run loop has not seen this end yet
        self._record_finished(component["uid"])

handle_component_failure

handle_component_failure(component: dict, component_fut: Future, override_error_message: Union[str, Exception] = None) -> None

Handles failure of a component (task or block) and sets the exception.

Marks the component's future as failed by setting an exception derived from either a provided override error or the component's own recorded error/stderr. Logs a warning if the future is already resolved.

Parameters:

Name Type Description Default
component dict

Dictionary with component details, including: - 'uid' (str): Unique component identifier - 'exception' or 'stderr': Error information from execution

required
component_fut Future

Future to mark as failed.

required
override_error_message Union[str, Exception]

Custom error message or exception to set instead of the recorded error.

None

Returns:

Type Description
None

None

Source code in doc_env/lib/python3.15/site-packages/radical/asyncflow/workflow_manager.py
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
def handle_component_failure(
    self,
    component: dict,
    component_fut: asyncio.Future,
    override_error_message: Union[str, Exception] = None,
) -> None:
    """Handles failure of a component (task or block) and sets the exception.

    Marks the component's future as failed by setting an exception derived from
    either a provided override error or the component's own recorded
    error/stderr. Logs a warning if the future is already resolved.

    Args:
        component (dict): Dictionary with component details, including:
            - 'uid' (str): Unique component identifier
            - 'exception' or 'stderr': Error information from execution
        component_fut (asyncio.Future): Future to mark as failed.
        override_error_message (Union[str, Exception], optional): Custom
            error message or exception to set instead of the recorded error.

    Returns:
        None
    """
    if component_fut.done():
        logger.warning(
            f'Attempted to handle an already failed component "{component["uid"]}"'
        )
        # Set outside the engine: the run loop has not seen this end yet
        self._record_finished(component["uid"])
        return

    # Determine the appropriate exception to set
    if override_error_message is not None:
        # If it's already an exception (like DependencyFailureError),
        # use it directly
        if isinstance(override_error_message, Exception):
            exception = override_error_message
        else:
            # If it's a string, wrap it in RuntimeError
            exception = RuntimeError(str(override_error_message))
    else:
        # Use the component's original exception or stderr
        original_error = (
            component.get("exception")
            or component.get("stderr")
            or "failed with unknown error"
        )

        # Ensure we have an Exception object
        if isinstance(original_error, Exception):
            exception = original_error
        else:
            # If it's a string (stderr) or any other type, wrap it in RuntimeError
            exception = RuntimeError(str(original_error))

    component_fut.set_exception(exception)
    component_fut.state = "FAILED"
    self._record_finished(component["uid"])

handle_component_cancellation

handle_component_cancellation(component: dict, component_fut: Future)

Handle cancellation of a component (task or block).

Source code in doc_env/lib/python3.15/site-packages/radical/asyncflow/workflow_manager.py
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
def handle_component_cancellation(
    self, component: dict, component_fut: asyncio.Future
):
    """Handle cancellation of a component (task or block)."""
    if component_fut.done():
        # Already resolved: nothing to do, but if it was set outside the engine,
        # the run loop has not seen this end yet
        self._record_finished(component["uid"])
        return

    # cancel() would send a task running on the backend back to the backend,
    # which reports here. A future that the engine did not create has only
    # cancel().
    cancel = getattr(component_fut, "_cancel_locally", component_fut.cancel)
    result = cancel()
    component_fut.state = "CANCELLED"
    if component_fut.done():
        self._record_finished(component["uid"])
    return result

task_callbacks

task_callbacks(task: Any, state: str, service_callback: Optional[Callable] = None) -> None

Processes task state changes and invokes appropriate handlers.

Handles state transitions for tasks, updates their futures, and triggers relevant state-specific handlers. Supports optional service-specific callbacks for extended functionality.

Parameters:

Name Type Description Default
task Union[dict, object]

Task object or dictionary containing task state information.

required
state str

New state of the task.

required
service_callback Optional[Callable]

Callback function for service tasks. Must be daemon-threaded to avoid blocking. Defaults to None.

None

Returns:

Type Description
None

None

State Transitions
  • DONE: Calls handle_component_success
  • RUNNING: Marks future as running
  • CANCELED: Cancels the future
  • FAILED: Calls handle_component_failure
Logging
  • Debug: Non-relevant state received
  • Info: Task state changes
  • Warning: Unknown task received
Example

::

1
2
3
4
5
6
7
8
def service_ready_callback(future, task, state):
    def wait_and_set():
        try:
            # Synchronous operation
            future.set_result(info)
        except Exception as e:
            future.set_exception(e)
    threading.Thread(target=wait_and_set, daemon=True).start()
Source code in doc_env/lib/python3.15/site-packages/radical/asyncflow/workflow_manager.py
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
@typeguard.typechecked
def task_callbacks(
    self, task: Any, state: str, service_callback: Optional[Callable] = None
) -> None:
    """Processes task state changes and invokes appropriate handlers.

    Handles state transitions for tasks, updates their futures, and triggers
    relevant state-specific handlers. Supports optional service-specific
    callbacks for extended functionality.

    Args:
        task (Union[dict, object]): Task object or dictionary containing task
            state information.
        state (str): New state of the task.
        service_callback (Optional[Callable], optional): Callback function
            for service tasks. Must be daemon-threaded to avoid blocking.
            Defaults to None.

    Returns:
        None

    State Transitions:
        - DONE: Calls handle_component_success
        - RUNNING: Marks future as running
        - CANCELED: Cancels the future
        - FAILED: Calls handle_component_failure

    Logging:
        - Debug: Non-relevant state received
        - Info: Task state changes
        - Warning: Unknown task received

    Example:
        ::

            def service_ready_callback(future, task, state):
                def wait_and_set():
                    try:
                        # Synchronous operation
                        future.set_result(info)
                    except Exception as e:
                        future.set_exception(e)
                threading.Thread(target=wait_and_set, daemon=True).start()
    """
    if (
        state not in self.task_states_map.terminal_states
        and state != self.task_states_map.RUNNING
    ):
        logger.debug(f"Non-relevant task state received: {state}. Skipping state.")
        return

    task_obj = task
    if isinstance(task, dict):
        task_dct = task
    else:
        task_dct = task.as_dict()

    if task_dct["uid"] not in self.components:
        logger.warning(
            f"Received an unknown task and will skip it: {task_dct['uid']}"
        )
        return

    comp = self.components[task_dct["uid"]]
    task_fut = comp["future"]
    comp_desc = comp["description"]
    logger.info(f"{task_dct['uid']} is in {state} state")

    if service_callback:
        # service tasks are marked done by a backend specific
        # mechanism that are provided during the callbacks only
        service_callback(task_fut, task_obj, state)

    # A task the backend has finished has nothing left to cancel there
    if self._pending_cancels and state != self.task_states_map.RUNNING:
        self._pending_cancels.discard(task_fut)

    uid = task_dct["uid"]

    tel_attrs = {
        "executable": comp_desc["_tel_executable"],
        "task_type": comp_desc["_tel_task_type"],
    }

    if state == self.task_states_map.DONE:
        self.handle_component_success(task_dct, task_fut)
        if self._telemetry is not None:
            now = time.time()
            start = self._task_start_times.pop(
                uid, self._task_submit_times.get(uid, now)
            )
            self._task_submit_times.pop(uid, None)
            self._emit(
                "TaskCompleted",
                task_id=uid,
                workflow_id=task_dct.get("workflow_id"),
                event_time=now,
                duration_seconds=now - start,
                attributes=tel_attrs,
            )
    elif state == self.task_states_map.RUNNING:
        # NOTE: with asyncio future the running state is
        # implicit: when a coroutine that awaits the future
        # is scheduled and started by the event loop, that's
        # when the "work" is running.
        # A task cancelled during submit keeps its CANCELLED state.
        if not task_fut.done():
            task_fut.state = "RUNNING"
        if self._telemetry is not None:
            now = time.time()
            self._task_start_times[uid] = now
            self._emit(
                "TaskStarted",
                task_id=uid,
                workflow_id=task_dct.get("workflow_id"),
                event_time=now,
                attributes=tel_attrs,
            )
    elif state == self.task_states_map.CANCELED:
        self.handle_component_cancellation(task_dct, task_fut)
        if self._telemetry is not None:
            now = time.time()
            start = self._task_start_times.pop(
                uid, self._task_submit_times.get(uid, now)
            )
            self._task_submit_times.pop(uid, None)
            self._emit(
                "TaskCanceled",
                task_id=uid,
                workflow_id=task_dct.get("workflow_id"),
                event_time=now,
                duration_seconds=now - start,
                attributes=tel_attrs,
            )
    elif state == self.task_states_map.FAILED:
        self.handle_component_failure(task_dct, task_fut)
        if self._telemetry is not None:
            now = time.time()
            start = self._task_start_times.pop(
                uid, self._task_submit_times.get(uid, now)
            )
            self._task_submit_times.pop(uid, None)
            # TELEMETRY-LIMITATION(L9): TaskFailed always carries error_type="unknown",
            # even when the task has an exception (for example the TimeoutError of a
            # timed-out inference task), so failure causes are invisible in this event.
            # RHAPSODY's Session uses the exception's type. Inference timeouts are still
            # marked by error.type on the task span.
            # Why not now: existing behaviour, reported and not changed here.
            # Planned: use the type of the exception set on the task future.
            # See the RHAPSODY docs, telemetry/reference.md#known-limitations.
            self._emit(
                "TaskFailed",
                task_id=uid,
                workflow_id=task_dct.get("workflow_id"),
                event_time=now,
                duration_seconds=now - start,
                error_type="unknown",
                attributes=tel_attrs,
            )

shutdown async

shutdown(skip_execution_backend: bool = False) -> None

Shut the engine down, or wait for the shutdown already running.

The engine shuts down once. The first call starts the shutdown; every later call waits for that same shutdown and returns when it has finished, also when a signal or an engine error started it (those start it without waiting). A call after it has finished returns at once.

Every task and block that has not finished when the shutdown starts is cancelled right away, inside the call, so none can still complete in between.

The first call's skip_execution_backend decides. A later call with a different value is logged and ignored: backends kept by skip_execution_backend=True stay running, and are shut down with their own shutdown().

Cancelling a caller stops only that caller's wait (it gets asyncio.CancelledError); the shutdown itself continues. If the shutdown fails or is cancelled, every caller waiting for it gets that outcome, it is logged at ERROR, and the next call starts it again. If other code cancels the shutdown itself, the waiters get asyncio.CancelledError although they were not cancelled (asyncio.current_task().cancelling() == 0).

Parameters:

Name Type Description Default
skip_execution_backend bool

If True, skips the shutdown of the execution backends (first call only).

False

Raises:

Type Description
RuntimeError

If called from an event loop other than the engine's. From another thread use asyncio.run_coroutine_threadsafe(engine.shutdown(), engine.loop).

Source code in doc_env/lib/python3.15/site-packages/radical/asyncflow/workflow_manager.py
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
async def shutdown(self, skip_execution_backend: bool = False) -> None:
    """Shut the engine down, or wait for the shutdown already running.

    The engine shuts down once. The first call starts the shutdown; every later
    call waits for that same shutdown and returns when it has finished, also when
    a signal or an engine error started it (those start it without waiting). A
    call after it has finished returns at once.

    Every task and block that has not finished when the shutdown starts is
    cancelled right away, inside the call, so none can still complete in between.

    The first call's ``skip_execution_backend`` decides. A later call with a
    different value is logged and ignored: backends kept by
    ``skip_execution_backend=True`` stay running, and are shut down with their own
    ``shutdown()``.

    Cancelling a caller stops only that caller's wait (it gets
    ``asyncio.CancelledError``); the shutdown itself continues. If the shutdown
    fails or is cancelled, every caller waiting for it gets that outcome, it is
    logged at ERROR, and the next call starts it again. If other code cancels the
    shutdown itself, the waiters get ``asyncio.CancelledError`` although they were
    not cancelled (``asyncio.current_task().cancelling() == 0``).

    Args:
        skip_execution_backend (bool): If True, skips the shutdown of the
            execution backends (first call only).

    Raises:
        RuntimeError: If called from an event loop other than the engine's. From
            another thread use
            ``asyncio.run_coroutine_threadsafe(engine.shutdown(), engine.loop)``.
    """
    if asyncio.get_running_loop() is not self.loop:
        raise RuntimeError(
            "shutdown() must run on the engine's event loop; from another thread "
            "use asyncio.run_coroutine_threadsafe(engine.shutdown(), engine.loop)"
        )
    await asyncio.shield(self._request_shutdown(skip_execution_backend))