amoghrajesh commented on code in PR #74517: URL: https://github.com/apache/airflow/pull/74517#discussion_r4665388697
########## providers/databricks/tests/unit/databricks/hooks/test_genie.py: ########## @@ -0,0 +1,327 @@ +# 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 builtins +import importlib.util +import json +from pathlib import Path +from unittest import mock + +import pytest +import requests + +from airflow.providers.common.ai.toolsets import ManagedAgentToolset +from airflow.providers.common.compat.sdk import AirflowOptionalProviderFeatureException +from airflow.providers.databricks.hooks.genie import ( + DatabricksGenieError, + DatabricksGenieHook, + _summarize_query_result, + _truncate_result, +) + + +class TestDatabricksGenieHook: + def test_query_result_marks_omitted_chunks_and_columns_as_truncated(self): + partial_rows = _summarize_query_result( + { + "statement_response": { + "manifest": { + "schema": {"columns": [{"name": "count"}]}, + "total_row_count": 10, + "total_chunk_count": 2, + "truncated": False, + }, + "result": {"data_array": [[str(index)] for index in range(5)]}, + } + } + ) + assert len(partial_rows["rows"]) == 5 + assert partial_rows["total_row_count"] == 10 + assert partial_rows["truncated"] is True + + capped_columns = _summarize_query_result( + { + "manifest": { + "schema": {"columns": [{"name": f"column_{index}"} for index in range(101)]}, + "total_row_count": 1, + "truncated": False, + }, + "result": {"data_array": [["value"]]}, + } + ) + assert len(capped_columns["columns"]) == 100 + assert capped_columns["truncated"] is True + + def test_direct_hook_works_without_common_ai(self): + original_import = builtins.__import__ + + def block_common_ai(name, *args, **kwargs): + if name.startswith("airflow.providers.common.ai"): + raise ImportError("common.ai is unavailable") + return original_import(name, *args, **kwargs) + + path = Path(__file__).parents[4] / "src/airflow/providers/databricks/hooks/genie.py" + spec = importlib.util.spec_from_file_location("_genie_without_common_ai", path) + assert spec is not None + assert spec.loader is not None + module = importlib.util.module_from_spec(spec) + with mock.patch("builtins.__import__", side_effect=block_common_ai): + spec.loader.exec_module(module) + + hook = module.DatabricksGenieHook() + hook._request = mock.create_autospec( + hook._request, + side_effect=[ + {"conversation_id": "conversation-1", "message_id": "message-1"}, + {"status": "COMPLETED", "attachments": [{"text": {"content": "Answer."}}]}, + ], + ) + result = hook.consult("space-1", "Question?") + assert result["answer"] == "Answer." + assert result["conversation_id"] == "conversation-1" + assert hook._request.call_count == 2 + with pytest.raises(AirflowOptionalProviderFeatureException, match="common.ai"): + hook.agent("space-1") + + def test_standard_managed_agent_toolset_returns_bounded_structured_ids(self): + hook = DatabricksGenieHook() + hook._request = mock.create_autospec( + hook._request, + side_effect=[ + {"conversation_id": "conversation-1", "message_id": "message-1"}, + {"status": "COMPLETED", "attachments": [{"text": {"content": "Answer."}}]}, + ], + ) + toolset = ManagedAgentToolset(hook.agent("space-1"), tool_name="ask_genie", max_retries=0) + + result = json.loads(toolset.invoke_sync("Question?")) + + assert result["space_id"] == "space-1" + assert result["conversation_id"] == "conversation-1" + assert result["message_id"] == "message-1" + assert result["answer"] == "Answer." + assert hook._request.call_count == 2 + + def test_consult_starts_once_polls_reads_and_returns_ids_and_query_result(self): + hook = DatabricksGenieHook(poll_interval=0.001) + hook._request = mock.Mock( + side_effect=[ + {"conversation_id": "conversation-1", "message_id": "message-1"}, + {"status": "ASKING_AI"}, + { + "status": "COMPLETED", + "attachments": [ + { + "attachment_id": "attachment-1", + "text": {"content": "There are 12 open orders."}, + "query": {"title": "Open orders", "query": "select count(*)"}, + } + ], + }, + { + "statement_response": { + "manifest": { + "schema": {"columns": [{"name": "count"}]}, + "total_row_count": 1, + }, + "result": {"data_array": [["12"]]}, + } + }, + ] + ) + + result = hook.consult("space-1", "How many open orders?", timeout=1) + + assert result == { + "space_id": "space-1", + "conversation_id": "conversation-1", + "message_id": "message-1", + "status": "COMPLETED", + "answer": "There are 12 open orders.", + "queries": [{"title": "Open orders", "query": "select count(*)"}], + "query_results": [ + {"columns": ["count"], "rows": [["12"]], "total_row_count": 1, "truncated": False} + ], + } + assert hook._request.call_count == 4 + assert hook._request.call_args_list[0].args[:2] == ( + "POST", + "spaces/space-1/start-conversation", + ) + assert hook._request.call_args_list[0].kwargs["retry_read"] is False + assert all(call.kwargs.get("retry_read") is True for call in hook._request.call_args_list[1:]) + + def test_resumed_consult_posts_into_existing_conversation_once(self): + hook = DatabricksGenieHook() + hook._request = mock.Mock( + side_effect=[ + {"conversation_id": "conversation-1", "message_id": "message-2"}, + {"status": "COMPLETED", "attachments": [{"text": {"content": "Answer."}}]}, + ] + ) + + hook.consult("space-1", "Another question", conversation_id="conversation-1") + + assert hook._request.call_args_list[0].args[:2] == ( + "POST", + "spaces/space-1/conversations/conversation-1/messages", + ) + assert hook._request.call_args_list[0].kwargs["retry_read"] is False + assert hook._request.call_count == 2 + + def test_non_idempotent_post_is_never_retried_after_timeout(self): Review Comment: Here and 3 more tests (`:214`, `:241`, `:265`) replace hook methods with bare `mock.Mock()`. Please add a `hook` fixture that uses `mock.patch.object(DatabricksGenieHook, ..., autospec=True)`. ########## providers/databricks/src/airflow/providers/databricks/hooks/genie.py: ########## @@ -0,0 +1,466 @@ +# 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. +"""Hook for Databricks Genie conversations.""" + +from __future__ import annotations + +import json +import time +from typing import TYPE_CHECKING, Any +from urllib.parse import quote, urlsplit + +import requests +from requests.auth import HTTPBasicAuth +from tenacity import RetryError + +from airflow.providers.common.compat.sdk import ( + AirflowException, + AirflowOptionalProviderFeatureException, +) +from airflow.providers.databricks.hooks.databricks_base import BaseDatabricksHook + +if TYPE_CHECKING: + from airflow.providers.common.ai.managed_agents.base import ( + BaseManagedAgentHook, + ManagedAgentCapabilities, + ManagedAgentRef, + ManagedAgentRequest, + ManagedAgentResponse, + ) +else: + try: + from airflow.providers.common.ai.managed_agents.base import ( + BaseManagedAgentHook, + ManagedAgentCapabilities, + ManagedAgentRef, + ManagedAgentRequest, + ManagedAgentResponse, + ) + except ImportError: + + def _needs_common_ai(*args: Any, **kwargs: Any) -> Any: + raise AirflowOptionalProviderFeatureException( + "Databricks Genie managed-agent integration needs the 'common.ai' extra of the " + "Databricks provider: pip install 'apache-airflow-providers-databricks[common.ai]'." + ) + + class BaseManagedAgentHook: + """Stand-in for the optional Common AI contract.""" + + agent = _needs_common_ai + + ManagedAgentCapabilities = ManagedAgentRef = ManagedAgentRequest = ManagedAgentResponse = ( + _needs_common_ai + ) + + +_MAX_RESPONSE_BYTES = 1024 * 1024 +_MAX_RESULT_BYTES = 48 * 1024 +_MAX_RESULT_ROWS = 100 +_POLL_INTERVAL_SECONDS = 1.0 +_PENDING_STATUSES = frozenset( + { + "FETCHING_METADATA", + "FILTERING_CONTEXT", + "ASKING_AI", + "PENDING_WAREHOUSE", + "EXECUTING_QUERY", + "SUBMITTED", + } +) + + +class DatabricksGenieError(AirflowException): + """A Genie request failed or returned a result that could not be used.""" + + def __init__(self, message: str, *, status_code: int | None = None) -> None: + super().__init__(message) + # AirflowException declares status_code as HTTPStatus; Genie keeps the raw code or None. + self.status_code = status_code # type: ignore[assignment] + + +class DatabricksGenieHook(BaseDatabricksHook, BaseManagedAgentHook): + """ + Consult a Genie space using the Databricks Workspace REST API. + + The Databricks connection supplies authentication. Genie start/send requests are sent once: + their outcome may be unknown after a timeout or server error, so the hook never retries them. + Message and query-result reads use the hook's configured retry policy. + """ + + agent_platform = "databricks.genie" + + def __init__(self, *args: Any, poll_interval: float = _POLL_INTERVAL_SECONDS, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + if poll_interval <= 0: + raise ValueError("poll_interval must be greater than zero") + self.poll_interval = poll_interval + + @staticmethod + def _validate_space_id(space_id: str) -> None: + if not isinstance(space_id, str) or not space_id.strip(): + raise ValueError("A Databricks Genie space ID must be a non-empty string.") + + def resolve_agent(self, agent: str) -> ManagedAgentRef: + self._validate_space_id(agent) + return ManagedAgentRef(platform=self.agent_platform, name=agent) + + def get_agent_capabilities(self, agent: str) -> ManagedAgentCapabilities: + self.resolve_agent(agent) + return ManagedAgentCapabilities(sessions=True, structured_output=True) + + def invoke_agent(self, agent: str, request: ManagedAgentRequest) -> ManagedAgentResponse: + self.resolve_agent(agent) + if request.vendor_options: + raise ValueError( + f"Databricks Genie does not support vendor_options: {sorted(request.vendor_options)}" + ) + prompt = request.prompt if request.prompt is not None else _messages_to_prompt(request.as_messages()) + timeout = request.timeout if request.timeout is not None else self.timeout_seconds + result = self.consult(agent, prompt, conversation_id=request.session_id, timeout=timeout) + return ManagedAgentResponse( + text=json.dumps(result, ensure_ascii=False, separators=(",", ":")), + raw=result, + structured=result, + session_id=result["conversation_id"], + trace_ref=result["message_id"], + ) + + def consult( + self, + space_id: str, + prompt: str, + *, + conversation_id: str | None = None, + timeout: float | None = None, + ) -> dict[str, Any]: + """Submit one question and return a bounded, structured Genie result.""" + self._validate_space_id(space_id) + if not prompt.strip(): + raise ValueError("A Genie question must not be empty.") + if timeout is not None and timeout <= 0: + raise ValueError("timeout must be greater than zero") + if conversation_id is not None and not conversation_id.strip(): + raise ValueError("conversation_id must not be empty") + + deadline = time.monotonic() + (timeout if timeout is not None else self.timeout_seconds) + space = quote(space_id, safe="") + if conversation_id is None: + endpoint = f"spaces/{space}/start-conversation" + body = {"content": prompt, "enable_visualization": False} + else: + conversation = quote(conversation_id, safe="") + endpoint = f"spaces/{space}/conversations/{conversation}/messages" + body = {"content": prompt, "enable_visualization": False} + + created = self._request("POST", endpoint, body=body, retry_read=False, deadline=deadline) + resolved_conversation_id = created.get("conversation_id") + message_id = created.get("message_id") or created.get("id") + if not isinstance(resolved_conversation_id, str) or not isinstance(message_id, str): + raise DatabricksGenieError( + "Genie accepted the consultation but returned no conversation or message ID; " + "the request will not be repeated." + ) + + while True: + message = self._request( + "GET", + f"spaces/{space}/conversations/{quote(resolved_conversation_id, safe='')}/messages/" + f"{quote(message_id, safe='')}", + retry_read=True, + deadline=deadline, + ) + status = message.get("status") + if status == "COMPLETED": + break + if status == "FAILED": + error = message.get("error") or {} + detail = error.get("error") if isinstance(error, dict) else str(error) + raise DatabricksGenieError( + f"Genie could not answer the question: {detail or 'unknown error'}" + ) + if status in {"CANCELLED", "QUERY_RESULT_EXPIRED"}: + raise DatabricksGenieError(f"Genie consultation ended with status {status}.") + if status not in _PENDING_STATUSES: + raise DatabricksGenieError(f"Genie returned an unknown message status: {status!r}.") + remaining = deadline - time.monotonic() + if remaining <= 0: + raise DatabricksGenieError( + f"Timed out waiting for Genie message {message_id}; " + f"conversation {resolved_conversation_id} " + "is available to inspect." + ) + time.sleep(min(self.poll_interval, remaining)) + + structured = self._summarize_result( + space_id, space, resolved_conversation_id, message_id, message, deadline + ) + return _truncate_result(structured) + + def _summarize_result( + self, + space_id: str, + space_path: str, + conversation_id: str, + message_id: str, + message: dict[str, Any], + deadline: float, + ) -> dict[str, Any]: + attachments = message.get("attachments") or [] + answers: list[str] = [] + queries: list[dict[str, Any]] = [] + query_results: list[dict[str, Any]] = [] + for attachment in attachments: + if not isinstance(attachment, dict): + continue + text_attachment = attachment.get("text") + if isinstance(text_attachment, dict) and isinstance(text_attachment.get("content"), str): + answers.append(text_attachment["content"]) + query = attachment.get("query") + if isinstance(query, dict): + queries.append( + { + key: query[key] + for key in ("title", "query", "description", "query_result_metadata") + if key in query + } + ) + attachment_id = attachment.get("attachment_id") + if isinstance(attachment_id, str) and attachment_id: + response = self._request( + "GET", + f"spaces/{space_path}/conversations/" + f"{quote(conversation_id, safe='')}/messages/" + f"{quote(message_id, safe='')}/attachments/" + f"{quote(attachment_id, safe='')}/query-result", + retry_read=True, + deadline=deadline, + ) + query_results.append(_summarize_query_result(response)) + result: dict[str, Any] = { + "space_id": space_id, + "conversation_id": conversation_id, + "message_id": message_id, + "status": message.get("status"), + "answer": "\n\n".join(answers), + } + if queries: + result["queries"] = queries + if query_results: + result["query_results"] = query_results + return result + + def _request( + self, + method: str, + endpoint: str, + *, + body: dict[str, Any] | None = None, + retry_read: bool, + deadline: float | None = None, + ) -> dict[str, Any]: + """Call one Genie endpoint; only GET requests are eligible for transport retries.""" + url = self._endpoint_url(f"api/2.0/genie/{endpoint}") + parsed_url = urlsplit(url) + is_loopback = parsed_url.hostname in {"localhost", "127.0.0.1", "::1"} + if parsed_url.scheme != "https" and not is_loopback: + raise DatabricksGenieError( + "Databricks Genie requires HTTPS so connection credentials are not sent in cleartext." + ) + headers = {**self.user_agent_header, **self._get_aad_headers()} + token = self._get_token() + auth = None + if token: + headers["Authorization"] = f"Bearer {token}" Review Comment: The token is going in here with `Authorization` header with `auth=None` (`:286`). `requests` then applies a matching `~/.netrc` entry and overwrites the header with Basic auth. Dont do that but use `_TokenAuth(token)` from `databricks_base`, as the fix in #76157 does (commit `cc56a4e`). ########## providers/databricks/src/airflow/providers/databricks/hooks/genie.py: ########## @@ -0,0 +1,466 @@ +# 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. +"""Hook for Databricks Genie conversations.""" + +from __future__ import annotations + +import json +import time +from typing import TYPE_CHECKING, Any +from urllib.parse import quote, urlsplit + +import requests +from requests.auth import HTTPBasicAuth +from tenacity import RetryError + +from airflow.providers.common.compat.sdk import ( + AirflowException, + AirflowOptionalProviderFeatureException, +) +from airflow.providers.databricks.hooks.databricks_base import BaseDatabricksHook + +if TYPE_CHECKING: + from airflow.providers.common.ai.managed_agents.base import ( + BaseManagedAgentHook, + ManagedAgentCapabilities, + ManagedAgentRef, + ManagedAgentRequest, + ManagedAgentResponse, + ) +else: + try: + from airflow.providers.common.ai.managed_agents.base import ( + BaseManagedAgentHook, + ManagedAgentCapabilities, + ManagedAgentRef, + ManagedAgentRequest, + ManagedAgentResponse, + ) + except ImportError: + + def _needs_common_ai(*args: Any, **kwargs: Any) -> Any: + raise AirflowOptionalProviderFeatureException( + "Databricks Genie managed-agent integration needs the 'common.ai' extra of the " + "Databricks provider: pip install 'apache-airflow-providers-databricks[common.ai]'." + ) + + class BaseManagedAgentHook: + """Stand-in for the optional Common AI contract.""" + + agent = _needs_common_ai + + ManagedAgentCapabilities = ManagedAgentRef = ManagedAgentRequest = ManagedAgentResponse = ( + _needs_common_ai + ) + + +_MAX_RESPONSE_BYTES = 1024 * 1024 +_MAX_RESULT_BYTES = 48 * 1024 +_MAX_RESULT_ROWS = 100 +_POLL_INTERVAL_SECONDS = 1.0 +_PENDING_STATUSES = frozenset( + { + "FETCHING_METADATA", + "FILTERING_CONTEXT", + "ASKING_AI", + "PENDING_WAREHOUSE", + "EXECUTING_QUERY", + "SUBMITTED", + } +) + + +class DatabricksGenieError(AirflowException): Review Comment: `DatabricksGenieError` lives in the hook module and needs `# type: ignore[assignment]` (`:93`) to store `status_code`. `exceptions.py` already has `DatabricksApiError` with `http_status_code`, and the trigger in #76157 catches that one. Move it to `exceptions.py` as a `DatabricksApiError` subclass, so callers catch one type. ########## providers/databricks/src/airflow/providers/databricks/hooks/genie.py: ########## @@ -0,0 +1,466 @@ +# 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. +"""Hook for Databricks Genie conversations.""" + +from __future__ import annotations + +import json +import time +from typing import TYPE_CHECKING, Any +from urllib.parse import quote, urlsplit + +import requests +from requests.auth import HTTPBasicAuth +from tenacity import RetryError + +from airflow.providers.common.compat.sdk import ( + AirflowException, + AirflowOptionalProviderFeatureException, +) +from airflow.providers.databricks.hooks.databricks_base import BaseDatabricksHook + +if TYPE_CHECKING: + from airflow.providers.common.ai.managed_agents.base import ( + BaseManagedAgentHook, + ManagedAgentCapabilities, + ManagedAgentRef, + ManagedAgentRequest, + ManagedAgentResponse, + ) +else: + try: + from airflow.providers.common.ai.managed_agents.base import ( + BaseManagedAgentHook, + ManagedAgentCapabilities, + ManagedAgentRef, + ManagedAgentRequest, + ManagedAgentResponse, + ) + except ImportError: + + def _needs_common_ai(*args: Any, **kwargs: Any) -> Any: + raise AirflowOptionalProviderFeatureException( + "Databricks Genie managed-agent integration needs the 'common.ai' extra of the " + "Databricks provider: pip install 'apache-airflow-providers-databricks[common.ai]'." + ) + + class BaseManagedAgentHook: + """Stand-in for the optional Common AI contract.""" + + agent = _needs_common_ai + + ManagedAgentCapabilities = ManagedAgentRef = ManagedAgentRequest = ManagedAgentResponse = ( + _needs_common_ai + ) + + +_MAX_RESPONSE_BYTES = 1024 * 1024 +_MAX_RESULT_BYTES = 48 * 1024 +_MAX_RESULT_ROWS = 100 +_POLL_INTERVAL_SECONDS = 1.0 +_PENDING_STATUSES = frozenset( + { + "FETCHING_METADATA", + "FILTERING_CONTEXT", + "ASKING_AI", + "PENDING_WAREHOUSE", + "EXECUTING_QUERY", + "SUBMITTED", + } +) + + +class DatabricksGenieError(AirflowException): + """A Genie request failed or returned a result that could not be used.""" + + def __init__(self, message: str, *, status_code: int | None = None) -> None: + super().__init__(message) + # AirflowException declares status_code as HTTPStatus; Genie keeps the raw code or None. + self.status_code = status_code # type: ignore[assignment] + + +class DatabricksGenieHook(BaseDatabricksHook, BaseManagedAgentHook): + """ + Consult a Genie space using the Databricks Workspace REST API. + + The Databricks connection supplies authentication. Genie start/send requests are sent once: + their outcome may be unknown after a timeout or server error, so the hook never retries them. + Message and query-result reads use the hook's configured retry policy. + """ + + agent_platform = "databricks.genie" + + def __init__(self, *args: Any, poll_interval: float = _POLL_INTERVAL_SECONDS, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + if poll_interval <= 0: + raise ValueError("poll_interval must be greater than zero") + self.poll_interval = poll_interval + + @staticmethod + def _validate_space_id(space_id: str) -> None: + if not isinstance(space_id, str) or not space_id.strip(): + raise ValueError("A Databricks Genie space ID must be a non-empty string.") + + def resolve_agent(self, agent: str) -> ManagedAgentRef: + self._validate_space_id(agent) + return ManagedAgentRef(platform=self.agent_platform, name=agent) + + def get_agent_capabilities(self, agent: str) -> ManagedAgentCapabilities: + self.resolve_agent(agent) + return ManagedAgentCapabilities(sessions=True, structured_output=True) + + def invoke_agent(self, agent: str, request: ManagedAgentRequest) -> ManagedAgentResponse: + self.resolve_agent(agent) + if request.vendor_options: + raise ValueError( + f"Databricks Genie does not support vendor_options: {sorted(request.vendor_options)}" + ) + prompt = request.prompt if request.prompt is not None else _messages_to_prompt(request.as_messages()) + timeout = request.timeout if request.timeout is not None else self.timeout_seconds + result = self.consult(agent, prompt, conversation_id=request.session_id, timeout=timeout) + return ManagedAgentResponse( + text=json.dumps(result, ensure_ascii=False, separators=(",", ":")), + raw=result, + structured=result, + session_id=result["conversation_id"], + trace_ref=result["message_id"], + ) + + def consult( + self, + space_id: str, + prompt: str, + *, + conversation_id: str | None = None, + timeout: float | None = None, + ) -> dict[str, Any]: + """Submit one question and return a bounded, structured Genie result.""" + self._validate_space_id(space_id) + if not prompt.strip(): + raise ValueError("A Genie question must not be empty.") + if timeout is not None and timeout <= 0: + raise ValueError("timeout must be greater than zero") + if conversation_id is not None and not conversation_id.strip(): + raise ValueError("conversation_id must not be empty") + + deadline = time.monotonic() + (timeout if timeout is not None else self.timeout_seconds) + space = quote(space_id, safe="") + if conversation_id is None: + endpoint = f"spaces/{space}/start-conversation" + body = {"content": prompt, "enable_visualization": False} + else: + conversation = quote(conversation_id, safe="") + endpoint = f"spaces/{space}/conversations/{conversation}/messages" + body = {"content": prompt, "enable_visualization": False} + + created = self._request("POST", endpoint, body=body, retry_read=False, deadline=deadline) + resolved_conversation_id = created.get("conversation_id") + message_id = created.get("message_id") or created.get("id") + if not isinstance(resolved_conversation_id, str) or not isinstance(message_id, str): + raise DatabricksGenieError( + "Genie accepted the consultation but returned no conversation or message ID; " + "the request will not be repeated." + ) + + while True: + message = self._request( + "GET", + f"spaces/{space}/conversations/{quote(resolved_conversation_id, safe='')}/messages/" + f"{quote(message_id, safe='')}", + retry_read=True, + deadline=deadline, + ) + status = message.get("status") + if status == "COMPLETED": + break + if status == "FAILED": + error = message.get("error") or {} + detail = error.get("error") if isinstance(error, dict) else str(error) + raise DatabricksGenieError( + f"Genie could not answer the question: {detail or 'unknown error'}" + ) + if status in {"CANCELLED", "QUERY_RESULT_EXPIRED"}: + raise DatabricksGenieError(f"Genie consultation ended with status {status}.") + if status not in _PENDING_STATUSES: + raise DatabricksGenieError(f"Genie returned an unknown message status: {status!r}.") + remaining = deadline - time.monotonic() + if remaining <= 0: + raise DatabricksGenieError( + f"Timed out waiting for Genie message {message_id}; " + f"conversation {resolved_conversation_id} " + "is available to inspect." + ) + time.sleep(min(self.poll_interval, remaining)) + + structured = self._summarize_result( + space_id, space, resolved_conversation_id, message_id, message, deadline + ) + return _truncate_result(structured) + + def _summarize_result( + self, + space_id: str, + space_path: str, + conversation_id: str, + message_id: str, + message: dict[str, Any], + deadline: float, + ) -> dict[str, Any]: + attachments = message.get("attachments") or [] + answers: list[str] = [] + queries: list[dict[str, Any]] = [] + query_results: list[dict[str, Any]] = [] + for attachment in attachments: + if not isinstance(attachment, dict): + continue + text_attachment = attachment.get("text") + if isinstance(text_attachment, dict) and isinstance(text_attachment.get("content"), str): + answers.append(text_attachment["content"]) + query = attachment.get("query") + if isinstance(query, dict): + queries.append( + { + key: query[key] + for key in ("title", "query", "description", "query_result_metadata") + if key in query + } + ) + attachment_id = attachment.get("attachment_id") + if isinstance(attachment_id, str) and attachment_id: + response = self._request( + "GET", + f"spaces/{space_path}/conversations/" + f"{quote(conversation_id, safe='')}/messages/" + f"{quote(message_id, safe='')}/attachments/" + f"{quote(attachment_id, safe='')}/query-result", + retry_read=True, + deadline=deadline, + ) + query_results.append(_summarize_query_result(response)) + result: dict[str, Any] = { + "space_id": space_id, + "conversation_id": conversation_id, + "message_id": message_id, + "status": message.get("status"), + "answer": "\n\n".join(answers), + } + if queries: + result["queries"] = queries + if query_results: + result["query_results"] = query_results + return result + + def _request( Review Comment: `_request` is 100 lines of its own HTTP client next to `BaseDatabricksHook._do_api_call`.Why cant `_do_api_call` take a no-retry flag and a size cap instead? ########## providers/databricks/provider.yaml: ########## Review Comment: The `common.ai` extra pins `apache-airflow-providers-common-ai>=0.11.0`. No `0.11.0` exists, and the managed-agent contract (#73532) first shipped in `1.0.0`. Pin `>=1.0.0`, and match it in `provider.yaml`. ########## providers/databricks/tests/unit/databricks/hooks/test_genie.py: ########## @@ -0,0 +1,327 @@ +# 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 builtins +import importlib.util +import json +from pathlib import Path +from unittest import mock + +import pytest +import requests + +from airflow.providers.common.ai.toolsets import ManagedAgentToolset +from airflow.providers.common.compat.sdk import AirflowOptionalProviderFeatureException +from airflow.providers.databricks.hooks.genie import ( + DatabricksGenieError, + DatabricksGenieHook, + _summarize_query_result, + _truncate_result, +) + + +class TestDatabricksGenieHook: + def test_query_result_marks_omitted_chunks_and_columns_as_truncated(self): + partial_rows = _summarize_query_result( + { + "statement_response": { + "manifest": { + "schema": {"columns": [{"name": "count"}]}, + "total_row_count": 10, + "total_chunk_count": 2, + "truncated": False, + }, + "result": {"data_array": [[str(index)] for index in range(5)]}, + } + } + ) + assert len(partial_rows["rows"]) == 5 + assert partial_rows["total_row_count"] == 10 + assert partial_rows["truncated"] is True + + capped_columns = _summarize_query_result( + { + "manifest": { + "schema": {"columns": [{"name": f"column_{index}"} for index in range(101)]}, + "total_row_count": 1, + "truncated": False, + }, + "result": {"data_array": [["value"]]}, + } + ) + assert len(capped_columns["columns"]) == 100 + assert capped_columns["truncated"] is True + + def test_direct_hook_works_without_common_ai(self): + original_import = builtins.__import__ + + def block_common_ai(name, *args, **kwargs): + if name.startswith("airflow.providers.common.ai"): + raise ImportError("common.ai is unavailable") + return original_import(name, *args, **kwargs) + + path = Path(__file__).parents[4] / "src/airflow/providers/databricks/hooks/genie.py" + spec = importlib.util.spec_from_file_location("_genie_without_common_ai", path) + assert spec is not None + assert spec.loader is not None + module = importlib.util.module_from_spec(spec) + with mock.patch("builtins.__import__", side_effect=block_common_ai): + spec.loader.exec_module(module) + + hook = module.DatabricksGenieHook() + hook._request = mock.create_autospec( + hook._request, + side_effect=[ + {"conversation_id": "conversation-1", "message_id": "message-1"}, + {"status": "COMPLETED", "attachments": [{"text": {"content": "Answer."}}]}, + ], + ) + result = hook.consult("space-1", "Question?") + assert result["answer"] == "Answer." + assert result["conversation_id"] == "conversation-1" + assert hook._request.call_count == 2 + with pytest.raises(AirflowOptionalProviderFeatureException, match="common.ai"): + hook.agent("space-1") + + def test_standard_managed_agent_toolset_returns_bounded_structured_ids(self): + hook = DatabricksGenieHook() + hook._request = mock.create_autospec( + hook._request, + side_effect=[ + {"conversation_id": "conversation-1", "message_id": "message-1"}, + {"status": "COMPLETED", "attachments": [{"text": {"content": "Answer."}}]}, + ], + ) + toolset = ManagedAgentToolset(hook.agent("space-1"), tool_name="ask_genie", max_retries=0) + + result = json.loads(toolset.invoke_sync("Question?")) + + assert result["space_id"] == "space-1" + assert result["conversation_id"] == "conversation-1" + assert result["message_id"] == "message-1" + assert result["answer"] == "Answer." + assert hook._request.call_count == 2 + + def test_consult_starts_once_polls_reads_and_returns_ids_and_query_result(self): Review Comment: Same as above ########## providers/databricks/tests/unit/databricks/hooks/test_genie.py: ########## @@ -0,0 +1,327 @@ +# 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 builtins +import importlib.util +import json +from pathlib import Path +from unittest import mock + +import pytest +import requests + +from airflow.providers.common.ai.toolsets import ManagedAgentToolset +from airflow.providers.common.compat.sdk import AirflowOptionalProviderFeatureException +from airflow.providers.databricks.hooks.genie import ( + DatabricksGenieError, + DatabricksGenieHook, + _summarize_query_result, + _truncate_result, +) + + +class TestDatabricksGenieHook: + def test_query_result_marks_omitted_chunks_and_columns_as_truncated(self): + partial_rows = _summarize_query_result( + { + "statement_response": { + "manifest": { + "schema": {"columns": [{"name": "count"}]}, + "total_row_count": 10, + "total_chunk_count": 2, + "truncated": False, + }, + "result": {"data_array": [[str(index)] for index in range(5)]}, + } + } + ) + assert len(partial_rows["rows"]) == 5 + assert partial_rows["total_row_count"] == 10 + assert partial_rows["truncated"] is True + + capped_columns = _summarize_query_result( + { + "manifest": { + "schema": {"columns": [{"name": f"column_{index}"} for index in range(101)]}, + "total_row_count": 1, + "truncated": False, + }, + "result": {"data_array": [["value"]]}, + } + ) + assert len(capped_columns["columns"]) == 100 + assert capped_columns["truncated"] is True + + def test_direct_hook_works_without_common_ai(self): + original_import = builtins.__import__ + + def block_common_ai(name, *args, **kwargs): + if name.startswith("airflow.providers.common.ai"): + raise ImportError("common.ai is unavailable") + return original_import(name, *args, **kwargs) + + path = Path(__file__).parents[4] / "src/airflow/providers/databricks/hooks/genie.py" + spec = importlib.util.spec_from_file_location("_genie_without_common_ai", path) + assert spec is not None + assert spec.loader is not None + module = importlib.util.module_from_spec(spec) + with mock.patch("builtins.__import__", side_effect=block_common_ai): + spec.loader.exec_module(module) + + hook = module.DatabricksGenieHook() + hook._request = mock.create_autospec( + hook._request, + side_effect=[ + {"conversation_id": "conversation-1", "message_id": "message-1"}, + {"status": "COMPLETED", "attachments": [{"text": {"content": "Answer."}}]}, + ], + ) + result = hook.consult("space-1", "Question?") + assert result["answer"] == "Answer." + assert result["conversation_id"] == "conversation-1" + assert hook._request.call_count == 2 + with pytest.raises(AirflowOptionalProviderFeatureException, match="common.ai"): + hook.agent("space-1") + + def test_standard_managed_agent_toolset_returns_bounded_structured_ids(self): + hook = DatabricksGenieHook() + hook._request = mock.create_autospec( + hook._request, + side_effect=[ + {"conversation_id": "conversation-1", "message_id": "message-1"}, + {"status": "COMPLETED", "attachments": [{"text": {"content": "Answer."}}]}, + ], + ) + toolset = ManagedAgentToolset(hook.agent("space-1"), tool_name="ask_genie", max_retries=0) + + result = json.loads(toolset.invoke_sync("Question?")) + + assert result["space_id"] == "space-1" + assert result["conversation_id"] == "conversation-1" + assert result["message_id"] == "message-1" + assert result["answer"] == "Answer." + assert hook._request.call_count == 2 + + def test_consult_starts_once_polls_reads_and_returns_ids_and_query_result(self): Review Comment: No test covers `consult` when the message ends `FAILED`, `CANCELLED` or with an unknown status (`:190-199`). The poll deadline (`:200-206`) is not covered either, and neither is the `vendor_options` refusal in `invoke_agent` (`:128`). These are the main error paths users hit. Add one parametrized `test_consult_raises_for_terminal_status` and one `test_consult_times_out`. ########## providers/databricks/src/airflow/providers/databricks/hooks/genie.py: ########## @@ -0,0 +1,466 @@ +# 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. +"""Hook for Databricks Genie conversations.""" + +from __future__ import annotations + +import json +import time +from typing import TYPE_CHECKING, Any +from urllib.parse import quote, urlsplit + +import requests +from requests.auth import HTTPBasicAuth +from tenacity import RetryError + +from airflow.providers.common.compat.sdk import ( + AirflowException, + AirflowOptionalProviderFeatureException, +) +from airflow.providers.databricks.hooks.databricks_base import BaseDatabricksHook + +if TYPE_CHECKING: + from airflow.providers.common.ai.managed_agents.base import ( + BaseManagedAgentHook, + ManagedAgentCapabilities, + ManagedAgentRef, + ManagedAgentRequest, + ManagedAgentResponse, + ) +else: + try: + from airflow.providers.common.ai.managed_agents.base import ( + BaseManagedAgentHook, + ManagedAgentCapabilities, + ManagedAgentRef, + ManagedAgentRequest, + ManagedAgentResponse, + ) + except ImportError: + + def _needs_common_ai(*args: Any, **kwargs: Any) -> Any: + raise AirflowOptionalProviderFeatureException( + "Databricks Genie managed-agent integration needs the 'common.ai' extra of the " + "Databricks provider: pip install 'apache-airflow-providers-databricks[common.ai]'." + ) + + class BaseManagedAgentHook: + """Stand-in for the optional Common AI contract.""" + + agent = _needs_common_ai + + ManagedAgentCapabilities = ManagedAgentRef = ManagedAgentRequest = ManagedAgentResponse = ( + _needs_common_ai + ) + + +_MAX_RESPONSE_BYTES = 1024 * 1024 +_MAX_RESULT_BYTES = 48 * 1024 +_MAX_RESULT_ROWS = 100 +_POLL_INTERVAL_SECONDS = 1.0 +_PENDING_STATUSES = frozenset( + { + "FETCHING_METADATA", + "FILTERING_CONTEXT", + "ASKING_AI", + "PENDING_WAREHOUSE", + "EXECUTING_QUERY", + "SUBMITTED", + } +) + + +class DatabricksGenieError(AirflowException): + """A Genie request failed or returned a result that could not be used.""" + + def __init__(self, message: str, *, status_code: int | None = None) -> None: + super().__init__(message) + # AirflowException declares status_code as HTTPStatus; Genie keeps the raw code or None. + self.status_code = status_code # type: ignore[assignment] + + +class DatabricksGenieHook(BaseDatabricksHook, BaseManagedAgentHook): + """ + Consult a Genie space using the Databricks Workspace REST API. + + The Databricks connection supplies authentication. Genie start/send requests are sent once: + their outcome may be unknown after a timeout or server error, so the hook never retries them. + Message and query-result reads use the hook's configured retry policy. + """ + + agent_platform = "databricks.genie" Review Comment: `agent_platform = "databricks.genie"` becomes a stored label in common.ai metrics and `ManagedAgentRef`. Renaming it later breaks dashboards. I think there is a need to confirm with `common.ai` folks if thats the case. -- 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]
