|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Prototype DynamicNodeSupervisor for concurrent dynamic dispatch. |
| 16 | +
|
| 17 | +This is the RFC spike artifact (see README.md). It layers concurrent |
| 18 | +``ctx.run_node()`` orchestration on the real ADK Workflow engine via a |
| 19 | +framework-owned supervisor. Two design decisions are encoded here and |
| 20 | +verified by the tests: |
| 21 | +
|
| 22 | +1. The concurrency gate is acquired around each LEAF dispatch (a single |
| 23 | + ``ctx.run_node`` call), NOT around drivers. Orchestration frames |
| 24 | + (drivers, fan-out, nested pipeline/parallel) hold no permit while |
| 25 | + awaiting children, so nesting a combinator inside a stage cannot |
| 26 | + deadlock. (Gating drivers DOES deadlock — see the contrast test.) |
| 27 | +
|
| 28 | +2. Fan-out uses ``asyncio.TaskGroup`` (structured concurrency), NOT |
| 29 | + ``asyncio.gather``. ``gather`` propagates an exception but does not |
| 30 | + cancel siblings. |
| 31 | +
|
| 32 | +Failure / cancellation contract (verified by the tests): |
| 33 | +
|
| 34 | +* Ordinary ``Exception`` in a branch -> that branch becomes ``None``; |
| 35 | + siblings are unaffected. |
| 36 | +* ``NodeInterruptedError`` (and other non-cancellation ``BaseException`` |
| 37 | + such as ``KeyboardInterrupt`` / ``SystemExit``) -> propagates, and |
| 38 | + ``TaskGroup`` cancels the remaining branches. |
| 39 | +* External cancellation of the combinator -> propagates down to the |
| 40 | + in-flight branches (standard structured concurrency). |
| 41 | +* A branch raising ``asyncio.CancelledError`` itself is treated by asyncio |
| 42 | + as that task's own cancellation: ``TaskGroup`` does NOT propagate it and |
| 43 | + does NOT cancel siblings; the branch's slot is left ``None`` and the |
| 44 | + others run to completion. (This is asyncio semantics, not something the |
| 45 | + supervisor can override without bespoke handling — see the test.) |
| 46 | +""" |
| 47 | + |
| 48 | +from __future__ import annotations |
| 49 | + |
| 50 | +import asyncio |
| 51 | +import os |
| 52 | +from typing import Any |
| 53 | +from typing import Awaitable |
| 54 | +from typing import Callable |
| 55 | +from typing import Sequence |
| 56 | + |
| 57 | +from google.adk.workflow._errors import NodeInterruptedError |
| 58 | + |
| 59 | +# Control exceptions are NEVER converted to None. NodeInterruptedError is a |
| 60 | +# BaseException by design so it cannot be swallowed by ``except Exception``. |
| 61 | +_CONTROL_EXC = ( |
| 62 | + NodeInterruptedError, |
| 63 | + asyncio.CancelledError, |
| 64 | + KeyboardInterrupt, |
| 65 | + SystemExit, |
| 66 | +) |
| 67 | + |
| 68 | + |
| 69 | +def default_gate() -> int: |
| 70 | + """min(16, cpu-2): matches the Claude Code reference runtime cap.""" |
| 71 | + return min(16, max(1, (os.cpu_count() or 3) - 2)) |
| 72 | + |
| 73 | + |
| 74 | +class DynamicNodeSupervisor: |
| 75 | + """Drives concurrent dynamic ``ctx.run_node()`` chains under one parent.""" |
| 76 | + |
| 77 | + def __init__(self, ctx, *, gate: int | None = None) -> None: |
| 78 | + self.ctx = ctx |
| 79 | + resolved_gate = gate if gate is not None else default_gate() |
| 80 | + if resolved_gate < 1: |
| 81 | + raise ValueError(f"gate must be >= 1, got {resolved_gate}") |
| 82 | + self.gate = asyncio.Semaphore(resolved_gate) |
| 83 | + self.peak_in_flight = 0 |
| 84 | + self._in_flight = 0 |
| 85 | + |
| 86 | + async def dispatch( |
| 87 | + self, child, *, node_input: Any = None, run_id: str | None = None |
| 88 | + ) -> Any: |
| 89 | + """One leaf dispatch. The gate is held ONLY for the child execution.""" |
| 90 | + async with self.gate: |
| 91 | + self._in_flight += 1 |
| 92 | + self.peak_in_flight = max(self.peak_in_flight, self._in_flight) |
| 93 | + try: |
| 94 | + return await self.ctx.run_node( |
| 95 | + child, node_input=node_input, run_id=run_id |
| 96 | + ) |
| 97 | + finally: |
| 98 | + self._in_flight -= 1 |
| 99 | + |
| 100 | + async def _guard_ordinary(self, factory: Callable[[], Awaitable[Any]]) -> Any: |
| 101 | + """Ordinary Exception -> None (drop the branch). Control exceptions escape.""" |
| 102 | + try: |
| 103 | + return await factory() |
| 104 | + except _CONTROL_EXC: |
| 105 | + raise |
| 106 | + except Exception: # noqa: BLE001 - includes DynamicNodeFailError |
| 107 | + return None |
| 108 | + |
| 109 | + async def _supervise( |
| 110 | + self, factories: Sequence[Callable[[], Awaitable[Any]]] |
| 111 | + ) -> list[Any]: |
| 112 | + """Structured fan-out via TaskGroup. See the failure/cancellation contract |
| 113 | + in the module docstring: ordinary failure -> None; NodeInterruptedError |
| 114 | + (and other non-cancellation BaseException) propagates and cancels the rest; |
| 115 | + a branch's own CancelledError leaves its slot None without cancelling |
| 116 | + siblings. Results preserve input order. |
| 117 | + """ |
| 118 | + results: list[Any] = [None] * len(factories) |
| 119 | + |
| 120 | + async def _run_one(i: int, f: Callable[[], Awaitable[Any]]) -> None: |
| 121 | + results[i] = await self._guard_ordinary(f) |
| 122 | + |
| 123 | + try: |
| 124 | + async with asyncio.TaskGroup() as tg: |
| 125 | + for i, f in enumerate(factories): |
| 126 | + tg.create_task(_run_one(i, f)) |
| 127 | + except* NodeInterruptedError: |
| 128 | + raise NodeInterruptedError() |
| 129 | + return results |
| 130 | + |
| 131 | + async def parallel( |
| 132 | + self, thunks: Sequence[Callable[[], Awaitable[Any]]] |
| 133 | + ) -> list[Any]: |
| 134 | + """BARRIER fan-out. thunks: zero-arg callables returning awaitables.""" |
| 135 | + return await self._supervise(thunks) |
| 136 | + |
| 137 | + async def pipeline( |
| 138 | + self, |
| 139 | + items: Sequence[Any], |
| 140 | + *stages: Callable[[Any, Any, int], Awaitable[Any]], |
| 141 | + gate_drivers: bool = False, |
| 142 | + ) -> list[Any]: |
| 143 | + """Barrier-free per-item pipelining. Stage signature: (prev, item, index). |
| 144 | +
|
| 145 | + Each item flows through all stages independently; item A may be in stage |
| 146 | + k while item B is in stage 1. An ordinary Exception in a stage drops that |
| 147 | + item to None; control exceptions propagate. |
| 148 | +
|
| 149 | + ``gate_drivers=True`` is the intentionally-BUGGY variant used by the |
| 150 | + contrast test to demonstrate the nested-combinator deadlock. |
| 151 | + """ |
| 152 | + |
| 153 | + def make_driver(item: Any, i: int) -> Callable[[], Awaitable[Any]]: |
| 154 | + async def drive() -> Any: |
| 155 | + prev = item |
| 156 | + for stage in stages: |
| 157 | + prev = await stage(prev, item, i) |
| 158 | + return prev |
| 159 | + |
| 160 | + if gate_drivers: |
| 161 | + |
| 162 | + async def gated() -> Any: |
| 163 | + async with self.gate: # gating the DRIVER -> deadlock on nesting |
| 164 | + return await drive() |
| 165 | + |
| 166 | + return gated |
| 167 | + return drive |
| 168 | + |
| 169 | + return await self._supervise( |
| 170 | + [make_driver(it, i) for i, it in enumerate(items)] |
| 171 | + ) |
0 commit comments