kaxil commented on code in PR #76015:
URL: https://github.com/apache/airflow/pull/76015#discussion_r4485825419


##########
providers/common/ai/tests/unit/common/ai/durable/test_openai_agents.py:
##########
@@ -519,3 +625,232 @@ def 
test_outside_a_task_it_runs_the_agent_as_runner_run_does(self):
 
         assert result.final_output == "answer: k0=42"
         assert model.calls == 2
+
+
+class _SlowRunHooks(RunHooks):
+    """Makes every tool call wait ``delays[call id]`` seconds before it is 
invoked."""
+
+    def __init__(self, delays: dict[str, float]) -> None:
+        self.delays = delays
+
+    async def on_tool_start(self, context, agent, tool) -> None:
+        await asyncio.sleep(self.delays[context.tool_call_id])
+
+
+class _SlowAgentHooks(AgentHooks):
+    """Makes every tool call of the agent wait ``delays[call id]`` seconds 
before it is invoked."""
+
+    def __init__(self, delays: dict[str, float]) -> None:
+        self.delays = delays
+
+    async def on_tool_start(self, context, agent, tool) -> None:
+        await asyncio.sleep(self.delays[context.tool_call_id])
+
+
+def _attempt_parallel(
+    storage: MemoryStorage,
+    model: Model,
+    tools: _SleepingTools,
+    *,
+    agent_hooks: AgentHooks | None = None,
+    guardrail_delays: dict[str, float] | None = None,
+    **kwargs: Any,
+):
+    """Run one attempt of an agent whose model asks for several tools at 
once."""
+    function_tools = tools.tools()
+    if guardrail_delays is not None:
+
+        @tool_input_guardrail
+        async def wait(data):
+            await asyncio.sleep(guardrail_delays[data.context.tool_call_id])
+            return ToolGuardrailFunctionOutput.allow()
+
+        for function_tool_ in function_tools:
+            function_tool_.tool_input_guardrails = [wait]
+    agent = Agent(name="analyst", model=model, tools=function_tools, 
hooks=agent_hooks)
+    journal = DurableJournal(storage, clean_up_after_run=True)
+    with journal_scope(journal):
+        return run_durably_sync(agent, "go", run_config=NO_TRACING, **kwargs), 
journal
+
+
+class TestParallelToolCalls:
+    def 
test_parallel_tool_calls_replay_when_their_bodies_finish_in_a_different_order(self):
+        """
+        Characterizes the documented claim that parallel calls keep the order 
they started in.
+
+        The model's response reserves a position for each tool call, so how 
long a tool body takes does not matter.
+        """
+        storage = MemoryStorage()
+        tools = _SleepingTools({"a": 0.05, "b": 0.01})
+        with pytest.raises(RuntimeError, match="worker lost"):
+            _attempt_parallel(storage, _ParallelModel(fail_on_answer=True), 
tools)
+        assert tools.calls == {"a": 1, "b": 1}
+
+        tools.body_delays = {"a": 0.01, "b": 0.05}
+        retry_model = _ParallelModel()
+        _, journal = _attempt_parallel(storage, retry_model, tools)
+
+        assert journal.stats.replayed == {"model": 1, "tool": 2}
+        assert tools.calls == {"a": 1, "b": 1}
+        assert retry_model.calls == 1
+
+    def test_only_the_parallel_tool_call_that_failed_runs_again_on_retry(self):
+        storage = MemoryStorage()
+        tools = _SleepingTools(failing={"b"})
+        with pytest.raises(Exception, match="lookup b failed"):
+            _attempt_parallel(storage, _ParallelModel(("a", "b", "c")), tools)
+        assert tools.calls == {"a": 1, "b": 1, "c": 1}
+
+        tools.failing = set()
+        retry_model = _ParallelModel(("a", "b", "c"))
+        _, journal = _attempt_parallel(storage, retry_model, tools)
+
+        assert tools.calls == {"a": 1, "b": 2, "c": 1}
+        assert journal.stats.replayed == {"model": 1, "tool": 2}
+        assert retry_model.calls == 1
+
+    def test_a_finished_run_does_not_keep_its_reserved_tool_steps(self):
+        gc.collect()
+        kept_before = len(_RESERVED_TOOL_STEPS)
+
+        _attempt_parallel(MemoryStorage(), _ParallelModel(), _SleepingTools())
+        gc.collect()
+
+        assert len(_RESERVED_TOOL_STEPS) == kept_before
+
+    @pytest.mark.parametrize("source", ["run-hook", "agent-hook", 
"tool-input-guardrail"])
+    def 
test_parallel_tool_calls_replay_when_what_runs_before_them_takes_a_different_time(self,
 source):
