kaxil commented on code in PR #76295:
URL: https://github.com/apache/airflow/pull/76295#discussion_r4470515829


##########
providers/databricks/src/airflow/providers/databricks/operators/databricks.py:
##########
@@ -82,6 +82,45 @@
 XCOM_RUN_PAGE_URL_KEY = "run_page_url"
 XCOM_STATEMENT_ID_KEY = "statement_id"
 
+# Databricks splits run state across life_cycle_state and result_state, while 
the ResumableJobMixin
+# status interface is a single string. The durable operators encode both as 
"LIFE_CYCLE:RESULT" and
+# decode them with the predicates below, so all three share one view of which 
runs can be rejoined.
+RUN_NOT_FOUND_STATUS = "NOT_FOUND:"
+ACTIVE_RUN_LIFE_CYCLE_STATES = (
+    "PENDING",
+    "QUEUED",
+    "RUNNING",
+    "TERMINATING",
+    "BLOCKED",
+    "WAITING_FOR_RETRY",
+)
+
+
+def fetch_run_status(hook: DatabricksHook, run_id: JsonValue) -> str:
+    """Return the encoded status of ``run_id``, or a sentinel if its run 
history is gone."""
+    try:
+        # The stored external id is always a Databricks run id; the mixin 
types it as JsonValue.
+        run_info = hook.get_run(cast("int", run_id))
+    except DatabricksApiError as e:
+        # A stored run whose history expired (or was deleted) returns 404. The 
sentinel is neither
+        # active nor succeeded, so the mixin resubmits fresh instead of 
failing the task.
+        if e.http_status_code == 404:
+            return RUN_NOT_FOUND_STATUS
+        raise
+    state = RunState(**run_info["state"])
+    return f"{state.life_cycle_state}:{state.result_state}"
+
+
+def is_run_active(status: str) -> bool:
+    """Whether an encoded status means the run is still going and can be 
reconnected to."""
+    return status.split(":", 1)[0] in ACTIVE_RUN_LIFE_CYCLE_STATES

Review Comment:
   Both `on_kill` paths cancel asynchronously and leave the stored id behind, 
and `TERMINATING` counts as active here. If you clear the Dag run while a 
notebook task is deferred, the next try can pick up the run that's being 
cancelled and fail with it. Could `get_job_status` wait out `TERMINATING` and 
decide on the final state? Dropping the id in `on_kill` would only help the 
sync case, since the trigger can't reach the store.



##########
providers/databricks/docs/operators/notebook.rst:
##########
@@ -80,3 +82,51 @@ attempt is observed, so downstream failure handling is not 
delayed by long-runni
 Only unlimited retries (``max_retries=-1``) keep the Airflow task waiting (or 
deferring) until the
 parent workflow run reaches a terminal state, because Databricks may still 
launch a retry attempt
 under the same ``task_key`` until then. Sibling tasks in the run continue 
independently.
+
+
+Durable execution
+-----------------
+
+Outside a
+:class:`~airflow.providers.databricks.operators.databricks_workflow.DatabricksWorkflowTaskGroup`,
+this operator submits a run and then waits for it, on the worker or in the 
Triggerer when
+``deferrable=True``. By default it runs in a *durable* mode: the Databricks 
run id is persisted to
+:doc:`task state store <apache-airflow:core-concepts/task-state-store>` before 
the wait begins, so if
+the worker crashes or is preempted and the task is retried, the operator 
reconnects to the run that
+is already executing on Databricks instead of submitting a duplicate.
+
+On retry the operator checks the prior run's state:
+
+* if it is still running, the operator reconnects and continues polling
+* if it already succeeded, the operator returns immediately without 
resubmitting
+* if it failed terminally, the operator submits a fresh run
+
+Pass ``durable=False`` to always submit a fresh run on retry.
+
+Unlike 
:class:`~airflow.providers.databricks.operators.databricks.DatabricksSubmitRunOperator`
 and
+:class:`~airflow.providers.databricks.operators.databricks.DatabricksRunNowOperator`,
 where
