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

dabla 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 0237eacfa24 Fail closed in WASB log handler when existing-log read 
fails (#74996)
0237eacfa24 is described below

commit 0237eacfa24e2a77e3594f86db211f98595a837b
Author: Eric Del Orefice <[email protected]>
AuthorDate: Wed Nov 25 06:58:57 2026 -0800

    Fail closed in WASB log handler when existing-log read fails (#74996)
    
    * Fail closed in WASB log handler when existing-log read fails
    
    An append-mode upload reads the existing blob so it can upload old and new
    content together. When that read failed for a reason other than "blob not
    found" (a throttled request, a timeout, a network error), the failure was
    treated as an empty log, and the upload then replaced the blob with only the
    new content. The local copy is truncated after a successful upload, so the
    earlier part of the attempt log was lost from both places. Reschedule-mode
    sensors reuse one attempt log across many uploads, so one failed read can
    drop every earlier poke.
    
    The GCS handler already refuses to upload in this case (#67511). This brings
    the WASB handler to the same contract: keep the local log, return False, and
    let the next upload retry.
    
    * Read the existing WASB log once, treating not-found as empty
    
    Replace the check_for_blob HEAD plus read_file GET with a single read_file 
call that treats ResourceNotFoundError as no log yet, as the GCS handler does. 
Patch WasbHook with autospec in the write tests.
---
 .../microsoft/azure/log/wasb_task_handler.py       | 22 ++++-
 .../microsoft/azure/log/test_wasb_task_handler.py  | 97 +++++++++++++++++-----
 2 files changed, 95 insertions(+), 24 deletions(-)

diff --git 
a/providers/microsoft/azure/src/airflow/providers/microsoft/azure/log/wasb_task_handler.py
 
b/providers/microsoft/azure/src/airflow/providers/microsoft/azure/log/wasb_task_handler.py
index d00c9143bb3..5c5389c1507 100644
--- 
a/providers/microsoft/azure/src/airflow/providers/microsoft/azure/log/wasb_task_handler.py
+++ 
b/providers/microsoft/azure/src/airflow/providers/microsoft/azure/log/wasb_task_handler.py
@@ -26,7 +26,7 @@ from typing import TYPE_CHECKING
 from urllib.parse import urlsplit, urlunsplit
 
 import attrs
-from azure.core.exceptions import HttpResponseError
+from azure.core.exceptions import HttpResponseError, ResourceNotFoundError
 
 from airflow.providers.common.compat.sdk import conf
 from airflow.providers.microsoft.azure.version_compat import AIRFLOW_V_3_0_PLUS
@@ -229,10 +229,24 @@ class WasbRemoteLogIO(LoggingMixin):  # noqa: D101
         :param log: the log to write to the remote_log_location
         :param remote_log_location: the log's location in remote storage
         :param append: if False, any existing log file is overwritten. If True,
-            the new log is appended to any existing logs.
+            the new log is appended to any existing logs; if the existing log 
cannot be
+            read, nothing is written and ``False`` is returned.
         """
-        if append and self.wasb_log_exists(remote_log_location):
-            old_log = self.wasb_read(remote_log_location)
+        if append:
+            try:
+                old_log = self.hook.read_file(self.wasb_container, 
remote_log_location)
+            except ResourceNotFoundError:
+                old_log = ""
+            except Exception as e:
+                # Uploading only the new content here would replace the 
existing blob and lose the
+                # log history already stored in it. Keep the local log and let 
the next upload retry.
+                self.log.warning(
+                    "Refusing to overwrite remote log %s: could not read 
existing content (%s). "
+                    "Keeping local logs for later retry.",
+                    remote_log_location,
+                    e,
+                )
+                return False
             if old_log:
                 sep = "" if old_log.endswith("\n") else "\n"
                 log = f"{old_log}{sep}{log}"
diff --git 
a/providers/microsoft/azure/tests/unit/microsoft/azure/log/test_wasb_task_handler.py
 
b/providers/microsoft/azure/tests/unit/microsoft/azure/log/test_wasb_task_handler.py
index d4c9eab9272..746379cfb10 100644
--- 
a/providers/microsoft/azure/tests/unit/microsoft/azure/log/test_wasb_task_handler.py
+++ 
b/providers/microsoft/azure/tests/unit/microsoft/azure/log/test_wasb_task_handler.py
@@ -25,6 +25,7 @@ from unittest import mock
 
 import pytest
 from azure.common import AzureHttpError
+from azure.core.exceptions import HttpResponseError, ResourceNotFoundError
 
 from airflow.providers.common.compat.sdk import timezone
 from airflow.providers.microsoft.azure.hooks.wasb import WasbHook
@@ -313,23 +314,17 @@ class TestWasbTaskHandler:
         assert rec.message == "Could not read logs from 
remote/log/location/1.log"
         assert rec.exc_info is not None
 
-    @mock.patch("airflow.providers.microsoft.azure.hooks.wasb.WasbHook")
-    @mock.patch.object(WasbRemoteLogIO, "wasb_read")
-    @mock.patch.object(WasbRemoteLogIO, "wasb_log_exists")
-    def test_write_log(self, mock_log_exists, mock_wasb_read, mock_hook):
-        mock_log_exists.return_value = True
-        mock_wasb_read.return_value = ""
+    @mock.patch("airflow.providers.microsoft.azure.hooks.wasb.WasbHook", 
autospec=True)
+    def test_write_log(self, mock_hook):
+        mock_hook.return_value.read_file.return_value = ""
         self.wasb_task_handler.io.write("text", self.remote_log_location)
         mock_hook.return_value.load_string.assert_called_once_with(
             "text", self.container_name, self.remote_log_location, 
overwrite=True
         )
 
-    @mock.patch("airflow.providers.microsoft.azure.hooks.wasb.WasbHook")
-    @mock.patch.object(WasbRemoteLogIO, "wasb_read")
-    @mock.patch.object(WasbRemoteLogIO, "wasb_log_exists")
-    def test_write_on_existing_log(self, mock_log_exists, mock_wasb_read, 
mock_hook):
-        mock_log_exists.return_value = True
-        mock_wasb_read.return_value = "old log"
+    @mock.patch("airflow.providers.microsoft.azure.hooks.wasb.WasbHook", 
autospec=True)
+    def test_write_on_existing_log(self, mock_hook):
+        mock_hook.return_value.read_file.return_value = "old log"
         self.wasb_task_handler.io.write("text", self.remote_log_location)
         mock_hook.return_value.load_string.assert_called_once_with(
             "old log\ntext",
@@ -338,14 +333,9 @@ class TestWasbTaskHandler:
             overwrite=True,
         )
 
-    @mock.patch("airflow.providers.microsoft.azure.hooks.wasb.WasbHook")
-    @mock.patch.object(WasbRemoteLogIO, "wasb_read")
-    @mock.patch.object(WasbRemoteLogIO, "wasb_log_exists")
-    def test_write_on_existing_log_already_newline_terminated(
-        self, mock_log_exists, mock_wasb_read, mock_hook
-    ):
-        mock_log_exists.return_value = True
-        mock_wasb_read.return_value = "old log\n"
+    @mock.patch("airflow.providers.microsoft.azure.hooks.wasb.WasbHook", 
autospec=True)
+    def test_write_on_existing_log_already_newline_terminated(self, mock_hook):
+        mock_hook.return_value.read_file.return_value = "old log\n"
         self.wasb_task_handler.io.write("text", self.remote_log_location)
         mock_hook.return_value.load_string.assert_called_once_with(
             "old log\ntext",
@@ -354,6 +344,73 @@ class TestWasbTaskHandler:
             overwrite=True,
         )
 
+    @mock.patch("airflow.providers.microsoft.azure.hooks.wasb.WasbHook", 
autospec=True)
+    def test_write_refuses_to_overwrite_when_existing_log_cannot_be_read(self, 
mock_hook, caplog):
+        """A failed read of the existing log must not be uploaded over as if 
the log were empty."""
+        mock_hook.return_value.read_file.side_effect = HttpResponseError(
+            message="Operation could not be completed within the specified 
time. ErrorCode:ServerBusy"
+        )
+
+        with caplog.at_level(logging.WARNING):
+            assert self.wasb_task_handler.io.write("text", 
self.remote_log_location) is False
+
+        mock_hook.return_value.load_string.assert_not_called()
+        assert (
+            "Refusing to overwrite remote log remote/log/location/1.log: could 
not read existing content"
+            in caplog.text
+        )
+        assert "ServerBusy" in caplog.text
+
+    @mock.patch("airflow.providers.microsoft.azure.hooks.wasb.WasbHook", 
autospec=True)
+    def test_write_when_remote_log_does_not_exist(self, mock_hook):
+        mock_hook.return_value.read_file.side_effect = ResourceNotFoundError(
+            "The specified blob does not exist."
+        )
+
+        assert self.wasb_task_handler.io.write("text", 
self.remote_log_location) is True
+
+        mock_hook.return_value.load_string.assert_called_once_with(
+            "text", self.container_name, self.remote_log_location, 
overwrite=True
+        )
+
+    def 
test_upload_keeps_remote_and_local_log_when_existing_log_cannot_be_read(self, 
tmp_path):
+        """A transient read failure leaves both copies intact, and the next 
upload appends everything."""
+        blobs: dict[str, str] = {}
+        fail_reads = {"enabled": False}
+
+        class FakeHook:
+            def read_file(self, container, blob_name, **kwargs):
+                if fail_reads["enabled"]:
+                    raise HttpResponseError(message="ErrorCode:ServerBusy")
+                if blob_name not in blobs:
+                    raise ResourceNotFoundError("The specified blob does not 
exist.")
+                return blobs[blob_name]
+
+            def load_string(self, string_data, container, blob_name, **kwargs):
+                blobs[blob_name] = string_data
+
+        io = WasbRemoteLogIO(
+            remote_base="remote/log/location",
+            base_log_folder=str(tmp_path),
+            delete_local_copy=False,
+            wasb_container=self.container_name,
+        )
+        io.hook = FakeHook()
+        remote_key = "remote/log/location/attempt=1.log"
+        local_log = tmp_path / "attempt=1.log"
+
+        for cycle in range(1, 5):
+            fail_reads["enabled"] = cycle == 3
+            with open(local_log, "a") as f:
+                f.write(f"cycle {cycle}\n")
+            io.upload("attempt=1.log")
+            if cycle == 3:
+                assert blobs[remote_key] == "cycle 1\ncycle 2\n"
+                assert local_log.read_text() == "cycle 3\n"
+
+        assert blobs[remote_key] == "cycle 1\ncycle 2\ncycle 3\ncycle 4\n"
+        assert local_log.read_text() == ""
+
     def test_upload_repeated_appends_no_duplication(self, tmp_path):
         """Each execution lifecycle of one attempt appends to the same local 
log and uploads it."""
         blobs: dict[str, str] = {}

Reply via email to