+        """A hook or guardrail the SDK awaits before invoking a tool can let a 
later call claim first."""
+        storage = MemoryStorage()
+        tools = _SleepingTools()
+
+        def attempt(model: Model, delays: dict[str, float]):
+            kwargs: dict[str, Any] = {}
+            if source == "run-hook":
+                kwargs["hooks"] = _SlowRunHooks(delays)
+            elif source == "agent-hook":
+                kwargs["agent_hooks"] = _SlowAgentHooks(delays)
+            else:
+                kwargs["guardrail_delays"] = delays
+            return _attempt_parallel(storage, model, tools, **kwargs)
+
+        with pytest.raises(RuntimeError, match="worker lost"):
+            attempt(_ParallelModel(fail_on_answer=True), {"call-a": 0.01, 
"call-b": 0.1})
+        assert tools.calls == {"a": 1, "b": 1}
+
+        _, journal = attempt(_ParallelModel(), {"call-a": 0.1, "call-b": 0.01})
+
+        assert journal.stats.replayed == {"model": 1, "tool": 2}
+        assert tools.calls == {"a": 1, "b": 1}
+
+
+class TestDurableExceptions:

Review Comment:
   The description now says why they're here (they pin the paths that go 
through the model wrapper the reservation lives in), which works for me.



##########
providers/common/ai/src/airflow/providers/common/ai/durable/openai_agents.py:
##########
@@ -236,17 +250,11 @@ def remember(ctx: Any, error: Exception) -> Any:
     async def on_invoke_tool(ctx: ToolContext[Any], arguments: str) -> Any:
         if _is_inside_a_call(durable_run):
             return await invoke(ctx, arguments)
-        try:
-            parsed = json.loads(arguments) if arguments else {}
-        except json.JSONDecodeError:
-            parsed = arguments
-        fingerprint = fingerprint_tool_call(
-            tool.name,
-            # As recorded model answers are masked, so a replayed call's 
arguments can be too.
-            mask_secrets(parsed if isinstance(parsed, dict) else {"arguments": 
parsed}),
-            ctx.tool_call_id,
+        step = _RESERVED_TOOL_STEPS.get(durable_run, {}).pop(ctx.tool_call_id, 
None) or durable_run.claim(
+            f"tool:{tool.name}",
+            kind="tool",
+            fingerprint=_build_tool_fingerprint(tool.name, arguments, 
ctx.tool_call_id),
         )

Review Comment:
   Fixed in aad6019b04a and reworked in 78f60663db2: `reserve` keeps the first 
call for a repeated id, and `claim_reserved` only hands a tool its reserved 
step when the name and fingerprint match, otherwise the call claims a new 
position. `test_tool_calls_sharing_a_call_id_each_replay_their_own_result` 
covers both the duplicate and the empty id.



##########
providers/common/ai/src/airflow/providers/common/ai/durable/openai_agents.py:
##########
@@ -345,24 +370,48 @@ async def get_response(
         )
         if step.replayed:
             try:
-                return ModelResponse(
+                replayed = ModelResponse(
                     
output=_OUTPUT_ITEMS.validate_python(step.payload["output"]),
                     usage=Usage(),
                     response_id=step.payload.get("response_id"),
                 )
             except (ValidationError, KeyError, TypeError) as error:
                 self.durable_run.reject(step, reason=f"the recorded model 
response cannot be read: {error}")
+            else:
+                self._reserve_tool_steps(replayed, tools)
+                return replayed
 
         async def call() -> ModelResponse:
             return await self.wrapped.get_response(
                 system_instructions, input, model_settings, tools, 
output_schema, handoffs, tracing, **kwargs
             )
 
         try:
-            return await step.run(call, to_record=_record_response)
+            response = await step.run(call, to_record=_record_response)
         except Exception:
             self.failed_step = step
             raise
+        self._reserve_tool_steps(response, tools)
+        return response
+
+    def _reserve_tool_steps(self, response: ModelResponse, tools: list[Tool]) 
-> None:
+        """
+        Claim a position for each of the response's tool calls, in the order 
the model made them.
+
+        A call whose tool never runs (held for approval, stopped by a 
guardrail) leaves its position
+        empty, which a retry runs live without disturbing the positions after 
it. A position
+        that replays is counted in ``stats.replayed`` when reserved, so one 
whose tool never runs
+        is over-counted.

Review Comment:
   Fixed rather than documented in 664de026a4d: a reserved step no longer 
counts in `stats.replayed` when it's reserved, only when its tool takes it 
(`count_as_replayed`, called from `claim_reserved`), so a call a guardrail 
stops isn't counted. 
`test_a_replayed_tool_call_a_guardrail_stops_is_not_counted_as_replayed` covers 
it.



-- 
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