zozo123 commented on code in PR #76157: URL: https://github.com/apache/airflow/pull/76157#discussion_r4665830128
########## providers/databricks/src/airflow/providers/databricks/hooks/genie.py: ########## @@ -0,0 +1,467 @@ +# 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 AuthBase, HTTPBasicAuth +from tenacity import RetryError + +from airflow.providers.common.compat.sdk import ( + AirflowException, + AirflowOptionalProviderFeatureException, +) +from airflow.providers.databricks.hooks.databricks_base import BaseDatabricksHook, _TokenAuth + +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} Review Comment: Done in 6d06c6be02, `body` is set once above the `if`. ########## providers/databricks/tests/unit/databricks/operators/test_genie.py: ########## @@ -0,0 +1,588 @@ +# 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 json +from unittest import mock + +import pytest + +from airflow.providers.common.compat.sdk import AirflowFailException, TaskDeferred +from airflow.providers.databricks.hooks.genie import DatabricksGenieError, DatabricksGenieHook +from airflow.providers.databricks.operators.genie import DatabricksGenieOperator +from airflow.providers.databricks.triggers.genie import DatabricksGenieMessageTrigger + +from tests_common.test_utils.version_compat import AIRFLOW_V_3_3_PLUS + +SPACE_ID = "space/1" +CONVERSATION_ID = "conversation-1" +MESSAGE_ID = "message-1" +QUESTION = "How many orders were placed last week?" +START = "spaces/space%2F1/start-conversation" +FOLLOW_UP = f"spaces/space%2F1/conversations/{CONVERSATION_ID}/messages" +MESSAGE = f"spaces/space%2F1/conversations/{CONVERSATION_ID}/messages/{MESSAGE_ID}" +ATTACHMENT_RESULT = f"{MESSAGE}/attachments/attachment-1/query-result" +KEY = DatabricksGenieOperator.external_id_key +SUBMISSION_KEY = f"{KEY}_submission" + +durable_only = pytest.mark.skipif( + not AIRFLOW_V_3_3_PLUS, reason="task_state_store (durable execution) requires Airflow 3.3+" +) + + +def message(status: str, **fields) -> dict: + return {"conversation_id": CONVERSATION_ID, "message_id": MESSAGE_ID, "status": status, **fields} + + +COMPLETED = message( + "COMPLETED", + attachments=[ + {"text": {"content": "There were 42 orders."}}, + { + "attachment_id": "attachment-1", + "query": {"title": "Orders", "query": "SELECT count(*) FROM orders"}, + }, + ], +) +QUERY_RESULT = { + "statement_response": { + "manifest": {"schema": {"columns": [{"name": "count"}]}, "total_row_count": 1}, + "result": {"data_array": [["42"]]}, + } +} +EXPECTED_RESULT = { + "space_id": SPACE_ID, + "conversation_id": CONVERSATION_ID, + "message_id": MESSAGE_ID, + "status": "COMPLETED", + "answer": "There were 42 orders.", + "queries": [{"title": "Orders", "query": "SELECT count(*) FROM orders"}], + "query_results": [{"columns": ["count"], "rows": [["42"]], "total_row_count": 1, "truncated": False}], +} + + +class FakeStore: + """Dict-backed task state store that records the order of operations.""" + + def __init__(self, journal: list, data: dict | None = None) -> None: + self.journal = journal + self.data = dict(data or {}) + + def get(self, key, default=None): + return self.data.get(key, default) + + def set(self, key, value, *, retention=None): + self.journal.append(("set", key)) + self.data[key] = value + + def delete(self, key): + self.journal.append(("delete", key)) + self.data.pop(key, None) + + +class FakeGenie: + """Replay Genie responses per (method, endpoint) and record every request.""" + + def __init__(self, journal: list) -> None: + self.journal = journal + self.responses: dict[tuple[str, str], list] = {} + self.bodies: list = [] + + def add(self, method: str, endpoint: str, *responses) -> None: + self.responses.setdefault((method, endpoint), []).extend(responses) + + def __call__(self, hook, method, endpoint, *, body=None, retry_read, deadline=None): + self.journal.append((method, endpoint)) + if method == "POST": + assert retry_read is False + self.bodies.append(body) + else: + assert retry_read is True + queue = self.responses.get((method, endpoint)) + assert queue, f"unexpected {method} {endpoint}" + response = queue.pop(0) if len(queue) > 1 else queue[0] + if isinstance(response, BaseException): + raise response + return response + + def calls(self, method: str) -> list: + return [call for call in self.journal if call[0] == method] + + [email protected] +def journal(): + return [] + + [email protected] +def genie(journal): + fake = FakeGenie(journal) + with mock.patch.object(DatabricksGenieHook, "_request", autospec=True, side_effect=fake): + yield fake + + [email protected] +def sleep(): + with mock.patch("airflow.providers.databricks.operators.genie.time.sleep", autospec=True) as sleep: + yield sleep + + +def make_operator(**kwargs) -> DatabricksGenieOperator: + kwargs.setdefault("space_id", SPACE_ID) + kwargs.setdefault("question", QUESTION) + kwargs.setdefault("deferrable", False) + return DatabricksGenieOperator(task_id="ask_genie", polling_period_seconds=2, **kwargs) + + +def stored_ref(**overrides) -> dict: + ref = { + "space_id": SPACE_ID, + "conversation_id": CONVERSATION_ID, + "message_id": MESSAGE_ID, + "fingerprint": make_operator()._fingerprint(), + } + ref.update(overrides) + return ref + + +def answered(genie: FakeGenie, *statuses: str, post: str = START) -> None: + genie.add("POST", post, {"conversation_id": CONVERSATION_ID, "message_id": MESSAGE_ID}) + genie.add("GET", MESSAGE, *[message(status) for status in statuses], COMPLETED) + genie.add("GET", ATTACHMENT_RESULT, QUERY_RESULT) + + [email protected](("field", "value"), [("polling_period_seconds", 0), ("timeout", -1)]) +def test_invalid_wait_options(field, value): + with pytest.raises(ValueError, match="must be positive"): + DatabricksGenieOperator(task_id="ask", space_id=SPACE_ID, question=QUESTION, **{field: value}) + + [email protected]( + ("kwargs", "match"), + [ + ({"space_id": " "}, "space ID must be a non-empty string"), + ({"question": " "}, "question must be a non-empty string"), + ({"question": None}, "question must be a non-empty string"), + ({"message_id": MESSAGE_ID}, "message_id requires conversation_id"), + ], +) +def test_invalid_request(genie, kwargs, match): + with pytest.raises(ValueError, match=match): + make_operator(**kwargs).execute({}) + assert genie.journal == [] + + +def test_template_fields(): Review Comment: Replaced in 6d06c6be02 with `test_templated_conversation_id_selects_follow_up_endpoint`, which renders a templated `conversation_id` and checks the question is posted to the follow up messages endpoint. ########## providers/databricks/tests/unit/databricks/hooks/test_genie.py: ########## @@ -0,0 +1,356 @@ +# 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 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 import genie as genie_module +from airflow.providers.databricks.hooks.databricks_base import _TokenAuth +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): + """Reload from the installed module path so wheel/compat layouts work.""" + 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) + + # Prefer module.__file__ over a hardcoded src/ tree path: Compat matrix + # installs the provider from a wheel, so the editable src tree is absent. + assert genie_module.__file__ is not None + spec = importlib.util.spec_from_file_location("_genie_without_common_ai", genie_module.__file__) + 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): + hook = DatabricksGenieHook() + hook._endpoint_url = mock.Mock( + return_value="https://workspace/api/2.0/genie/spaces/id/start-conversation" + ) + hook.user_agent_header = {} + hook._get_aad_headers = mock.Mock(return_value={}) + hook._get_token = mock.Mock(return_value="secret-token") + hook._get_requests_kwargs = mock.Mock(return_value={}) + + with ( + mock.patch( + "airflow.providers.databricks.hooks.genie.requests.request", + side_effect=requests.Timeout("timeout"), + ) as request, + pytest.raises(DatabricksGenieError, match="did not retry") as error, + ): + hook._request( + "POST", + "spaces/id/start-conversation", + body={"content": "question"}, + retry_read=False, + ) + + assert request.call_count == 1 + assert "secret-token" not in str(error.value) + + def test_token_request_uses_token_auth_so_netrc_cannot_override_bearer(self): Review Comment: Done in 6d06c6be02. Added a `stub_hook` fixture that patches the connection lookups with autospec'd mocks, plus a `build_response` helper, and switched the remaining hook `_request` mocks to `mock.create_autospec`. Also added tests for the new prepare step. -- 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]
