eemario commented on code in PR #1456:
URL: https://github.com/apache/flink-agents/pull/1456#discussion_r4703381650


##########
python/flink_agents/plan/actions/tool_call_action.py:
##########
@@ -309,54 +265,54 @@ async def _execute_parallel(
     success: dict,
     error: dict,
 ) -> None:
-    # Sub-agent calls run through durable execution inside the setup, so they
-    # cannot join the tool batch below; they are dispatched concurrently on
-    # their own (submit every call, then await each) so that, like the batched
-    # tool calls, they overlap instead of running one by one. The agent phase
-    # completes before the tool batch, so a sub-agent handle is never left
-    # submitted-but-unawaited if the batch below raises.
-    agent_executions = []
-    tool_executions = []
-    for execution in executions:
-        if execution.agent is not None:
-            agent_executions.append(execution)
-        else:
-            tool_executions.append(execution)
-    await _dispatch_agent_executions(agent_executions, ctx, responses, 
success, error)
-    outcomes: list[Outcome] = []
-    result_observed_at = None
+    prepared = []
+    futures = []
     try:
-        futures = [
-            ctx.durable_execute_async(
-                execution.func,
-                *execution.args,
-                **execution.kwargs,
-                durable_id="tool-call:" + execution.id,
-            )
-            for execution in tool_executions
-        ]
-        outcomes = await ctx.gather(*futures)
-        result_observed_at = datetime.now(timezone.utc)
-        for index, (execution, outcome) in enumerate(
-            zip(tool_executions, outcomes, strict=True)
-        ):
-            outcomes[index] = _record_outcome(
-                execution, outcome, responses, success, error
-            )
-    except Exception as e:
-        raise_if_uncapturable(e)
-        if result_observed_at is None:
-            result_observed_at = datetime.now(timezone.utc)
-        for execution in tool_executions:
-            _record_execution_exception(execution, e, responses, success, 
error)
+        for execution in executions:
+            try:
+                future = await _prepare_async(execution, ctx)
+                futures.append(future)
+                prepared.append(execution)
+            except Exception as failure:  # noqa: PERF203
+                raise_if_uncapturable(failure)
+                _record_execution_exception(
+                    execution, failure, responses, success, error
+                )
+                _report_execution(
+                    execution, ctx, Outcome.failure(failure), 
datetime.now(timezone.utc)
+                )
+        try:
+            outcomes = await ctx.gather(*futures)
+        except Exception as failure:
+            raise_if_uncapturable(failure)
+            observed_at = datetime.now(timezone.utc)
+            for execution in prepared:
+                _record_execution_exception(
+                    execution, failure, responses, success, error
+                )
+                _report_execution(execution, ctx, None, observed_at)
+            return
+        observed_at = datetime.now(timezone.utc)
+        for execution, outcome in zip(prepared, outcomes, strict=True):
+            outcome = _record_outcome(execution, outcome, responses, success, 
error)
+            _report_execution(execution, ctx, outcome, observed_at)
     finally:
-        for index, execution in enumerate(tool_executions):
-            _report_execution(
-                execution,
-                ctx,
-                outcomes[index] if index < len(outcomes) else None,
-                result_observed_at,
-            )
+        for execution in prepared:
+            if execution.occurrence.on_cancel is not None:
+                execution.occurrence.on_cancel()
+
+
+async def _prepare_async(execution: _ToolCallExecution, ctx: RunnerContext) -> 
Any:
+    if isinstance(execution.tool, AsyncTool):
+        return await execution.tool.call_async(
+            ctx, execution.occurrence, **execution.kwargs

Review Comment:
   Are `ctx` and `call_context` intended to be reserved in subagent inputs? I 
sent a tool request with `{"ctx": "review the diff"}` to a registered subagent. 
Both sequential and parallel execution failed with `SubagentTool.call_async() 
got multiple values for argument 'ctx'` before `submit()` was called. The 
previous path passed the input dictionary intact. Could we preserve fields 
declared by the subagent’s schema, or report the restriction when the tool 
schema is built?



##########
python/flink_agents/runtime/async_future.py:
##########
@@ -0,0 +1,413 @@
+################################################################################
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+# limitations under the License.
+#################################################################################
+"""Runtime scheduling shared by single awaits and mixed gathers.
+
+Only callable execution runs on the worker pool. Preparation, journal updates,
+subgraph polling and outcome mapping run on the action's mailbox continuation.
+"""
+
+import logging
+import time
+from concurrent.futures import CancelledError
+from functools import partial
+from threading import Lock
+from typing import Any, Callable
+
+from typing_extensions import override
+
+from flink_agents.api.core_options import AgentExecutionOptions
+from flink_agents.api.duration import format_duration, positive_seconds
+from flink_agents.api.runner_context import AsyncFuture, DurableFuture, Outcome
+from flink_agents.plan.exceptions import raise_if_uncapturable
+from flink_agents.runtime.durable_exception import is_java_interruption
+
+_LOG = logging.getLogger(__name__)
+
+
+def rethrow_fatal(error: BaseException | None) -> None:
+    """Keep runtime faults and interrupted attempts out of durable outcomes."""
+    if error is None:
+        return
+    raise_if_uncapturable(error)
+    if (
+        not isinstance(error, Exception)
+        or isinstance(error, CancelledError | InterruptedError)
+        or is_java_interruption(error)
+    ):
+        raise error
+
+
+class SchedulableFuture(AsyncFuture[Any]):
+    """Internal lifecycle for a call driven by the runtime scheduler."""
+
+    def __init__(self, ctx: Any) -> None:
+        """Bind the handle to its creating runner context."""
+        AsyncFuture.__init__(self)
+        self._ctx = ctx
+
+    @property
+    def call_identity(self) -> object:
+        """Identity shared by views of the same scheduled call."""
+        return self
+
+    def validate(self, ctx: Any) -> None:
+        """Check ownership before any call in the batch can produce side 
effects."""
+        if self._ctx is not None and self._ctx is not ctx:
+            message = "An async future must be gathered by the context that 
created it"
+            raise ValueError(message)
+
+    def __await__(self) -> Any:
+        # Scheduling/bridge failures are never cached as a call's terminal 
result.
+        if not self._is_done():
+            yield from self._resolve()
+        outcome = self._get_completed_outcome()
+        if outcome.error is not None:
+            raise outcome.error
+        return outcome.value
+
+    def _resolve(self) -> Any:
+        return (yield from resolve_calls(self._ctx, (self,), 1, None))
+
+    def prepare(self) -> Outcome | None:
+        """Reserve state in input order; return a replayed outcome if 
available."""
+        return self._get_completed_outcome() if self._is_done() else None
+
+    def start(self) -> None:
+        """Start the prepared operation without waiting for its result."""
+        raise NotImplementedError
+
+    def ready(self) -> bool:
+        """Whether a non-cancelled result is available for mailbox-side 
collection."""
+        raise NotImplementedError
+
+    def finish(self, timeout: TimeoutError | None = None) -> Outcome:
+        """Collect and record a result, or locally complete a timed-out 
wait."""
+        raise NotImplementedError
+
+    def prevent_start(self) -> None:
+        """Fence queued work before cancellation, so it cannot start 
afterwards."""
+
+    def cancel(self) -> None:
+        """Cancel outstanding work without recording a terminal result."""
+
+    def close(self) -> None:
+        """Release registrations after completion, cancellation or a runtime 
fault."""
+
+
+class SingleAsyncFuture(SchedulableFuture):
+    """One callable submitted to the shared async pool."""
+
+    def __init__(
+        self,
+        ctx: Any,
+        func: Callable | None,
+        args: tuple = (),
+        kwargs: dict | None = None,
+    ) -> None:
+        """Store the callable without submitting work to the executor."""
+        super().__init__(ctx)
+        self._execution = partial(func, *args, **(kwargs or {})) if func else 
None

Review Comment:
   Could we use `if func is not None` here? I tried `await 
ctx.execute_async(callback)` with an object whose `__len__` returns `0` and 
whose `__call__` returns `42`. Calling it directly returns `42`, but `if func` 
evaluates to false, so the worker ends up calling `None` and raises 
`TypeError`. A regression test with that callback would cover this case.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to