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


##########
providers/databricks/src/airflow/providers/databricks/hooks/model_serving.py:
##########
@@ -0,0 +1,302 @@
+# 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.
+"""Expose Databricks Model Serving's OpenAI-compatible chat endpoint as a 
pydantic-ai model hook."""
+
+from __future__ import annotations
+
+import asyncio
+import concurrent.futures
+import contextvars
+import functools
+import inspect
+from typing import TYPE_CHECKING, Any, cast
+from urllib.parse import urlsplit
+
+from tenacity import RetryError
+
+from airflow.providers.common.compat.sdk import AirflowException, 
AirflowOptionalProviderFeatureException
+from airflow.providers.databricks.hooks.databricks_base import 
BaseDatabricksHook
+
+_COMMON_AI_REQUIREMENT_MESSAGE = (
+    "This feature requires apache-airflow-providers-common-ai>=1.0.0 (a 
PydanticAIHook with "
+    "'fallback_conn_ids'). "
+    "Install with apache-airflow-providers-databricks[common.ai]."
+)
+
+try:
+    import httpx2
+
+    from airflow.providers.common.ai.hooks.pydantic_ai import PydanticAIHook
+except ImportError:
+    raise 
AirflowOptionalProviderFeatureException(_COMMON_AI_REQUIREMENT_MESSAGE)
+
+if "fallback_conn_ids" not in 
inspect.signature(PydanticAIHook.__init__).parameters:
+    raise 
AirflowOptionalProviderFeatureException(_COMMON_AI_REQUIREMENT_MESSAGE)
+
+if TYPE_CHECKING:
+    from collections.abc import AsyncGenerator, Generator
+
+    from httpx2 import Request, Response
+
+# OpenAIProvider rejects an empty api_key, but _DatabricksServingAuth 
overwrites Authorization on
+# every request, so this value is never sent.
+_UNUSED_TOKEN_PLACEHOLDER = "unused-overridden-per-request"
+
+# Token refreshes run here, never on asyncio's default executor: ``asend()`` 
reads its reply on that
+# executor while holding the comms lock, so blocking lookups that fill it 
leave nothing to run the
+# read and the task hangs (common.ai>=1.1.0 guards against the same thing with 
``_executor`` in
+# ``hooks/pydantic_ai.py``). Some ``_get_token`` paths do such lookups at 
request time (AWS
+# federation resolves a second Airflow connection through ``StsHook``). Kept 
local: common.ai's
+# ``_run_off_loop`` only exists from 1.1.0.
+_executor = concurrent.futures.ThreadPoolExecutor(max_workers=1, 
thread_name_prefix="databricks-serving-auth")
+
+
+def _is_valid_host(host: str | None) -> bool:
+    """Return whether ``host`` is a bare ``hostname[:port]`` as left by 
``BaseDatabricksHook._parse_host``."""
+    if not host or host.endswith(":") or any(char.isspace() for char in host):
+        return False
+    parsed = urlsplit(f"//{host}")
+    if not parsed.hostname or parsed.netloc != host or parsed.username is not 
None:
+        return False
+    try:
+        parsed.port
+    except ValueError:
+        return False
+    return True
+
+
+def _is_transient_token_failure(error: BaseException) -> bool:
+    """Return whether ``error`` follows an exhausted retry of a token 
request."""
+    # BaseDatabricksHook has no dedicated exception type: a tenacity 
RetryError on the chain is the
+    # only signal that the token endpoint was unreachable, not misconfigured.
+    seen: set[int] = set()
+    node: BaseException | None = error
+    while node is not None and id(node) not in seen:
+        if isinstance(node, RetryError):
+            return True
+        seen.add(id(node))
+        node = node.__cause__ or node.__context__
+    return False
+
+
+def _get_databricks_token(databricks_hook: BaseDatabricksHook) -> str:
+    """Return the token for ``databricks_hook``, accepting Login ``token`` 
with a Password as a PAT."""
+    # ``_get_token`` returns None only when no other auth setting applies, so 
a PAT login never
+    # takes over from OAuth, Azure or federation settings. The base hook sends 
such a connection as
+    # Basic auth, which this hook cannot use against /serving-endpoints.
+    token = databricks_hook._get_token()
+    if token:
+        return token
+    conn = databricks_hook.databricks_conn
+    if conn.login == "token" and conn.password:
+        return conn.password
+    return cast("str", databricks_hook._get_token(raise_error=True))
+
+
+class _DatabricksServingAuth(httpx2.Auth):
+    """
+    Refresh the ``Authorization`` header on every request from a Databricks 
hook.
+
+    ``_get_token()`` may block: the OAuth service principal, Azure AD and 
federation paths make
+    HTTP or SDK calls, with retries, to fetch an expiring token. 
``async_auth_flow`` is overridden
+    to run the refresh on a worker thread instead of the httpx2 default of 
driving the sync
+    ``auth_flow`` inline on the event loop. ``auth_flow`` itself is kept for 
sync ``httpx2.Client``
+    callers, which have no event loop to block.
+
+    A token fetch that still cannot reach the token endpoint after its retries 
raises
+    ``httpx2.ConnectError`` so that ``fallback_conn_ids`` can fail over. Any 
other failure, such as
+    missing credentials or a rejected secret, keeps its original exception. 
That guarantee needs
+    ``openai>=3.15.0``: earlier versions catch every exception raised while 
sending a request and

Review Comment:
   openai 3.8 to 3.14 still fit the pins (pydantic-ai-slim 2.46 asks for 
`openai>=3.8.0`), and there a missing credential silently falls back. Could 
`_get_provider_kwargs` fetch the token once and re-raise anything 
`_is_transient_token_failure` doesn't match? That way a bad connection fails on 
any openai version.



##########
providers/databricks/docs/connections/pydantic_ai_databricks.rst:
##########
@@ -0,0 +1,186 @@
+ .. 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.
+
+.. _howto/connection:pydanticai_databricks:
+
+Pydantic AI (Databricks Model Serving) connection
+=================================================
+
+The ``pydanticai_databricks`` connection type configures access to
+`Databricks Model Serving 
<https://docs.databricks.com/aws/en/machine-learning/model-serving/>`__
+through its OpenAI-compatible Chat Completions API, via the pydantic-ai 
framework. It backs
+``PydanticAIDatabricksHook``, the dedicated subclass of ``PydanticAIHook`` for 
Databricks.
+
+This connection type sources credentials from an existing
+:ref:`Databricks connection <howto/connection:databricks>`, so the token-based 
authentication
+methods that connection supports (OAuth, Azure AD, managed identity, 
federation) are reused and
+refreshed on every request, except for the settings this hook rejects (see 
Authentication below).
+
+Install with:
+
+.. code-block:: bash
+
+    pip install 'apache-airflow-providers-databricks[common.ai]' 
'apache-airflow-providers-common-ai[openai]'
+
+The ``common.ai`` extra provides the Common AI hook this one builds on, but 
not the OpenAI client
+the Chat Completions API calls go through, so also install 
``apache-airflow-providers-common-ai[openai]``.
+
+Choosing a connection type
+--------------------------
+
+For a personal access token, a plain ``pydanticai`` connection is enough: set 
the Model to
+``openai-chat:<endpoint>``, the Host to 
``https://<workspace>/serving-endpoints`` and put the token
+in Password (see 
:doc:`apache-airflow-providers-common-ai:connections/pydantic_ai`). Use
+``pydanticai_databricks`` when you want to reuse an existing Databricks 
connection, or when the
+credential needs a fresh token per request, such as OAuth for a service 
principal, Azure or
+token federation. A personal access token also works with this connection type.
+
+Default Connection IDs
+----------------------
+
+The ``PydanticAIDatabricksHook`` uses ``pydanticai_databricks_default`` by 
default.
+
+Configuring the Connection
+--------------------------
+
+This connection type needs two connections: this one, and an existing 
``databricks`` connection it
+points at. All fields below are ``extra`` (JSON) fields on the 
``pydanticai_databricks``
+connection; ``Schema``, ``Port``, ``Login``, ``Host``, and ``Password`` are 
hidden in the
+connection form because the workspace host and credentials come from the 
Databricks connection
+instead.
+
+Model
+    Serving endpoint name (e.g. ``my-serving-endpoint``).
+
+    A bare name is resolved to ``openai-chat:<name>``, which uses the Chat 
Completions API.
+    Databricks documents querying chat models through the OpenAI client for
+    `Foundation Model APIs
+    
<https://docs.databricks.com/aws/en/machine-learning/model-serving/score-foundation-models>`__,
+    `external models 
<https://docs.databricks.com/aws/en/machine-learning/foundation-models/external-models>`__
 and
+    `custom LLM endpoints
+    
<https://docs.databricks.com/aws/en/machine-learning/model-serving/serve-custom-llms>`__
+    served with the chat task. Databricks does not document Chat Completions 
for other endpoint types,
+    such as embedding or traditional ML endpoints; this hook is not intended 
for them.
+
+    In pydantic-ai, the ``openai:`` prefix selects the Responses API and 
``openai-chat:`` selects
+    Chat Completions, as described in the
+    `pydantic-ai OpenAI documentation 
<https://pydantic.dev/docs/ai/models/openai/>`__. An explicit
+    ``openai:<name>`` therefore sends Responses API requests. Databricks 
documents its Responses API
+    passthrough for OpenAI models; see
+    `Query chat models
+    
<https://docs.databricks.com/aws/en/machine-learning/model-serving/query-chat-models>`__.
+
+Fallback Connections
+    Other connection IDs to fail over to, in order, while this provider is 
unavailable. Stored in
+    ``extra["fallback_conn_ids"]``. Entries may name any ``pydanticai`` 
connection type, so one
+    chain can span vendors. Fail-over also happens when the Databricks token 
endpoint cannot be
+    reached or keeps failing after its retries; a configuration error, such as 
unset or rejected

Review Comment:
   An Entra ID outage on an Azure SPN connection comes back as 
`ClientAuthenticationError` with no `RetryError` on it, because 
`_retryable_error` only retries requests/aiohttp errors. So that one fails the 
task. AWS federation's `StsHook` call looks the same. Maybe scope this sentence 
to Databricks-issued tokens?



##########
providers/databricks/tests/unit/databricks/hooks/test_model_serving.py:
##########
@@ -0,0 +1,724 @@
+# 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.
+from __future__ import annotations
+
+import pytest
+
+pytest.importorskip("airflow.providers.common.ai.hooks.pydantic_ai")
+pytest.importorskip("pydantic_ai.providers.openai")
+
+import contextvars
+import importlib
+import json
+import sys
+import threading
+from importlib.metadata import version as get_package_version
+from unittest import mock
+
+import httpx2
+from openai import AsyncOpenAI
+from packaging.version import Version
+from pydantic_ai import Agent
+from pydantic_ai.exceptions import ModelAPIError
+from pydantic_ai.messages import ModelResponse, TextPart
+from pydantic_ai.models.fallback import FallbackModel
+from pydantic_ai.models.function import FunctionModel
+from pydantic_ai.models.openai import OpenAIChatModel
+from pydantic_ai.providers.openai import OpenAIProvider
+from requests import exceptions as requests_exceptions
+from tenacity import Future, RetryError
+
+from airflow.models import Connection
+from airflow.providers.common.ai.hooks.pydantic_ai import PydanticAIHook
+from airflow.providers.common.compat.sdk import AirflowException, 
AirflowOptionalProviderFeatureException
+from airflow.providers.databricks import hooks as databricks_hooks
+from airflow.providers.databricks.hooks.databricks_base import 
BaseDatabricksHook
+from airflow.providers.databricks.hooks.model_serving import (
+    _UNUSED_TOKEN_PLACEHOLDER,
+    PydanticAIDatabricksHook,
+    _DatabricksServingAuth,
+)
+
+MODULE_PATH = "airflow.providers.databricks.hooks.model_serving"
+SERVING_URL = "https://adb-1.azuredatabricks.net/serving-endpoints";
+CONNECTION_EXTRA = {"model": "databricks-claude-sonnet-4-5", 
"databricks_conn_id": "databricks_conn"}
+DATABRICKS_CONN_URI = Connection(conn_type="pydanticai_databricks", 
extra=CONNECTION_EXTRA).get_uri()
+LEFTOVER_PASSWORD_CONN_URI = Connection(
+    conn_type="pydanticai_databricks", password="leftover-password", 
extra=CONNECTION_EXTRA
+).get_uri()
+# openai before 3.15.0 wraps any exception raised while sending a request, 
including one from an
+# httpx2 auth, in APIConnectionError; from 3.15.0 only httpx2 request errors 
are wrapped.
+_OPENAI_WRAPS_EVERY_SEND_ERROR = Version(get_package_version("openai")) < 
Version("3.15.0")
+PRIMARY_CONN_URI = Connection(
+    conn_type="pydanticai",
+    password="sk-test",
+    extra={"model": "openai:gpt-5", "fallback_conn_ids": ["fallback_conn"]},
+).get_uri()
+
+
+def _mock_databricks_hook(mock_hook_cls):
+    mock_hook = mock_hook_cls.return_value
+    mock_hook.host = "adb-1.azuredatabricks.net"
+    mock_hook.databricks_conn_id = "databricks_conn"
+    mock_hook.proxies = None
+    mock_hook.databricks_conn.extra_dejson = {}
+    mock_hook._endpoint_url.return_value = SERVING_URL
+    mock_hook._get_token.return_value = "real-token"
+    return mock_hook
+
+
+def _build_token_error(error: Exception, *, cause: BaseException | None = 
None, context=None) -> Exception:
+    error.__cause__ = cause
+    error.__context__ = context
+    return error
+
+
+def _retry_exhausted() -> RetryError:
+    return RetryError(Future(1))
+
+
+def _token_errors_by_kind() -> dict[str, tuple[Exception, bool]]:
+    """Map each kind of token failure to the exception ``_get_token`` raises 
and whether it is transient."""
+    return {
+        "retry_exhausted_explicit_cause": (
+            _build_token_error(
+                AirflowException("API requests to Databricks failed"), 
cause=_retry_exhausted()
+            ),
+            True,
+        ),
+        "retry_exhausted_implicit_context": (
+            _build_token_error(AirflowException("API requests to Azure 
failed"), context=_retry_exhausted()),
+            True,
+        ),
+        "managed_identity_connection_error": (
+            _build_token_error(
+                ConnectionError("Failed to reach Azure Metadata Service"), 
context=_retry_exhausted()
+            ),
+            True,
+        ),
+        "not_configured": (AirflowException("Token authentication isn't 
configured"), False),
+        "rejected_credentials": (
+            _build_token_error(
+                AirflowException("Response: Unauthorized, Status Code: 401"),
+                context=requests_exceptions.HTTPError("401"),
+            ),
+            False,
+        ),
+        "metadata_not_azure": (
+            _build_token_error(ConnectionError("Can't reach Azure Metadata 
Service"), context=ValueError()),
+            False,
+        ),
+    }
+
+
+class TestDatabricksConnIdResolution:
+    def test_hook_argument_wins_over_extra(self):
+        hook = PydanticAIDatabricksHook(databricks_conn_id="explicit_conn")
+        assert hook._get_databricks_conn_id({"databricks_conn_id": 
"extra_conn"}) == "explicit_conn"
+
+    def test_falls_back_to_extra(self):
+        hook = PydanticAIDatabricksHook()
+        assert hook._get_databricks_conn_id({"databricks_conn_id": 
"extra_conn"}) == "extra_conn"
+
+    def test_raises_when_neither_is_set(self):
+        hook = PydanticAIDatabricksHook(llm_conn_id="pydanticai_conn")
+        with pytest.raises(ValueError, match="Databricks connection"):
+            hook._get_databricks_conn_id({})
+
+
+class TestGetProviderKwargs:
+    @mock.patch(f"{MODULE_PATH}.BaseDatabricksHook", autospec=True)
+    def test_ignores_connection_password_and_host(self, mock_hook_cls):
+        """Leftover Password/Host on the pydanticai_databricks connection must 
not reach the provider."""
+        _mock_databricks_hook(mock_hook_cls)
+
+        hook = PydanticAIDatabricksHook(databricks_conn_id="databricks_conn")
+        kwargs = hook._get_provider_kwargs(
+            api_key="leftover-password", 
base_url="https://ignored.example.com";, extra={}
+        )
+
+        assert kwargs["base_url"] == SERVING_URL
+        
mock_hook_cls.return_value._endpoint_url.assert_called_once_with("serving-endpoints")
+        assert kwargs["api_key"] == _UNUSED_TOKEN_PLACEHOLDER
+        mock_hook_cls.return_value._get_token.assert_not_called()
+        assert isinstance(kwargs["http_client"], httpx2.AsyncClient)
+        # Pin that per-request refresh is actually wired up: deleting 
`auth=...` from
+        # `_get_databricks_hook` would leave every assertion above green.
+        client_auth = kwargs["http_client"].auth
+        assert isinstance(client_auth, _DatabricksServingAuth)
+        assert client_auth._databricks_hook is mock_hook_cls.return_value
+
+    @mock.patch(f"{MODULE_PATH}.BaseDatabricksHook", autospec=True)
+    def test_databricks_hook_built_once(self, mock_hook_cls):
+        """A second call must reuse the same Databricks hook, not rebuild 
it."""
+        _mock_databricks_hook(mock_hook_cls)
+
+        hook = PydanticAIDatabricksHook(databricks_conn_id="databricks_conn")
+        first = hook._get_provider_kwargs(None, None, {})
+        second = hook._get_provider_kwargs(None, None, {})
+
+        mock_hook_cls.assert_called_once_with(
+            databricks_conn_id="databricks_conn", 
caller="PydanticAIDatabricksHook"
+        )
+        assert first["http_client"] is second["http_client"]
+
+    @pytest.mark.parametrize(
+        "raw_host",
+        [
+            pytest.param(None, id="none"),
+            pytest.param("", id="empty"),
+            pytest.param("https://";, id="scheme-only"),
+            pytest.param("  ", id="blank"),
+            pytest.param("adb-1.azuredatabricks.net/serving-endpoints", 
id="with-path"),
+            pytest.param("adb-1.azuredatabricks.net#frag", id="with-fragment"),
+            pytest.param("adb-1.azuredatabricks.net:", id="empty-port"),
+            pytest.param("adb-1.azuredatabricks.net:abc", 
id="non-numeric-port"),
+            pytest.param("adb-1.azuredatabricks.net:99999", 
id="port-out-of-range"),
+            pytest.param("[email protected]", 
id="userinfo-username"),
+            pytest.param("@adb-1.azuredatabricks.net", 
id="userinfo-empty-username"),
+            pytest.param("svc:[email protected]", 
id="userinfo-username-and-password"),
+            
pytest.param("svc:[email protected]/serving-endpoints", 
id="userinfo-and-path"),
+            pytest.param(":443", id="port-only"),
+            pytest.param("https://[::1]:443";, id="ipv6-with-scheme"),
+            pytest.param("https://adb-1.azuredatabricks.net  ", 
id="trailing-whitespace-with-scheme"),
+        ],
+    )
+    @mock.patch(f"{MODULE_PATH}.BaseDatabricksHook", autospec=True)
+    def test_raises_when_databricks_connection_has_no_valid_host(self, 
mock_hook_cls, raw_host):
+        mock_hook = _mock_databricks_hook(mock_hook_cls)
+        # Feed the host through the real normalisation the Databricks hook 
applies to the connection.
+        mock_hook.host = BaseDatabricksHook._parse_host(raw_host) if raw_host 
else raw_host
+
+        hook = PydanticAIDatabricksHook(databricks_conn_id="databricks_conn")
+        with pytest.raises(ValueError, match="'databricks_conn' has no valid 
host") as exc_info:
+            hook._get_provider_kwargs(None, None, {})
+
+        # The host may carry credentials, so the message must never echo any 
part of it.
+        assert "s3cr3t" not in str(exc_info.value)
+        assert "svc" not in str(exc_info.value)
+        mock_hook._endpoint_url.assert_not_called()
+        assert hook._databricks_hook is None
+
+    @pytest.mark.parametrize(
+        "raw_host",
+        [
+            pytest.param("adb-1.azuredatabricks.net", id="bare"),
+            pytest.param("https://adb-1.azuredatabricks.net";, 
id="with-scheme"),
+            pytest.param("adb-1.azuredatabricks.net/", id="trailing-slash"),
+            pytest.param("https://adb-1.azuredatabricks.net/";, 
id="scheme-and-trailing-slash"),
+            pytest.param("adb-1.azuredatabricks.net:443", id="with-port"),
+            pytest.param("https://svc:[email protected]";, 
id="scheme-drops-userinfo"),
+            pytest.param("[::1]:443", id="ipv6-bare"),
+        ],
+    )
+    @mock.patch(f"{MODULE_PATH}.BaseDatabricksHook", autospec=True)
+    def test_accepts_host_shapes_the_databricks_hook_accepts(self, 
mock_hook_cls, raw_host):
+        mock_hook = _mock_databricks_hook(mock_hook_cls)
+        mock_hook.host = BaseDatabricksHook._parse_host(raw_host)
+
+        hook = PydanticAIDatabricksHook(databricks_conn_id="databricks_conn")
+
+        assert hook._get_provider_kwargs(None, None, {})["base_url"] == 
SERVING_URL
+        mock_hook._endpoint_url.assert_called_once_with("serving-endpoints")
+
+    @pytest.mark.parametrize(
+        "proxies",
+        [
+            pytest.param({"https": "http://user:[email protected]:3128"}, 
id="https"),
+            pytest.param({"http": "http://proxy.example:3128"}, id="http"),
+            pytest.param(
+                {"http": "http://proxy.example:3128";, "https": 
"http://proxy.example:3128"}, id="both"
+            ),
+        ],
+    )
+    @mock.patch(f"{MODULE_PATH}.BaseDatabricksHook", autospec=True)
+    def test_raises_when_databricks_connection_sets_proxies(self, 
mock_hook_cls, proxies):
+        mock_hook = _mock_databricks_hook(mock_hook_cls)
+        mock_hook.proxies = proxies
+
+        hook = PydanticAIDatabricksHook(databricks_conn_id="databricks_conn")
+        with pytest.raises(ValueError, match="'databricks_conn' sets the 
'proxies' extra") as exc_info:
+            hook._get_provider_kwargs(None, None, {})
+
+        assert "secret" not in str(exc_info.value)
+        assert hook._databricks_hook is None
+
+    @mock.patch(f"{MODULE_PATH}.BaseDatabricksHook", autospec=True)
+    def test_raises_when_databricks_connection_sets_azure_resource_id(self, 
mock_hook_cls):
+        mock_hook = _mock_databricks_hook(mock_hook_cls)
+        mock_hook.databricks_conn.extra_dejson = {"azure_resource_id": 
"/subscriptions/s3cr3t-sub"}
+
+        hook = PydanticAIDatabricksHook(databricks_conn_id="databricks_conn")
+        with pytest.raises(
+            ValueError, match="'databricks_conn' sets the 'azure_resource_id' 
extra"
+        ) as exc_info:
+            hook._get_provider_kwargs(None, None, {})
+
+        assert "s3cr3t-sub" not in str(exc_info.value)
+        mock_hook._endpoint_url.assert_not_called()
+        assert hook._databricks_hook is None
+
+    @pytest.mark.parametrize(
+        ("databricks_conn_kwargs", "expected_error"),
+        [
+            pytest.param(
+                {"host": "adb-1.azuredatabricks.net", "extra": {"proxies": 
{"https": "http://p:1"}}},
+                "sets the 'proxies' extra",
+                id="proxies",
+            ),
+            pytest.param(
+                {
+                    "host": "adb-1.azuredatabricks.net",
+                    "extra": {"azure_resource_id": 
"/subscriptions/s3cr3t-sub"},
+                },
+                "sets the 'azure_resource_id' extra",
+                id="azure-resource-id",
+            ),
+            pytest.param(
+                {"extra": {"host": "svc:[email protected]"}},
+                "has no valid host",
+                id="extra-host-with-userinfo",
+            ),
+            pytest.param(
+                {"host": "svc:[email protected]"},
+                "has no valid host",
+                id="connection-host-with-userinfo",
+            ),
+        ],
+    )
+    def test_rejects_unsupported_settings_on_a_real_databricks_connection(
+        self, databricks_conn_kwargs, expected_error
+    ):
+        """Run the guards against a real ``BaseDatabricksHook`` so a change in 
its attributes is caught."""
+        databricks_conn = Connection(conn_type="databricks", password="tok", 
**databricks_conn_kwargs)
+
+        with mock.patch.dict("os.environ", 
AIRFLOW_CONN_DBX=databricks_conn.get_uri()):
+            hook = PydanticAIDatabricksHook(databricks_conn_id="dbx")
+            with pytest.raises(ValueError, match=expected_error) as exc_info:
+                hook._get_databricks_hook({})
+
+        for secret in ("s3cr3t", "p:1", "svc"):
+            assert secret not in str(exc_info.value)
+        assert hook._databricks_hook is None
+
+    @mock.patch.dict(
+        "os.environ",
+        AIRFLOW_CONN_DBX=Connection(
+            conn_type="databricks", host="https://adb-1.azuredatabricks.net";, 
password="tok"
+        ).get_uri(),
+    )
+    def test_accepts_a_plain_real_databricks_connection(self):
+        hook = PydanticAIDatabricksHook(databricks_conn_id="dbx")
+
+        databricks_hook = hook._get_databricks_hook({})
+
+        assert isinstance(databricks_hook, BaseDatabricksHook)
+        assert hook._base_url == SERVING_URL
+
+    @mock.patch(f"{MODULE_PATH}.BaseDatabricksHook", autospec=True)
+    def test_failed_first_build_is_not_remembered(self, mock_hook_cls):
+        """A failed first build must not leave half-built state that the 
second call silently reuses."""
+        _mock_databricks_hook(mock_hook_cls)
+        mock_hook_cls.return_value._endpoint_url.side_effect = 
[RuntimeError("no host"), SERVING_URL]
+
+        hook = PydanticAIDatabricksHook(databricks_conn_id="databricks_conn")
+        with pytest.raises(RuntimeError, match="no host"):
+            hook._get_provider_kwargs(None, None, {})
+        kwargs = hook._get_provider_kwargs(None, None, {})
+
+        assert kwargs["base_url"] == SERVING_URL
+        assert isinstance(kwargs["http_client"], httpx2.AsyncClient)
+
+
+class TestBareModelNameQualification:
+    def test_bare_model_name_gets_openai_chat_prefix(self):
+        hook = 
PydanticAIDatabricksHook(model_id="databricks-claude-sonnet-4-5")
+        assert (
+            hook._qualify_model_name("databricks-claude-sonnet-4-5")
+            == "openai-chat:databricks-claude-sonnet-4-5"
+        )
+
+    def test_already_prefixed_model_name_is_unchanged(self):
+        hook = PydanticAIDatabricksHook(model_id="openai:my-endpoint")
+        assert hook._qualify_model_name("openai:my-endpoint") == 
"openai:my-endpoint"
+
+
+class TestDatabricksServingAuth:
+    def test_auth_flow_refreshes_token_per_request(self):
+        """Each request must ask the Databricks hook again, not reuse headers 
set on the client."""
+        databricks_hook = mock.create_autospec(BaseDatabricksHook, 
instance=True)
+        databricks_hook._get_token.side_effect = ["token-1", "token-2"]
+        seen_auth_headers = []
+
+        def handler(request: httpx2.Request) -> httpx2.Response:
+            seen_auth_headers.append(request.headers["Authorization"])
+            return httpx2.Response(200, json={"ok": True})
+
+        client = httpx2.Client(
+            auth=_DatabricksServingAuth(databricks_hook), 
transport=httpx2.MockTransport(handler)
+        )
+        client.get("https://example.com/x";)
+        client.get("https://example.com/x";)
+
+        assert seen_auth_headers == ["Bearer token-1", "Bearer token-2"]
+        databricks_hook._get_token.assert_called_with()
+
+    @pytest.mark.asyncio
+    async def test_async_auth_flow_refreshes_off_the_event_loop(self):
+        """`_get_token` may block (OAuth refresh, a connection lookup); it 
must run in a worker
+        thread, not inline on the event loop -- calling 
`BaseHook.get_connection` synchronously
+        from the loop thread while an async send is in flight raises 
`DeadlockImminentError`."""
+        loop_thread_ident = threading.get_ident()
+        seen_threads: list[threading.Thread] = []
+        tokens = iter(["token-1", "token-2"])
+
+        def get_token(raise_error: bool = False) -> str:
+            seen_threads.append(threading.current_thread())
+            return next(tokens)
+
+        databricks_hook = mock.create_autospec(BaseDatabricksHook, 
instance=True)
+        databricks_hook._get_token.side_effect = get_token
+        seen_auth_headers = []
+
+        async def handler(request: httpx2.Request) -> httpx2.Response:
+            seen_auth_headers.append(request.headers["Authorization"])
+            return httpx2.Response(200, json={"ok": True})
+
+        async with httpx2.AsyncClient(
+            auth=_DatabricksServingAuth(databricks_hook), 
transport=httpx2.MockTransport(handler)
+        ) as client:
+            await client.get("https://example.com/x";)
+            await client.get("https://example.com/x";)
+
+        assert seen_auth_headers == ["Bearer token-1", "Bearer token-2"]
+        assert seen_threads, "_get_token was never called"
+        assert all(thread.ident != loop_thread_ident for thread in 
seen_threads)
+        # The dedicated executor, not asyncio's default one: blocking lookups 
there can starve
+        # `asend()`'s reply read.
+        assert all(thread.name.startswith("databricks-serving-auth") for 
thread in seen_threads)
+
+    @pytest.mark.asyncio
+    async def 
test_async_auth_flow_carries_contextvars_into_worker_thread(self):
+        """`_get_token` may resolve Airflow connections, which relies on the 
caller's context."""
+        marker: contextvars.ContextVar[str] = contextvars.ContextVar("marker", 
default="unset")
+        seen_values: list[str] = []
+
+        def get_token(raise_error: bool = False) -> str:
+            seen_values.append(marker.get())
+            return "token"
+
+        databricks_hook = mock.create_autospec(BaseDatabricksHook, 
instance=True)
+        databricks_hook._get_token.side_effect = get_token
+
+        async with httpx2.AsyncClient(
+            auth=_DatabricksServingAuth(databricks_hook),
+            transport=httpx2.MockTransport(lambda request: 
httpx2.Response(200, json={})),
+        ) as client:
+            marker.set("from-caller")
+            await client.get("https://example.com/x";)
+
+        assert seen_values == ["from-caller"]
+
+    @pytest.mark.parametrize("kind", list(_token_errors_by_kind()))
+    def test_token_failure_is_converted_only_when_transient(self, kind):
+        error, is_transient = _token_errors_by_kind()[kind]
+        databricks_hook = mock.create_autospec(BaseDatabricksHook, 
instance=True)
+        databricks_hook._get_token.side_effect = error
+        handler = mock.Mock(spec=["__call__"])
+        client = httpx2.Client(
+            auth=_DatabricksServingAuth(databricks_hook), 
transport=httpx2.MockTransport(handler)
+        )
+
+        with pytest.raises(httpx2.ConnectError if is_transient else 
type(error)) as exc_info:
+            client.get("https://example.com/x";)
+
+        if is_transient:
+            assert exc_info.value.__cause__ is error
+            assert exc_info.value.request.url == "https://example.com/x";
+        else:
+            assert exc_info.value is error
+        handler.assert_not_called()
+
+    @pytest.mark.parametrize(
+        ("login", "expected"),
+        [
+            pytest.param("token", "Bearer the-pat", id="login-token-is-a-pat"),
+            pytest.param(None, "Bearer the-pat", id="empty-login-is-a-pat"),
+            pytest.param("some-user", None, id="other-login-is-not-a-pat"),
+        ],
+    )
+    def test_auth_flow_treats_login_token_with_password_as_pat(self, login, 
expected):
+        """The base hook sends Login ``token`` as Basic auth; serving 
endpoints need a Bearer header."""
+        databricks_conn = Connection(
+            conn_type="databricks", host="adb-1.azuredatabricks.net", 
login=login, password="the-pat"

Review Comment:
   Every case sets `password="the-pat"`, so dropping `and conn.password` from 
`_get_databricks_token` keeps the suite green and a blank password goes out as 
`Bearer None`. Worth a `login="token"` case with no password that expects 
"Token authentication isn't configured"?



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