Lee-W commented on code in PR #76797:
URL: https://github.com/apache/airflow/pull/76797#discussion_r4677901098


##########
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:
   `_get_provider_kwargs` now fetches the token once and re-raises anything 
`_is_transient_token_failure` doesn't match, so a bad connection fails when the 
model is built, whatever the openai version.
   
   Fallback members are built with the chain, so a misconfigured Databricks 
fallback connection now fails the task up front as well.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to