dabla commented on code in PR #76917:
URL: https://github.com/apache/airflow/pull/76917#discussion_r4660224460
##########
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:
**[nit]** With the floor at 2.66.0, pydantic-ai's own `durable_unit_scope()`
could mark an Airflow tool step, and would cover more than
`CapabilityOperationId`.
The PR body says the floor (2.46) has no `durable_unit_scope`. Since #76974
the floor is `pydantic-ai-slim>=2.66.0`, which has it:
`CallableOperationBackend.bind` enters it around every unit, and
`_invoke_capability_operation` already runs a nested `@durable_operation`
inline when `in_durable_unit()` is true. The case this guard fixes exists only
because `_JournaledToolset.call_tool` runs the leaf's tool outside that scope.
The guard handles one operation type. Another nested operation that
pydantic-ai gates on `in_durable_unit()`, such as a `DurableWorkspace` call
(`durable_exec/_workspace.py`, `in_durable_context and not in_durable_unit()`),
still reaches `case _:` from inside an Airflow toolset tool and takes a
position of its own, which is the divergence this branch removes for
capabilities. I read that path, I did not run it. Entering
`durable_unit_scope()` around the leaf call in `_JournaledToolset.call_tool`
would close it for every operation type; the `parent.durable_run is
active.durable_run` check here would still be needed for agents a tool starts.
##########
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:
**[nit]** The warning leaves out the case where the task fails instead of
running again.
It says such an agent "runs again without durable execution; a task with a
HITL review fails on it instead". `durable_execution.rst` (the
`durable-not-journaled` list) adds the third outcome: the task fails when a
step a live run would repeat already ran. That is the outcome an upgrading user
most needs to see here, because it is the one that turns a passing task into a
failing one (see comment [3] in `operators/agent.py`).
##########
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:
**[nit]** The `ModelFallback` import guard and its `skipif` are dead since
the rebase.
The comment says "the provider supports older releases", but
`pyproject.toml` on this branch has `pydantic-ai-slim>=2.66.0` (#76974, merged
2026-11-19) and `ModelFallback` ships from 2.64.0. `HAS_MODEL_FALLBACK` is
always true, so the `try`/`except ImportError`, the `if HAS_MODEL_FALLBACK else
None` and the `skipif` in `_REFUSED_ONCE_RUNNING` can go, and the import can
join the other `pydantic_ai.capabilities` imports.
##########
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:
**[warning]** Under the default, a `ModelFallback` to a model instance that
kicks in after the first step fails the task on every attempt; with
`durable=False` the same task succeeds on try 1.
Probe at this head (pydantic-ai-slim 2.66.0), reusing `_agent_op` and
`_durable_context` from `test_agent.py`: the primary model calls `my_tool`,
then answers the next request with `ModelHTTPError(503)`; the capability is
`ModelFallback(FunctionModel(fallback))`; `retries=2`.
| | try 1 | try 2 | try 3 | tool runs | fallback requests |
|---|---|---|---|---|---|
| `durable=False` | `done` | | | 1 | 1 |
| default (`durable=None`) | `UserError` | `UserError` | `UserError` | 1 | 0
|
The error is pydantic-ai's "The model instance ... was not registered with
`AirflowDurability`". On try 1 `holds_steps()` is true because the tool ran; on
the retries it is true because the journal lists run 0, so the refusal is kept
each time. The existing parametrised case (`fallback-model`) only covers a
primary that fails on its first request, where nothing ran yet and the rerun is
safe.
A provider outage in the middle of a run is the case `ModelFallback` is
there for, and the PR's own rule is that turning on the default never fails a
task that worked without it. Both inputs are known before the run starts, so
the decision can be taken up front instead of after steps ran:
- `_why_not_durable_by_default` (through `_iter_capabilities`) can see a
`ModelFallback` that holds `Model` instances, or a `SelectModel`, and leave
durable execution off with the reason in the task log, as it does for a
`SandboxToolset`; or
- the operator registers the `ModelFallback` instances when it attaches the
capability (`AirflowDurability.__init__` passes `models=` through), which is
the way pydantic-ai's message names for getting an instance into a durable run.
I have not tried this one.
`SelectModel` with a callable cannot be inspected for what it returns, so
the first option is the only one for 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]