This is an automated email from the ASF dual-hosted git repository.

vatsrahul1001 pushed a commit to branch v3-4-test
in repository https://gitbox.apache.org/repos/asf/airflow.git


The following commit(s) were added to refs/heads/v3-4-test by this push:
     new 0383923f61a [v3-4-test] Task success should be agnostic of 
clear_on_success cleanup failure (#76021) (#77684)
0383923f61a is described below

commit 0383923f61a5d1c0d43891a1734667813759cbe3
Author: Rahul Vats <[email protected]>
AuthorDate: Fri Nov 27 19:34:27 2026 +0530

    [v3-4-test] Task success should be agnostic of clear_on_success cleanup 
failure (#76021) (#77684)
    
    (cherry picked from commit 2e541862b7fc40d61b603cb01a06d3ef731e605d)
    
    Co-authored-by: Amogh Desai <[email protected]>
    Co-authored-by: Claude <[email protected]>
---
 .../docs/core-concepts/task-state-store.rst        |  16 +++
 task-sdk/src/airflow/sdk/execution_time/context.py |  11 --
 .../src/airflow/sdk/execution_time/task_runner.py  |  54 +++++++-
 .../task_sdk/execution_time/test_task_runner.py    | 144 +++++++++++++++++----
 4 files changed, 185 insertions(+), 40 deletions(-)

diff --git a/airflow-core/docs/core-concepts/task-state-store.rst 
b/airflow-core/docs/core-concepts/task-state-store.rst
index 8cfb58e8087..9bda390e163 100644
--- a/airflow-core/docs/core-concepts/task-state-store.rst
+++ b/airflow-core/docs/core-concepts/task-state-store.rst
@@ -332,4 +332,20 @@ When ``[state_store] clear_on_success = True``, all task 
state store keys for a
 
    ``clear_on_success`` clears **task state store only**. Asset store is 
scoped to the asset, not the task instance, and is never affected by this 
setting. Asset store persists across runs and must be cleared explicitly.
 
+.. note::
+
+   With a custom ``[workers] state_store_backend``, the worker deletes the 
backend's entries only
+   after the success has been reported, once the task's callbacks and 
listeners have run. If that
+   deletion fails the task stays successful and the failure is logged. The Dag 
id, run id, task id
+   and region of the entries are logged just before the deletion starts.
+
+   Those entries are then orphaned: the API server has already removed the 
metadata-DB references,
+   ``airflow state-store clean`` covers the metastore backend only, and
+   :meth:`~airflow.sdk.state.BaseStoreBackend.cleanup` is a no-op unless your 
backend implements
+   it. Because the storage scope includes the run id, the next Dag run writes 
elsewhere rather than
+   overwriting them. Removing them is up to your storage's own lifecycle or 
TTL policy, or a
+   ``cleanup()`` implementation on your backend. Nothing in Airflow calls 
``cleanup()`` for a
+   worker backend, so it has to be called from your own maintenance process, 
as described in
+   :doc:`/administration-and-deployment/task-and-asset-state-store-cleanup`.
+
 See :doc:`/administration-and-deployment/task-and-asset-state-store` for full 
configuration details.
diff --git a/task-sdk/src/airflow/sdk/execution_time/context.py 
b/task-sdk/src/airflow/sdk/execution_time/context.py
index b7e69b41a4f..9cd4986fa86 100644
--- a/task-sdk/src/airflow/sdk/execution_time/context.py
+++ b/task-sdk/src/airflow/sdk/execution_time/context.py
@@ -885,17 +885,6 @@ class TaskStateStoreAccessor:
         if backend is not None:
             await backend.aclear(self._scope)
 
-    def _clear_backend_only(self) -> None:
-        """
-        Clear external storage via the worker backend without sending a comms 
message.
-
-        Used by clear_on_success: the server already clears DB rows as part of 
SucceedTask,
-        so the comms round-trip is redundant.
-        """
-        backend = _get_worker_state_store_backend()
-        if backend is not None:
-            backend.clear(self._scope)
-
 
 class AssetStateStoreAccessor:
     """
diff --git a/task-sdk/src/airflow/sdk/execution_time/task_runner.py 
b/task-sdk/src/airflow/sdk/execution_time/task_runner.py
index 71607ce353e..fb26af85f83 100644
--- a/task-sdk/src/airflow/sdk/execution_time/task_runner.py
+++ b/task-sdk/src/airflow/sdk/execution_time/task_runner.py
@@ -236,6 +236,9 @@ class RuntimeTaskInstance(TaskInstance):
     _terminal_state_send_failed: bool = False
     """True when the supervisor IPC send for a non-success terminal state 
raised; signals main() to sys.exit(1) after finalize() so the supervisor 
doesn't misclassify the run as SUCCESS via exit code 0."""
 
+    _state_store_clear_owed: bool = False
+    """True once a successful task has been reported to the supervisor and 
``clear_on_success`` still owes the custom backend a delete; finalize() does it 
last, after every callback and listener, so a slow remote delete cannot eat the 
task_success_overtime budget ahead of them. finalize() is the seam both the 
subprocess and the in-process (dag.test()) paths cross."""
+
     _failure_metrics_emitted: bool = False
     """True once the failure counters have been recorded, so a second pass 
through the failure path (one attempt raised part-way through) does not count 
the same failure twice."""
 
@@ -1837,12 +1840,54 @@ def run(
                 # a retry policy turned the exception into a reschedule.
                 if error is not None or state in (TaskInstanceState.FAILED, 
TaskInstanceState.UP_FOR_RETRY):
                     ti._terminal_state_send_failed = True
+            else:
+                if state == TaskInstanceState.SUCCESS:
+                    ti._state_store_clear_owed = True
 
     # Return the message to make unit tests easier too
     ti.state = state
     return state, msg, error
 
 
+def _clear_task_state_store_on_success(context: Context, log: Logger) -> None:
+    """
+    Clear the custom state store backend once the task is recorded as 
successful.
+
+    Called at the end of finalize(), never before the terminal state is 
reported: the
+    backend is remote storage, so a failure deleting from it must not turn a 
task that
+    succeeded into a failed one, and a slow delete must not spend the 
task_success_overtime
+    budget that the success callbacks and listeners need.
+    """
+    if not conf.getboolean("state_store", "clear_on_success"):
+        return
+    try:
+        # Inside the try: the backend is built on first use, so a bad [workers]
+        # state_store_backend class path raises here for a task that never 
touched
+        # task_state_store, and @cache does not cache the raise.
+        if _get_worker_state_store_backend() is None:
+            return
+        scope = context["task_state_store"]._scope
+        # Logged before the delete: if it hangs past task_success_overtime, 
the supervisor
+        # kills the task and this line is the only record of which entries 
were left.
+        log.info(
+            "Clearing task state as clear_on_success is enabled.",
+            dag_id=scope.dag_id,
+            run_id=scope.run_id,
+            task_id=scope.task_id,
+            region_id=str(scope.region_id),
+            region_index=scope.region_index,
+        )
+        # clear() rather than a backend-only delete: success callbacks and 
listeners run
+        # before this and can set() new keys, whose DB refs must go before the 
objects do.
+        context["task_state_store"].clear()
+    except Exception:
+        log.exception(
+            "Failed to clear task state from custom backend; the task stays 
successful. Nothing in Airflow "
+            "reclaims these entries -- the database references are already 
gone and the next run uses a "
+            "different run_id -- so only the storage's own lifecycle or TTL 
policy will remove them."
+        )
+
+
 def _handle_current_task_success(
     context: Context,
     ti: RuntimeTaskInstance,
@@ -1860,12 +1905,6 @@ def _handle_current_task_success(
     task_outlets = list(_build_asset_profiles(ti.task.outlets))
     outlet_events = list(_serialize_outlet_events(context["outlet_events"]))
 
-    if conf.getboolean("state_store", "clear_on_success") and 
_get_worker_state_store_backend() is not None:
-        log.info(
-            "Clearing task state from custom backend as clear_on_success is 
enabled. The database references will be cleared by the API server."
-        )
-        context["task_state_store"]._clear_backend_only()
-
     msg = SucceedTask(
         end_date=end_date,
         task_outlets=task_outlets,
@@ -2544,6 +2583,9 @@ def finalize(
     except Exception:
         log.exception("error calling listener")
 
+    if ti._state_store_clear_owed:
+        _clear_task_state_store_on_success(context, log)
+
     log.info("::endgroup::")
 
 
diff --git a/task-sdk/tests/task_sdk/execution_time/test_task_runner.py 
b/task-sdk/tests/task_sdk/execution_time/test_task_runner.py
index 0c44da0635a..4fb0046c8c8 100644
--- a/task-sdk/tests/task_sdk/execution_time/test_task_runner.py
+++ b/task-sdk/tests/task_sdk/execution_time/test_task_runner.py
@@ -203,6 +203,7 @@ from airflow.sdk.execution_time.task_runner import (
 from airflow.sdk.execution_time.xcom import XCom
 from airflow.sdk.importers import DagSourceCode
 from airflow.sdk.serde import deserialize
+from airflow.sdk.state import BaseStoreBackend
 from airflow.triggers.base import BaseEventTrigger, BaseTrigger, TriggerEvent
 from airflow.triggers.callback import CallbackTrigger
 from airflow.triggers.testing import SuccessTrigger
@@ -7429,38 +7430,135 @@ class TestTaskInstanceStateOperations:
         ]
         assert ClearTaskStateStore not in sent_types
 
-    @conf_vars({("state_store", "clear_on_success"): "True"})
-    def test_clear_on_success_clears_backend_without_comms_roundtrip(
-        self, create_runtime_ti, mock_supervisor_comms
-    ):
-        """clear_on_success calls backend.clear() directly without sending 
ClearTaskStateStore comms."""
-        mock_backend = mock.MagicMock()
-
-        class MyOperator(BaseOperator):
-            def execute(self, context):
-                pass
-
-        task = MyOperator(task_id="t")
-        runtime_ti = create_runtime_ti(task=task)
-
+    @staticmethod
+    @contextlib.contextmanager
+    def _patch_state_backend(backend):
+        # Both modules resolve the backend independently, so both lookups need 
patching.
         with (
             mock.patch(
                 
"airflow.sdk.execution_time.context._get_worker_state_store_backend",
-                return_value=mock_backend,
+                return_value=backend,
             ),
             mock.patch(
                 
"airflow.sdk.execution_time.task_runner._get_worker_state_store_backend",
-                return_value=mock_backend,
+                return_value=backend,
             ),
         ):
-            run(runtime_ti, context=runtime_ti.get_template_context(), 
log=mock.MagicMock())
+            yield backend
 
-        mock_backend.clear.assert_called_once()
-        sent_types = [
-            type(call.kwargs.get("msg") or (call.args[0] if call.args else 
None))
-            for call in mock_supervisor_comms.send.call_args_list
-        ]
-        assert ClearTaskStateStore not in sent_types
+    @staticmethod
+    def _run_and_finalize(runtime_ti, log):
+        # The clear lives at the tail of finalize(), so run() alone would not 
reach it.
+        context = runtime_ti.get_template_context()
+        state, msg, error = run(runtime_ti, context=context, log=log)
+        finalize(runtime_ti, state, context, log, error)
+        return state, msg, error
+
+    @conf_vars({("state_store", "clear_on_success"): "True"})
+    def test_clear_on_success_clears_db_refs_before_backend(self, 
create_runtime_ti, mock_supervisor_comms):
+        """clear_on_success sends ClearTaskStateStore before deleting from the 
backend."""
+        backend = mock.create_autospec(BaseStoreBackend, instance=True)
+        order = []
+        mock_supervisor_comms.send.side_effect = lambda msg, **kwargs: 
order.append(type(msg).__name__)
+        backend.clear.side_effect = lambda *a, **kw: order.append("clear")
+
+        class MyOperator(BaseOperator):
+            def execute(self, context):
+                pass
+
+        runtime_ti = create_runtime_ti(task=MyOperator(task_id="t"))
+
+        with self._patch_state_backend(backend):
+            self._run_and_finalize(runtime_ti, mock.MagicMock())
+
+        backend.clear.assert_called_once()
+        assert order.index("ClearTaskStateStore") < order.index("clear")
+
+    @conf_vars({("state_store", "clear_on_success"): "True"})
+    def test_clear_on_success_runs_after_success_is_reported(self, 
create_runtime_ti, mock_supervisor_comms):
+        """The backend is cleared only after SucceedTask is reported and the 
success callbacks have run."""
+        backend = mock.create_autospec(BaseStoreBackend, instance=True)
+        order = []
+        mock_supervisor_comms.send.side_effect = lambda msg, **kwargs: 
order.append(type(msg).__name__)
+        backend.clear.side_effect = lambda *a, **kw: order.append("clear")
+
+        class MyOperator(BaseOperator):
+            def execute(self, context):
+                pass
+
+        task = MyOperator(task_id="t", on_success_callback=lambda context: 
order.append("callback"))
+        runtime_ti = create_runtime_ti(task=task)
+
+        with self._patch_state_backend(backend):
+            state, _, _ = self._run_and_finalize(runtime_ti, mock.MagicMock())
+
+        assert state == TaskInstanceState.SUCCESS
+        assert order.index("SucceedTask") < order.index("callback") < 
order.index("clear")
+
+    @conf_vars({("state_store", "clear_on_success"): "True"})
+    def test_clear_on_success_failure_does_not_fail_the_task(self, 
create_runtime_ti, mock_supervisor_comms):
+        """A backend that cannot be cleared leaves the task successful and 
logs where the orphans are."""
+        backend = mock.create_autospec(BaseStoreBackend, instance=True)
+        backend.clear.side_effect = ConnectionError("object storage is down")
+
+        class MyOperator(BaseOperator):
+            def execute(self, context):
+                pass
+
+        runtime_ti = create_runtime_ti(task=MyOperator(task_id="t"))
+        log = mock.MagicMock()
+
+        with self._patch_state_backend(backend):
+            state, msg, error = self._run_and_finalize(runtime_ti, log)
+
+        backend.clear.assert_called_once()
+        assert state == TaskInstanceState.SUCCESS
+        assert error is None
+        assert isinstance(msg, SucceedTask)
+        assert runtime_ti._terminal_state_send_failed is False
+        log.exception.assert_called_once()
+        scope = runtime_ti.get_template_context()["task_state_store"]._scope
+        log.info.assert_any_call(
+            "Clearing task state as clear_on_success is enabled.",
+            dag_id=scope.dag_id,
+            run_id=scope.run_id,
+            task_id=scope.task_id,
+            region_id=str(scope.region_id),
+            region_index=scope.region_index,
+        )
+
+    @conf_vars({("state_store", "clear_on_success"): "True"})
+    @pytest.mark.parametrize("outcome", ["task_raised", "success_send_raised"])
+    def test_clear_on_success_skipped_when_success_was_not_delivered(
+        self, outcome, create_runtime_ti, mock_supervisor_comms
+    ):
+        """A task that did not report success keeps its state, so its retry 
can resume from it."""
+        backend = mock.create_autospec(BaseStoreBackend, instance=True)
+
+        class MyOperator(BaseOperator):
+            def execute(self, context):
+                if outcome == "task_raised":
+                    raise RuntimeError("training blew up")
+
+        if outcome == "success_send_raised":
+
+            def send(msg, **kwargs):
+                if isinstance(msg, SucceedTask):
+                    raise ConnectionError("supervisor socket gone")
+                return None
+
+            mock_supervisor_comms.send.side_effect = send
+
+        runtime_ti = create_runtime_ti(task=MyOperator(task_id="t"))
+
+        with self._patch_state_backend(backend):
+            state, _, _ = self._run_and_finalize(runtime_ti, mock.MagicMock())
+
+        assert state == (
+            TaskInstanceState.SUCCESS if outcome == "success_send_raised" else 
TaskInstanceState.FAILED
+        )
+        assert runtime_ti._state_store_clear_owed is False
+        backend.clear.assert_not_called()
 
 
 class _WalkerModelA(BaseModel):

Reply via email to