kaxil commented on code in PR #76882:
URL: https://github.com/apache/airflow/pull/76882#discussion_r4573332438
##########
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:
Done, renamed to `claim_next_step` in 75e2b27c7ee.
##########
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:
Yeah, they were. They were written for this PR's own `pause()`, which got
replaced by the one #76786 put on main, so they ended up testing main's code. I
mutated `pause()` and its resume branch seven ways, and every mutant they catch
is already caught by main's `TestPause` tests, so I dropped all three in
d92c090cd29.
--
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]