+``durable`` has no effect in deferrable mode, durable execution here also 
covers
+``deferrable=True``: the run id is stored before the task defers, so a try 
lost while the Triggerer
+was waiting still reconnects on the next one.
+
+Durable execution requires Airflow 3.3 or newer, since it relies on the task 
state store. On
+earlier Airflow versions the flag is a no-op and the operator always submits a 
fresh run on retry.
+If the task state store is unavailable at runtime, the operator logs that 
crash recovery is
+disabled and behaves the same way.
+
+Inside a ``DatabricksWorkflowTaskGroup`` nothing changes: the run is submitted 
by the workflow
+launch task and this operator only monitors its own task within that shared 
run, so a retry already
+reconnects rather than resubmitting.
+
+The stored run id is not deleted automatically; that only happens when someone 
runs
+``airflow state-store clean``. If a task's ``retry_delay`` is longer than
+``[state_store] default_retention_days`` (30 days by default) and cleanup runs 
in between, the run
+id is gone by the next retry and the operator submits a fresh run instead of 
reconnecting. Avoid
+running cleanup on a schedule shorter than your longest ``retry_delay``. See
+:doc:`apache-airflow:administration-and-deployment/task-and-asset-state-store-cleanup`.
+
+Clearing a task is treated the same as a retry, which matters for a task whose 
run already

Review Comment:
   This isn't what the default clear does afaik. The UI/REST task clear 
discards task state unless `keep_task_state` is set, so the next try submits a 
new run. Keeping the id is true for Clear Run on the Dag run, mark 
success/failed downstream clears, a task clear with `keep_task_state`, and the 
CLI. Can this say which clears keep it? Same in `task.rst`.



##########
providers/databricks/src/airflow/providers/databricks/operators/databricks.py:
##########
@@ -2020,15 +2029,24 @@ def _get_run_json(self) -> dict[str, Any]:
     def _launch_job(self, context: Context | None = None) -> int | None:
         """Launch the job on Databricks."""
         run_json = self._get_run_json()
+        # Return as soon as the run exists. A page URL lookup or an xcom push 
here would run
+        # before the mixin can persist the run id, so a failure would strand 
the run and let the
+        # retry submit a duplicate.
         self.databricks_run_id = self._hook.submit_run(run_json)

Review Comment:
   `runs/submit` goes out without an `idempotency_token`, so if the response is 
lost (read timeout, 502) the hook's retry re-POSTs and Databricks creates a 
second run. We'd persist and monitor only the second one. SubmitRun already 
takes a token. Could `_get_run_json` set one per try? It'd need the 
`try_number` in it, otherwise a retry after a terminal failure gets the old 
failed run back. Fine as a follow-up since it predates this PR, but it's the 
same duplicate-run case.



