This is an automated email from the ASF dual-hosted git repository.
kaxil pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new e3e04d1bce5 Add a resumable deferrable Databricks Genie operator
(#76157)
e3e04d1bce5 is described below
commit e3e04d1bce529d4991f35b795a1f563f46f51281
Author: Yossi Eliaz <[email protected]>
AuthorDate: Tue Nov 24 14:46:47 2026 +0200
Add a resumable deferrable Databricks Genie operator (#76157)
* Databricks: support Genie consultations via hook and common.ai adapter
(#74194)
* Make Genie consultations safe for direct and managed-agent use
Direct consultations must remain available without Common AI, while
managed-agent callers need bounded results and single-send behavior for
non-idempotent requests. Keep provider release metadata under release-manager
control.
* Fix Genie query result truncation reporting
* Drop common.ai extra duplicated when rebasing the Genie hook onto main
* Add a resumable Databricks Genie operator
Genie questions can take minutes to answer, and a worker crash or task retry
should not ask the same question twice or lose an answer that already
exists.
The operator records the Genie message it started so retries reconnect to
it,
refuses to guess after an unconfirmed submission, and can release the worker
slot while a triggerer waits for the message to finish.
* Fix mypy override error in DatabricksGenieOperator.submit_job
ResumableJobMixin.submit_job returns JsonValue, and dict[str, str] is not
compatible with it because dict is invariant. Return Any, matching the other
external-ID overrides on the operator.
* Fix mypy assignment error on DatabricksGenieError.status_code
* Fix Genie hook test for wheel/compat installs
Resolve genie.py via the installed module __file__ instead of a
hardcoded providers/.../src path so Compat matrix jobs that install
the provider from a wheel no longer FileNotFoundError.
Co-authored-by: Yossi Eliaz <[email protected]>
* Fail Genie reconnect on unknown status instead of resubmitting
An unrecognized or missing Genie message status was treated as terminal by
ResumableJobMixin, so a retry could ask again while the first message was
still running. Align submission-marker handling with fingerprint checks so
a changed question is not blocked by a prior unconfirmed try.
Signed-off-by: Yossi Eliaz <[email protected]>
Signed-off-by: Cursor Agent <[email protected]>
Co-authored-by: Yossi Eliaz <[email protected]>
* Use Databricks _TokenAuth for Genie token HTTP requests
Passing auth=None with a Bearer header lets requests apply a matching
~/.netrc entry and overwrite the token with Basic auth. Match the base
Databricks hook so token requests keep the intended credentials.
Signed-off-by: Yossi Eliaz <[email protected]>
Co-authored-by: Yossi Eliaz <[email protected]>
* Annotate Genie request auth as AuthBase for mypy
Signed-off-by: Yossi Eliaz <[email protected]>
* Address Genie operator review: marker ordering, shared statuses, docs
Resolve the URL, the HTTPS check and credentials before writing the
submission marker, so a failure that sends nothing (for example a token
endpoint error) no longer blocks the next try. Keep one
GENIE_TERMINAL_STATUSES in the hook for the operator and trigger, give
helpers verb names, qualify the reconnect promise for durable=False and
older Airflow, document the 403 case and its recovery, and tidy tests
with a stubbed hook fixture and a response builder.
Signed-off-by: Yossi Eliaz <[email protected]>
* Follow the Genie hook review: shared error type and fuller tests
Move DatabricksGenieError into exceptions.py as a DatabricksApiError
subclass that carries http_status_code, so callers and the trigger catch
one type and the type ignore is gone. Add tests for consult ending
FAILED, CANCELLED, expired or unknown, for the consult deadline, and for
the vendor_options refusal in invoke_agent. Hook tests now use fixtures
built on mock.patch.object with autospec instead of bare mocks.
Signed-off-by: Yossi Eliaz <[email protected]>
* Document Genie clears with keep_task_state and use exampleinclude
Spell out what a default clear does on Airflow 3.4 and later, which
discards the task state and asks Genie again, versus a clear that keeps
task state, for running, completed, failed, unconfirmed and 403 cases.
Show a run scoped attach through params, and make the unconfirmed
submission errors describe the clear behavior instead of promising a
refusal. Move the hook and attach examples into the Genie system test
and pull them into the docs with exampleinclude.
Signed-off-by: Yossi Eliaz <[email protected]>
---------
Signed-off-by: zozo123 <[email protected]>
Signed-off-by: Yossi Eliaz <[email protected]>
Signed-off-by: Cursor Agent <[email protected]>
Co-authored-by: Dhanush A G <[email protected]>
Co-authored-by: Garvit Arora <[email protected]>
Co-authored-by: Yossi Eliaz <[email protected]>
---
providers/databricks/docs/operators/genie.rst | 63 ++
.../databricks/docs/operators/genie_operator.rst | 161 +++++
providers/databricks/provider.yaml | 5 +
.../src/airflow/providers/databricks/exceptions.py | 9 +
.../providers/databricks/get_provider_info.py | 5 +
.../airflow/providers/databricks/hooks/genie.py | 481 ++++++++++++++
.../providers/databricks/operators/genie.py | 387 ++++++++++++
.../airflow/providers/databricks/triggers/genie.py | 132 ++++
.../system/databricks/example_databricks_genie.py | 132 ++++
.../tests/unit/databricks/hooks/test_genie.py | 384 ++++++++++++
.../tests/unit/databricks/operators/test_genie.py | 688 +++++++++++++++++++++
.../tests/unit/databricks/triggers/test_genie.py | 170 +++++
12 files changed, 2617 insertions(+)
diff --git a/providers/databricks/docs/operators/genie.rst
b/providers/databricks/docs/operators/genie.rst
new file mode 100644
index 00000000000..237a41a9f8f
--- /dev/null
+++ b/providers/databricks/docs/operators/genie.rst
@@ -0,0 +1,63 @@
+ .. 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]'
+
+.. exampleinclude::
/../../databricks/tests/system/databricks/example_databricks_genie.py
+ :language: python
+ :dedent: 4
+ :start-after: [START howto_hook_databricks_genie_toolset]
+ :end-before: [END howto_hook_databricks_genie_toolset]
+
+The hook can also be called directly without Common AI:
+
+.. exampleinclude::
/../../databricks/tests/system/databricks/example_databricks_genie.py
+ :language: python
+ :dedent: 4
+ :start-after: [START howto_hook_databricks_genie_consult]
+ :end-before: [END howto_hook_databricks_genie_consult]
+
+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. To ask Genie as a standalone Airflow
task that reconnects to
+its message after a worker failure, use
+:class:`~airflow.providers.databricks.operators.genie.DatabricksGenieOperator`;
see
+:ref:`howto/operator:DatabricksGenieOperator`.
diff --git a/providers/databricks/docs/operators/genie_operator.rst
b/providers/databricks/docs/operators/genie_operator.rst
new file mode 100644
index 00000000000..6bab8eee517
--- /dev/null
+++ b/providers/databricks/docs/operators/genie_operator.rst
@@ -0,0 +1,161 @@
+ .. 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
+ :dedent: 4
+ :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
+ :dedent: 4
+ :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.
+
+Durable execution
+-----------------
+
+On Airflow 3.3 and later the operator is durable by default. It stores the
conversation and message
+IDs in the :doc:`task state store
<apache-airflow:core-concepts/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. See :doc:`apache-airflow:core-concepts/resumable-tasks` for how
resumable tasks work.
+On retry the operator checks the stored message:
+
+* 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 (Genie answers 404), 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.
+
+Clearing the task
+^^^^^^^^^^^^^^^^^
+
+Retries always keep the task state. Clearing does not by default: clearing a
task instance from the
+UI or the REST API (so ``airflowctl`` too) discards it from Airflow 3.4, and
every other clear, such as
+``airflow tasks clear`` or clearing a whole Dag run, does so from Airflow 3.5.
To keep it, tick
+**Keep task state and resume** in the Clear dialog, or send
``"keep_task_state": true`` in the
+request. From Airflow 3.5, ``airflow tasks clear --keep-task-state`` keeps it
too. On Airflow 3.3 a
+clear keeps the task state like a retry. What the next attempt does then
depends on what the task
+state holds:
+
+.. list-table::
+ :header-rows: 1
+ :widths: 30 35 35
+
+ * - Task state holds
+ - Default clear
+ - Clear that keeps task state
+ * - A message that is still running
+ - Asks the question again in a new message. Genie cannot cancel the first
one, so both run.
+ - Waits for the running message.
+ * - A completed message
+ - Asks the question again in a new message.
+ - Returns the stored answer without asking.
+ * - A failed, cancelled or expired message
+ - Asks the question again in a new message.
+ - Asks the question again in a new message.
+ * - An unconfirmed submission (see below)
+ - Asks the question again, so it may be asked twice.
+ - Refuses to ask until you attach or set ``resubmit_unconfirmed=True``.
+ * - A message hidden behind a 403 (see below)
+ - Asks the question again in a new message.
+ - Fails the same way.
+
+With ``[state_store] clear_on_success`` on, the stored IDs are deleted when
the task succeeds, so
+clearing a succeeded task asks again even when task state is kept.
+
+Attaching to a message
+^^^^^^^^^^^^^^^^^^^^^^
+
+Set ``conversation_id`` and ``message_id`` to wait for a message that already
exists instead of
+asking. The operator returns that message's answer and replaces any stored IDs
with it. Both fields
+are templated. A fixed ``message_id`` in the Dag applies to every later run,
which would then return
+the same old answer without asking, so pass the IDs for one run through params
instead and trigger
+or clear that run with them. Empty values ask the question as usual:
+
+.. exampleinclude::
/../../databricks/tests/system/databricks/example_databricks_genie.py
+ :language: python
+ :dedent: 4
+ :start-after: [START howto_operator_databricks_genie_attach]
+ :end-before: [END howto_operator_databricks_genie_attach]
+
+Unconfirmed submissions
+^^^^^^^^^^^^^^^^^^^^^^^
+
+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``, so Airflow does not retry it and the next
attempt only comes from
+a clear. The durable state remembers the unconfirmed submission, but a default
clear discards it and
+asks the question again without any check. Inspect the Genie space before
clearing, then either:
+
+* attach to the message you found with ``conversation_id`` and ``message_id``
as shown above; the
+ operator waits for it and returns its answer without asking,
+* clear with task state kept and set ``resubmit_unconfirmed=True`` to accept
that the question may be
+ asked twice, or
+* clear with the default to ask again, accepting the same risk.
+
+A clear that keeps task state and changes neither setting refuses to ask again.
+
+A request that Databricks rejects with a 4xx response created nothing, so
Airflow's normal retries
+apply to it.
+
+Messages hidden behind a 403
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+Genie may also answer 403 for a message that does not exist, so it does not
reveal which resources
+are there. The operator treats only 404 as a missing message, so a stored
message that Genie hides
+behind a 403 fails the try instead of being asked again, and retries fail the
same way because they
+keep the stored IDs. First check that the connection can still read the Genie
space and fix its
+permissions if it cannot. If access is fine, the stored message is gone: a
default clear discards the
+stored IDs and asks again, or you can attach to a message you know exists. A
new Dag run starts with
+empty task state and is not affected.
+
+Cancellation
+------------
+
+Genie has no API to cancel a chat message, so killing or timing out the task
leaves the message
+running in Databricks. With durable execution the next try reconnects to it.
With ``durable=False``,
+or on Airflow before 3.3 where there is no task state store, the next try asks
the question again in
+a new message.
diff --git a/providers/databricks/provider.yaml
b/providers/databricks/provider.yaml
index d67e3cd2336..1938d80136a 100644
--- a/providers/databricks/provider.yaml
+++ b/providers/databricks/provider.yaml
@@ -126,6 +126,8 @@ integrations:
- /docs/apache-airflow-providers-databricks/operators/run_now.rst
- /docs/apache-airflow-providers-databricks/operators/task.rst
- /docs/apache-airflow-providers-databricks/operators/agent.rst
+ - /docs/apache-airflow-providers-databricks/operators/genie.rst
+ - /docs/apache-airflow-providers-databricks/operators/genie_operator.rst
logo: /docs/integration-logos/Databricks.png
tags: [service]
- integration-name: Databricks SQL
@@ -158,6 +160,7 @@ operators:
python-modules:
- airflow.providers.databricks.operators.databricks
- airflow.providers.databricks.operators.agent
+ - airflow.providers.databricks.operators.genie
- integration-name: Databricks SQL
python-modules:
- airflow.providers.databricks.operators.databricks_sql
@@ -190,6 +193,7 @@ hooks:
- airflow.providers.databricks.hooks.databricks
- airflow.providers.databricks.hooks.databricks_base
- airflow.providers.databricks.hooks.agent
+ - airflow.providers.databricks.hooks.genie
- integration-name: Databricks SQL
python-modules:
- airflow.providers.databricks.hooks.databricks_sql
@@ -199,6 +203,7 @@ triggers:
python-modules:
- airflow.providers.databricks.triggers.databricks
- airflow.providers.databricks.triggers.agent
+ - airflow.providers.databricks.triggers.genie
sensors:
- integration-name: Databricks
diff --git
a/providers/databricks/src/airflow/providers/databricks/exceptions.py
b/providers/databricks/src/airflow/providers/databricks/exceptions.py
index 1a63de52605..5329442b11d 100644
--- a/providers/databricks/src/airflow/providers/databricks/exceptions.py
+++ b/providers/databricks/src/airflow/providers/databricks/exceptions.py
@@ -63,6 +63,15 @@ class DatabricksDeltaTableError(AirflowException):
"""Raised when a Delta table cannot be read or its version cannot be
determined."""
+class DatabricksGenieError(DatabricksApiError):
+ """
+ Raised when a Databricks Genie request fails or returns a result that
cannot be used.
+
+ ``http_status_code`` holds the HTTP status Genie answered with, or
``None`` when there was no usable
+ response, for example after a timeout, a connection error or an invalid
body.
+ """
+
+
class DatabricksUnityMCPError(DatabricksApiError):
"""Raised when a call to a Unity Gateway MCP Service fails."""
diff --git
a/providers/databricks/src/airflow/providers/databricks/get_provider_info.py
b/providers/databricks/src/airflow/providers/databricks/get_provider_info.py
index ce56c2cdcfb..9a8e67a1bb9 100644
--- a/providers/databricks/src/airflow/providers/databricks/get_provider_info.py
+++ b/providers/databricks/src/airflow/providers/databricks/get_provider_info.py
@@ -37,6 +37,8 @@ def get_provider_info():
"/docs/apache-airflow-providers-databricks/operators/run_now.rst",
"/docs/apache-airflow-providers-databricks/operators/task.rst",
"/docs/apache-airflow-providers-databricks/operators/agent.rst",
+
"/docs/apache-airflow-providers-databricks/operators/genie.rst",
+
"/docs/apache-airflow-providers-databricks/operators/genie_operator.rst",
],
"logo": "/docs/integration-logos/Databricks.png",
"tags": ["service"],
@@ -81,6 +83,7 @@ def get_provider_info():
"python-modules": [
"airflow.providers.databricks.operators.databricks",
"airflow.providers.databricks.operators.agent",
+ "airflow.providers.databricks.operators.genie",
],
},
{
@@ -123,6 +126,7 @@ def get_provider_info():
"airflow.providers.databricks.hooks.databricks",
"airflow.providers.databricks.hooks.databricks_base",
"airflow.providers.databricks.hooks.agent",
+ "airflow.providers.databricks.hooks.genie",
],
},
{
@@ -136,6 +140,7 @@ def get_provider_info():
"python-modules": [
"airflow.providers.databricks.triggers.databricks",
"airflow.providers.databricks.triggers.agent",
+ "airflow.providers.databricks.triggers.genie",
],
}
],
diff --git
a/providers/databricks/src/airflow/providers/databricks/hooks/genie.py
b/providers/databricks/src/airflow/providers/databricks/hooks/genie.py
new file mode 100644
index 00000000000..cd8411934ef
--- /dev/null
+++ b/providers/databricks/src/airflow/providers/databricks/hooks/genie.py
@@ -0,0 +1,481 @@
+# 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, NamedTuple
+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 (
+ AirflowOptionalProviderFeatureException,
+)
+from airflow.providers.databricks.exceptions import DatabricksGenieError
+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",
+ }
+)
+GENIE_TERMINAL_STATUSES = frozenset({"COMPLETED", "FAILED", "CANCELLED",
"QUERY_RESULT_EXPIRED"})
+
+
+class _PreparedRequest(NamedTuple):
+ """URL, headers, auth and transport options for one Genie call, resolved
before anything is sent."""
+
+ url: str
+ headers: dict[str, str]
+ auth: AuthBase
+ requests_kwargs: dict[str, Any]
+
+
+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="")
+ body = {"content": prompt, "enable_visualization": False}
+ if conversation_id is None:
+ endpoint = f"spaces/{space}/start-conversation"
+ else:
+ conversation = quote(conversation_id, safe="")
+ endpoint = f"spaces/{space}/conversations/{conversation}/messages"
+
+ 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,
+ prepared: _PreparedRequest | None = None,
+ ) -> dict[str, Any]:
+ """
+ Call one Genie endpoint; only GET requests are eligible for transport
retries.
+
+ :param prepared: The result of :meth:`_prepare_request` for
``endpoint``, so a caller can resolve
+ the connection, the HTTPS check and credentials before it records
that it is about to send.
+ """
+ url, headers, auth, requests_kwargs = (
+ prepared if prepared is not None else
self._prepare_request(endpoint)
+ )
+
+ def send() -> dict[str, Any]:
+ response = requests.request(
+ method,
+ url,
+ json=body if method == "POST" else None,
+ auth=auth,
+ headers=headers,
+ timeout=self._bounded_timeout(deadline),
+ stream=True,
+ **requests_kwargs,
+ )
+ try:
+ if not response.ok:
+ if (
+ method == "GET"
+ and retry_read
+ and (response.status_code >= 500 or
response.status_code == 429)
+ ):
+ response.raise_for_status()
+ raise self._http_error(response.status_code)
+ payload = bytearray()
+ for chunk in response.iter_content(16 * 1024):
+ payload.extend(chunk)
+ if len(payload) > _MAX_RESPONSE_BYTES:
+ raise DatabricksGenieError(
+ f"Genie response exceeded the
{_MAX_RESPONSE_BYTES}-byte safety limit."
+ )
+ if not payload:
+ return {}
+ try:
+ decoded = json.loads(payload)
+ except json.JSONDecodeError as exc:
+ raise DatabricksGenieError("Databricks Genie returned
invalid JSON.") from exc
+ if not isinstance(decoded, dict):
+ raise DatabricksGenieError("Genie returned a non-object
response.")
+ return decoded
+ finally:
+ response.close()
+
+ if not retry_read:
+ try:
+ return send()
+ except (requests.exceptions.RequestException, TimeoutError) as exc:
+ raise DatabricksGenieError(
+ "The Genie request may have been accepted, but Databricks
did not confirm its "
+ "result. The hook did not retry it; inspect the Genie
conversation before "
+ "submitting again."
+ ) from exc
+ except DatabricksGenieError as exc:
+ if exc.http_status_code is None or exc.http_status_code >= 500:
+ raise DatabricksGenieError(
+ f"{exc} The request may have been accepted; its
outcome is unknown "
+ "and the hook did not retry it."
+ ) from exc
+ raise
+
+ try:
+ for attempt in self._get_retry_object():
+ with attempt:
+ if deadline is not None and time.monotonic() >= deadline:
+ raise DatabricksGenieError("Timed out waiting for a
Genie read request.")
+ return send()
+ except RetryError as exc:
+ last_error = exc.last_attempt.exception()
+ response = getattr(last_error, "response", None)
+ if response is not None:
+ raise self._http_error(response.status_code) from exc
+ raise DatabricksGenieError(
+ f"A Genie read request failed after {self.retry_limit}
attempts."
+ ) from exc
+ except requests.exceptions.HTTPError as exc:
+ response = exc.response
+ if response is not None:
+ raise self._http_error(response.status_code) from exc
+ raise
+ raise AssertionError("retry loop must return or raise")
+
+ def _prepare_request(self, endpoint: str) -> _PreparedRequest:
+ """Resolve the URL, enforce HTTPS and fetch credentials for one Genie
endpoint without sending."""
+ 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()}
+ # Pass _TokenAuth (not auth=None with a Bearer header) so requests
does not
+ # apply a matching ~/.netrc entry and overwrite the token with Basic
auth.
+ token = self._get_token()
+ auth: AuthBase
+ if token:
+ auth = _TokenAuth(token)
+ else:
+ auth = HTTPBasicAuth(self._get_connection_attr("login"),
self.databricks_conn.password)
+ return _PreparedRequest(url, headers, auth,
self._get_requests_kwargs())
+
+ def _bounded_timeout(self, deadline: float | None) -> float:
+ if deadline is None:
+ return self.timeout_seconds
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise DatabricksGenieError("Timed out waiting for a Genie read
request.")
+ return min(float(self.timeout_seconds), remaining)
+
+ @staticmethod
+ def _http_error(status_code: int) -> DatabricksGenieError:
+ if status_code == 401:
+ message = (
+ "Databricks authentication failed (HTTP 401); check the
Databricks connection credentials."
+ )
+ elif status_code == 403:
+ message = (
+ "Databricks denied access to the Genie space or conversation
(HTTP 403). "
+ "Genie may also return 403 when a resource does not exist; "
+ "verify the ID and permissions."
+ )
+ elif status_code == 404:
+ message = "The Genie space, conversation, message, or result was
not found (HTTP 404)."
+ elif status_code == 429:
+ message = "Databricks rate-limited the Genie request (HTTP 429);
retry after the task delay."
+ else:
+ message = f"Databricks Genie returned HTTP {status_code}."
+ return DatabricksGenieError(message, http_status_code=status_code)
+
+
+def _messages_to_prompt(messages: list[dict[str, Any]]) -> str:
+ parts: list[str] = []
+ for message in messages:
+ content = message.get("content", "")
+ if isinstance(content, str):
+ parts.append(content)
+ elif isinstance(content, list):
+ for item in content:
+ if (
+ isinstance(item, dict)
+ and item.get("type") == "text"
+ and isinstance(item.get("text"), str)
+ ):
+ parts.append(item["text"])
+ prompt = "\n".join(parts).strip()
+ if not prompt:
+ raise ValueError("Genie consultations require a text prompt.")
+ return prompt
+
+
+def _summarize_query_result(response: dict[str, Any]) -> dict[str, Any]:
+ statement = response.get("statement_response", response)
+ if not isinstance(statement, dict):
+ return {"result": "unavailable"}
+ manifest = statement.get("manifest") or {}
+ result = statement.get("result") or {}
+ columns = [
+ column.get("name") for column in manifest.get("schema",
{}).get("columns", []) if column.get("name")
+ ]
+ rows = result.get("data_array") or []
+ returned_rows = rows[:_MAX_RESULT_ROWS]
+ total_row_count = manifest.get("total_row_count", len(rows))
+ total_chunk_count = manifest.get("total_chunk_count", 1)
+ return {
+ "columns": columns[:100],
+ "rows": returned_rows,
+ "total_row_count": total_row_count,
+ "truncated": (
+ bool(manifest.get("truncated"))
+ or len(rows) > len(returned_rows)
+ or len(columns) > 100
+ or (isinstance(total_row_count, int) and total_row_count >
len(returned_rows))
+ or (isinstance(total_chunk_count, int) and total_chunk_count > 1)
+ ),
+ }
+
+
+def _truncate_result(result: dict[str, Any]) -> dict[str, Any]:
+ """Bound tool output while keeping valid JSON and the consultation
identifiers."""
+ encoded = json.dumps(result, ensure_ascii=False, separators=(",", ":"))
+ if len(encoded.encode("utf-8")) <= _MAX_RESULT_BYTES:
+ return result
+ bounded = dict(result)
+ bounded["truncated"] = True
+ for key in ("query_results", "queries"):
+ if key in bounded:
+ bounded[key] = [{"truncated": True} for _ in bounded[key]]
+ answer = bounded.get("answer", "")
+ low, high = 0, len(answer)
+ while low < high:
+ middle = (low + high + 1) // 2
+ bounded["answer"] = answer[:middle]
+ encoded_size = len(json.dumps(bounded, ensure_ascii=False,
separators=(",", ":")).encode("utf-8"))
+ if encoded_size <= _MAX_RESULT_BYTES:
+ low = middle
+ else:
+ high = middle - 1
+ bounded["answer"] = answer[:low]
+ return bounded
diff --git
a/providers/databricks/src/airflow/providers/databricks/operators/genie.py
b/providers/databricks/src/airflow/providers/databricks/operators/genie.py
new file mode 100644
index 00000000000..81559bde3ff
--- /dev/null
+++ b/providers/databricks/src/airflow/providers/databricks/operators/genie.py
@@ -0,0 +1,387 @@
+# 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.exceptions import DatabricksGenieError
+from airflow.providers.databricks.hooks.genie import (
+ _PENDING_STATUSES,
+ GENIE_TERMINAL_STATUSES,
+ 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"
+_UNCONFIRMED_HINT = (
+ "Airflow will not retry this task. Inspect the Genie space before clearing
it: a default clear "
+ "discards the task state and asks the question again, while a clear that
keeps task state "
+ "refuses to ask until you attach with conversation_id and message_id or
set "
+ "resubmit_unconfirmed=True."
+)
+
+
+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.
With durable execution
+ (the default on Airflow 3.3 and later), a retry after a worker crash or
timeout reconnects to the
+ stored message instead of asking again. With ``durable=False``, or on
older Airflow without the task
+ state store, every try asks 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. A later try that still finds the
unconfirmed submission in task state
+ refuses to submit again; set ``conversation_id`` and ``message_id`` to
attach to the message you
+ found, or ``resubmit_unconfirmed=True`` to ask again. A clear that
discards task state (the default
+ from Airflow 3.4) asks again without that check.
+
+ .. 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``. A fixed value
applies to every Dag run, so
+ prefer a run-scoped template such as ``"{{ params.genie_message_id
}}"``. (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. With durable execution the next try reconnects to it; with
``durable=False``, or on
+ Airflow before 3.3, the next try asks again. 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 _compute_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 _get_task_state_store(self, context: Context) -> Any:
+ return context.get("task_state_store") if self.durable else None
+
+ def _describe_next_try(self, context: Context) -> str:
+ """Say what a retry does, since only durable execution or an explicit
message_id reconnects."""
+ if self.message_id is not None or self._get_task_state_store(context)
is not None:
+ return "A retry reconnects to the message."
+ return "A retry asks the question again, because durable execution is
off or unavailable."
+
+ 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._compute_fingerprint(),
+ }
+ self.log.info(
+ "Attaching to Genie message %s in conversation %s",
self.message_id, self.conversation_id
+ )
+ if (store := self._get_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:
+ 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"
+ # Resolve the connection, the HTTPS check and credentials first: if
any of them fails, nothing
+ # was sent, so no marker may be written that would block the next try.
+ prepared = self.hook._prepare_request(endpoint)
+
+ store = self._get_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._compute_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._compute_fingerprint()})
+
+ try:
+ created = self.hook._request(
+ "POST",
+ endpoint,
+ body={"content": self.question, "enable_visualization": False},
+ retry_read=False,
+ prepared=prepared,
+ )
+ except DatabricksGenieError as err:
+ if err.http_status_code is not None and err.http_status_code < 500:
+ # Databricks rejected the request, so nothing was created and
a retry may submit again.
+ if store is not None:
+ store.delete(self._submission_key)
+ raise
+ raise AirflowFailException(f"{err} {_UNCONFIRMED_HINT}") from err
+
+ conversation_id = created.get("conversation_id")
+ message_id = created.get("message_id") or created.get("id")
+ if not isinstance(conversation_id, str) or not isinstance(message_id,
str):
+ raise AirflowFailException(
+ f"Genie accepted the question but returned no conversation or
message ID. {_UNCONFIRMED_HINT}"
+ )
+ ref = {
+ "space_id": self.space_id,
+ "conversation_id": conversation_id,
+ "message_id": message_id,
+ "fingerprint": self._compute_fingerprint(),
+ }
+ self.log.info("Asked Genie message %s in conversation %s", message_id,
conversation_id)
+ if store is not None:
+ # Persist before dropping the marker so no crash can lose both.
+ store.set(self.external_id_key, ref)
+ store.delete(self._submission_key)
+ return ref
+
+ def _build_message_path(self, ref: GenieMessageRef) -> str:
+ return (
+ f"spaces/{quote(ref['space_id'], safe='')}/conversations/"
+ f"{quote(ref['conversation_id'],
safe='')}/messages/{quote(ref['message_id'], safe='')}"
+ )
+
+ def _get_message(self, ref: GenieMessageRef, deadline: float | None =
None) -> dict[str, Any]:
+ return self.hook._request("GET", self._build_message_path(ref),
retry_read=True, deadline=deadline)
+
+ def get_job_status(self, external_id: Any, context: Context) -> str:
+ if not isinstance(external_id, dict) or external_id.get("fingerprint")
!= self._compute_fingerprint():
+ self.log.warning("Stored Genie message was for a different
question; asking again")
+ return _STALE
+ try:
+ message = self._get_message(external_id)
+ except DatabricksGenieError as err:
+ if err.http_status_code == 404:
+ return _NOT_FOUND
+ raise
+ status = message.get("status")
+ if status in _PENDING_STATUSES or status in GENIE_TERMINAL_STATUSES:
+ return str(status)
+ raise DatabricksGenieError(f"Genie returned an unknown message status:
{status!r}.")
+
+ def is_job_active(self, status: str) -> bool:
+ return status in _PENDING_STATUSES
+
+ def is_job_succeeded(self, status: str) -> bool:
+ return status == "COMPLETED"
+
+ def _check_message(self, message: dict[str, Any], ref: GenieMessageRef) ->
bool:
+ """Return whether the message is completed, raise if it ended without
an answer."""
+ status = message.get("status")
+ if status == "COMPLETED":
+ return True
+ if status in _PENDING_STATUSES:
+ return False
+ 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 message {ref['message_id']}: {detail
or 'unknown error'}"
+ )
+ if status in {"CANCELLED", "QUERY_RESULT_EXPIRED"}:
+ raise DatabricksGenieError(f"Genie message {ref['message_id']}
ended with status {status}.")
+ raise DatabricksGenieError(f"Genie returned an unknown message status:
{status!r}.")
+
+ def poll_until_complete(self, external_id: Any, context: Context) -> Any:
+ """
+ Wait for the message and return its bounded result.
+
+ ``execute_resumable`` returns this value directly when it reconnects
to an
+ active message, so polling returns the result instead of ``None``.
+ """
+ ref: GenieMessageRef = external_id
+ deadline = time.monotonic() + self.timeout
+ message = self._get_message(ref, deadline)
+ if not self._check_message(message, ref) and self.deferrable:
+ self.log.info("Deferring until Genie message %s completes",
ref["message_id"])
+ self.defer(
+ trigger=DatabricksGenieMessageTrigger(
+ space_id=ref["space_id"],
+ conversation_id=ref["conversation_id"],
+ message_id=ref["message_id"],
+ databricks_conn_id=self.databricks_conn_id,
+ polling_period_seconds=self.polling_period_seconds,
+ retry_limit=self.databricks_retry_limit,
+ retry_delay=self.databricks_retry_delay,
+ ),
+ method_name="execute_complete",
+ timeout=timedelta(seconds=self.timeout),
+ kwargs={"ref": ref},
+ )
+ while not self._check_message(message, ref):
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ raise DatabricksGenieError(
+ f"Timed out after {self.timeout} seconds waiting for Genie
message "
+ f"{ref['message_id']}. {self._describe_next_try(context)}"
+ )
+ time.sleep(min(self.polling_period_seconds, remaining))
+ message = self._get_message(ref, deadline)
+ return self._summarize(message, ref, deadline)
+
+ def _summarize(self, message: dict[str, Any], ref: GenieMessageRef,
deadline: float) -> dict[str, Any]:
+ result = self.hook._summarize_result(
+ ref["space_id"],
+ quote(ref["space_id"], safe=""),
+ ref["conversation_id"],
+ ref["message_id"],
+ message,
+ deadline,
+ )
+ self._result = _truncate_result(result)
+ return self._result
+
+ def get_job_result(self, external_id: Any, context: Context) -> dict[str,
Any]:
+ ref: GenieMessageRef = external_id
+ if self._result is not None and self._result.get("message_id") ==
ref["message_id"]:
+ return self._result
+ deadline = time.monotonic() + self.timeout
+ message = self._get_message(ref, deadline)
+ if not self._check_message(message, ref):
+ raise DatabricksGenieError(f"Genie message {ref['message_id']} has
not completed yet.")
+ return self._summarize(message, ref, deadline)
+
+ def execute_complete(
+ self, context: Context, event: dict[str, Any] | None = None, *, ref:
GenieMessageRef
+ ) -> dict[str, Any]:
+ if (
+ not event
+ or event.get("conversation_id") != ref["conversation_id"]
+ or event.get("message_id") != ref["message_id"]
+ or event.get("status") not in ("success", "error")
+ ):
+ raise DatabricksGenieError(f"Genie message {ref['message_id']}
trigger returned an invalid event")
+ if event["status"] == "error":
+ status_code = event.get("status_code")
+ raise DatabricksGenieError(
+ f"Polling Genie message {ref['message_id']} failed
({event.get('error_type')}); "
+ f"inspect the triggerer logs.
{self._describe_next_try(context)}",
+ http_status_code=status_code if isinstance(status_code, int)
else None,
+ )
+ return self.get_job_result(ref, context)
diff --git
a/providers/databricks/src/airflow/providers/databricks/triggers/genie.py
b/providers/databricks/src/airflow/providers/databricks/triggers/genie.py
new file mode 100644
index 00000000000..4a5e6e3f8dd
--- /dev/null
+++ b/providers/databricks/src/airflow/providers/databricks/triggers/genie.py
@@ -0,0 +1,132 @@
+# 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.
+"""Triggers for Databricks Genie conversations."""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import AsyncIterator
+from typing import Any
+from urllib.parse import quote, urlsplit
+
+from airflow.providers.databricks.exceptions import DatabricksApiError
+from airflow.providers.databricks.hooks.genie import (
+ _PENDING_STATUSES,
+ GENIE_TERMINAL_STATUSES,
+ DatabricksGenieHook,
+)
+from airflow.triggers.base import BaseTrigger, TriggerEvent
+
+
+class DatabricksGenieMessageTrigger(BaseTrigger):
+ """
+ Wait for a Genie message to reach a terminal status.
+
+ 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 or
credentials.
+
+ :param space_id: Genie space ID.
+ :param conversation_id: Genie conversation ID.
+ :param message_id: Genie message ID to poll.
+ :param databricks_conn_id: Databricks connection. Defaults to
``databricks_default``.
+ :param polling_period_seconds: Seconds between status checks. Defaults to
``5``.
+ :param retry_limit: Attempts for each status read. Defaults to ``3``.
+ :param retry_delay: Minimum seconds between read attempts. Defaults to
``1``.
+ """
+
+ def __init__(
+ self,
+ *,
+ space_id: str,
+ conversation_id: str,
+ message_id: str,
+ databricks_conn_id: str = "databricks_default",
+ polling_period_seconds: float = 5,
+ retry_limit: int = 3,
+ retry_delay: float = 1,
+ ) -> None:
+ super().__init__()
+ if polling_period_seconds <= 0:
+ raise ValueError("polling_period_seconds must be positive")
+ self.space_id = space_id
+ self.conversation_id = conversation_id
+ self.message_id = message_id
+ self.databricks_conn_id = databricks_conn_id
+ self.polling_period_seconds = polling_period_seconds
+ self.retry_limit = retry_limit
+ self.retry_delay = retry_delay
+
+ def serialize(self) -> tuple[str, dict[str, Any]]:
+ return (
+
"airflow.providers.databricks.triggers.genie.DatabricksGenieMessageTrigger",
+ {
+ "space_id": self.space_id,
+ "conversation_id": self.conversation_id,
+ "message_id": self.message_id,
+ "databricks_conn_id": self.databricks_conn_id,
+ "polling_period_seconds": self.polling_period_seconds,
+ "retry_limit": self.retry_limit,
+ "retry_delay": self.retry_delay,
+ },
+ )
+
+ def _build_event(self, **fields: Any) -> TriggerEvent:
+ return TriggerEvent(
+ {"conversation_id": self.conversation_id, "message_id":
self.message_id, **fields}
+ )
+
+ async def run(self) -> AsyncIterator[TriggerEvent]:
+ endpoint = (
+ f"2.0/genie/spaces/{quote(self.space_id, safe='')}/conversations/"
+ f"{quote(self.conversation_id,
safe='')}/messages/{quote(self.message_id, safe='')}"
+ )
+ try:
+ async with DatabricksGenieHook(
+ databricks_conn_id=self.databricks_conn_id,
+ retry_limit=self.retry_limit,
+ retry_delay=self.retry_delay,
+ caller="DatabricksGenieMessageTrigger",
+ ) as hook:
+ await hook._a_cache_databricks_conn()
+ url = urlsplit(hook._endpoint_url(f"api/{endpoint}"))
+ if url.scheme != "https" and url.hostname not in {"localhost",
"127.0.0.1", "::1"}:
+ self.log.error("Databricks Genie requires HTTPS; refusing
to poll %s", url.hostname)
+ yield self._build_event(status="error",
error_type="insecure_connection")
+ return
+ while True:
+ message = await hook._a_do_api_call(("GET", endpoint))
+ status = message.get("status") if isinstance(message,
dict) else None
+ if status in GENIE_TERMINAL_STATUSES:
+ yield self._build_event(status="success",
message_status=status)
+ return
+ if status not in _PENDING_STATUSES:
+ self.log.error("Genie returned an unknown message
status: %r", status)
+ yield self._build_event(status="error",
error_type="invalid_response")
+ return
+ self.log.info(
+ "Genie message %s is %s; checking again in %s seconds",
+ self.message_id,
+ status,
+ self.polling_period_seconds,
+ )
+ await asyncio.sleep(self.polling_period_seconds)
+ except DatabricksApiError as err:
+ self.log.exception("Polling Genie message %s failed",
self.message_id)
+ yield self._build_event(status="error", error_type="api_error",
status_code=err.http_status_code)
+ except Exception:
+ self.log.exception("Polling Genie message %s failed",
self.message_id)
+ yield self._build_event(status="error",
error_type="unexpected_error")
diff --git
a/providers/databricks/tests/system/databricks/example_databricks_genie.py
b/providers/databricks/tests/system/databricks/example_databricks_genie.py
new file mode 100644
index 00000000000..7c5f847f25d
--- /dev/null
+++ b/providers/databricks/tests/system/databricks/example_databricks_genie.py
@@ -0,0 +1,132 @@
+# 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.
+"""
+Ask a Databricks Genie space a question as a standalone, resumable task.
+
+Configure DATABRICKS_GENIE_SPACE_ID and the databricks_default connection
before running this system test.
+"""
+
+from __future__ import annotations
+
+import os
+from datetime import datetime
+
+from airflow.providers.common.compat.sdk import DAG, task
+from airflow.providers.databricks.operators.genie import
DatabricksGenieOperator
+
+DAG_ID = "example_databricks_genie"
+SPACE_ID = os.environ.get("DATABRICKS_GENIE_SPACE_ID", "your-genie-space-id")
+CONN_ID = os.environ.get("DATABRICKS_GENIE_CONN_ID", "databricks_default")
+QUESTION = "How many orders were placed last week?"
+
+
+@task
+def verify_result(result: dict) -> None:
+ """Verify that Genie answered and returned its identifiers."""
+ assert result["status"] == "COMPLETED"
+ assert result["space_id"] == SPACE_ID
+ assert result["conversation_id"]
+ assert result["message_id"]
+
+
+@task
+def consult_genie() -> dict:
+ """Ask Genie directly through the hook, without an operator."""
+ # [START howto_hook_databricks_genie_consult]
+ from airflow.providers.databricks.hooks.genie import DatabricksGenieHook
+
+ hook = DatabricksGenieHook(databricks_conn_id=CONN_ID)
+ result = hook.consult(SPACE_ID, QUESTION)
+ # [END howto_hook_databricks_genie_consult]
+ return result
+
+
+@task
+def ask_genie_tool() -> dict:
+ """Ask Genie through the Common AI managed-agent toolset."""
+ import json
+
+ # [START howto_hook_databricks_genie_toolset]
+ from airflow.providers.common.ai.toolsets import ManagedAgentToolset
+ from airflow.providers.databricks.hooks.genie import DatabricksGenieHook
+
+ hook = DatabricksGenieHook(databricks_conn_id=CONN_ID)
+ toolset = ManagedAgentToolset(
+ hook.agent(SPACE_ID),
+ tool_name="ask_analytics_genie",
+ description="Answers questions about the analytics tables in this
Genie space.",
+ max_retries=0,
+ )
+ # [END howto_hook_databricks_genie_toolset]
+ return json.loads(toolset.invoke_sync(QUESTION))
+
+
+with DAG(
+ dag_id=DAG_ID,
+ schedule="@once",
+ start_date=datetime(2021, 1, 1),
+ tags=["example"],
+ catchup=False,
+ params={"genie_conversation_id": "", "genie_message_id": ""},
+) as dag:
+ # [START howto_operator_databricks_genie]
+ ask = DatabricksGenieOperator(
+ task_id="ask_genie",
+ space_id=SPACE_ID,
+ question=QUESTION,
+ databricks_conn_id=CONN_ID,
+ timeout=600,
+ )
+ # [END howto_operator_databricks_genie]
+
+ # [START howto_operator_databricks_genie_deferrable]
+ follow_up = DatabricksGenieOperator(
+ task_id="ask_genie_follow_up",
+ space_id=SPACE_ID,
+ question="Break that down by region.",
+ conversation_id="{{
ti.xcom_pull(task_ids='ask_genie')['conversation_id'] }}",
+ databricks_conn_id=CONN_ID,
+ deferrable=True,
+ timeout=600,
+ )
+ # [END howto_operator_databricks_genie_deferrable]
+
+ # [START howto_operator_databricks_genie_attach]
+ attach = DatabricksGenieOperator(
+ task_id="attach_genie",
+ space_id=SPACE_ID,
+ question=QUESTION,
+ # Set both params when triggering or clearing one run to wait for an
existing message.
+ conversation_id="{{ params.genie_conversation_id }}",
+ message_id="{{ params.genie_message_id }}",
+ databricks_conn_id=CONN_ID,
+ )
+ # [END howto_operator_databricks_genie_attach]
+
+ ask >> verify_result.override(task_id="verify_ask")(ask.output) >>
follow_up
+ follow_up >>
verify_result.override(task_id="verify_follow_up")(follow_up.output)
+ verify_result.override(task_id="verify_attach")(attach.output)
+ verify_result.override(task_id="verify_consult")(consult_genie())
+ verify_result.override(task_id="verify_tool")(ask_genie_tool())
+
+ from tests_common.test_utils.watcher import watcher
+
+ list(dag.tasks) >> watcher()
+
+from tests_common.test_utils.system_tests import get_test_run # noqa: E402
+
+test_run = get_test_run(dag)
diff --git a/providers/databricks/tests/unit/databricks/hooks/test_genie.py
b/providers/databricks/tests/unit/databricks/hooks/test_genie.py
new file mode 100644
index 00000000000..9fd16ca9dda
--- /dev/null
+++ b/providers/databricks/tests/unit/databricks/hooks/test_genie.py
@@ -0,0 +1,384 @@
+# 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 io
+import json
+from types import SimpleNamespace
+from unittest import mock
+
+import pytest
+import requests
+
+from airflow.providers.common.ai.managed_agents.base import ManagedAgentRequest
+from airflow.providers.common.ai.toolsets import ManagedAgentToolset
+from airflow.providers.common.compat.sdk import AirflowException,
AirflowOptionalProviderFeatureException
+from airflow.providers.databricks.exceptions import DatabricksApiError,
DatabricksGenieError
+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 (
+ DatabricksGenieHook,
+ _summarize_query_result,
+ _truncate_result,
+)
+
+REQUEST = "airflow.providers.databricks.hooks.genie.requests.request"
+GENIE_URL = "https://workspace/api/2.0/genie/message"
+
+
+def build_response(
+ status_code: int = 200, content: bytes = b'{"status":"COMPLETED"}', url:
str = GENIE_URL
+) -> requests.Response:
+ response = requests.Response()
+ response.status_code = status_code
+ response.raw = io.BytesIO(content)
+ response.url = url
+ return response
+
+
+MESSAGE_PATH = "spaces/space-1/conversations/conversation-1/messages/message-1"
+CREATED = {"conversation_id": "conversation-1", "message_id": "message-1"}
+ANSWERED = {"status": "COMPLETED", "attachments": [{"text": {"content":
"Answer."}}]}
+
+
[email protected]
+def hook():
+ with mock.patch.object(
+ DatabricksGenieHook, "user_agent_header",
new_callable=mock.PropertyMock, return_value={}
+ ):
+ yield DatabricksGenieHook(retry_limit=2, retry_delay=0.001,
poll_interval=0.001)
+
+
[email protected]
+def genie_request():
+ """Replace the hook's HTTP call, so consult tests only script Genie's
answers."""
+ with mock.patch.object(DatabricksGenieHook, "_request", autospec=True) as
request:
+ yield request
+
+
[email protected]
+def connection():
+ """Spec'd stand-ins for the connection lookups, so ``_request`` runs
without a real connection."""
+ with (
+ mock.patch.object(DatabricksGenieHook, "_endpoint_url", autospec=True,
return_value=GENIE_URL) as url,
+ mock.patch.object(DatabricksGenieHook, "_get_aad_headers",
autospec=True, return_value={}),
+ mock.patch.object(
+ DatabricksGenieHook, "_get_token", autospec=True,
return_value="secret-token"
+ ) as token,
+ mock.patch.object(DatabricksGenieHook, "_get_requests_kwargs",
autospec=True, return_value={}),
+ ):
+ yield SimpleNamespace(endpoint_url=url, get_token=token)
+
+
+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()
+ with mock.patch.object(
+ module.DatabricksGenieHook, "_request", autospec=True,
side_effect=[CREATED, ANSWERED]
+ ) as request:
+ result = hook.consult("space-1", "Question?")
+ assert result["answer"] == "Answer."
+ assert result["conversation_id"] == "conversation-1"
+ assert 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,
genie_request):
+ genie_request.side_effect = [CREATED, ANSWERED]
+ 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 genie_request.call_count == 2
+
+ def test_invoke_agent_refuses_vendor_options(self, hook, genie_request):
+ request = ManagedAgentRequest(prompt="Question?",
vendor_options={"space_id": "other-space"})
+
+ with pytest.raises(ValueError, match=r"does not support
vendor_options: \['space_id'\]"):
+ hook.invoke_agent("space-1", request)
+ genie_request.assert_not_called()
+
+ def
test_consult_starts_once_polls_reads_and_returns_ids_and_query_result(self,
hook, genie_request):
+ genie_request.side_effect = [
+ CREATED,
+ {"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}
+ ],
+ }
+ calls = genie_request.call_args_list
+ assert len(calls) == 4
+ assert calls[0].args[1:] == ("POST",
"spaces/space-1/start-conversation")
+ assert calls[0].kwargs["retry_read"] is False
+ assert all(call.kwargs.get("retry_read") is True for call in calls[1:])
+
+ def test_resumed_consult_posts_into_existing_conversation_once(self, hook,
genie_request):
+ genie_request.side_effect = [{**CREATED, "message_id": "message-2"},
ANSWERED]
+
+ hook.consult("space-1", "Another question",
conversation_id="conversation-1")
+
+ calls = genie_request.call_args_list
+ assert calls[0].args[1:] == ("POST",
"spaces/space-1/conversations/conversation-1/messages")
+ assert calls[0].kwargs["retry_read"] is False
+ assert len(calls) == 2
+
+ @pytest.mark.parametrize(
+ ("message", "match"),
+ [
+ pytest.param(
+ {"status": "FAILED", "error": {"error": "bad SQL"}},
+ "could not answer the question: bad SQL",
+ id="failed",
+ ),
+ pytest.param({"status": "CANCELLED"}, "ended with status
CANCELLED", id="cancelled"),
+ pytest.param(
+ {"status": "QUERY_RESULT_EXPIRED"}, "ended with status
QUERY_RESULT_EXPIRED", id="expired"
+ ),
+ pytest.param(
+ {"status": "SOMETHING_NEW"}, "unknown message status:
'SOMETHING_NEW'", id="unknown"
+ ),
+ ],
+ )
+ def test_consult_raises_for_terminal_status(self, hook, genie_request,
message, match):
+ genie_request.side_effect = [CREATED, message]
+
+ with pytest.raises(DatabricksGenieError, match=match) as error:
+ hook.consult("space-1", "Question?")
+
+ assert isinstance(error.value, DatabricksApiError)
+ assert error.value.http_status_code is None
+ assert genie_request.call_args_list[1].args[1:] == ("GET",
MESSAGE_PATH)
+
+ def test_consult_times_out(self, hook, genie_request):
+ genie_request.side_effect = [CREATED, {"status": "ASKING_AI"}]
+
+ with (
+ mock.patch.object(genie_module.time, "monotonic", autospec=True,
side_effect=[0, 11]),
+ mock.patch.object(genie_module.time, "sleep", autospec=True) as
sleep,
+ pytest.raises(DatabricksGenieError, match="Timed out waiting for
Genie message message-1"),
+ ):
+ hook.consult("space-1", "Question?", timeout=10)
+
+ sleep.assert_not_called()
+ assert [call.args[1] for call in genie_request.call_args_list] ==
["POST", "GET"]
+
+ def test_non_idempotent_post_is_never_retried_after_timeout(self, hook,
connection):
+ with (
+ mock.patch(REQUEST, autospec=True,
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, hook,
connection):
+ """_TokenAuth keeps requests from applying ~/.netrc over the bearer
token."""
+ with mock.patch(REQUEST, autospec=True, return_value=build_response())
as request:
+ assert hook._request("GET", "message", retry_read=True) ==
{"status": "COMPLETED"}
+
+ auth = request.call_args.kwargs["auth"]
+ assert isinstance(auth, _TokenAuth)
+ assert auth.token == "secret-token"
+ assert "Authorization" not in request.call_args.kwargs["headers"]
+
+ def test_get_read_is_retried_after_a_server_error(self, hook, connection):
+ responses = [build_response(503, b'{"error":"temporarily
unavailable"}'), build_response()]
+ with mock.patch(REQUEST, autospec=True, side_effect=responses) as
request:
+ result = hook._request("GET", "message", retry_read=True)
+
+ assert result == {"status": "COMPLETED"}
+ assert request.call_count == 2
+
+ @pytest.mark.parametrize(
+ "response",
+ [
+ pytest.param(build_response(503, b'{"error":"temporarily
unavailable"}'), id="server-error"),
+ pytest.param(build_response(200, b"not json"), id="invalid-json"),
+ ],
+ )
+ def test_ambiguous_post_is_never_retried(self, hook, connection, response):
+ with (
+ mock.patch(REQUEST, autospec=True, return_value=response) as
request,
+ pytest.raises(DatabricksGenieError, match="outcome is unknown") as
error,
+ ):
+ hook._request("POST", "message", body={"content": "question"},
retry_read=False)
+
+ assert request.call_count == 1
+ assert "secret-token" not in str(error.value)
+
+ def test_rejected_request_carries_http_status_code(self, hook, connection):
+ with (
+ mock.patch(REQUEST, autospec=True,
return_value=build_response(404, b"{}")),
+ pytest.raises(DatabricksApiError, match="not found") as error,
+ ):
+ hook._request("GET", "message", retry_read=True)
+
+ assert isinstance(error.value, DatabricksGenieError)
+ assert error.value.http_status_code == 404
+
+ def
test_remote_http_endpoint_is_rejected_before_credentials_are_sent(self, hook,
connection):
+ connection.endpoint_url.return_value =
"http://workspace.example/api/2.0/genie/message"
+ with (
+ mock.patch(REQUEST, autospec=True) as request,
+ pytest.raises(DatabricksGenieError, match="requires HTTPS"),
+ ):
+ hook._request("GET", "message", retry_read=True)
+ request.assert_not_called()
+ connection.get_token.assert_not_called()
+
+ def test_credential_failure_is_raised_before_anything_is_sent(self, hook,
connection):
+ connection.get_token.side_effect = AirflowException("token endpoint
unavailable")
+ with (
+ mock.patch(REQUEST, autospec=True) as request,
+ pytest.raises(AirflowException, match="token endpoint
unavailable"),
+ ):
+ hook._prepare_request("spaces/id/start-conversation")
+ request.assert_not_called()
+
+ def
test_prepared_request_is_sent_without_resolving_credentials_again(self, hook,
connection):
+ prepared = hook._prepare_request("spaces/id/start-conversation")
+ connection.get_token.reset_mock()
+ connection.endpoint_url.reset_mock()
+
+ with mock.patch(REQUEST, autospec=True, return_value=build_response())
as request:
+ hook._request(
+ "POST",
+ "spaces/id/start-conversation",
+ body={"content": "question"},
+ retry_read=False,
+ prepared=prepared,
+ )
+
+ connection.get_token.assert_not_called()
+ connection.endpoint_url.assert_not_called()
+ assert request.call_args.args == ("POST", GENIE_URL)
+ assert request.call_args.kwargs["auth"] is prepared.auth
+
+ @pytest.mark.parametrize(
+ ("status", "message"),
+ [
+ (401, "authentication failed"),
+ (403, "may also return 403"),
+ (404, "not found"),
+ (429, "rate-limited"),
+ ],
+ )
+ def test_clear_errors_for_common_status_codes(self, status, message):
+ assert message in str(DatabricksGenieHook._http_error(status)).lower()
+
+ def test_large_result_keeps_ids_and_valid_bounded_answer(self):
+ result = _truncate_result(
+ {
+ "space_id": "space",
+ "conversation_id": "conversation",
+ "message_id": "message",
+ "status": "COMPLETED",
+ "answer": "x" * 100_000,
+ "query_results": [{"rows": [["x"] * 20]}],
+ }
+ )
+ encoded = json.dumps(result, ensure_ascii=False, separators=(",",
":")).encode()
+ assert len(encoded) <= 48 * 1024
+ assert result["space_id"] == "space"
+ assert result["conversation_id"] == "conversation"
+ assert result["message_id"] == "message"
+ assert result["truncated"] is True
diff --git a/providers/databricks/tests/unit/databricks/operators/test_genie.py
b/providers/databricks/tests/unit/databricks/operators/test_genie.py
new file mode 100644
index 00000000000..a159a46f7af
--- /dev/null
+++ b/providers/databricks/tests/unit/databricks/operators/test_genie.py
@@ -0,0 +1,688 @@
+# 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 AirflowException,
AirflowFailException, TaskDeferred
+from airflow.providers.databricks.exceptions import DatabricksGenieError
+from airflow.providers.databricks.hooks.genie import 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"
+PREPARED = mock.sentinel.prepared
+
+durable_only = pytest.mark.skipif(
+ not AIRFLOW_V_3_3_PLUS, reason="task_state_store (durable execution)
requires Airflow 3.3+"
+)
+
+
+def build_message(status: str, **fields) -> dict:
+ return {"conversation_id": CONVERSATION_ID, "message_id": MESSAGE_ID,
"status": status, **fields}
+
+
+COMPLETED = build_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 = []
+ self.prepare_errors: list[BaseException] = []
+
+ def add(self, method: str, endpoint: str, *responses) -> None:
+ self.responses.setdefault((method, endpoint), []).extend(responses)
+
+ def prepare(self, hook, endpoint):
+ self.journal.append(("prepare", endpoint))
+ if self.prepare_errors:
+ raise self.prepare_errors.pop(0)
+ return PREPARED
+
+ def __call__(self, hook, method, endpoint, *, body=None, retry_read,
deadline=None, prepared=None):
+ self.journal.append((method, endpoint))
+ if method == "POST":
+ assert retry_read is False
+ assert prepared is PREPARED
+ 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),
+ mock.patch.object(DatabricksGenieHook, "_prepare_request",
autospec=True, side_effect=fake.prepare),
+ ):
+ 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 build_stored_ref(**overrides) -> dict:
+ ref = {
+ "space_id": SPACE_ID,
+ "conversation_id": CONVERSATION_ID,
+ "message_id": MESSAGE_ID,
+ "fingerprint": make_operator()._compute_fingerprint(),
+ }
+ ref.update(overrides)
+ return ref
+
+
+def stub_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, *[build_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_templated_conversation_id_selects_follow_up_endpoint(genie):
+ stub_answered(genie, post=FOLLOW_UP)
+ op = make_operator(conversation_id="{{ params.conversation }}")
+
+ op.render_template_fields(context={"params": {"conversation":
CONVERSATION_ID}})
+
+ assert op.conversation_id == CONVERSATION_ID
+ assert op.execute({}) == EXPECTED_RESULT
+ assert genie.calls("POST") == [("POST", FOLLOW_UP)]
+
+
+def test_hook_configuration():
+ op = make_operator(databricks_conn_id="genie", databricks_retry_limit=5,
databricks_retry_delay=2)
+ assert op.hook.databricks_conn_id == "genie"
+ assert op.hook.retry_limit == 5
+ assert op.hook.retry_delay == 2
+ assert op.hook.poll_interval == 2
+
+
+def test_asks_new_conversation_and_waits(genie, sleep):
+ stub_answered(genie, "SUBMITTED", "EXECUTING_QUERY")
+
+ assert make_operator(durable=False).execute({}) == EXPECTED_RESULT
+
+ assert genie.calls("POST") == [("POST", START)]
+ assert genie.bodies == [{"content": QUESTION, "enable_visualization":
False}]
+ assert genie.calls("GET").count(("GET", MESSAGE)) == 3
+ assert sleep.call_count == 2
+
+
[email protected]("empty", ["", None])
+def test_empty_optional_ids_start_new_conversation(genie, empty):
+ stub_answered(genie)
+ make_operator(conversation_id=empty, message_id=empty,
durable=False).execute({})
+ assert genie.calls("POST") == [("POST", START)]
+
+
+def test_asks_follow_up_in_existing_conversation(genie):
+ stub_answered(genie, post=FOLLOW_UP)
+ assert make_operator(conversation_id=CONVERSATION_ID,
durable=False).execute({}) == EXPECTED_RESULT
+ assert genie.calls("POST") == [("POST", FOLLOW_UP)]
+
+
+def test_accepts_message_id_under_id_key(genie):
+ genie.add("POST", START, {"conversation_id": CONVERSATION_ID, "id":
MESSAGE_ID})
+ genie.add("GET", MESSAGE, COMPLETED)
+ genie.add("GET", ATTACHMENT_RESULT, QUERY_RESULT)
+ assert make_operator(durable=False).execute({})["message_id"] == MESSAGE_ID
+
+
[email protected](
+ ("status", "match"),
+ [
+ ("FAILED", "could not answer message message-1: no warehouse"),
+ ("CANCELLED", "ended with status CANCELLED"),
+ ("QUERY_RESULT_EXPIRED", "ended with status QUERY_RESULT_EXPIRED"),
+ ("SOMETHING_NEW", "unknown message status: 'SOMETHING_NEW'"),
+ ],
+)
+def test_remote_terminal_failure(genie, status, match):
+ genie.add("POST", START, {"conversation_id": CONVERSATION_ID,
"message_id": MESSAGE_ID})
+ genie.add("GET", MESSAGE, build_message(status, error={"error": "no
warehouse"}))
+ with pytest.raises(DatabricksGenieError, match=match):
+ make_operator(durable=False).execute({})
+
+
+def test_failed_message_without_detail(genie):
+ genie.add("POST", START, {"conversation_id": CONVERSATION_ID,
"message_id": MESSAGE_ID})
+ genie.add("GET", MESSAGE, build_message("FAILED", error="boom"))
+ with pytest.raises(DatabricksGenieError, match="could not answer message
message-1: boom"):
+ make_operator(durable=False).execute({})
+
+
+def test_synchronous_timeout(genie, sleep):
+ genie.add("POST", START, {"conversation_id": CONVERSATION_ID,
"message_id": MESSAGE_ID})
+ genie.add("GET", MESSAGE, build_message("ASKING_AI"))
+ with (
+ mock.patch(
+ "airflow.providers.databricks.operators.genie.time.monotonic",
+ autospec=True,
+ side_effect=[0, 5, 11],
+ ),
+ pytest.raises(DatabricksGenieError, match="Timed out after 10 seconds
.* asks the question again"),
+ ):
+ make_operator(durable=False, timeout=10).execute({})
+ sleep.assert_called_once_with(2)
+
+
+def test_result_is_bounded(genie):
+ genie.add("POST", START, {"conversation_id": CONVERSATION_ID,
"message_id": MESSAGE_ID})
+ genie.add("GET", MESSAGE, build_message("COMPLETED", attachments=[{"text":
{"content": "x" * 200_000}}]))
+
+ result = make_operator(durable=False).execute({})
+
+ assert result["truncated"] is True
+ assert result["message_id"] == MESSAGE_ID
+ assert len(json.dumps(result, separators=(",", ":")).encode()) <= 48 * 1024
+
+
+def test_defers_with_ids_only(genie):
+ genie.add("POST", START, {"conversation_id": CONVERSATION_ID,
"message_id": MESSAGE_ID})
+ genie.add("GET", MESSAGE, build_message("SUBMITTED"))
+ op = make_operator(durable=False, deferrable=True,
databricks_conn_id="genie", timeout=60)
+
+ with pytest.raises(TaskDeferred) as deferred:
+ op.execute({})
+
+ trigger = deferred.value.trigger
+ assert isinstance(trigger, DatabricksGenieMessageTrigger)
+ assert trigger.serialize()[1] == {
+ "space_id": SPACE_ID,
+ "conversation_id": CONVERSATION_ID,
+ "message_id": MESSAGE_ID,
+ "databricks_conn_id": "genie",
+ "polling_period_seconds": 2,
+ "retry_limit": 3,
+ "retry_delay": 1,
+ }
+ assert deferred.value.method_name == "execute_complete"
+ assert deferred.value.timeout.total_seconds() == 60
+ assert deferred.value.kwargs == {"ref": build_stored_ref()}
+
+
+def test_deferrable_does_not_defer_completed_message(genie):
+ stub_answered(genie)
+ assert make_operator(durable=False, deferrable=True).execute({}) ==
EXPECTED_RESULT
+
+
+def test_execute_complete_fetches_result_on_worker(genie):
+ genie.add("GET", MESSAGE, COMPLETED)
+ genie.add("GET", ATTACHMENT_RESULT, QUERY_RESULT)
+ event = {"status": "success", "conversation_id": CONVERSATION_ID,
"message_id": MESSAGE_ID}
+
+ assert make_operator().execute_complete({}, event, ref=build_stored_ref())
== EXPECTED_RESULT
+
+
+def test_execute_complete_raises_for_failed_message(genie):
+ genie.add("GET", MESSAGE, build_message("CANCELLED"))
+ event = {"status": "success", "conversation_id": CONVERSATION_ID,
"message_id": MESSAGE_ID}
+ with pytest.raises(DatabricksGenieError, match="ended with status
CANCELLED"):
+ make_operator().execute_complete({}, event, ref=build_stored_ref())
+
+
+def test_execute_complete_rejects_pending_message(genie):
+ genie.add("GET", MESSAGE, build_message("ASKING_AI"))
+ event = {"status": "success", "conversation_id": CONVERSATION_ID,
"message_id": MESSAGE_ID}
+ with pytest.raises(DatabricksGenieError, match="has not completed yet"):
+ make_operator().execute_complete({}, event, ref=build_stored_ref())
+
+
[email protected](("status_code", "expected"), [(503, 503), ("503",
None), (None, None)])
+def test_execute_complete_error_event(genie, status_code, expected):
+ event = {
+ "status": "error",
+ "conversation_id": CONVERSATION_ID,
+ "message_id": MESSAGE_ID,
+ "error_type": "api_error",
+ "status_code": status_code,
+ }
+ with pytest.raises(DatabricksGenieError, match=r"failed
\(api_error\).*asks the question again") as err:
+ make_operator().execute_complete({}, event, ref=build_stored_ref())
+ assert err.value.http_status_code == expected
+ assert genie.journal == []
+
+
[email protected](
+ "event",
+ [
+ None,
+ {},
+ {"status": "unknown", "conversation_id": CONVERSATION_ID,
"message_id": MESSAGE_ID},
+ {"status": "success", "conversation_id": "other", "message_id":
MESSAGE_ID},
+ {"status": "success", "conversation_id": CONVERSATION_ID,
"message_id": "other"},
+ ],
+)
+def test_execute_complete_invalid_event(genie, event):
+ with pytest.raises(DatabricksGenieError, match="invalid event"):
+ make_operator().execute_complete({}, event, ref=build_stored_ref())
+
+
[email protected]("status_code", [None, 500, 503])
+def test_unconfirmed_submission_fails_without_retry(genie, status_code):
+ genie.add("POST", START, DatabricksGenieError("unknown outcome",
http_status_code=status_code))
+ with pytest.raises(
+ AirflowFailException, match="unknown outcome.*a default clear discards
the task state"
+ ):
+ make_operator(durable=False).execute({})
+
+
+def test_accepted_submission_without_ids_fails_without_retry(genie):
+ genie.add("POST", START, {"conversation_id": CONVERSATION_ID})
+ with pytest.raises(AirflowFailException, match="returned no conversation
or message ID"):
+ make_operator(durable=False).execute({})
+
+
[email protected]("status_code", [400, 401, 403, 404, 429])
+def test_rejected_submission_is_retryable(genie, status_code):
+ genie.add("POST", START, DatabricksGenieError("rejected",
http_status_code=status_code))
+ with pytest.raises(DatabricksGenieError, match="rejected") as err:
+ make_operator(durable=False).execute({})
+ assert not isinstance(err.value, AirflowFailException)
+
+
+def test_template_fields_include_attach_ids():
+ assert {"conversation_id", "message_id"} <=
set(DatabricksGenieOperator.template_fields)
+
+
+ATTACH_TEMPLATES = {
+ "conversation_id": "{{ params.genie_conversation_id }}",
+ "message_id": "{{ params.genie_message_id }}",
+}
+
+
+def test_run_scoped_params_attach_to_existing_message(genie):
+ genie.add("GET", MESSAGE, COMPLETED)
+ genie.add("GET", ATTACHMENT_RESULT, QUERY_RESULT)
+ op = make_operator(**ATTACH_TEMPLATES)
+
+ op.render_template_fields(
+ context={"params": {"genie_conversation_id": CONVERSATION_ID,
"genie_message_id": MESSAGE_ID}}
+ )
+
+ assert op.execute({}) == EXPECTED_RESULT
+ assert genie.calls("POST") == []
+
+
+def test_empty_run_scoped_params_ask_the_question(genie):
+ stub_answered(genie)
+ op = make_operator(**ATTACH_TEMPLATES)
+
+ op.render_template_fields(context={"params": {"genie_conversation_id": "",
"genie_message_id": ""}})
+
+ assert op.execute({}) == EXPECTED_RESULT
+ assert genie.calls("POST") == [("POST", START)]
+
+
+def test_attach_to_existing_message_without_store(genie):
+ genie.add("GET", MESSAGE, COMPLETED)
+ genie.add("GET", ATTACHMENT_RESULT, QUERY_RESULT)
+ op = make_operator(question=None, conversation_id=CONVERSATION_ID,
message_id=MESSAGE_ID)
+ assert op.execute({}) == EXPECTED_RESULT
+ assert genie.calls("POST") == []
+
+
+@durable_only
+class TestDurable:
+ @staticmethod
+ def run(op, store) -> dict:
+ return op.execute({"ti": mock.Mock(spec=["stats_tags"],
stats_tags={}), "task_state_store": store})
+
+ def test_persists_ids_before_waiting(self, genie, journal):
+ stub_answered(genie, "SUBMITTED")
+ store = FakeStore(journal)
+
+ assert self.run(make_operator(), store) == EXPECTED_RESULT
+
+ first_get = journal.index(("GET", MESSAGE))
+ assert journal[:first_get] == [
+ ("prepare", START),
+ ("set", SUBMISSION_KEY),
+ ("POST", START),
+ ("set", KEY),
+ ("delete", SUBMISSION_KEY),
+ ("set", KEY),
+ ]
+ assert store.data == {KEY: build_stored_ref()}
+
+ def test_deferrable_persists_ids_before_deferring(self, genie, journal):
+ genie.add("POST", START, {"conversation_id": CONVERSATION_ID,
"message_id": MESSAGE_ID})
+ genie.add("GET", MESSAGE, build_message("SUBMITTED"))
+ store = FakeStore(journal)
+
+ with pytest.raises(TaskDeferred):
+ self.run(make_operator(deferrable=True), store)
+
+ assert store.data == {KEY: build_stored_ref()}
+
+ @pytest.mark.parametrize("status", ["SUBMITTED", "ASKING_AI",
"EXECUTING_QUERY"])
+ def test_reconnects_to_running_message(self, genie, journal, sleep,
status):
+ genie.add("GET", MESSAGE, build_message(status),
build_message(status), COMPLETED)
+ genie.add("GET", ATTACHMENT_RESULT, QUERY_RESULT)
+ store = FakeStore(journal, {KEY: build_stored_ref()})
+
+ assert self.run(make_operator(), store) == EXPECTED_RESULT
+
+ assert genie.calls("POST") == []
+ assert [entry for entry in journal if entry[0] in ("set", "delete")]
== []
+
+ def test_reconnect_defers_again(self, genie, journal):
+ genie.add("GET", MESSAGE, build_message("ASKING_AI"))
+ store = FakeStore(journal, {KEY: build_stored_ref()})
+
+ with pytest.raises(TaskDeferred) as deferred:
+ self.run(make_operator(deferrable=True), store)
+
+ assert deferred.value.kwargs == {"ref": build_stored_ref()}
+ assert genie.calls("POST") == []
+
+ def test_completed_message_returns_answer_without_asking(self, genie,
journal):
+ genie.add("GET", MESSAGE, COMPLETED)
+ genie.add("GET", ATTACHMENT_RESULT, QUERY_RESULT)
+ store = FakeStore(journal, {KEY: build_stored_ref()})
+
+ assert self.run(make_operator(), store) == EXPECTED_RESULT
+ assert genie.calls("POST") == []
+
+ @pytest.mark.parametrize(
+ ("stored", "first_response"),
+ [
+ pytest.param(build_stored_ref(), build_message("FAILED"),
id="failed"),
+ pytest.param(build_stored_ref(), build_message("CANCELLED"),
id="cancelled"),
+ pytest.param(
+ build_stored_ref(), DatabricksGenieError("gone",
http_status_code=404), id="deleted"
+ ),
+ pytest.param(build_stored_ref(fingerprint="other"), None,
id="other-question"),
+ pytest.param("legacy-id", None, id="unexpected-shape"),
+ ],
+ )
+ def test_asks_again_when_stored_message_cannot_be_used(self, genie,
journal, stored, first_response):
+ if first_response is not None:
+ genie.add("GET", MESSAGE, first_response)
+ stub_answered(genie)
+ store = FakeStore(journal, {KEY: stored})
+
+ assert self.run(make_operator(), store) == EXPECTED_RESULT
+
+ assert genie.calls("POST") == [("POST", START)]
+ assert store.data == {KEY: build_stored_ref()}
+
+ def test_stored_message_lookup_error_propagates(self, genie, journal):
+ genie.add("GET", MESSAGE, DatabricksGenieError("denied",
http_status_code=403))
+ store = FakeStore(journal, {KEY: build_stored_ref()})
+
+ with pytest.raises(DatabricksGenieError, match="denied"):
+ self.run(make_operator(), store)
+ assert genie.calls("POST") == []
+
+ @pytest.mark.parametrize(
+ ("payload", "match"),
+ [
+ pytest.param(
+ build_message("SOMETHING_NEW"), "unknown message status:
'SOMETHING_NEW'", id="unknown"
+ ),
+ pytest.param(
+ {"conversation_id": CONVERSATION_ID, "message_id": MESSAGE_ID},
+ "unknown message status: None",
+ id="missing",
+ ),
+ ],
+ )
+ def test_unknown_or_missing_status_does_not_resubmit(self, genie, journal,
payload, match):
+ genie.add("GET", MESSAGE, payload)
+ store = FakeStore(journal, {KEY: build_stored_ref()})
+
+ with pytest.raises(DatabricksGenieError, match=match):
+ self.run(make_operator(), store)
+ assert genie.calls("POST") == []
+ assert store.data == {KEY: build_stored_ref()}
+
+ def test_changed_question_does_not_reuse_answer(self, genie, journal):
+ genie.add("POST", START, DatabricksGenieError("rejected",
http_status_code=400))
+ store = FakeStore(journal, {KEY: build_stored_ref()})
+
+ with pytest.raises(DatabricksGenieError, match="rejected"):
+ self.run(make_operator(question="Something else?"), store)
+
+ assert genie.calls("GET") == []
+ assert genie.bodies == [{"content": "Something else?",
"enable_visualization": False}]
+
+ def test_timeout_says_next_try_reconnects(self, genie, journal, sleep):
+ genie.add("POST", START, {"conversation_id": CONVERSATION_ID,
"message_id": MESSAGE_ID})
+ genie.add("GET", MESSAGE, build_message("ASKING_AI"))
+ with (
+ mock.patch(
+ "airflow.providers.databricks.operators.genie.time.monotonic",
+ autospec=True,
+ side_effect=[0, 5, 11],
+ ),
+ pytest.raises(
+ DatabricksGenieError, match="Timed out after 10 seconds .*
reconnects to the message"
+ ),
+ ):
+ self.run(make_operator(timeout=10), FakeStore(journal))
+
+ def test_failure_before_send_leaves_no_marker(self, genie, journal):
+ """A token endpoint failure happens before anything is sent, so the
next try may submit."""
+ stub_answered(genie)
+ genie.prepare_errors.append(AirflowException("token endpoint
unavailable"))
+ store = FakeStore(journal)
+
+ with pytest.raises(AirflowException, match="token endpoint
unavailable"):
+ self.run(make_operator(), store)
+ assert store.data == {}
+ assert genie.calls("POST") == []
+
+ assert self.run(make_operator(), store) == EXPECTED_RESULT
+ assert genie.calls("POST") == [("POST", START)]
+ assert store.data == {KEY: build_stored_ref()}
+
+ def test_unconfirmed_submission_blocks_next_try(self, genie, journal):
+ genie.add("POST", START, DatabricksGenieError("unknown outcome",
http_status_code=None))
+ store = FakeStore(journal)
+
+ with pytest.raises(AirflowFailException, match="unknown outcome"):
+ self.run(make_operator(), store)
+ assert store.data == {SUBMISSION_KEY: {"fingerprint":
make_operator()._compute_fingerprint()}}
+
+ with pytest.raises(AirflowFailException, match="never confirmed the
outcome"):
+ self.run(make_operator(), store)
+ assert genie.calls("POST") == [("POST", START)]
+
+ def test_clear_that_discards_task_state_asks_again(self, genie, journal):
+ """A default clear on Airflow 3.4+ deletes the marker, so nothing
stops a second submission."""
+ genie.add(
+ "POST",
+ START,
+ DatabricksGenieError("unknown outcome", http_status_code=None),
+ {"conversation_id": CONVERSATION_ID, "message_id": MESSAGE_ID},
+ )
+ genie.add("GET", MESSAGE, COMPLETED)
+ genie.add("GET", ATTACHMENT_RESULT, QUERY_RESULT)
+ with pytest.raises(AirflowFailException, match="unknown outcome"):
+ self.run(make_operator(), FakeStore(journal))
+
+ assert self.run(make_operator(), FakeStore(journal)) == EXPECTED_RESULT
+ assert genie.calls("POST") == [("POST", START), ("POST", START)]
+
+ def test_changed_question_ignores_submission_marker(self, genie, journal):
+ stub_answered(genie)
+ store = FakeStore(journal, {SUBMISSION_KEY: {"fingerprint":
make_operator()._compute_fingerprint()}})
+ op = make_operator(question="Something else?")
+
+ assert self.run(op, store) == EXPECTED_RESULT
+
+ assert genie.calls("POST") == [("POST", START)]
+ assert genie.bodies == [{"content": "Something else?",
"enable_visualization": False}]
+ assert store.data == {KEY: {**build_stored_ref(), "fingerprint":
op._compute_fingerprint()}}
+
+ def test_accepted_submission_without_ids_blocks_next_try(self, genie,
journal):
+ genie.add("POST", START, {"message_id": MESSAGE_ID})
+ store = FakeStore(journal)
+
+ with pytest.raises(AirflowFailException, match="returned no
conversation or message ID"):
+ self.run(make_operator(), store)
+ assert SUBMISSION_KEY in store.data
+
+ def test_resubmit_unconfirmed_asks_again(self, genie, journal):
+ stub_answered(genie)
+ store = FakeStore(journal, {SUBMISSION_KEY: {"fingerprint": "x"}})
+
+ assert self.run(make_operator(resubmit_unconfirmed=True), store) ==
EXPECTED_RESULT
+ assert store.data == {KEY: build_stored_ref()}
+
+ @pytest.mark.parametrize("status_code", [400, 403, 429])
+ def test_rejected_submission_clears_marker(self, genie, journal,
status_code):
+ genie.add("POST", START, DatabricksGenieError("rejected",
http_status_code=status_code))
+ store = FakeStore(journal)
+
+ with pytest.raises(DatabricksGenieError, match="rejected"):
+ self.run(make_operator(), store)
+ assert store.data == {}
+
+ def test_attach_recovers_unconfirmed_submission(self, genie, journal):
+ genie.add("GET", MESSAGE, COMPLETED)
+ genie.add("GET", ATTACHMENT_RESULT, QUERY_RESULT)
+ other = build_stored_ref(message_id="older")
+ store = FakeStore(journal, {SUBMISSION_KEY: {"fingerprint": "x"}, KEY:
other})
+ op = make_operator(conversation_id=CONVERSATION_ID,
message_id=MESSAGE_ID)
+
+ assert self.run(op, store) == EXPECTED_RESULT
+
+ assert genie.calls("POST") == []
+ assert store.data == {KEY: {**build_stored_ref(), "fingerprint":
op._compute_fingerprint()}}
+
+ def test_not_durable_ignores_store(self, genie, journal):
+ stub_answered(genie)
+ store = FakeStore(journal, {KEY: build_stored_ref(), SUBMISSION_KEY:
{"fingerprint": "x"}})
+
+ assert self.run(make_operator(durable=False), store) == EXPECTED_RESULT
+
+ assert genie.calls("POST") == [("POST", START)]
+ assert [entry for entry in journal if entry[0] in ("set", "delete")]
== []
+
+ def test_cached_result_is_not_fetched_twice(self, genie, journal):
+ stub_answered(genie)
+ self.run(make_operator(), FakeStore(journal))
+ assert genie.calls("GET").count(("GET", ATTACHMENT_RESULT)) == 1
diff --git a/providers/databricks/tests/unit/databricks/triggers/test_genie.py
b/providers/databricks/tests/unit/databricks/triggers/test_genie.py
new file mode 100644
index 00000000000..f82d3a62165
--- /dev/null
+++ b/providers/databricks/tests/unit/databricks/triggers/test_genie.py
@@ -0,0 +1,170 @@
+# 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
+
+from unittest import mock
+
+import pytest
+
+from airflow.providers.databricks.exceptions import DatabricksApiError
+from airflow.providers.databricks.triggers.genie import
DatabricksGenieMessageTrigger
+
+SPACE_ID = "space/1"
+CONVERSATION_ID = "conversation-1"
+MESSAGE_ID = "message-1"
+ENDPOINT =
f"2.0/genie/spaces/space%2F1/conversations/{CONVERSATION_ID}/messages/{MESSAGE_ID}"
+IDS = {"conversation_id": CONVERSATION_ID, "message_id": MESSAGE_ID}
+
+
+def make_trigger(**kwargs) -> DatabricksGenieMessageTrigger:
+ return DatabricksGenieMessageTrigger(
+ space_id=SPACE_ID,
+ conversation_id=CONVERSATION_ID,
+ message_id=MESSAGE_ID,
+ databricks_conn_id="genie",
+ polling_period_seconds=2,
+ **kwargs,
+ )
+
+
[email protected]
+def hook():
+ with mock.patch(
+ "airflow.providers.databricks.triggers.genie.DatabricksGenieHook",
autospec=True
+ ) as hook_class:
+ hook = hook_class.return_value
+ hook.__aenter__.return_value = hook
+ hook._endpoint_url.side_effect = lambda endpoint:
f"https://workspace.cloud.databricks.com/{endpoint}"
+ yield hook
+
+
[email protected]
+def sleep():
+ with
mock.patch("airflow.providers.databricks.triggers.genie.asyncio.sleep",
autospec=True) as sleep:
+ yield sleep
+
+
+async def collect_events(trigger) -> list[dict]:
+ return [event.payload async for event in trigger.run()]
+
+
+def test_serialization_has_ids_and_no_credentials():
+ trigger = make_trigger(retry_limit=5, retry_delay=3)
+ path, kwargs = trigger.serialize()
+ assert path ==
"airflow.providers.databricks.triggers.genie.DatabricksGenieMessageTrigger"
+ assert kwargs == {
+ "space_id": SPACE_ID,
+ "conversation_id": CONVERSATION_ID,
+ "message_id": MESSAGE_ID,
+ "databricks_conn_id": "genie",
+ "polling_period_seconds": 2,
+ "retry_limit": 5,
+ "retry_delay": 3,
+ }
+ assert DatabricksGenieMessageTrigger(**kwargs).serialize() ==
trigger.serialize()
+
+
[email protected]("period", [0, -1])
+def test_invalid_polling_period(period):
+ with pytest.raises(ValueError, match="must be positive"):
+ DatabricksGenieMessageTrigger(
+ space_id=SPACE_ID,
+ conversation_id=CONVERSATION_ID,
+ message_id=MESSAGE_ID,
+ polling_period_seconds=period,
+ )
+
+
[email protected]("terminal", ["COMPLETED", "FAILED", "CANCELLED",
"QUERY_RESULT_EXPIRED"])
[email protected]
+async def test_waits_for_terminal_status(hook, sleep, terminal):
+ hook._a_do_api_call.side_effect = [{"status": "SUBMITTED"}, {"status":
"ASKING_AI"}, {"status": terminal}]
+
+ assert await collect_events(make_trigger()) == [{**IDS, "status":
"success", "message_status": terminal}]
+
+ hook._a_do_api_call.assert_has_calls([mock.call(("GET", ENDPOINT))] * 3)
+ assert sleep.await_args_list == [mock.call(2), mock.call(2)]
+
+
[email protected]
+async def test_restarted_trigger_polls_same_message(hook, sleep):
+ hook._a_do_api_call.side_effect = [{"status": "EXECUTING_QUERY"},
{"status": "COMPLETED"}]
+ restarted = DatabricksGenieMessageTrigger(**make_trigger().serialize()[1])
+
+ assert await collect_events(restarted) == [{**IDS, "status": "success",
"message_status": "COMPLETED"}]
+
+
[email protected]("response", [{"status": "SOMETHING_NEW"}, {}, ["not",
"an", "object"]])
[email protected]
+async def test_unknown_status(hook, sleep, response):
+ hook._a_do_api_call.return_value = response
+ assert await collect_events(make_trigger()) == [
+ {**IDS, "status": "error", "error_type": "invalid_response"}
+ ]
+ sleep.assert_not_called()
+
+
[email protected]("status_code", [401, 403, 404, 429, 503, None])
[email protected]
+async def test_api_error(hook, status_code):
+ hook._a_do_api_call.side_effect = DatabricksApiError("boom",
http_status_code=status_code)
+ assert await collect_events(make_trigger()) == [
+ {**IDS, "status": "error", "error_type": "api_error", "status_code":
status_code}
+ ]
+
+
[email protected]
+async def test_unexpected_error(hook):
+ hook._a_do_api_call.side_effect = RuntimeError("private detail")
+ payloads = await collect_events(make_trigger())
+ assert payloads == [{**IDS, "status": "error", "error_type":
"unexpected_error"}]
+
+
[email protected](
+ "base",
+ ["http://workspace.cloud.databricks.com",
"ftp://workspace.cloud.databricks.com"],
+)
[email protected]
+async def test_refuses_cleartext_connection(hook, base):
+ hook._endpoint_url.side_effect = lambda endpoint: f"{base}/{endpoint}"
+ assert await collect_events(make_trigger()) == [
+ {**IDS, "status": "error", "error_type": "insecure_connection"}
+ ]
+ hook._a_do_api_call.assert_not_called()
+
+
[email protected]
+async def test_allows_loopback_http(hook):
+ hook._endpoint_url.side_effect = lambda endpoint:
f"http://127.0.0.1:8080/{endpoint}"
+ hook._a_do_api_call.return_value = {"status": "COMPLETED"}
+ assert await collect_events(make_trigger()) == [
+ {**IDS, "status": "success", "message_status": "COMPLETED"}
+ ]
+
+
[email protected]
+async def test_hook_configuration():
+ with mock.patch(
+ "airflow.providers.databricks.triggers.genie.DatabricksGenieHook",
autospec=True
+ ) as hook_class:
+ hook_class.return_value.__aenter__.side_effect = RuntimeError("stop")
+ assert await collect_events(make_trigger(retry_limit=4,
retry_delay=2)) == [
+ {**IDS, "status": "error", "error_type": "unexpected_error"}
+ ]
+ hook_class.assert_called_once_with(
+ databricks_conn_id="genie", retry_limit=4, retry_delay=2,
caller="DatabricksGenieMessageTrigger"
+ )