kaxil commented on code in PR #76917:
URL: https://github.com/apache/airflow/pull/76917#discussion_r4700030300
##########
providers/common/ai/docs/changelog.rst:
##########
@@ -25,6 +25,48 @@
Changelog
---------
+.. warning::
+ **Durable execution is on by default for** ``AgentOperator`` **and**
``@task.agent``
+
+ On Airflow 3.3 and later, an agent task that can retry (``retries`` above 0,
or from
+ Airflow 3.4 a ``retry_policy``) now records each model response and tool
call it completes, and a retry
+ replays them instead of running them again. ``durable`` defaults to ``None``
instead of
+ ``False``. What changes on a retry:
+
+ * A tool call the failed attempt completed is not run again; its recorded
result is
+ returned to the model. A tool whose effect does not outlive the attempt,
such as a file in
+ a temporary directory, or whose answer has to be current, needs the
metadata
+ ``{"airflow": False}`` to run on every attempt
(:ref:`durable-tool-opt-out`).
+ * The agent's ``run_id``, and its ``conversation_id`` when there is no
message history,
+ stay those of the first attempt on every retry, in the ``run_id`` XCom and
the
+ ``gen_ai.agent.call.id`` span attribute too.
+ * Each step is one write to the task state store, which keeps model
responses and masked
+ tool results in the metadata database until the agent run succeeds. A task
that fails its
+ last retry keeps them, with no expiry, until its Dag run is purged or the
entries are
+ deleted (:ref:`durable-journal-storage`).
+
+ On Airflow 3.3, a clear does not delete the journal, so a cleared task that
failed now
+ replays what its failed attempts recorded instead of starting over; from
Airflow 3.4 a
+ clear starts over unless it keeps the task state (:ref:`durable-clear`).
+
+ Where durable execution cannot apply (a ``SandboxToolset``, an
``MCPToolset`` without an
+ ``id``, a toolset in a capability the operator cannot give an id to), it
stays off and the
+ task log says why. A sandbox a function or ``DynamicToolset`` builds per run
cannot be seen
+ before the run, so pass ``durable=False`` to that task. An agent pydantic-ai
refuses only once
+ its durable run has started, such as one a capability moves to a model
instance the agent was
Review Comment:
Agreed, that is the outcome an upgrading user needs most. The warning now
says the task fails instead when a step a live rerun would repeat already ran
(a tool call, say) or when it has a HITL review, and it lists the model-switch
case too. Changed in fb1cfecb32d.
##########
providers/common/ai/src/airflow/providers/common/ai/durable/capability.py:
##########
@@ -615,6 +616,13 @@ async def execute(
# Local validation of the arguments the recorded call was made
with: nothing to
# save by replaying it, and it is the same on every attempt,
so it takes no position.
return await body()
+ case CapabilityOperationId() if (parent := get_executing_step())
is not None and (
Review Comment:
I tried it. With `durable_unit_scope()` entered around the leaf call,
`test_an_agent_a_tool_runs_records_its_own_operations` fails: the inner agent's
accrual runs twice on the retry instead of once, because pydantic-ai runs a
nested operation inline under the scope before it reaches our backend, so an
agent a tool starts stops journaling its own operations. That also means the
`parent.durable_run` check isn't what keeps that case working. I also ran the
workspace case (`LocalWorkspace`, a tool calling `ctx.workspace.stat`, fail
then retry) and at 2.66.0 it records no step of its own and nothing after the
tool reruns, so I couldn't get it to diverge. Leaving the guard as is. Did you
see it diverge with a different backend?
##########
providers/common/ai/src/airflow/providers/common/ai/operators/agent.py:
##########
@@ -1238,19 +1389,119 @@ 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():
Review Comment:
Reproduced: tool runs, the primary 503s, the fallback model is refused on
every try, and `durable=False` succeeds. It also fails with a `ModelFallback`
over model names, so registering instances through `models=` wouldn't cover it.
Took your first option in fb1cfecb32d: a `ModelFallback`, or any capability
whose `get_model()` selects a model per request such as `SelectModel`, now
turns durable off before the run and the log says why. Tests run it with a tool
call before the outage and fail without the change. A `fallback_conn_ids` chain
keeps durable execution.
##########
providers/common/ai/tests/unit/common/ai/operators/test_agent.py:
##########
@@ -109,11 +123,32 @@
)
from tests_common.test_utils.compat import OperatorSerialization
-from tests_common.test_utils.version_compat import AIRFLOW_V_3_0_PLUS,
AIRFLOW_V_3_1_PLUS, AIRFLOW_V_3_3_PLUS
+from tests_common.test_utils.version_compat import (
+ AIRFLOW_V_3_0_PLUS,
+ AIRFLOW_V_3_1_PLUS,
+ AIRFLOW_V_3_3_PLUS,
+ AIRFLOW_V_3_4_PLUS,
+)
+from unit.common.ai.durable.capabilities import (
+ IdlessLedger,
+ LedgerRenamedForRun,
+ RouterThatActs,
+ ToolsetRebuiltForRun,
+)
from unit.common.ai.durable.memory_storage import MemoryStorage
from unit.common.ai.sandbox.fake_tags import TaggedBackend
from unit.common.ai.tool_parts import is_tool_retry
+if AIRFLOW_V_3_3_PLUS:
+ from airflow.sdk import ExceptionRetryPolicy
+
+try: # pydantic-ai-slim ships ModelFallback from 2.64.0; the provider
supports older releases.
Review Comment:
Right, the floor is 2.66.0 so the guard was dead. I dropped that commit, so
`ModelFallback` is imported with the other `pydantic_ai.capabilities` imports.
##########
providers/common/ai/src/airflow/providers/common/ai/durable/journal.py:
##########
@@ -332,6 +335,16 @@ def position(self) -> int:
"""The position the next claimed step will take."""
return self._position
+ def ran_steps(self) -> bool:
+ """
+ Whether this attempt ran a step of this run that running it live again
would repeat.
+
+ Any step it recorded counts, and any other step it started, even one
that raised or is never
+ recorded: a tool or a capability's hook may act before raising. A
model request that raised
+ does not, so a run ``ModelFallback`` moved off a failed request can go
again.
+ """
+ return bool(self._written_positions or self._live_kinds - {"model"})
Review Comment:
Reproduced with a `DynamicToolset` standing in for the MCP one (the FastMCP
server isn't installed in the test image): discovery records a step, then a
`SelectModel` switch is refused on every try, while `durable=False` succeeds.
Fixed in fb1cfecb32d by deciding before the run, so that agent runs without
durable execution and the log says why. A capability that builds its model
switch in `for_run` can't be seen up front and would still hit it. Should I
handle that as well?
--
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]