##########
providers/databricks/tests/unit/databricks/operators/test_databricks.py:
##########
@@ -5267,3 +5269,218 @@ def 
test_monitor_waits_out_waiting_for_retry_state(self, mock_databricks_hook, m
 
         operator.monitor_databricks_job()
         assert mock_databricks_hook.return_value.get_run.call_count == 3
+
+
[email protected](
+    not AIRFLOW_V_3_3_PLUS, reason="task_state_store (durable execution) 
requires Airflow 3.3+"
+)
+class TestDatabricksTaskBaseOperatorDurable:
+    @pytest.fixture(params=["notebook", "task"])
+    def make_operator(self, request):
+        def _make(**kwargs):
+            if request.param == "notebook":
+                return DatabricksNotebookOperator(
+                    task_id=TASK_ID,
+                    notebook_path="/test",
+                    source="WORKSPACE",
+                    new_cluster=NEW_CLUSTER,
+                    **kwargs,
+                )
+            return DatabricksTaskOperator(
+                task_id=TASK_ID,
+                task_config={"notebook_task": NOTEBOOK_TASK},
+                new_cluster=NEW_CLUSTER,
+                **kwargs,
+            )
+
+        return _make
+
+    @staticmethod
+    def _task_store(stored_run_id=None):
+        task_store = MagicMock(spec_set=["get", "set"])
+        task_store.get.return_value = stored_run_id
+        return task_store
+
+    
@mock.patch("airflow.providers.databricks.operators.databricks.DatabricksHook")
+    def test_persists_run_id_on_fresh_submit(self, db_mock_class, 
make_operator):
+        op = make_operator()
+        op.monitor_databricks_job = MagicMock()

Review Comment:
   Nothing in this class drives `execute()` with `deferrable=True` or checks 
that the run id is stored before the defer, which is the part that differs from 
SubmitRun/RunNow. An `if self.deferrable:` bypass in `execute` would pass the 
whole class. Could one test assert `task_state_store.set` is called before 
`defer`?



##########
providers/databricks/src/airflow/providers/databricks/operators/databricks.py:
##########
@@ -82,6 +82,45 @@
 XCOM_RUN_PAGE_URL_KEY = "run_page_url"
 XCOM_STATEMENT_ID_KEY = "statement_id"
 
+# Databricks splits run state across life_cycle_state and result_state, while 
the ResumableJobMixin
+# status interface is a single string. The durable operators encode both as 
"LIFE_CYCLE:RESULT" and
+# decode them with the predicates below, so all three share one view of which 
runs can be rejoined.
+RUN_NOT_FOUND_STATUS = "NOT_FOUND:"
+ACTIVE_RUN_LIFE_CYCLE_STATES = (
+    "PENDING",
+    "QUEUED",
+    "RUNNING",
+    "TERMINATING",
+    "BLOCKED",
+    "WAITING_FOR_RETRY",
+)
+
+
+def fetch_run_status(hook: DatabricksHook, run_id: JsonValue) -> str:
+    """Return the encoded status of ``run_id``, or a sentinel if its run 
history is gone."""
+    try:
+        # The stored external id is always a Databricks run id; the mixin 
types it as JsonValue.
+        run_info = hook.get_run(cast("int", run_id))
+    except DatabricksApiError as e:
+        # A stored run whose history expired (or was deleted) returns 404. The 
sentinel is neither
+        # active nor succeeded, so the mixin resubmits fresh instead of 
failing the task.
+        if e.http_status_code == 404:

Review Comment:
   I don't think Databricks sends a 404 here. `runs/get` for a missing or 
expired run returns 400 `INVALID_PARAMETER_VALUE` with "Run N does not exist", 
which is the case the Databricks SDK's error overrides map to 
`ResourceDoesNotExist`. So a stale stored id (past run retention, deleted, or a 
different workspace on the conn) fails every retry instead of resubmitting, and 
nothing replaces it. `DatabricksApiError` only carries the status code, but 
`BaseDatabricksHook._get_error_code` already parses the error code, so it could 
be passed through. Since `fetch_run_status` is shared now, the fix covers 
SubmitRun and RunNow too. Could the test mock the real response as well?



##########
providers/databricks/src/airflow/providers/databricks/operators/databricks.py:
##########
@@ -2294,10 +2338,13 @@ def execute(self, context: Context) -> None:
                     metadata=workflow_run_metadata,
                     logger=self.log,
                 )
-        else:
-            self._launch_job(context=context)
-        if self.wait_for_termination:
-            self.monitor_databricks_job()
+            # The run id comes from the upstream launch task's xcom, so a 
retry already reconnects
+            # to the shared run rather than submitting anything.
+            if self.wait_for_termination:
+                self.monitor_databricks_job()
+            return
+
+        self.execute_resumable(context)

Review Comment:
   With `durable` on by default this changes what a clear that keeps task state 
does to an unchanged Dag. Clear Run on a Dag run whose notebook run succeeded 
now re-pushes the old xcoms and runs nothing, and with 
`wait_for_termination=False` it submits nothing while the earlier run is still 
going. The per-task UI clear still resubmits, so the result depends on which 
clear the user picked. Is that intended for these two operators? If so, the 
`wait_for_termination=False` case at least needs to be in the docs.



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

To unsubscribe, e-mail: [email protected]

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

Reply via email to