amoghrajesh commented on code in PR #76882:
URL: https://github.com/apache/airflow/pull/76882#discussion_r4563443866


##########
providers/common/ai/tests/unit/common/ai/durable/test_journal.py:
##########
@@ -666,6 +667,82 @@ async def 
_failed_attempt_then_retry_that_diverges_at_once(memory_storage):
 
 
 class TestPause:
+    """A run that waits for input resumes by replaying what the attempt that 
paused recorded."""
+
+    @pytest.mark.asyncio
+    async def 
test_the_resume_replays_what_the_paused_attempt_recorded_after_an_earlier_failure(

Review Comment:
   Were these missing tests for `DurableRun.pause()`? Seems these are tests for 
soemthing already on which is already on main. Actually even: 
`test_an_entry_an_earlier_attempt_left_where_the_paused_one_recorded_nothing_runs_live`
 and  
`test_a_pause_short_of_an_earlier_one_leaves_none_of_its_later_steps_to_replay`



##########
providers/common/ai/src/airflow/providers/common/ai/operators/agent.py:
##########
@@ -238,11 +261,136 @@ def _answered_request(event: dict[str, Any]) -> int | 
None:
         return -1
 
 
-def _is_awaiting_input(error: BaseException) -> bool:
+def _is_awaiting_input(error: BaseException) -> TypeGuard[TaskAwaitingInput]:
     """Whether ``error`` is the pause for tool approval, which only Airflow 
3.3+ raises."""
     return AIRFLOW_V_3_3_PLUS and isinstance(error, TaskAwaitingInput)
 
 
+def _refuse_external_calls(requests: DeferredToolRequests) -> None:
+    """Fail on tool calls that hand their work to an external system, which 
AgentOperator cannot resolve."""
+    if requests.calls:
+        raise UnsupportedToolDeferralError(
+            "The agent called tools that need external execution "
+            f"({', '.join(call.tool_name for call in requests.calls)}); 
AgentOperator only "
+            "supports tools that need approval."
+        )
+
+
+def _fingerprint_call_content(call: ToolCallPart) -> str | None:
+    """Fingerprint what a reviewer sees of a call, its tool and arguments, but 
not the id the model gave it."""
+    return fingerprint_tool_call(call.tool_name, call.args_as_dict(), None)
+
+
+@dataclass
+class _ToolApprovalAnswer:
+    """
+    A reviewer's answer, and what it was given for.
+
+    :param step: Which approval step of the run asked, counting replayed ones, 
so the answer
+        never reaches another step, such as a later call with the same 
arguments.
+    :param calls: The calls the reviewer saw, as ``(tool name, content 
fingerprint)``.
+    :param toolset_ids: The agent's rendered toolset ids when the reviewer 
answered.
+    """
+
+    step: int
+    calls: list[tuple[str, str | None]]
+    toolset_ids: list[str]
+    approval: bool | ToolDenied
+
+    def take(self, pending: Sequence[ToolCallPart]) -> dict[str, bool | 
ToolDenied]:
+        """
+        Return the answer for each pending call it was given for, by the 
call's current id.
+
+        A call matches on its tool and arguments, so a model request asked 
again on resume, whose
+        calls get new ids, still gets the answer, and a different call with a 
reused id does not.
+        Each answered call is used once: a step asked again can hold the same 
call twice where
+        the reviewer saw it once.
+        """
+        settled: dict[str, bool | ToolDenied] = {}
+        for call in pending:
+            answered = (call.tool_name, _fingerprint_call_content(call))
+            if answered[1] is not None and answered in self.calls:
+                self.calls.remove(answered)
+                settled[call.tool_call_id] = self.approval
+        return settled
+
+    def dump(self) -> dict[str, Any]:
+        denied = self.approval.message if isinstance(self.approval, 
ToolDenied) else None
+        return {
+            "step": self.step,
+            "calls": [list(call) for call in self.calls],
+            "toolset_ids": self.toolset_ids,
+            "denied": denied,
+        }
+
+    @classmethod
+    def load(cls, stored: dict[str, Any]) -> _ToolApprovalAnswer:
+        denied = stored["denied"]
+        return cls(
+            step=stored["step"],
+            calls=[(name, fingerprint) for name, fingerprint in 
stored["calls"]],
+            toolset_ids=stored["toolset_ids"],
+            approval=True if denied is None else ToolDenied(denied),
+        )
+
+
+@dataclass
+class _DurableToolApproval(AbstractCapability[Any]):
+    """
+    Settles the tool calls a durable run is waiting to have approved, as a 
step of its journal.
+
+    It runs first (outermost) and settles every call or parks the task, so the 
whole decision is
+    one step, ``decide``: the reviewers' answers, then the other capabilities'
+    ``handle_deferred_tool_calls`` handlers, then a request for whatever is 
left. A parked step
+    is not recorded, so the resumed run, which replays every step before it, 
reaches it again
+    with the answer. Once recorded, a retry replays the decision instead of 
asking anyone again,
+    and replays the approved calls instead of running them twice.
+
+    :param next_step: Number the approval step about to run for these calls, 
replayed or not,
+        or return ``None`` when ``decide`` itself is asking the other handlers.
+    :param settle: The body of ``decide``.
+    """
+
+    next_step: Callable[[DeferredToolRequests], int | None] = field(repr=False)

Review Comment:
   `next_step` holds a callable that also raises for nested approvals, but it 
reads like an `int` to me. Can we rename it to `claim_next_step`, matching 
`_claim_next_approval_step`, which it points at?



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