dabla commented on code in PR #76917:
URL: https://github.com/apache/airflow/pull/76917#discussion_r4710301243


##########
providers/common/ai/src/airflow/providers/common/ai/operators/agent.py:
##########
@@ -1238,19 +1414,121 @@ def _run_and_report_on_failure(
                 result, _ = self._run_agent_tracked(agent, self.prompt, 
run_usage=run_usage, **run_kwargs)
             return result
         except BaseException as error:
-            if not _is_awaiting_input(error):
-                self._report_failed_run(context, run_usage, 
run_id=run_kwargs["run_id"])
-            elif error.method_name == _DURABLE_APPROVAL_RESUME:
-                # The durable run paused for approval. Its usage so far, known 
only now that the run
-                # has settled it, goes with the pause, so the resume reports 
both sides of it.
-                error.kwargs = {
-                    **(error.kwargs or {}),
-                    "usage": _RUN_USAGE_ADAPTER.dump_python(run_usage, 
mode="json"),
-                    "attempt_usage": _RUN_USAGE_ADAPTER.dump_python(
-                        subtract_run_usage(run_usage, self._run_usage_base), 
mode="json"
-                    ),
-                }
-            raise
+            if self._may_run_again_without_durable(error):
+                refusal = str(error)
+            else:
+                if not _is_awaiting_input(error):
+                    self._report_failed_run(context, run_usage, 
run_id=run_kwargs["run_id"])
+                elif error.method_name == _DURABLE_APPROVAL_RESUME:
+                    # The durable run paused for approval. Its usage so far, 
known only now that the run
+                    # has settled it, goes with the pause, so the resume 
reports both sides of it.
+                    error.kwargs = {
+                        **(error.kwargs or {}),
+                        "usage": _RUN_USAGE_ADAPTER.dump_python(run_usage, 
mode="json"),
+                        "attempt_usage": _RUN_USAGE_ADAPTER.dump_python(
+                            subtract_run_usage(run_usage, 
self._run_usage_base), mode="json"
+                        ),
+                    }
+                raise
+        return self._run_again_without_durable(context, run_usage, run_kwargs, 
reason=refusal)
+
+    def _may_run_again_without_durable(self, error: BaseException) -> bool:
+        """
+        Whether a run pydantic-ai refused under the default can run again 
without durable execution.
+
+        pydantic-ai refuses some agents only once their durable run has 
started, such as one a
+        capability moves to a model instance the agent was not built with. 
``durable=True`` keeps
+        the error. Under the default, the run goes again without durable 
execution, unless a step
+        a live run would repeat already ran. A task with a HITL review fails
+        instead: a resumed review decides again, so its regeneration would be 
refused after the
+        reviewer has answered.
+        """
+        if (
+            self.durable is not None
+            or (journal := self._durable_journal) is None
+            or not isinstance(error, UserError)
+            or not _raised_by_durable_execution(error)
+        ):
+            return False
+        if journal.holds_steps():
+            why = "running it again without durable execution could repeat 
steps that already ran"
+        elif self.enable_hitl_review:
+            why = "the review's regenerations would be refused the same way"
+        else:
+            return True
+        self._log_kept_refusal("run", why, error)
+        return False
+
+    def _run_again_without_durable(
+        self, context: Context, run_usage: RunUsage, run_kwargs: dict[str, 
Any], *, reason: str
+    ) -> Any:
+        """Turn durable execution off for this attempt and run the agent 
again, as the default would have."""
+        self.log.info(
+            "Durable execution is off for this task, and the agent runs again 
without it: %s", reason
+        )
+        if (journal := self._durable_journal) is not None:
+            # The refused run recorded no step, but left its entry and the 
run's id.
+            journal.cleanup()
+        self._durable_journal = None
+        self._is_durable_run = False
+        agent = self._build_agent(approval_context=context)
+        ti = context["task_instance"]
+        self._run_identity_attrs = self._span_attributes(ti)
+        stamp_identity_on_agent_spans(agent, self._run_identity_attrs)
+        # The ids a durable run keeps across attempts give way to this 
attempt's own.
+        run_kwargs = {key: value for key, value in run_kwargs.items() if key 
!= "conversation_id"}
+        run_kwargs["run_id"] = make_task_instance_run_key(ti)
+        return self._run_and_report_on_failure(context, agent, run_usage, 
run_kwargs)
+
+    def _decide_durable(self, context: Context) -> None:
+        """
+        Decide whether this run is durable, and log why when the default 
turned it off.
+
+        ``durable=True`` and ``durable=False`` decide it themselves. The 
default turns it on
+        where a retry can replay the journal and every step can be recorded, 
and off, with the
+        reason in the task log, everywhere else.
+        """
+        if self.durable is not None:
+            self._is_durable_run = self.durable
+            return
+        if _contains_capability(self._declared_capabilities, 
AirflowDurability):
+            # Inside a running task the capability opens a journal of its own 
(current_journal).
+            self._is_durable_run = False
+            self.log.info(
+                "Durable execution is left to the AirflowDurability capability 
the agent was given, "
+                "which deletes each agent run's steps as soon as that run 
succeeds."
+            )
+            return
+        reason = self._why_not_durable_by_default(context)
+        self._is_durable_run = reason is None

Review Comment:
   Confirmed at fb1cfecb32d: try 1 journals a tool call and fails, a 
`ModelFallback` is added, try 2 logs "Durable execution is off for this task" 
and calls the tool a second time. I approved a minute after this comment 
without having seen it, so count this as open on my side too.
   
   One thing to add: the journal of try 1 is also left behind after try 2 
succeeds, since `_complete_run` only cleans up a journal the attempt opened. 
Whichever way the up-front decision goes when the journal holds steps (fail 
like the build path, or run live), the path that runs live should delete 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