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


##########
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:
   Reproduced. Try 1 ran a tool and failed; for try 2 I added a `SelectModel` 
(also tried a `ModelFallback`, a toolset without an id, and `retries` lowered 
to 0). The default turned durable execution off before the run, nothing looked 
at the journal, and the tool ran again live.
   
   Fixed in fd8220584cc with the same rule as the build path. When the default 
is off, `execute` checks the journal once, and if an earlier attempt started an 
agent run it fails the task with `DurableJournalError`. The message names the 
reason and the way out (`durable=False`, undoing the Dag change, or deleting 
the task state). `durable=True` and `durable=False` behave as before. Like the 
build path, an attempt that failed on its first model request counts too, since 
a step that raised before it was recorded can't be told from none.
   
   The test records a tool call on try 1, changes the Dag for try 2, and 
asserts the tool is not called again and the journal is left alone. Checking 
the HITL resume turned up a second gap: approving a review after the default 
turned off left the first run's journal behind, so approving now deletes it.



##########
providers/common/ai/src/airflow/providers/common/ai/operators/agent.py:
##########
@@ -547,7 +634,18 @@ class AgentOperator(CancellableAgentRunMixin, 
BaseOperator, HITLReviewMixin, Usa
         :ref:`the cross-attempt usage budget <agent-usage-budget>` for how
         it is persisted, reset, and how ``durable`` replay and HITL
         regeneration interact with it.
-    :param durable: When ``True``, attaches
+    :param durable: Whether a retry replays what earlier attempts completed 
instead of
+        running it again. ``None`` (default) turns it on on Airflow 3.3+ for a 
task that
+        can retry (``retries`` above 0, or from Airflow 3.4 a 
``retry_policy``), and off for
+        any other task. It also turns it off, with the reason in the task log, 
where it cannot
+        apply: a ``SandboxToolset``, an ``MCPToolset`` without an ``id``, a 
toolset without an
+        ``id`` inside a combined or wrapper capability or built by a 
``Toolset`` capability, a
+        capability pydantic-ai refuses to run durably 
(``Capability(toolsets=...)`` with a
+        toolset without an ``id`` among them), or a context with no task state 
store; and it

Review Comment:
   Done in fd8220584cc. The `durable` docstring now lists a `ModelFallback` or 
a capability that selects the model per request, and the fail-instead case (the 
Dag changed between attempts and an earlier attempt started an agent run), so 
it matches `durable_execution.rst` and the changelog warning.



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