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

Lee-W 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 d68b87f15a4 Prevent duplicate durable agent calls after storage read 
failures (#76381)
d68b87f15a4 is described below

commit d68b87f15a4db305dcafa19b01cb6a408aaa6d66
Author: Vincent Hsiao <[email protected]>
AuthorDate: Fri Nov 27 21:14:01 2026 +0800

    Prevent duplicate durable agent calls after storage read failures (#76381)
    
    * Prevent duplicate durable agent calls after storage read failures
    
    * Fail safely when durable journals cannot be read
    
    * Improve durable journal failure diagnostics
    
    * Fail corrupt durable journals without retrying
    
    * Handle durable journal cleanup failures
---
 providers/common/ai/docs/changelog.rst             | 11 ++++
 providers/common/ai/docs/durable_execution.rst     | 14 +++++
 .../airflow/providers/common/ai/durable/storage.py | 30 +++++++---
 .../tests/unit/common/ai/durable/test_storage.py   | 70 +++++++++++++++++++---
 4 files changed, 109 insertions(+), 16 deletions(-)

diff --git a/providers/common/ai/docs/changelog.rst 
b/providers/common/ai/docs/changelog.rst
index f90b283d797..f25a0aa9090 100644
--- a/providers/common/ai/docs/changelog.rst
+++ b/providers/common/ai/docs/changelog.rst
@@ -117,6 +117,17 @@ Changelog
   ``fallback_rules`` against the last connection's error, and show the model 
each connection's error
   and how many durable journal steps the attempt replayed and recorded.
 
+.. note::
+  **Significant change: durable journal failures**
+
+  On Airflow < 3.3, a durable journal that cannot be read or is corrupt now
+  fails the task attempt instead of treating the journal as absent and running
+  completed LLM calls or tool operations again. Before upgrading, S3 roles for
+  durable ObjectStorage journals must grant ``s3:ListBucket`` on the bucket, in
+  addition to permissions to read, write and delete journal objects. A storage
+  read failure follows the task's retry policy; a corrupt journal is not 
retried
+  and must be repaired or deleted before the task is run again.
+
 .. note::
   ``@task.llm``, ``@task.agent``, ``@task.llm_sql``, ``@task.llm_branch``,
   ``@task.llm_file_analysis`` and ``@task.llm_schema_compare`` now render only 
the prompt returned
diff --git a/providers/common/ai/docs/durable_execution.rst 
b/providers/common/ai/docs/durable_execution.rst
index 3cc25a6d254..81c1f531db7 100644
--- a/providers/common/ai/docs/durable_execution.rst
+++ b/providers/common/ai/docs/durable_execution.rst
@@ -171,6 +171,20 @@ Without the option, the task fails with:
 
     ValueError: Durable execution on Airflow before 3.3 needs [common.ai] 
durable_cache_path to be set, to say where its journal is kept. Example: 
durable_cache_path = file:///tmp/airflow_durable_cache
 
+For S3, the IAM role must also have ``s3:ListBucket`` permission on the 
bucket, in
+addition to permissions to read, write, and delete journal objects. Without
+``s3:ListBucket``, S3 returns ``403 Access Denied`` instead of ``404 Not 
Found``
+when the journal does not exist. This is treated as a storage read failure, so 
even
+the first task attempt fails. Read failures stop the attempt to avoid repeating
+completed LLM calls or tool operations when an existing journal cannot be read.
+They raise the original storage error, so Airflow retries them according to the
+task's configured retry policy.
+
+A corrupt journal also fails the task attempt and is left unchanged, but 
Airflow does
+not retry it. The ``path`` field on the ``Durable: journal is corrupt`` 
task-log warning
+names the file to inspect and restore before running the task again. Deleting 
it allows
+completed LLM calls and tool operations to run again.
+
 .. _durable-replay:
 
 How a retry replays
diff --git 
a/providers/common/ai/src/airflow/providers/common/ai/durable/storage.py 
b/providers/common/ai/src/airflow/providers/common/ai/durable/storage.py
index e566903a63d..bbf149f1d72 100644
--- a/providers/common/ai/src/airflow/providers/common/ai/durable/storage.py
+++ b/providers/common/ai/src/airflow/providers/common/ai/durable/storage.py
@@ -24,6 +24,7 @@ from collections.abc import Iterable
 from functools import lru_cache
 from typing import Any
 
+from airflow.providers.common.ai.exceptions import DurableJournalError
 from airflow.providers.common.ai.utils.task_logger import get_task_logger
 
 log = get_task_logger()
@@ -94,10 +95,25 @@ class DurableStorage:
         try:
             cache = json.loads(path.read_text())
             if not isinstance(cache, dict):
-                # JSON that is not an object holds no steps, just like a 
cut-off file.
+                # JSON that is not an object is as corrupt as a cut-off file.
                 raise ValueError("the journal file does not hold a JSON 
object")
-        except (FileNotFoundError, OSError, json.JSONDecodeError, ValueError):
+        except FileNotFoundError:
             cache = {}
+        except OSError:
+            log.warning(
+                "Durable: could not read the journal; failing this attempt so 
finished steps don't run again",
+                path=str(path),
+            )
+            raise
+        except (json.JSONDecodeError, UnicodeDecodeError, ValueError) as err:
+            log.warning(
+                "Durable: journal is corrupt; failing this attempt so finished 
steps don't run again",
+                path=str(path),
+            )
+            raise DurableJournalError(
+                "durable execution cannot replay a corrupt journal; inspect or 
restore the journal before retrying"
+            ) from err
+
         self._cache = cache
         return self._cache
 
@@ -141,18 +157,18 @@ class DurableStorage:
 
     def delete_steps(self, keys: Iterable[str]) -> None:
         """Remove these steps, and the journal file once nothing is left in 
it."""
-        cache = self._load_cache()
-        for key in keys:
-            cache.pop(key, None)
         # Runs after the run has already succeeded, so it must never raise; a 
file left
         # behind holds only steps a retry of this run would replay.
         try:
+            cache = self._load_cache()
+            for key in keys:
+                cache.pop(key, None)
             if cache:
                 self._write(json.dumps(cache))
             else:
                 self._get_path().unlink()
-                self._cache = None
+                self._cache = {}
         except FileNotFoundError:
-            self._cache = None
+            self._cache = {}
         except Exception:
             log.warning("Durable: could not clean up the journal file", 
exc_info=True)
diff --git a/providers/common/ai/tests/unit/common/ai/durable/test_storage.py 
b/providers/common/ai/tests/unit/common/ai/durable/test_storage.py
index 09ed9414cdf..bd513eccb65 100644
--- a/providers/common/ai/tests/unit/common/ai/durable/test_storage.py
+++ b/providers/common/ai/tests/unit/common/ai/durable/test_storage.py
@@ -25,6 +25,7 @@ from structlog.typing import FilteringBoundLogger
 from airflow.providers.common.ai.durable import storage as storage_module
 from airflow.providers.common.ai.durable.journal import DurableJournal
 from airflow.providers.common.ai.durable.storage import DurableStorage
+from airflow.providers.common.ai.exceptions import DurableJournalError
 from airflow.providers.common.compat.sdk import ObjectStoragePath
 
 from tests_common.test_utils.config import conf_vars
@@ -84,6 +85,17 @@ class TestSaveLoad:
     def test_missing_key_is_none(self, storage):
         assert storage.load_step("missing") is None
 
+    @patch.object(storage_module, "log", spec=FilteringBoundLogger)
+    @patch.object(ObjectStoragePath, "read_text", autospec=True, 
side_effect=OSError("S3 is unavailable"))
+    def 
test_a_storage_read_failure_stops_the_task_before_it_can_replay_live(self, _, 
mock_log, storage):
+        with pytest.raises(OSError, match="S3 is unavailable"):
+            storage.load_step("k")
+
+        mock_log.warning.assert_called_once_with(
+            "Durable: could not read the journal; failing this attempt so 
finished steps don't run again",
+            path=str(storage._get_path()),
+        )
+
     def 
test_an_entry_that_cannot_be_encoded_is_skipped_and_the_rest_kept(self, 
storage):
         circular: dict = {}
         circular["self"] = circular
@@ -108,6 +120,33 @@ class TestSaveLoad:
 
 
 class TestDeleteSteps:
+    @patch.object(storage_module, "log", spec=FilteringBoundLogger)
+    @patch.object(
+        DurableStorage,
+        "_load_cache",
+        autospec=True,
+        side_effect=DurableJournalError("the journal is corrupt"),
+    )
+    def test_a_corrupt_journal_does_not_make_cleanup_raise(self, _, mock_log, 
storage):
+        storage.delete_steps(["a"])
+
+        mock_log.warning.assert_called_once_with(
+            "Durable: could not clean up the journal file", exc_info=True
+        )
+
+    @pytest.mark.parametrize("journal_exists", [True, False])
+    @patch.object(ObjectStoragePath, "read_text", autospec=True, 
side_effect=OSError("S3 is unavailable"))
+    def test_saving_after_cleanup_does_not_read_storage(self, mock_read, 
storage, journal_exists):
+        storage._cache = {}
+        if journal_exists:
+            storage.save_step("a", ENTRY)
+
+        storage.delete_steps(["a"])
+
+        assert storage.save_step("b", ENTRY)
+        assert storage.load_step("b") == ENTRY
+        mock_read.assert_not_called()
+
     def test_deleting_the_last_steps_removes_the_file(self, storage, tmp_path):
         storage.save_step("a", ENTRY)
 
@@ -184,19 +223,32 @@ class TestStoreFailures:
 
 class TestJournalThatIsNotAnObject:
     @pytest.mark.parametrize(
-        "content",
+        ("content", "cause_type"),
         [
-            pytest.param(b"{truncated", id="cut off mid-write"),
-            pytest.param(b'["not", "a", "journal"]', id="a JSON list"),
-            pytest.param(b"null", id="JSON null"),
+            pytest.param(b"{truncated", json.JSONDecodeError, id="cut off 
mid-write"),
+            pytest.param(b'["not", "a", "journal"]', ValueError, id="a JSON 
list"),
+            pytest.param(b"null", ValueError, id="JSON null"),
+            pytest.param(b"\xff", UnicodeDecodeError, id="invalid encoding"),
         ],
     )
-    def test_is_handled_like_a_journal_cut_off_mid_write(self, storage, 
content):
-        storage._get_path().write_bytes(content)
+    @patch.object(storage_module, "log", spec=FilteringBoundLogger)
+    def test_is_not_treated_as_a_missing_journal(self, mock_log, storage, 
content, cause_type):
+        journal = storage._get_path()
+        journal.write_bytes(content)
+
+        with pytest.raises(DurableJournalError) as exc_info:
+            storage.load_step("k")
+        assert isinstance(exc_info.value.__cause__, cause_type)
+        mock_log.warning.assert_called_once_with(
+            "Durable: journal is corrupt; failing this attempt so finished 
steps don't run again",
+            path=str(journal),
+        )
 
-        assert storage.load_step("k") is None
-        assert storage.save_step("k", ENTRY)
-        assert storage.load_step("k") == ENTRY
+        with pytest.raises(DurableJournalError) as exc_info:
+            storage.save_step("k", ENTRY)
+        assert isinstance(exc_info.value.__cause__, cause_type)
+
+        assert journal.read_bytes() == content
 
 
 class TestMissingConfig:

Reply via email to