kaxil commented on code in PR #76157: URL: https://github.com/apache/airflow/pull/76157#discussion_r4665712579
########## providers/databricks/src/airflow/providers/databricks/operators/genie.py: ########## @@ -0,0 +1,365 @@ +# 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. +"""Operators for asking Databricks Genie spaces questions as standalone tasks.""" + +from __future__ import annotations + +import hashlib +import time +from collections.abc import Sequence +from datetime import timedelta +from functools import cached_property +from typing import TYPE_CHECKING, Any +from urllib.parse import quote + +from airflow.providers.common.compat.sdk import AirflowFailException, BaseOperator, ResumableJobMixin, conf +from airflow.providers.databricks.hooks.genie import ( + _PENDING_STATUSES, + DatabricksGenieError, + DatabricksGenieHook, + _truncate_result, +) +from airflow.providers.databricks.triggers.genie import DatabricksGenieMessageTrigger + +if TYPE_CHECKING: + from airflow.providers.common.compat.sdk import Context + +GenieMessageRef = dict[str, str] + +_NOT_FOUND = "NOT_FOUND" +_STALE = "STALE" +_TERMINAL_STATUSES = frozenset({"COMPLETED", "FAILED", "CANCELLED", "QUERY_RESULT_EXPIRED"}) + + +class DatabricksGenieOperator(ResumableJobMixin, BaseOperator): + """ + Ask a Databricks Genie space one question and return a bounded, structured answer. + + The operator submits the question once, persists the Genie conversation and message IDs to task + state before waiting, then polls (or defers) until the message finishes. A retry after a worker + crash or timeout reconnects to the stored message instead of asking again. + + Genie has no idempotency key, so a submission whose outcome is unknown (a timeout, a connection + error or a 5xx response) cannot be told apart from one that was never received. The operator fails + without retrying in that case and the next try refuses to submit again; set ``conversation_id`` and + ``message_id`` to attach to the message you found, or ``resubmit_unconfirmed=True`` to ask again. + + .. seealso:: + For more information on how to use this operator, take a look at the guide: + :ref:`howto/operator:DatabricksGenieOperator` + + :param space_id: Genie space ID. (templated) + :param question: Question to ask. Required unless ``message_id`` is set. (templated) + :param databricks_conn_id: Databricks connection. Defaults to ``databricks_default``. (templated) + :param conversation_id: Existing conversation to ask the question in. The operator never deletes it. + Defaults to ``None``, which starts a new conversation. An empty string means ``None``. (templated) + :param message_id: Existing message to wait for instead of asking a question. Requires + ``conversation_id``. An empty string means ``None``. (templated) + :param polling_period_seconds: Seconds between status checks. Defaults to ``5``. + :param timeout: Maximum seconds to wait for the answer in one try. Timing out does not cancel the + message; the next try reconnects to it. Defaults to ``1800``. + :param resubmit_unconfirmed: Ask the question again even though an earlier submission's outcome is + unknown and may have created a message. Defaults to ``False``. + :param databricks_retry_limit: Attempts for each Genie read. Submissions are never retried. + Defaults to ``3``. + :param databricks_retry_delay: Minimum seconds between read attempts. Defaults to ``1``. + :param deferrable: Release the worker while waiting. Defaults to ``[operators] default_deferrable``, + with a fallback of ``False``. + :param durable: When ``True`` (the default), the Genie message IDs are persisted to task state + before waiting so a retry reconnects instead of asking again. Requires Airflow 3.3+; on earlier + versions every try asks the question again. + """ + + template_fields: Sequence[str] = ( + "space_id", + "question", + "databricks_conn_id", + "conversation_id", + "message_id", + ) + ui_color = "#1CB1C2" + external_id_key = "databricks_genie_message" + + def __init__( + self, + *, + space_id: str, + question: str | None = None, + databricks_conn_id: str = "databricks_default", + conversation_id: str | None = None, + message_id: str | None = None, + polling_period_seconds: float = 5, + timeout: float = 1800, + resubmit_unconfirmed: bool = False, + databricks_retry_limit: int = 3, + databricks_retry_delay: float = 1, + deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False), + durable: bool | None = None, + **kwargs: Any, + ) -> None: + # Named here (not left to **kwargs) so default_args reaches it on every supported Airflow version. + if durable is not None: + kwargs["durable"] = durable + super().__init__(**kwargs) + if polling_period_seconds <= 0: + raise ValueError("polling_period_seconds must be positive") + if timeout <= 0: + raise ValueError("timeout must be positive") + self.space_id = space_id + self.question = question + self.databricks_conn_id = databricks_conn_id + self.conversation_id = conversation_id + self.message_id = message_id + self.polling_period_seconds = polling_period_seconds + self.timeout = timeout + self.resubmit_unconfirmed = resubmit_unconfirmed + self.databricks_retry_limit = databricks_retry_limit + self.databricks_retry_delay = databricks_retry_delay + self.deferrable = deferrable + self._result: dict[str, Any] | None = None + + @cached_property + def hook(self) -> DatabricksGenieHook: + return DatabricksGenieHook( + self.databricks_conn_id, + retry_limit=self.databricks_retry_limit, + retry_delay=self.databricks_retry_delay, + caller=type(self).__name__, + poll_interval=self.polling_period_seconds, + ) + + @property + def _submission_key(self) -> str: + return f"{self.external_id_key}_submission" + + def _fingerprint(self) -> str: Review Comment: Could the helpers get verb names? `_fingerprint`, `_task_state_store` and `_message_path` here, `_event` in the trigger, and `message`, `stored_ref`, `answered` and `events` in the tests read as attributes at the call site. Something like `_compute_fingerprint`, `_get_task_state_store`, `_build_message_path` and `_build_event` would do. ########## providers/databricks/src/airflow/providers/databricks/operators/genie.py: ########## @@ -0,0 +1,365 @@ +# 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. +"""Operators for asking Databricks Genie spaces questions as standalone tasks.""" + +from __future__ import annotations + +import hashlib +import time +from collections.abc import Sequence +from datetime import timedelta +from functools import cached_property +from typing import TYPE_CHECKING, Any +from urllib.parse import quote + +from airflow.providers.common.compat.sdk import AirflowFailException, BaseOperator, ResumableJobMixin, conf +from airflow.providers.databricks.hooks.genie import ( + _PENDING_STATUSES, + DatabricksGenieError, + DatabricksGenieHook, + _truncate_result, +) +from airflow.providers.databricks.triggers.genie import DatabricksGenieMessageTrigger + +if TYPE_CHECKING: + from airflow.providers.common.compat.sdk import Context + +GenieMessageRef = dict[str, str] + +_NOT_FOUND = "NOT_FOUND" +_STALE = "STALE" +_TERMINAL_STATUSES = frozenset({"COMPLETED", "FAILED", "CANCELLED", "QUERY_RESULT_EXPIRED"}) + + +class DatabricksGenieOperator(ResumableJobMixin, BaseOperator): + """ + Ask a Databricks Genie space one question and return a bounded, structured answer. + + The operator submits the question once, persists the Genie conversation and message IDs to task + state before waiting, then polls (or defers) until the message finishes. A retry after a worker + crash or timeout reconnects to the stored message instead of asking again. + + Genie has no idempotency key, so a submission whose outcome is unknown (a timeout, a connection + error or a 5xx response) cannot be told apart from one that was never received. The operator fails + without retrying in that case and the next try refuses to submit again; set ``conversation_id`` and + ``message_id`` to attach to the message you found, or ``resubmit_unconfirmed=True`` to ask again. + + .. seealso:: + For more information on how to use this operator, take a look at the guide: + :ref:`howto/operator:DatabricksGenieOperator` + + :param space_id: Genie space ID. (templated) + :param question: Question to ask. Required unless ``message_id`` is set. (templated) + :param databricks_conn_id: Databricks connection. Defaults to ``databricks_default``. (templated) + :param conversation_id: Existing conversation to ask the question in. The operator never deletes it. + Defaults to ``None``, which starts a new conversation. An empty string means ``None``. (templated) + :param message_id: Existing message to wait for instead of asking a question. Requires + ``conversation_id``. An empty string means ``None``. (templated) + :param polling_period_seconds: Seconds between status checks. Defaults to ``5``. + :param timeout: Maximum seconds to wait for the answer in one try. Timing out does not cancel the + message; the next try reconnects to it. Defaults to ``1800``. + :param resubmit_unconfirmed: Ask the question again even though an earlier submission's outcome is + unknown and may have created a message. Defaults to ``False``. + :param databricks_retry_limit: Attempts for each Genie read. Submissions are never retried. + Defaults to ``3``. + :param databricks_retry_delay: Minimum seconds between read attempts. Defaults to ``1``. + :param deferrable: Release the worker while waiting. Defaults to ``[operators] default_deferrable``, + with a fallback of ``False``. + :param durable: When ``True`` (the default), the Genie message IDs are persisted to task state + before waiting so a retry reconnects instead of asking again. Requires Airflow 3.3+; on earlier + versions every try asks the question again. + """ + + template_fields: Sequence[str] = ( + "space_id", + "question", + "databricks_conn_id", + "conversation_id", + "message_id", + ) + ui_color = "#1CB1C2" + external_id_key = "databricks_genie_message" + + def __init__( + self, + *, + space_id: str, + question: str | None = None, + databricks_conn_id: str = "databricks_default", + conversation_id: str | None = None, + message_id: str | None = None, + polling_period_seconds: float = 5, + timeout: float = 1800, + resubmit_unconfirmed: bool = False, + databricks_retry_limit: int = 3, + databricks_retry_delay: float = 1, + deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False), + durable: bool | None = None, + **kwargs: Any, + ) -> None: + # Named here (not left to **kwargs) so default_args reaches it on every supported Airflow version. + if durable is not None: + kwargs["durable"] = durable + super().__init__(**kwargs) + if polling_period_seconds <= 0: + raise ValueError("polling_period_seconds must be positive") + if timeout <= 0: + raise ValueError("timeout must be positive") + self.space_id = space_id + self.question = question + self.databricks_conn_id = databricks_conn_id + self.conversation_id = conversation_id + self.message_id = message_id + self.polling_period_seconds = polling_period_seconds + self.timeout = timeout + self.resubmit_unconfirmed = resubmit_unconfirmed + self.databricks_retry_limit = databricks_retry_limit + self.databricks_retry_delay = databricks_retry_delay + self.deferrable = deferrable + self._result: dict[str, Any] | None = None + + @cached_property + def hook(self) -> DatabricksGenieHook: + return DatabricksGenieHook( + self.databricks_conn_id, + retry_limit=self.databricks_retry_limit, + retry_delay=self.databricks_retry_delay, + caller=type(self).__name__, + poll_interval=self.polling_period_seconds, + ) + + @property + def _submission_key(self) -> str: + return f"{self.external_id_key}_submission" + + def _fingerprint(self) -> str: + """Identify the question so a retry never reconnects to an answer for a different one.""" + material = "\x1f".join((self.space_id, self.conversation_id or "", self.question or "")) + return hashlib.sha256(material.encode("utf-8")).hexdigest() + + def _task_state_store(self, context: Context) -> Any: + return context.get("task_state_store") if self.durable else None + + def _validate(self) -> None: + self.conversation_id = self.conversation_id or None + self.message_id = self.message_id or None + self.hook._validate_space_id(self.space_id) + if self.message_id is not None: + if self.conversation_id is None: + raise ValueError("message_id requires conversation_id") + elif not isinstance(self.question, str) or not self.question.strip(): + raise ValueError("question must be a non-empty string unless message_id is set") + + def execute(self, context: Context) -> dict[str, Any]: + self._validate() + if self.message_id is None: + return self.execute_resumable(context) + ref = { + "space_id": self.space_id, + "conversation_id": self.conversation_id, + "message_id": self.message_id, + "fingerprint": self._fingerprint(), + } + self.log.info( + "Attaching to Genie message %s in conversation %s", self.message_id, self.conversation_id + ) + if (store := self._task_state_store(context)) is not None: + store.set(self.external_id_key, ref) + store.delete(self._submission_key) + return self.poll_until_complete(ref, context) + + def submit_job(self, context: Context) -> Any: + store = self._task_state_store(context) + if store is not None: + marker = store.get(self._submission_key) + if ( + marker is not None + and not self.resubmit_unconfirmed + and (not isinstance(marker, dict) or marker.get("fingerprint") == self._fingerprint()) + ): + raise AirflowFailException( + "An earlier try submitted this Genie question but Databricks never confirmed the " + "outcome, so a message may already exist. Inspect the Genie space, then set " + "conversation_id and message_id to attach to it, or set resubmit_unconfirmed=True " + "to ask again." + ) + store.set(self._submission_key, {"fingerprint": self._fingerprint()}) + + space = quote(self.space_id, safe="") + if self.conversation_id is None: + endpoint = f"spaces/{space}/start-conversation" + else: + endpoint = f"spaces/{space}/conversations/{quote(self.conversation_id, safe='')}/messages" + try: + created = self.hook._request( Review Comment: The marker is set a few lines up, but `_request` still has to look up the connection, pass the HTTPS check and fetch a token before it sends anything. If one of those fails, the marker stays and the next try stops with "An earlier try submitted this Genie question" although nothing was sent. I reproduced it with a `service_principal_oauth` connection and the token endpoint down on the first try: zero Genie requests on either try, and the second try raised `AirflowFailException`, so one token blip ends the task's retries. Could the URL, scheme check and auth be resolved before the marker is written, or the marker be removed for anything raised before the send? ########## providers/databricks/src/airflow/providers/databricks/operators/genie.py: ########## @@ -0,0 +1,365 @@ +# 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. +"""Operators for asking Databricks Genie spaces questions as standalone tasks.""" + +from __future__ import annotations + +import hashlib +import time +from collections.abc import Sequence +from datetime import timedelta +from functools import cached_property +from typing import TYPE_CHECKING, Any +from urllib.parse import quote + +from airflow.providers.common.compat.sdk import AirflowFailException, BaseOperator, ResumableJobMixin, conf +from airflow.providers.databricks.hooks.genie import ( + _PENDING_STATUSES, + DatabricksGenieError, + DatabricksGenieHook, + _truncate_result, +) +from airflow.providers.databricks.triggers.genie import DatabricksGenieMessageTrigger + +if TYPE_CHECKING: + from airflow.providers.common.compat.sdk import Context + +GenieMessageRef = dict[str, str] + +_NOT_FOUND = "NOT_FOUND" +_STALE = "STALE" +_TERMINAL_STATUSES = frozenset({"COMPLETED", "FAILED", "CANCELLED", "QUERY_RESULT_EXPIRED"}) Review Comment: `GENIE_TERMINAL_STATUSES` in the trigger module is the same set. Could one copy live next to `_PENDING_STATUSES` in the hook, so the operator and the trigger can't drift on when a message is done? ########## providers/databricks/docs/operators/genie_operator.rst: ########## @@ -0,0 +1,84 @@ + .. 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/operator:DatabricksGenieOperator: + +Ask a Databricks Genie space +============================ + +Use :class:`~airflow.providers.databricks.operators.genie.DatabricksGenieOperator` to ask a Genie space +one question as a standalone task. The operator returns the same bounded result as +:ref:`DatabricksGenieHook <howto/databricks-genie>` through XCom: the space, conversation and message +IDs, the message status, the text answer, generated queries and capped query results. + +.. exampleinclude:: /../../databricks/tests/system/databricks/example_databricks_genie.py + :language: python + :start-after: [START howto_operator_databricks_genie] + :end-before: [END howto_operator_databricks_genie] + +By default the operator starts a new conversation. Set ``conversation_id`` to ask a follow-up in an +existing conversation. The operator never deletes or cancels conversations, so a conversation you +supply stays yours. + +Set ``deferrable=True`` to release the worker while Genie works. The trigger only reads the message +status; the worker fetches the answer and query results when the task resumes, so the trigger event +never carries Genie output. + +.. exampleinclude:: /../../databricks/tests/system/databricks/example_databricks_genie.py + :language: python + :start-after: [START howto_operator_databricks_genie_deferrable] + :end-before: [END howto_operator_databricks_genie_deferrable] + +``timeout`` limits how long one try waits for the answer. Timing out does not cancel the message. + +Retries and resuming Review Comment: The resumable tasks concept page tells readers that each Databricks operator page has a "Durable execution" section, and `run_now.rst` and `submit_run.rst` use that heading and link back to the concept page. Could this section do the same, so someone coming from there finds it? ########## providers/databricks/docs/operators/genie_operator.rst: ########## @@ -0,0 +1,84 @@ + .. 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/operator:DatabricksGenieOperator: + +Ask a Databricks Genie space +============================ + +Use :class:`~airflow.providers.databricks.operators.genie.DatabricksGenieOperator` to ask a Genie space +one question as a standalone task. The operator returns the same bounded result as +:ref:`DatabricksGenieHook <howto/databricks-genie>` through XCom: the space, conversation and message +IDs, the message status, the text answer, generated queries and capped query results. + +.. exampleinclude:: /../../databricks/tests/system/databricks/example_databricks_genie.py + :language: python + :start-after: [START howto_operator_databricks_genie] + :end-before: [END howto_operator_databricks_genie] + +By default the operator starts a new conversation. Set ``conversation_id`` to ask a follow-up in an +existing conversation. The operator never deletes or cancels conversations, so a conversation you +supply stays yours. + +Set ``deferrable=True`` to release the worker while Genie works. The trigger only reads the message +status; the worker fetches the answer and query results when the task resumes, so the trigger event +never carries Genie output. + +.. exampleinclude:: /../../databricks/tests/system/databricks/example_databricks_genie.py + :language: python + :start-after: [START howto_operator_databricks_genie_deferrable] + :end-before: [END howto_operator_databricks_genie_deferrable] + +``timeout`` limits how long one try waits for the answer. Timing out does not cancel the message. + +Retries and resuming +-------------------- + +On Airflow 3.3 and later the operator is durable by default. It stores the conversation and message +IDs in the task state store before it waits, so a retry after a worker crash, a timeout or a failed +trigger reconnects to the same message instead of asking again: + +* A message that is still running is awaited again. +* A completed message returns its answer without asking again. +* A message that failed, was cancelled or whose result expired is asked again in a new message. +* A stored message that no longer exists, or that was asked for a different space, conversation or Review Comment: Only a 404 counts as "no longer exists" in `get_job_status`. The hook's own 403 message says Genie may return 403 for a missing resource, and in that case every retry fails here and the question is never asked again. Should the 403 case be mentioned here, with how to recover from it? ########## 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: This is the fifth copy of the same stubbed hook and hand-built `requests.Response` in this file. A fixture for the stubbed hook and a small response builder would leave each test with only its own setup and assertions. The stubs are bare `mock.Mock()` as well, so a renamed hook method would not fail any of these tests. ########## 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: This repeats the tuple from the operator, so it only fails when someone edits one and not the other. Would a test that renders a templated `conversation_id` and checks the endpoint it is sent to be more useful? ########## providers/databricks/docs/operators/genie.rst: ########## @@ -0,0 +1,66 @@ + .. 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/databricks-genie: + +Databricks Genie consultations +============================== + +The ``DatabricksGenieHook`` submits a question to a Genie space, waits for the message to finish, +and returns a bounded result with the space, conversation, and message IDs. It uses the +credentials in an Airflow ``databricks`` connection and implements Common AI's public +``BaseManagedAgentHook`` contract. + +Install the optional Common AI integration when using its managed-agent toolset: + +.. code-block:: bash + + pip install 'apache-airflow-providers-databricks[common.ai]' + +.. code-block:: python + + from airflow.providers.common.ai.toolsets import ManagedAgentToolset + from airflow.providers.databricks.hooks.genie import DatabricksGenieHook + + hook = DatabricksGenieHook(databricks_conn_id="databricks_analytics") + toolset = ManagedAgentToolset( + hook.agent("your-genie-space-id"), + tool_name="ask_analytics_genie", + description="Answers questions about the analytics tables in this Genie space.", + max_retries=0, + ) + +The hook can also be called directly without Common AI: + +.. code-block:: python + + result = hook.consult("your-genie-space-id", "How many orders were placed last week?") + +The result contains IDs and structured answer, generated query, and query-result fields. Large +responses are capped. A request that starts a conversation or posts a message is sent once; after +a timeout or server failure its outcome may be unknown, so inspect the conversation before +submitting again. Message and query-result reads may be retried. A 403 can mean either that access +was denied or that the resource is missing, because Genie may conceal missing resources this way. + +Genie MCP through Unity Gateway is enough when an external model or MCP client should discover and +call Genie directly through the organization's governed MCP endpoint. The native Databricks API +integration is useful when an Airflow-managed agent needs Genie as a typed tool backed by an Airflow +Databricks connection, and when the caller needs the Genie space/conversation/message IDs and +bounded query results in its response. Both paths still enforce Genie and Unity Catalog permissions. + +This hook handles consultations only. Resuming a consultation through a standalone Airflow task +across worker failure is a separate feature and is not provided here. Review Comment: This PR adds that task, so this sentence is out of date once it merges. Could it point to `DatabricksGenieOperator` instead? ########## providers/databricks/docs/operators/genie_operator.rst: ########## @@ -0,0 +1,84 @@ + .. 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/operator:DatabricksGenieOperator: + +Ask a Databricks Genie space +============================ + +Use :class:`~airflow.providers.databricks.operators.genie.DatabricksGenieOperator` to ask a Genie space +one question as a standalone task. The operator returns the same bounded result as +:ref:`DatabricksGenieHook <howto/databricks-genie>` through XCom: the space, conversation and message +IDs, the message status, the text answer, generated queries and capped query results. + +.. exampleinclude:: /../../databricks/tests/system/databricks/example_databricks_genie.py + :language: python + :start-after: [START howto_operator_databricks_genie] + :end-before: [END howto_operator_databricks_genie] + +By default the operator starts a new conversation. Set ``conversation_id`` to ask a follow-up in an +existing conversation. The operator never deletes or cancels conversations, so a conversation you +supply stays yours. + +Set ``deferrable=True`` to release the worker while Genie works. The trigger only reads the message +status; the worker fetches the answer and query results when the task resumes, so the trigger event +never carries Genie output. + +.. exampleinclude:: /../../databricks/tests/system/databricks/example_databricks_genie.py + :language: python + :start-after: [START howto_operator_databricks_genie_deferrable] + :end-before: [END howto_operator_databricks_genie_deferrable] + +``timeout`` limits how long one try waits for the answer. Timing out does not cancel the message. + +Retries and resuming +-------------------- + +On Airflow 3.3 and later the operator is durable by default. It stores the conversation and message +IDs in the task state store before it waits, so a retry after a worker crash, a timeout or a failed +trigger reconnects to the same message instead of asking again: + +* A message that is still running is awaited again. +* A completed message returns its answer without asking again. +* A message that failed, was cancelled or whose result expired is asked again in a new message. +* A stored message that no longer exists, or that was asked for a different space, conversation or + question, is asked again. + +Set ``durable=False`` to ask again on every try. On Airflow versions before 3.3 there is no task state +store, so every try asks again; the operator logs the IDs right after it submits the question so you +can attach to the message by hand. + +Genie's start-conversation and create-message APIs have no idempotency key. When Databricks does not +confirm a submission (a timeout, a connection error, a 5xx response, or a response without IDs) the +message may or may not exist, and listing the conversation cannot reliably tell. The operator then fails +with ``AirflowFailException`` instead of retrying, and while the durable state remembers that unconfirmed +submission the next try refuses to ask again. Inspect the Genie space, then either: + +* set ``conversation_id`` and ``message_id`` to attach to the message you found; the operator waits for + it and returns its answer without asking, or +* set ``resubmit_unconfirmed=True`` to accept that the question may be asked twice. + +A request that Databricks rejects with a 4xx response created nothing, so Airflow's normal retries +apply to it. + +Cancellation +------------ + +Genie has no API to cancel a chat message, so killing or timing out the task leaves the message +running in Databricks. The next try reconnects to it. Review Comment: This only holds while the durable state is in play. With `durable=False`, or on an Airflow version without the task state store, the next try asks again, as the section above says. The `timeout` docstring and the two error messages in the operator that end with "the next try reconnects" make the same promise. ########## 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: `body` is the same in both branches, so it can be set once above the `if`. -- 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]
