This is an automated email from the ASF dual-hosted git repository.
Lee-W pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new 8c6adb23bec Keep durable replay across edits to a fallback chain
(#76801)
8c6adb23bec is described below
commit 8c6adb23bec3fe8e46233d447c44e2f9c1c9aefc
Author: Wei Lee <[email protected]>
AuthorDate: Tue Nov 24 17:06:56 2026 +0800
Keep durable replay across edits to a fallback chain (#76801)
---
providers/common/ai/docs/changelog.rst | 19 +
providers/common/ai/docs/durable_execution.rst | 4 +
providers/common/ai/docs/recovery.rst | 35 +-
.../providers/common/ai/durable/capability.py | 62 ++-
.../providers/common/ai/durable/fingerprint.py | 21 +-
.../providers/common/ai/durable/member_stamp.py | 108 ++++++
.../providers/common/ai/hooks/pydantic_ai.py | 34 +-
.../unit/common/ai/durable/test_capability.py | 426 ++++++++++++++++++++-
.../unit/common/ai/durable/test_fingerprint.py | 22 ++
.../unit/common/ai/durable/test_member_stamp.py | 105 +++++
.../tests/unit/common/ai/hooks/test_pydantic_ai.py | 111 ++++--
11 files changed, 897 insertions(+), 50 deletions(-)
diff --git a/providers/common/ai/docs/changelog.rst
b/providers/common/ai/docs/changelog.rst
index 8af3c038618..78996ece22b 100644
--- a/providers/common/ai/docs/changelog.rst
+++ b/providers/common/ai/docs/changelog.rst
@@ -25,6 +25,25 @@
Changelog
---------
+.. note::
+ **Durable replay of a fallback chain**
+
+ A recorded model step through a ``fallback_conn_ids`` chain now replays
after the chain is
+ edited, as long as the connection that answered it is still in the chain and
at least one
+ fallback connection remains; with a single connection the hook passes the
bare model
+ instead of a chain, so every step runs live. A step answered by a connection
that was
+ removed from the chain, or whose ``model`` changed, runs live. The step also
needs the
+ connection that answered it to remain in the chain under the same ID, so two
connections
+ serving the same model are told apart; renaming a connection runs its steps
live, while
+ changing its host or credentials does not. A response the model left
suspended is resumed
+ by pydantic-ai on the first connection in the chain that serves its model,
which need not
+ be the one that answered it. The fingerprint of a chain request no longer
lists the
+ connections, so the first retry after upgrading a task whose durable journal
holds steps
+ recorded through a chain by an earlier version runs every step live, tools
included. A
+ ``FallbackModel`` built outside the hook keeps the earlier behaviour: its
steps replay
+ while the chain is unchanged, and run live once it is edited.
+ See :doc:`recovery`.
+
.. note::
``@task.llm_batch`` now runs OpenAI and Anthropic batches through
pydantic-ai's ``Model.batch_*``
methods and adds a Gemini adapter (``google:<model>``, Gemini Developer API
only; a Vertex
diff --git a/providers/common/ai/docs/durable_execution.rst
b/providers/common/ai/docs/durable_execution.rst
index 649ea1da0ad..3cc25a6d254 100644
--- a/providers/common/ai/docs/durable_execution.rst
+++ b/providers/common/ai/docs/durable_execution.rst
@@ -192,6 +192,10 @@ again, and the task log says so:
Durable: the run took a different path from the previous attempt; this
step and every step after it run again
+For a ``fallback_conn_ids`` chain, the fingerprint names the chain as a whole
rather
+than its connections, and a recorded response replays only if the model that
answered
+it is still in the chain; see :doc:`recovery`.
+
A changed agent costs a re-run; it never replays results that belong to another
conversation. Settings that only affect transport, ``timeout`` and the prompt
cache
settings, are left out of the fingerprint, so changing them does not cause a
re-run.
diff --git a/providers/common/ai/docs/recovery.rst
b/providers/common/ai/docs/recovery.rst
index 5ce975973ec..88efc5367c2 100644
--- a/providers/common/ai/docs/recovery.rst
+++ b/providers/common/ai/docs/recovery.rst
@@ -134,11 +134,36 @@ then sends its first live request through the chain from
the top. The run contin
first connection that answers, whether or not that is the one that answered
before.
A recorded model step replays only if the retry's request has the same
fingerprint, and
-for a chain the model in the fingerprint is the whole chain, whichever
connection
-answered. Adding, removing or reordering a connection in
``fallback_conn_ids``, or
-changing the ``model`` of a connection in it, between attempts therefore makes
the retry
-run every step live, tools included. Changing a connection's credentials or
host does
-not. "How a retry replays" in :doc:`durable_execution` gives the full matching
rules.
+for a chain the fingerprint names the chain as a whole, not its connections.
Each
+recorded response also notes which model of the chain answered it, and the
step replays
+only if that model is still in the chain. Adding, removing or reordering other
+connections in ``fallback_conn_ids`` between attempts therefore keeps the
steps that a
+remaining connection answered, as long as at least one fallback connection
remains. With
+a single connection the hook passes the bare model to the agent instead of a
chain, so
+the fingerprint changes and every step runs live; so does going from one
connection to
+two. A step answered by a connection that was removed from the chain, or whose
``model``
+changed, runs live along with every step after it, tools included, and the
task log
+names the reason.
+
+For a chain the hook builds, the response also notes the connection that
answered,
+and the step replays only if a connection with that ID still serves the same
model,
+so two connections that serve the same model are told apart. A connection is
matched
+by its ID, not by what it points at: renaming a connection runs the steps it
answered
+live, while changing its host or credentials does not invalidate them. A
response the
+model left suspended, such as an Anthropic ``pause_turn``, is resumed by
pydantic-ai on
+the first connection in the chain that serves its model, which need not be the
one that
+answered it. If that connection fails with an error the chain falls back on,
the chain
+abandons the suspended response, tries to cancel its job on that connection,
which need
+not be the one that started it, and generates the turn again from the top of
the chain.
+
+A ``FallbackModel`` built outside the hook, whose members do not record which
one
+answered, keeps the earlier rule: its steps replay while the chain is
unchanged and run
+live once it is edited.
+
+Upgrading to this behaviour changes the fingerprint of every model step
recorded
+through a chain, so the first retry after the upgrade of a task whose journal
was
+written by an earlier version runs live. "How a retry replays" in
:doc:`durable_execution`
+gives the full matching rules.
What is not covered
-------------------
diff --git
a/providers/common/ai/src/airflow/providers/common/ai/durable/capability.py
b/providers/common/ai/src/airflow/providers/common/ai/durable/capability.py
index c03da24e961..07999839ae5 100644
--- a/providers/common/ai/src/airflow/providers/common/ai/durable/capability.py
+++ b/providers/common/ai/src/airflow/providers/common/ai/durable/capability.py
@@ -51,6 +51,7 @@ from pydantic_ai.exceptions import (
UnexpectedModelBehavior,
)
from pydantic_ai.messages import ModelResponse, ToolReturn
+from pydantic_ai.models.fallback import FallbackModel
from pydantic_ai.tools import AgentDepsT, DeferredToolRequests
from pydantic_ai.toolsets import AbstractToolset, DynamicToolset,
FunctionToolset, ToolsetTool
from pydantic_ai.toolsets.wrapper import WrapperToolset
@@ -63,6 +64,11 @@ from airflow.providers.common.ai.durable.fingerprint import (
fingerprint_tool_call,
)
from airflow.providers.common.ai.durable.journal import Unrecordable,
current_journal
+from airflow.providers.common.ai.durable.member_stamp import (
+ MemberStampingModel,
+ get_member_conn_id,
+ get_member_model_id,
+)
from airflow.providers.common.ai.durable.replay_usage import
ReplayUsageLedger, is_successful_tool_payload
from airflow.providers.common.ai.exceptions import DurableJournalError,
DurableToolMetadataError
from airflow.providers.common.ai.utils.masking import mask_secrets
@@ -207,6 +213,9 @@ def _lacks_id(leaf: AbstractToolset[Any]) ->
TypeGuard[FunctionToolset[Any] | Dy
# Why a recorded step that matched is run live anyway: it was written by a
version whose
# types have changed since, so replaying it would fail on every retry.
_UNLOADABLE = "the recorded result no longer loads, so it was written by
another version"
+# A chain replays a step only if its answering member is still in the chain; a
response without
+# a stamp cannot say who answered, so the step runs live.
+_UNSTAMPED_ANSWERER = "the recorded response does not say which fallback chain
member answered it"
# How an operation's step is run: looked up in the journal and recorded, or
always run live.
_StepMode: TypeAlias = Literal["journal", "live"]
@@ -655,11 +664,15 @@ class
_AirflowOperationBackend(CallableOperationBackend[_StepMode]):
step = self._claim(active, operation_id, name, kind="model",
fingerprint=fingerprint)
if step.replayed:
response = _load_model_response(step.payload, streaming=streaming)
- ledger.record_model_replay(response, continuation=continuation)
- ledger.track_chain(response, parameters)
- if response.state != "suspended":
- ledger.credit_successors(active.durable_run, step.position)
- return step.payload
+ model = await self._durability._model_for_fingerprint(model_id,
run_context)
+ if reason := _find_unusable_answerer(response, model):
+ active.durable_run.reject(step, reason=reason)
+ else:
+ ledger.record_model_replay(response, continuation=continuation)
+ ledger.track_chain(response, parameters)
+ if response.state != "suspended":
+ ledger.credit_successors(active.durable_run, step.position)
+ return step.payload
ledger.record_live_model_request(had_request_credit=had_request_credit)
payload = await step.run(body)
if isinstance(payload, Unrecordable):
@@ -686,8 +699,17 @@ class
_AirflowOperationBackend(CallableOperationBackend[_StepMode]):
# here as well as in the request itself is safe.
model = await self._durability._model_for_fingerprint(model_id,
run_context)
prepared_settings, prepared_parameters =
model.prepare_request(model_settings, parameters)
+ # A chain whose members all stamp their answers is fingerprinted by a
fixed name, not its
+ # members: editing the chain must not invalidate steps a surviving
member answered.
+ # ``_find_unusable_answerer`` rejects the replay of a step whose
answering member left
+ # the chain. Any other chain cannot say who answered, so it keeps the
member-listing name.
+ # The agent writes the chain's own id (``fallback:a,b``) on every
response it puts in the
+ # history, replayed ones too, so a replayed response carries the
edited chain's id and
+ # that field has to stay out of the fingerprint.
+ stamped = _get_stamped_members(model) is not None
+ identity = "fallback" if stamped else
f"{model.system}:{model.model_name}"
return fingerprint_model_request(
- f"{model.system}:{model.model_name}", messages, prepared_settings,
prepared_parameters
+ identity, messages, prepared_settings, prepared_parameters,
exclude_response_model_id=stamped
)
@@ -808,6 +830,34 @@ def _decode_tool_payload(payload: Any) -> Any:
raise DurableJournalError(f"durable execution found a tool result it
cannot replay: {kind!r}")
+def _get_stamped_members(model: Model) -> list[MemberStampingModel] | None:
+ if not isinstance(model, FallbackModel):
+ return None
+ members = [member for member in model.models if isinstance(member,
MemberStampingModel)]
+ return members if len(members) == len(model.models) else None
+
+
+def _find_unusable_answerer(response: ModelResponse, model: Model) -> str |
None:
+ """Return why a recorded response cannot replay into ``model``'s chain, or
``None`` if it can."""
+ if (members := _get_stamped_members(model)) is None:
+ return None
+ if (member_model_id := get_member_model_id(response)) is None:
+ return _UNSTAMPED_ANSWERER
+ member_conn_id = get_member_conn_id(response)
+ answerers = {(member.conn_id, member.model_id) for member in members}
+ if (member_conn_id, member_model_id) not in answerers:
+ answerer = (
+ member_model_id if member_conn_id is None else f"{member_model_id}
on connection {member_conn_id}"
+ )
+ if any(model_id == member_model_id for _, model_id in answerers):
+ return (
+ f"the model that answered this step, {answerer}, "
+ "is in the fallback chain only under a different connection"
+ )
+ return f"the model that answered this step, {answerer}, is no longer
in the fallback chain"
+ return None
+
+
def _load_model_response(payload: object, *, streaming: bool) -> ModelResponse:
"""
Decode a model response payload.
diff --git
a/providers/common/ai/src/airflow/providers/common/ai/durable/fingerprint.py
b/providers/common/ai/src/airflow/providers/common/ai/durable/fingerprint.py
index 14c71e03b6c..b53dea776ce 100644
--- a/providers/common/ai/src/airflow/providers/common/ai/durable/fingerprint.py
+++ b/providers/common/ai/src/airflow/providers/common/ai/durable/fingerprint.py
@@ -36,6 +36,9 @@ Fields that pydantic-ai regenerates on every attempt
(message-level
timestamps of the nested calls code mode records on a ``run_code`` return) are
excluded from the fingerprint, and registered secrets in the message history
are
masked before hashing, as they are in the tool results the journal records.
+A chain whose members all stamp their answers also leaves out the ``model_id``
of
+the responses in the history: the agent writes the id of the current chain on
each
+response it replays, so an edited chain would otherwise change every later
step.
Plain JSON tool arguments and settings are hashed exactly as before.
Everything
else is rendered by pydantic: the message history and the request parameters by
their json-mode dump, which is also what they were always hashed from, and
other
@@ -200,7 +203,9 @@ def _strip_part(part: Any) -> Any:
return cleaned
-def _strip_volatile(messages_dump: list[dict[str, Any]]) -> list[dict[str,
Any]]:
+def _strip_volatile(
+ messages_dump: list[dict[str, Any]], *, exclude_response_model_id: bool =
False
+) -> list[dict[str, Any]]:
"""
Drop per-attempt fields from a dumped message list.
@@ -212,6 +217,8 @@ def _strip_volatile(messages_dump: list[dict[str, Any]]) ->
list[dict[str, Any]]
stripped = []
for message in messages_dump:
cleaned = {k: v for k, v in message.items() if k not in
_VOLATILE_MESSAGE_KEYS}
+ if exclude_response_model_id and cleaned.get("kind") == "response":
+ cleaned.pop("model_id", None)
if isinstance(cleaned.get("parts"), list):
cleaned["parts"] = [_strip_part(part) for part in cleaned["parts"]]
stripped.append(cleaned)
@@ -545,6 +552,7 @@ def fingerprint_model_request(
model_request_parameters: ModelRequestParameters,
*,
step: int | None = None,
+ exclude_response_model_id: bool = False,
) -> str | None:
"""
Fingerprint a model request: model identity, message history, settings,
and request parameters.
@@ -554,6 +562,13 @@ def fingerprint_model_request(
model invalidates the cached response; only each tool's ``capability_id``
and
``airflow`` metadata key, and ``deferred_capability_ids``, are left out.
+ ``exclude_response_model_id`` leaves the ``model_id`` of every response in
the history
+ out of the hash. Pass ``True`` only for a fallback chain whose members all
stamp which
+ of them answered: the agent writes the chain's id on every response it
puts in the
+ history, replayed ones too, so editing the chain would otherwise change
the fingerprint
+ of every later step. Leave it ``False`` for any other model, so that
journals recorded
+ by earlier versions still match.
+
Returns ``None`` when the request cannot be fingerprinted. The journal then
replays the step without verification, and only right after a step that
replayed. Model settings, the tool definitions in the request parameters
and
@@ -582,7 +597,9 @@ def fingerprint_model_request(
# live run's history is (an output function's result, for
one), so a replayed
# history can hold ``***`` where the live one held the secret.
Masking the
# history here as well makes both match.
- "messages": _strip_volatile(mask_secrets(dumped)),
+ "messages": _strip_volatile(
+ mask_secrets(dumped),
exclude_response_model_id=exclude_response_model_id
+ ),
"settings": _render(_content_settings(model_settings)),
"params": _normalize_params(params),
}
diff --git
a/providers/common/ai/src/airflow/providers/common/ai/durable/member_stamp.py
b/providers/common/ai/src/airflow/providers/common/ai/durable/member_stamp.py
new file mode 100644
index 00000000000..5d1b261386f
--- /dev/null
+++
b/providers/common/ai/src/airflow/providers/common/ai/durable/member_stamp.py
@@ -0,0 +1,108 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Record which member of a ``FallbackModel`` chain answered a model
request."""
+
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any
+
+from pydantic_ai.models.wrapper import WrapperModel
+
+if TYPE_CHECKING:
+ from pydantic_ai.messages import ModelMessage, ModelResponse
+ from pydantic_ai.models import Model, ModelRequestParameters,
StreamedResponse
+ from pydantic_ai.settings import ModelSettings
+ from pydantic_ai.tools import RunContext
+
+MEMBER_STAMP_KEY = "__airflow_common_ai__"
+MEMBER_MODEL_ID_KEY = "member_model_id"
+MEMBER_CONN_ID_KEY = "member_conn_id"
+
+
+def get_member_model_id(response: ModelResponse) -> str | None:
+ """Return the ``model_id`` of the chain member that produced ``response``,
if it was stamped."""
+ stamp = (response.metadata or {}).get(MEMBER_STAMP_KEY)
+ if not isinstance(stamp, dict):
+ return None
+ member_model_id = stamp.get(MEMBER_MODEL_ID_KEY)
+ return member_model_id if isinstance(member_model_id, str) else None
+
+
+def get_member_conn_id(response: ModelResponse) -> str | None:
+ """Return the connection ID of the chain member that produced
``response``, if it was stamped with one."""
+ stamp = (response.metadata or {}).get(MEMBER_STAMP_KEY)
+ if not isinstance(stamp, dict):
+ return None
+ member_conn_id = stamp.get(MEMBER_CONN_ID_KEY)
+ return member_conn_id if isinstance(member_conn_id, str) else None
+
+
+@dataclass(init=False)
+class MemberStampingModel(WrapperModel):
+ """
+ Stamp each response with the ``model_id`` of the wrapped model.
+
+ pydantic-ai's ``FallbackModel`` only records which member answered on
suspended responses,
+ so a durable replay cannot otherwise tell whether the recorded answer came
from a model
+ that is still in the chain. The stamp lives under its own key rather than
the
+ ``__pydantic_ai__`` namespace that pydantic-ai owns.
+
+ The hook also passes the ID of the connection the model came from, so a
replay can tell two
+ connections that serve the same model apart. It is a name, not an
identity: it says nothing
+ about the connection's host or credentials. A member built without one
stamps only the model.
+ """
+
+ conn_id: str | None = None
+
+ def __init__(self, wrapped: Model, *, conn_id: str | None = None) -> None:
+ super().__init__(wrapped)
+ self.conn_id = conn_id
+
+ def _stamp(self, response: ModelResponse | StreamedResponse) -> None:
+ if response.metadata is None:
+ response.metadata = {}
+ stamp = {MEMBER_MODEL_ID_KEY: self.wrapped.model_id}
+ if self.conn_id is not None:
+ stamp[MEMBER_CONN_ID_KEY] = self.conn_id
+ response.metadata[MEMBER_STAMP_KEY] = stamp
+
+ async def request(
+ self,
+ messages: list[ModelMessage],
+ model_settings: ModelSettings | None,
+ model_request_parameters: ModelRequestParameters,
+ ) -> ModelResponse:
+ response = await super().request(messages, model_settings,
model_request_parameters)
+ self._stamp(response)
+ return response
+
+ @asynccontextmanager
+ async def request_stream(
+ self,
+ messages: list[ModelMessage],
+ model_settings: ModelSettings | None,
+ model_request_parameters: ModelRequestParameters,
+ run_context: RunContext[Any] | None = None,
+ ) -> AsyncIterator[StreamedResponse]:
+ async with super().request_stream(
+ messages, model_settings, model_request_parameters, run_context
+ ) as streamed_response:
+ self._stamp(streamed_response)
+ yield streamed_response
diff --git
a/providers/common/ai/src/airflow/providers/common/ai/hooks/pydantic_ai.py
b/providers/common/ai/src/airflow/providers/common/ai/hooks/pydantic_ai.py
index 114e6307edb..d13a9737771 100644
--- a/providers/common/ai/src/airflow/providers/common/ai/hooks/pydantic_ai.py
+++ b/providers/common/ai/src/airflow/providers/common/ai/hooks/pydantic_ai.py
@@ -34,6 +34,7 @@ from pydantic_ai.models.fallback import FallbackModel
from pydantic_ai.providers import infer_provider_class
from typing_extensions import ParamSpec
+from airflow.providers.common.ai.durable.member_stamp import
MemberStampingModel
from airflow.providers.common.ai.hooks.ollama import OllamaBackend
from airflow.providers.common.ai.observability import
genai_instrumentation_settings
from airflow.providers.common.ai.utils.toolset_base import MaskingCapability
@@ -407,13 +408,21 @@ class PydanticAIHook(BaseHook):
return self._model
model = self._resolve_own_model()
- fallback_models = self._resolve_fallback_models()
+ fallback_members = self._resolve_fallback_models()
# Pin pydantic-ai's own default explicitly: the retry-layers docs pin
this exact
# scope (UnexpectedModelBehavior, UsageLimitExceeded, and
ContentFilterError are
# deliberately excluded), and pyproject has no upper bound on
pydantic-ai-slim, so
# an upstream default change would otherwise move that documented
behaviour silently.
self._model = (
- FallbackModel(model, *fallback_models,
fallback_on=(ModelAPIError,)) if fallback_models else model
+ FallbackModel(
+ *(
+ MemberStampingModel(member, conn_id=conn_id)
+ for conn_id, member in ((self.llm_conn_id, model),
*fallback_members)
+ ),
+ fallback_on=(ModelAPIError,),
+ )
+ if fallback_members
+ else model
)
return self._model
@@ -724,9 +733,9 @@ class PydanticAIHook(BaseHook):
)
return [stripped for item in raw if (stripped := item.strip())]
- def _resolve_fallback_models(self) -> list[Model]:
+ def _resolve_fallback_models(self) -> list[tuple[str, Model]]:
"""
- Resolve one ``Model`` per fallback connection, in the configured order.
+ Resolve each fallback connection's ID and ``Model``, in the configured
order.
Each connection is resolved through the hook registered for its own
``conn_type``, so a chain can mix providers whose credentials live in
@@ -751,7 +760,7 @@ class PydanticAIHook(BaseHook):
self.log.info("Resolving LLM fallback chain: %s", " ->
".join([self.llm_conn_id, *fallback_conn_ids]))
- models: list[Model] = []
+ members: list[tuple[str, Model]] = []
seen: set[str] = set()
for conn_id in fallback_conn_ids:
if conn_id == self.llm_conn_id:
@@ -788,15 +797,18 @@ class PydanticAIHook(BaseHook):
f"{FALLBACK_CONN_IDS_EXTRA_KEY}. Chains are not resolved
recursively -- list "
f"every provider directly on '{self.llm_conn_id}' instead."
)
- models.append(
- hook._resolve_own_model(
- forwarded_model_id=forwarded_model_id,
- forwarded_from_conn_id=self.llm_conn_id,
- forwarded_model_provider=forwarded_model_provider,
+ members.append(
+ (
+ conn_id,
+ hook._resolve_own_model(
+ forwarded_model_id=forwarded_model_id,
+ forwarded_from_conn_id=self.llm_conn_id,
+ forwarded_model_provider=forwarded_model_provider,
+ ),
)
)
- return models
+ return members
def _get_conn_if_model_configured(self) -> Model | None:
"""Return the hook model only when the hook or connection explicitly
configures one."""
diff --git
a/providers/common/ai/tests/unit/common/ai/durable/test_capability.py
b/providers/common/ai/tests/unit/common/ai/durable/test_capability.py
index f23827c94c9..0501e1dbba3 100644
--- a/providers/common/ai/tests/unit/common/ai/durable/test_capability.py
+++ b/providers/common/ai/tests/unit/common/ai/durable/test_capability.py
@@ -35,7 +35,7 @@ import pytest
from pydantic import BaseModel
from pydantic_ai import Agent, CancellationToken, RunContext
from pydantic_ai.capabilities import AbstractCapability, SetToolMetadata,
durable_operation
-from pydantic_ai.exceptions import ModelRetry, UnexpectedModelBehavior
+from pydantic_ai.exceptions import ModelAPIError, ModelHTTPError, ModelRetry,
UnexpectedModelBehavior
from pydantic_ai.mcp import MCPToolset
from pydantic_ai.messages import (
ModelMessage,
@@ -46,7 +46,9 @@ from pydantic_ai.messages import (
ToolReturn,
ToolReturnPart,
)
+from pydantic_ai.models.fallback import FallbackModel
from pydantic_ai.models.function import AgentInfo, FunctionModel
+from pydantic_ai.settings import ModelSettings
from pydantic_ai.toolsets import DynamicToolset, FunctionToolset
from pydantic_ai.toolsets.wrapper import WrapperToolset
from pydantic_ai.usage import RequestUsage, RunUsage, UsageLimits
@@ -59,7 +61,14 @@ from airflow.providers.common.ai.durable.capability import (
_GivenIds,
_JournalCodec,
)
-from airflow.providers.common.ai.durable.journal import DurableJournal,
Unrecordable, journal_scope
+from airflow.providers.common.ai.durable.fingerprint import
fingerprint_model_request
+from airflow.providers.common.ai.durable.journal import (
+ DurableJournal,
+ DurableRun,
+ Unrecordable,
+ journal_scope,
+)
+from airflow.providers.common.ai.durable.member_stamp import
MemberStampingModel
from airflow.providers.common.ai.exceptions import DurableJournalError,
SQLToolsetConnectionError
from airflow.providers.common.ai.toolsets.sql import SQLToolset
from airflow.providers.common.ai.utils.toolset_base import AirflowToolset,
ensure_masked
@@ -70,6 +79,7 @@ from unit.common.ai.sqlite_connection import
create_orders_table, run_sql, sqlit
from unit.common.ai.tool_parts import is_tool_result, is_tool_retry
if TYPE_CHECKING:
+ from pydantic_ai.models import Model
from pydantic_ai.toolsets.abstract import ToolsetTool
PNG = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR"
@@ -1928,3 +1938,415 @@ class TestReplayUsage:
assert result.output == "done"
assert usage.requests == 3
+
+
+class TestFallbackChainEdits:
+ """Editing a fallback chain between attempts keeps the steps a surviving
member answered."""
+
+ @staticmethod
+ def build_chain(
+ calls: Calls,
+ members: list[tuple[str, float | None]],
+ *,
+ up: set[str],
+ stamped: bool = True,
+ ) -> FallbackModel:
+ def build_member(name: str, temperature: float | None) -> Model:
+ def respond(messages: list[ModelMessage], info: AgentInfo) ->
ModelResponse:
+ calls.bump(name)
+ if name not in up:
+ raise ModelHTTPError(500, name)
+ return ModelResponse(parts=[TextPart(f"{name} answered")])
+
+ model = FunctionModel(
+ respond,
+ model_name=name,
+ settings=ModelSettings(temperature=temperature) if temperature
is not None else None,
+ )
+ return MemberStampingModel(model) if stamped else model
+
+ return FallbackModel(
+ *(build_member(name, temperature) for name, temperature in
members),
+ fallback_on=(ModelAPIError,),
+ )
+
+ @staticmethod
+ def build_agent(chain: FallbackModel) -> Agent[None, str]:
+ return Agent(chain, name="chained", capabilities=[AirflowDurability()])
+
+ @pytest.mark.parametrize(
+ ("members", "up", "output", "replayed", "calls_by_member"),
+ [
+ pytest.param(
+ [("c", None), ("b", None)], {"c"}, "b answered", 1, {"b": 1,
"c": 0}, id="member added before"
+ ),
+ pytest.param(
+ [("b", None), ("a", None)], {"a"}, "b answered", 1, {"b": 1,
"a": 1}, id="members reordered"
+ ),
+ pytest.param(
+ [("a", None), ("b", 0.9)], set(), "b answered", 1, {"b": 1},
id="member settings changed"
+ ),
+ pytest.param(
+ [("a", None)], {"a"}, "a answered", 0, {"a": 2, "b": 1},
id="answering member removed"
+ ),
+ pytest.param(
+ [("a", None), ("b2", None)],
+ {"b2"},
+ "b2 answered",
+ 0,
+ {"a": 2, "b": 1, "b2": 1},
+ id="answering member's model changed",
+ ),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def
test_a_step_replays_only_while_its_answering_member_is_in_the_chain(
+ self, memory_storage, members, up, output, replayed, calls_by_member
+ ):
+ calls = Calls()
+ first = self.build_chain(calls, [("a", None), ("b", None)], up={"b"})
+ await attempt(memory_storage, self.build_agent(first))
+
+ journal = DurableJournal(memory_storage)
+ with (
+ journal_scope(journal),
+ mock.patch.object(DurableRun, "reject", autospec=True,
side_effect=DurableRun.reject) as reject,
+ ):
+ result = await self.build_agent(self.build_chain(calls, members,
up=up)).run("go")
+
+ assert result.output == output
+ assert journal.stats.replayed["model"] == replayed
+ assert {name: calls[name] for name in calls_by_member} ==
calls_by_member
+ reason = "the model that answered this step, function:b, is no longer
in the fallback chain"
+ assert [call.kwargs["reason"] for call in reject.call_args_list] == (
+ [reason] if replayed == 0 else []
+ )
+
+ @pytest.mark.parametrize(
+ ("second_attempt", "replayed", "calls_by_member"),
+ [
+ pytest.param([("a", None), ("b", None)], 1, {"a": 1, "b": 1},
id="chain unchanged"),
+ pytest.param([("b", None), ("c", None)], 0, {"a": 1, "b": 2, "c":
0}, id="chain edited"),
+ ],
+ )
+ @pytest.mark.parametrize("stamped_members", [0, 1], ids=["unstamped
chain", "mixed chain"])
+ @pytest.mark.asyncio
+ async def
test_a_chain_with_an_unstamped_member_replays_only_while_unchanged(
+ self, memory_storage, stamped_members, second_attempt, replayed,
calls_by_member
+ ):
+ calls = Calls()
+
+ def build(members: list[tuple[str, float | None]]) -> FallbackModel:
+ chain = self.build_chain(calls, members, up={"b"}, stamped=False)
+ chain.models[:stamped_members] = [MemberStampingModel(m) for m in
chain.models[:stamped_members]]
+ return chain
+
+ await attempt(memory_storage, self.build_agent(build([("a", None),
("b", None)])))
+
+ journal = DurableJournal(memory_storage)
+ with journal_scope(journal):
+ await self.build_agent(build(second_attempt)).run("go")
+
+ assert journal.stats.replayed["model"] == replayed
+ assert {name: calls[name] for name in calls_by_member} ==
calls_by_member
+
+ @pytest.mark.parametrize(
+ ("second_attempt", "output", "replayed", "calls_by_conn"),
+ [
+ pytest.param(
+ [("primary", True)],
+ "primary answered",
+ 0,
+ {"primary": 2, "gateway": 1},
+ id="answering connection removed",
+ ),
+ pytest.param(
+ [("primary", False), ("gateway2", True)],
+ "gateway2 answered",
+ 0,
+ {"primary": 2, "gateway": 1, "gateway2": 1},
+ id="answering connection renamed",
+ ),
+ pytest.param(
+ [("gateway", True)],
+ "gateway answered",
+ 1,
+ {"primary": 1, "gateway": 1},
+ id="other connection removed",
+ ),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def
test_a_step_replays_only_while_its_answering_connection_is_in_the_chain(
+ self, memory_storage, second_attempt, output, replayed, calls_by_conn
+ ):
+ calls = Calls()
+
+ def build(members: list[tuple[str, bool]]) -> Agent[None, str]:
+ def member(conn_id: str, up: bool) -> MemberStampingModel:
+ def respond(messages: list[ModelMessage], info: AgentInfo) ->
ModelResponse:
+ calls.bump(conn_id)
+ if not up:
+ raise ModelHTTPError(500, conn_id)
+ return ModelResponse(parts=[TextPart(f"{conn_id}
answered")])
+
+ return MemberStampingModel(FunctionModel(respond,
model_name="m"), conn_id=conn_id)
+
+ return self.build_agent(
+ FallbackModel(*(member(*entry) for entry in members),
fallback_on=(ModelAPIError,))
+ )
+
+ await attempt(memory_storage, build([("primary", False), ("gateway",
True)]))
+
+ journal = DurableJournal(memory_storage)
+ with (
+ journal_scope(journal),
+ mock.patch.object(DurableRun, "reject", autospec=True,
side_effect=DurableRun.reject) as reject,
+ ):
+ result = await build(second_attempt).run("go")
+
+ assert result.output == output
+ assert journal.stats.replayed["model"] == replayed
+ assert {conn_id: calls[conn_id] for conn_id in calls_by_conn} ==
calls_by_conn
+ reason = (
+ "the model that answered this step, function:m on connection
gateway, "
+ "is in the fallback chain only under a different connection"
+ )
+ assert [call.kwargs["reason"] for call in reject.call_args_list] == (
+ [reason] if replayed == 0 else []
+ )
+
+ @pytest.mark.parametrize(
+ ("first_conn_id", "second_conn_id", "answerer"),
+ [
+ pytest.param(None, "gateway", "function:m", id="connection added"),
+ pytest.param("gateway", None, "function:m on connection gateway",
id="connection dropped"),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_a_member_without_a_connection_id_matches_only_one_without(
+ self, memory_storage, first_conn_id, second_conn_id, answerer
+ ):
+ calls = Calls()
+
+ def build(members: list[tuple[str, str | None, bool]]) -> Agent[None,
str]:
+ def member(name: str, conn_id: str | None, up: bool) ->
MemberStampingModel:
+ def respond(messages: list[ModelMessage], info: AgentInfo) ->
ModelResponse:
+ calls.bump(name)
+ if not up:
+ raise ModelHTTPError(500, name)
+ return ModelResponse(parts=[TextPart(f"{name} answered")])
+
+ return MemberStampingModel(FunctionModel(respond,
model_name="m"), conn_id=conn_id)
+
+ return self.build_agent(
+ FallbackModel(*(member(*entry) for entry in members),
fallback_on=(ModelAPIError,))
+ )
+
+ await attempt(memory_storage, build([("down", "down", False),
("first", first_conn_id, True)]))
+
+ journal = DurableJournal(memory_storage)
+ with (
+ journal_scope(journal),
+ mock.patch.object(DurableRun, "reject", autospec=True,
side_effect=DurableRun.reject) as reject,
+ ):
+ result = await build([("second", second_conn_id, True)]).run("go")
+
+ assert result.output == "second answered"
+ assert journal.stats.replayed["model"] == 0
+ assert {name: calls[name] for name in ("down", "first", "second")} == {
+ "down": 1,
+ "first": 1,
+ "second": 1,
+ }
+ assert [call.kwargs["reason"] for call in reject.call_args_list] == [
+ f"the model that answered this step, {answerer}, "
+ "is in the fallback chain only under a different connection"
+ ]
+
+ @pytest.mark.parametrize(
+ ("second_attempt", "calls_of_c"),
+ [
+ pytest.param(["a", "c"], 0, id="member after the answerer
replaced"),
+ pytest.param(["c", "a"], 1, id="member added before the answerer"),
+ ],
+ )
+ @pytest.mark.parametrize("with_conn_ids", [False, True], ids=["no conn
ids", "conn ids"])
+ @pytest.mark.asyncio
+ async def test_a_chain_edit_keeps_replaying_after_the_first_model_step(
+ self, memory_storage, second_attempt, calls_of_c, with_conn_ids
+ ):
+ calls = Calls()
+ fail_final = [True]
+
+ def build(names: list[str]) -> Agent[None, str]:
+ def down(messages: list[ModelMessage], info: AgentInfo) ->
ModelResponse:
+ raise ModelHTTPError(500, "down")
+
+ def member(name: str) -> MemberStampingModel:
+ conn_id = f"conn_{name}" if with_conn_ids else None
+ if name == "a":
+ return MemberStampingModel(
+ FunctionModel(clock_then_lookup(calls,
fail_final=fail_final), model_name="a"),
+ conn_id=conn_id,
+ )
+
+ def respond(messages: list[ModelMessage], info: AgentInfo) ->
ModelResponse:
+ calls.bump(name)
+ return down(messages, info)
+
+ return MemberStampingModel(FunctionModel(respond,
model_name=name), conn_id=conn_id)
+
+ chain = FallbackModel(*(member(name) for name in names),
fallback_on=(ModelAPIError,))
+ return Agent(
+ chain,
+ name="chained",
+ toolsets=[_build_ops_toolset(calls)],
+ capabilities=[AirflowDurability()],
+ )
+
+ with pytest.raises(RuntimeError, match="worker died"):
+ await attempt(memory_storage, build(["a", "b"]))
+ fail_final[0] = False
+ journal = DurableJournal(memory_storage)
+ with journal_scope(journal):
+ result = await build(second_attempt).run("go")
+
+ assert result.output == "done"
+ assert journal.stats.replayed["model"] == 2
+ assert (calls["clock"], calls["lookup"], calls["model"]) == (1, 1, 4)
+ assert calls["c"] == calls_of_c
+
+ @pytest.mark.asyncio
+ async def test_a_stamped_chain_rejects_a_response_without_a_stamp(self,
memory_storage):
+ calls = Calls()
+ chain = self.build_chain(calls, [("a", None), ("b", None)], up={"b"})
+ await attempt(memory_storage, self.build_agent(chain))
+ for entry in memory_storage.steps():
+ if entry["kind"] == "model":
+ entry["payload"]["metadata"] = None
+
+ journal = DurableJournal(memory_storage)
+ with (
+ journal_scope(journal),
+ mock.patch.object(DurableRun, "reject", autospec=True,
side_effect=DurableRun.reject) as reject,
+ ):
+ chain = self.build_chain(calls, [("a", None), ("b", None)],
up={"b"})
+ await self.build_agent(chain).run("go")
+
+ assert journal.stats.replayed["model"] == 0
+ assert calls["b"] == 2
+ reason = "the recorded response does not say which fallback chain
member answered it"
+ assert [call.kwargs["reason"] for call in reject.call_args_list] ==
[reason]
+
+ @pytest.mark.asyncio
+ async def
test_a_streamed_step_replays_while_its_answering_member_is_in_the_chain(self,
memory_storage):
+ calls = Calls()
+
+ def build(names: list[str]) -> Agent[None, str]:
+ def stream_as(name: str):
+ async def stream(messages: list[ModelMessage], info:
AgentInfo):
+ calls.bump(name)
+ if name == "a":
+ raise ModelHTTPError(500, name)
+ yield f"{name} answered"
+ return
+
+ return stream
+
+ chain = FallbackModel(
+ *(
+
MemberStampingModel(FunctionModel(stream_function=stream_as(name),
model_name=name))
+ for name in names
+ ),
+ fallback_on=(ModelAPIError,),
+ )
+ return Agent(chain, name="chained",
capabilities=[AirflowDurability()])
+
+ async def run_streamed(names: list[str]) -> str:
+ async with build(names).run_stream("go") as streamed:
+ return await streamed.get_output()
+
+ with journal_scope(DurableJournal(memory_storage)):
+ assert await run_streamed(["a", "b"]) == "b answered"
+ journal = DurableJournal(memory_storage)
+ with journal_scope(journal):
+ assert await run_streamed(["b", "a"]) == "b answered"
+
+ assert journal.stats.replayed["model"] == 1
+ assert calls["b"] == 1
+
+ @pytest.mark.asyncio
+ async def
test_a_suspended_response_of_a_removed_member_is_not_continued(self,
memory_storage):
+ calls = Calls()
+ histories: list[list[ModelMessage]] = []
+
+ def build(members: list[str]) -> Agent[None, str]:
+ def respond_as(name: str):
+ def respond(messages: list[ModelMessage], info: AgentInfo) ->
ModelResponse:
+ calls.bump(name)
+ histories.append(messages)
+ if name == "a" and "b" in members:
+ raise ModelHTTPError(500, "a")
+ suspended = name == "b" and calls["b"] == 1
+ return ModelResponse(
+ parts=[TextPart(f"{name} segment")],
+ state="suspended" if suspended else "complete",
+ )
+
+ return respond
+
+ chain = FallbackModel(
+ *(MemberStampingModel(FunctionModel(respond_as(name),
model_name=name)) for name in members),
+ fallback_on=(ModelAPIError,),
+ )
+ return Agent(chain, name="chained",
capabilities=[AirflowDurability()])
+
+ await attempt(memory_storage, build(["a", "b"]))
+ assert calls["b"] == 2
+ histories.clear()
+
+ journal = DurableJournal(memory_storage)
+ with journal_scope(journal):
+ await build(["a"]).run("go")
+
+ assert journal.stats.replayed["model"] == 0
+ [history] = histories
+ assert [message for message in history if isinstance(message,
ModelResponse)] == []
+
+ @pytest.mark.parametrize(
+ ("build_model", "expected"),
+ [
+ pytest.param(
+ lambda: FunctionModel(
+ lambda messages, info:
ModelResponse(parts=[TextPart("hi")]), model_name="solo"
+ ),
+ [("function:solo", False)],
+ id="single model",
+ ),
+ pytest.param(
+ lambda: TestFallbackChainEdits.build_chain(
+ Calls(), [("a", None), ("b", None)], up={"a", "b"},
stamped=False
+ ),
+ [("fallback:function,function:fallback:a,b", False)],
+ id="chain of unstamped members",
+ ),
+ ],
+ )
+ @pytest.mark.asyncio
+ @mock.patch(
+
"airflow.providers.common.ai.durable.capability.fingerprint_model_request",
+ autospec=True,
+ side_effect=fingerprint_model_request,
+ )
+ async def test_a_model_without_a_stamped_chain_keeps_its_fingerprint(
+ self, mock_fingerprint_model_request, memory_storage, build_model,
expected
+ ):
+ agent = Agent(build_model(), name="solo",
capabilities=[AirflowDurability()])
+
+ await attempt(memory_storage, agent)
+
+ assert [
+ (call.args[0], call.kwargs["exclude_response_model_id"])
+ for call in mock_fingerprint_model_request.call_args_list
+ ] == expected
diff --git
a/providers/common/ai/tests/unit/common/ai/durable/test_fingerprint.py
b/providers/common/ai/tests/unit/common/ai/durable/test_fingerprint.py
index a2076fd5c32..93477467300 100644
--- a/providers/common/ai/tests/unit/common/ai/durable/test_fingerprint.py
+++ b/providers/common/ai/tests/unit/common/ai/durable/test_fingerprint.py
@@ -441,6 +441,28 @@ class TestModelRequestFingerprint:
assert high is not None
assert low != high
+ def test_a_stamped_chain_leaves_out_which_chain_a_response_came_from(self):
+ """An agent stamps its own chain's id on every response it replays, so
an edited chain differs only there."""
+
+ def history(model_id: str) -> list:
+ return [
+ ModelRequest(parts=[UserPromptPart("go")]),
+ ModelResponse(parts=[TextPart("hi")], model_id=model_id),
+ ModelRequest(parts=[UserPromptPart("next")]),
+ ]
+
+ old = history("fallback:a,b")
+ new = history("fallback:a,c")
+ params = ModelRequestParameters()
+
+ assert fingerprint_model_request(
+ "m", old, None, params, exclude_response_model_id=True
+ ) == fingerprint_model_request("m", new, None, params,
exclude_response_model_id=True)
+ assert fingerprint_model_request("m", old, None, params) !=
fingerprint_model_request(
+ "m", new, None, params
+ )
+ assert fingerprint_model_request("m", old, None, params) ==
_json_mode_reference("m", old, params)
+
class TestToolCallFingerprint:
def test_stable_for_identical_call(self):
diff --git
a/providers/common/ai/tests/unit/common/ai/durable/test_member_stamp.py
b/providers/common/ai/tests/unit/common/ai/durable/test_member_stamp.py
new file mode 100644
index 00000000000..ba59c6791a8
--- /dev/null
+++ b/providers/common/ai/tests/unit/common/ai/durable/test_member_stamp.py
@@ -0,0 +1,105 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Chain members stamp the responses they answer, so a replay can tell who
answered."""
+
+from __future__ import annotations
+
+import pytest
+from pydantic_ai import Agent
+from pydantic_ai.exceptions import ModelAPIError, ModelHTTPError
+from pydantic_ai.messages import ModelMessage, ModelResponse, TextPart
+from pydantic_ai.models.fallback import FallbackModel
+from pydantic_ai.models.function import AgentInfo, FunctionModel
+
+from airflow.providers.common.ai.durable.member_stamp import (
+ MEMBER_CONN_ID_KEY,
+ MEMBER_MODEL_ID_KEY,
+ MEMBER_STAMP_KEY,
+ MemberStampingModel,
+ get_member_conn_id,
+ get_member_model_id,
+)
+
+pytestmark = pytest.mark.asyncio
+
+
+def build_chain(conn_ids: tuple[str | None, str | None] = (None, None)) ->
FallbackModel:
+ def fail(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
+ raise ModelHTTPError(500, "first")
+
+ async def fail_stream(messages: list[ModelMessage], info: AgentInfo):
+ raise ModelHTTPError(500, "first")
+ yield ""
+
+ def answer(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
+ return ModelResponse(parts=[TextPart("from second")])
+
+ async def answer_stream(messages: list[ModelMessage], info: AgentInfo):
+ yield "from second"
+
+ first = FunctionModel(fail, stream_function=fail_stream,
model_name="first")
+ second = FunctionModel(answer, stream_function=answer_stream,
model_name="second")
+ return FallbackModel(
+ MemberStampingModel(first, conn_id=conn_ids[0]),
+ MemberStampingModel(second, conn_id=conn_ids[1]),
+ fallback_on=(ModelAPIError,),
+ )
+
+
+class TestMemberStamp:
+ async def test_a_response_names_the_member_that_answered(self):
+ chain = build_chain()
+
+ result = await Agent(chain).run("go")
+
+ assert result.response.metadata[MEMBER_STAMP_KEY] ==
{MEMBER_MODEL_ID_KEY: "function:second"}
+ assert get_member_model_id(result.response) == "function:second"
+
+ async def test_a_member_built_with_a_conn_id_stamps_it(self):
+ chain = build_chain(conn_ids=("first_conn", "second_conn"))
+
+ result = await Agent(chain).run("go")
+
+ assert result.response.metadata[MEMBER_STAMP_KEY] == {
+ MEMBER_MODEL_ID_KEY: "function:second",
+ MEMBER_CONN_ID_KEY: "second_conn",
+ }
+ assert get_member_conn_id(result.response) == "second_conn"
+
+ @pytest.mark.parametrize(
+ "metadata",
+ [
+ pytest.param(None, id="no stamp"),
+ pytest.param({MEMBER_STAMP_KEY: {MEMBER_MODEL_ID_KEY: "m"}},
id="no conn id in the stamp"),
+ pytest.param({MEMBER_STAMP_KEY: {MEMBER_CONN_ID_KEY: 3}}, id="conn
id is not a string"),
+ ],
+ )
+ async def test_get_member_conn_id_without_a_usable_value(self, metadata):
+ assert get_member_conn_id(ModelResponse(parts=[TextPart("hi")],
metadata=metadata)) is None
+
+ async def test_a_streamed_response_names_the_member_that_answered(self):
+ chain = build_chain()
+
+ async with Agent(chain).run_stream("go") as streamed:
+ await streamed.get_output()
+
+ assert get_member_model_id(streamed.response) == "function:second"
+
+ async def test_the_chain_keeps_its_own_identity(self):
+ chain = build_chain()
+
+ assert chain.model_id == "fallback:function:first,function:second"
diff --git a/providers/common/ai/tests/unit/common/ai/hooks/test_pydantic_ai.py
b/providers/common/ai/tests/unit/common/ai/hooks/test_pydantic_ai.py
index 4ea6707acb6..1f6abbbc6e0 100644
--- a/providers/common/ai/tests/unit/common/ai/hooks/test_pydantic_ai.py
+++ b/providers/common/ai/tests/unit/common/ai/hooks/test_pydantic_ai.py
@@ -34,8 +34,8 @@ import pytest
from pydantic_ai import Agent
from pydantic_ai.capabilities import AbstractCapability
from pydantic_ai.exceptions import FallbackExceptionGroup, ModelAPIError
-from pydantic_ai.messages import ModelResponse, TextPart, ToolCallPart,
ToolReturnPart
-from pydantic_ai.models import Model
+from pydantic_ai.messages import ModelRequest, ModelResponse, TextPart,
ToolCallPart, ToolReturnPart
+from pydantic_ai.models import Model, ModelRequestParameters
from pydantic_ai.models.fallback import FallbackModel
from pydantic_ai.models.function import FunctionModel
from pydantic_ai.models.openai import OpenAIChatModel
@@ -43,6 +43,11 @@ from pydantic_ai.models.test import TestModel
from pydantic_ai.providers import infer_provider_class
from airflow.models.connection import Connection
+from airflow.providers.common.ai.durable.member_stamp import (
+ MemberStampingModel,
+ get_member_conn_id,
+ get_member_model_id,
+)
from airflow.providers.common.ai.get_provider_info import get_provider_info
from airflow.providers.common.ai.hooks.pydantic_ai import (
ModelReadinessBackend,
@@ -64,6 +69,15 @@ from airflow.providers_manager import HookInfo
_GOOGLE_MODEL_PREFIX_RE = re.compile(r"google[\w-]*(?=:)")
+def get_chain_members(model: FallbackModel) -> list[Model]:
+ """Return the models of a chain with the member-stamping wrapper taken
off."""
+ members = []
+ for member in model.models:
+ assert isinstance(member, MemberStampingModel)
+ members.append(member.wrapped)
+ return members
+
+
def build_backend(*, model_name: str, base_url: str | None) ->
ModelReadinessBackend:
raise NotImplementedError
@@ -907,12 +921,60 @@ class TestPydanticAIHookFallback:
model = hook.get_conn()
assert isinstance(model, FallbackModel)
- assert model.models == [
+ assert get_chain_members(model) == [
infer_model_stub.models["openai:gpt-5.6-sol"],
infer_model_stub.models["anthropic:claude-opus-4-6"],
infer_model_stub.models["groq:llama-4"],
]
+ @pytest.mark.asyncio
+ async def test_response_is_stamped_with_the_member_that_answered(self,
registry, infer_model_stub):
+ def fail(messages, info):
+ raise ModelAPIError("primary", "down")
+
+ def answer(messages, info):
+ return ModelResponse(parts=[TextPart("answered")])
+
+ infer_model_stub.models["openai:gpt-5.6-sol"] = FunctionModel(fail,
model_name="primary-model")
+ infer_model_stub.models["anthropic:claude-opus-4-6"] = FunctionModel(
+ answer, model_name="second-model"
+ )
+ registry.add("primary", extra={"model": "openai:gpt-5.6-sol"})
+ registry.add("second", extra={"model": "anthropic:claude-opus-4-6"})
+
+ model = PydanticAIHook(llm_conn_id="primary",
fallback_conn_ids=["second"]).get_conn()
+ response = await model.request([ModelRequest.user_text_prompt("go")],
None, ModelRequestParameters())
+
+ assert get_member_model_id(response) == "function:second-model"
+ assert get_member_conn_id(response) == "second"
+
+ @pytest.mark.asyncio
+ async def
test_two_connections_serving_one_model_each_stamp_their_own_conn_id(
+ self, registry, infer_model_stub
+ ):
+ asked = []
+
+ def fail_then_answer(messages, info):
+ asked.append(info)
+ if len(asked) == 1:
+ raise ModelAPIError("shared", "down")
+ return ModelResponse(parts=[TextPart("answered")])
+
+ infer_model_stub.models["openai:gpt-5.6-sol"] =
FunctionModel(fail_then_answer, model_name="shared")
+ registry.add("primary", extra={"model": "openai:gpt-5.6-sol"})
+ registry.add("gateway", extra={"model": "openai:gpt-5.6-sol"})
+
+ model = PydanticAIHook(llm_conn_id="primary",
fallback_conn_ids=["gateway"]).get_conn()
+ response = await model.request([ModelRequest.user_text_prompt("go")],
None, ModelRequestParameters())
+
+ assert isinstance(model, FallbackModel)
+ assert [member.conn_id for member in model.models if
isinstance(member, MemberStampingModel)] == [
+ "primary",
+ "gateway",
+ ]
+ assert get_member_conn_id(response) == "gateway"
+ assert get_member_model_id(response) == "function:shared"
+
@patch("airflow.providers.common.ai.hooks.pydantic_ai.FallbackModel",
autospec=True)
def test_chain_pins_fallback_on_to_model_api_error(self,
mock_fallback_model, registry, infer_model_stub):
"""The chain must not drift with pydantic-ai's own ``fallback_on``
default.
@@ -926,13 +988,14 @@ class TestPydanticAIHookFallback:
PydanticAIHook(llm_conn_id="primary",
fallback_conn_ids=["second"]).get_conn()
- assert mock_fallback_model.mock_calls == [
- call(
- infer_model_stub.models["openai:gpt-5.6-sol"],
- infer_model_stub.models["anthropic:claude-opus-4-6"],
- fallback_on=(ModelAPIError,),
- )
+ mock_fallback_model.assert_called_once()
+ members = mock_fallback_model.call_args.args
+ kwargs = mock_fallback_model.call_args.kwargs
+ assert [member.wrapped for member in members] == [
+ infer_model_stub.models["openai:gpt-5.6-sol"],
+ infer_model_stub.models["anthropic:claude-opus-4-6"],
]
+ assert kwargs == {"fallback_on": (ModelAPIError,)}
def test_chain_from_connection_extra(self, registry, infer_model_stub):
"""A deployment manager can configure failover without touching Dag
code."""
@@ -945,7 +1008,7 @@ class TestPydanticAIHookFallback:
model = PydanticAIHook(llm_conn_id="primary").get_conn()
assert isinstance(model, FallbackModel)
- assert model.models == [
+ assert get_chain_members(model) == [
infer_model_stub.models["openai:gpt-5.6-sol"],
infer_model_stub.models["anthropic:claude-opus-4-6"],
]
@@ -961,7 +1024,7 @@ class TestPydanticAIHookFallback:
model = PydanticAIHook(llm_conn_id="primary",
fallback_conn_ids=["second"]).get_conn()
assert isinstance(model, FallbackModel)
- assert model.models[1] is
infer_model_stub.models["anthropic:claude-opus-4-6"]
+ assert get_chain_members(model)[1] is
infer_model_stub.models["anthropic:claude-opus-4-6"]
def test_empty_list_param_disables_the_extra_chain(self, registry,
infer_model_stub):
"""``[]`` is an explicit opt-out, distinct from ``None`` meaning "read
the extra"."""
@@ -998,7 +1061,7 @@ class TestPydanticAIHookFallback:
model = hook.get_conn()
assert isinstance(model, FallbackModel)
- assert model.models == [
+ assert get_chain_members(model) == [
infer_model_stub.models["openai:gpt-5.6-sol"],
infer_model_stub.models["bedrock:us.anthropic.claude-opus-4-5"],
]
@@ -1027,7 +1090,7 @@ class TestPydanticAIHookFallback:
model = hook.get_conn()
assert isinstance(model, FallbackModel)
- assert model.models == [
+ assert get_chain_members(model) == [
infer_model_stub.models["azure:gpt-5-nano"],
infer_model_stub.models["bedrock:gpt-5-nano"],
]
@@ -1053,7 +1116,7 @@ class TestPydanticAIHookFallback:
model = PydanticAIAzureHook(llm_conn_id="primary").get_conn()
assert isinstance(model, FallbackModel)
- assert model.models == [
+ assert get_chain_members(model) == [
infer_model_stub.models["azure:gpt-5-nano"],
infer_model_stub.models["bedrock:gpt-5-nano"],
]
@@ -1074,7 +1137,7 @@ class TestPydanticAIHookFallback:
model = hook.get_conn()
assert isinstance(model, FallbackModel)
- assert model.models[1] is
infer_model_stub.models["bedrock:us.anthropic.claude-opus-4-5"]
+ assert get_chain_members(model)[1] is
infer_model_stub.models["bedrock:us.anthropic.claude-opus-4-5"]
def test_prefixed_model_id_not_forwarded_to_fallback(self, registry,
infer_model_stub):
"""A prefixed ``model_id`` pins the primary's own platform and is
unusable on a fallback."""
@@ -1118,7 +1181,7 @@ class TestPydanticAIHookFallback:
model = hook.get_conn()
assert isinstance(model, FallbackModel)
- assert model.models == [
+ assert get_chain_members(model) == [
infer_model_stub.models["bedrock:us.anthropic.claude-opus-4-6-v1:0"],
infer_model_stub.models["bedrock:us.anthropic.claude-opus-4-6-v1:0"],
]
@@ -1161,7 +1224,7 @@ class TestPydanticAIHookFallback:
model = PydanticAIHook(llm_conn_id="gateway").get_conn()
assert isinstance(model, FallbackModel)
- assert model.models == [
+ assert get_chain_members(model) == [
infer_model_stub.models["openai-chat:claude-sonnet-4-5"],
infer_model_stub.models["anthropic:claude-sonnet-4-5"],
]
@@ -1174,7 +1237,7 @@ class TestPydanticAIHookFallback:
model = PydanticAIHook(llm_conn_id="gateway",
model_id="llama3:70b").get_conn()
assert isinstance(model, FallbackModel)
- assert model.models == [
+ assert get_chain_members(model) == [
infer_model_stub.models["openai-chat:llama3:70b"],
infer_model_stub.models["openai-chat:llama3:70b"],
]
@@ -1257,7 +1320,7 @@ class TestPydanticAIHookFallback:
model = PydanticAIHook(llm_conn_id="primary",
fallback_conn_ids=fallback_conn_ids).get_conn()
assert isinstance(model, FallbackModel)
- assert model.models == [
+ assert get_chain_members(model) == [
infer_model_stub.models["openai:gpt-5.6-sol"],
infer_model_stub.models["anthropic:claude-opus-4-6"],
]
@@ -1273,7 +1336,7 @@ class TestPydanticAIHookFallback:
model = PydanticAIHook(llm_conn_id="primary").get_conn()
assert isinstance(model, FallbackModel)
- assert model.models == [
+ assert get_chain_members(model) == [
infer_model_stub.models["openai:gpt-5.6-sol"],
infer_model_stub.models["anthropic:claude-opus-4-6"],
]
@@ -1294,7 +1357,7 @@ class TestPydanticAIHookFallback:
model = PydanticAIHook(llm_conn_id="primary", fallback_conn_ids=["
second "]).get_conn()
assert isinstance(model, FallbackModel)
- assert model.models == [
+ assert get_chain_members(model) == [
infer_model_stub.models["openai:gpt-5.6-sol"],
infer_model_stub.models["anthropic:claude-opus-4-6"],
]
@@ -2784,7 +2847,7 @@ class TestPydanticAIHookAsync:
model = await PydanticAIHook(llm_conn_id="primary").aget_conn()
assert isinstance(model, FallbackModel)
- assert model.models == [
+ assert get_chain_members(model) == [
infer_model_stub.models["openai:gpt-5.6-sol"],
infer_model_stub.models["anthropic:claude-opus-4-6"],
infer_model_stub.models["groq:llama-4"],
@@ -3002,8 +3065,8 @@ class TestPydanticAIHookConnectionCache:
assert isinstance(first_model, FallbackModel)
assert isinstance(second_model, FallbackModel)
assert (
- first_model.models
- == second_model.models
+ get_chain_members(first_model)
+ == get_chain_members(second_model)
== [
infer_model_stub.models["openai:gpt-5.6-sol"],
infer_model_stub.models["anthropic:claude-opus-4-6"],