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 1d7959a624f Detect when enhanced Power BI refreshes finish or fail 
(#74600)
1d7959a624f is described below

commit 1d7959a624fcab14907cadfed8e4b17d7e9eae54
Author: Omar Massfih <[email protected]>
AuthorDate: Sun Oct 25 23:00:20 2026 +0100

    Detect when enhanced Power BI refreshes finish or fail (#74600)
    
    * Fix enhanced Power BI refresh execution status
    
    * Prevent accidental cancellation of enhanced Power BI refreshes
    
    * Prevent null Power BI refresh details from cancelling refreshes
    
    * Use shared JSON loader for Power BI test fixture
    
    * Fix durable retries for enhanced Power BI refreshes
    
    A failed enhanced refresh can still appear active in history. Durable 
retries
    must use execution details to submit a fresh refresh after failure and avoid
    repeating already completed work.
    
    ---------
    
    Co-authored-by: Omar Massfih <[email protected]>
    Co-authored-by: David Blain <[email protected]>
---
 .../providers/microsoft/azure/hooks/powerbi.py     |  58 ++++++-
 .../providers/microsoft/azure/operators/powerbi.py |  17 +-
 .../unit/microsoft/azure/hooks/test_powerbi.py     | 191 ++++++++++++++++++++-
 .../unit/microsoft/azure/operators/test_powerbi.py |  95 ++++++++++
 .../azure/resources/powerbi_completed_refresh.json | 122 +++++++++++++
 .../azure/resources/powerbi_completed_refresh.md   |  36 ++++
 .../unit/microsoft/azure/triggers/test_powerbi.py  |  94 ++++++++++
 7 files changed, 603 insertions(+), 10 deletions(-)

diff --git 
a/providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/powerbi.py
 
b/providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/powerbi.py
index 3c2d006795e..3bdfe40bc7a 100644
--- 
a/providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/powerbi.py
+++ 
b/providers/microsoft/azure/src/airflow/providers/microsoft/azure/hooks/powerbi.py
@@ -33,6 +33,7 @@ class PowerBIDatasetRefreshFields(Enum):
     REQUEST_ID = "request_id"
     STATUS = "status"
     ERROR = "error"
+    REFRESH_TYPE = "refresh_type"
 
 
 class PowerBIDatasetRefreshStatus:
@@ -42,9 +43,12 @@ class PowerBIDatasetRefreshStatus:
     FAILED = "Failed"
     COMPLETED = "Completed"
     DISABLED = "Disabled"
+    TIMED_OUT = "TimedOut"
+    CANCELLED = "Cancelled"
 
-    TERMINAL_STATUSES = {FAILED, COMPLETED}
-    FAILURE_STATUSES = {FAILED, DISABLED}
+    TERMINAL_STATUSES = {FAILED, COMPLETED, DISABLED, TIMED_OUT, CANCELLED}
+    FAILURE_STATUSES = TERMINAL_STATUSES - {COMPLETED}
+    ACTIVE_EXTENDED_STATUSES = {"NotStarted", "InProgress"}
 
 
 class PowerBIDatasetRefreshException(AirflowException):
@@ -76,6 +80,7 @@ class PowerBIHook(KiotaRequestAdapterHook):
     conn_name_attr: str = "conn_id"
     default_conn_name: str = "powerbi_default"
     hook_name: str = "Power BI"
+    VIA_ENHANCED_API = "ViaEnhancedApi"
 
     def __init__(
         self,
@@ -148,16 +153,20 @@ class PowerBIHook(KiotaRequestAdapterHook):
         """
         Convert raw refresh details into a dictionary containing required 
fields.
 
+        Refresh history entries retain their type for execution-detail polling.
+
         :param refresh_details: Raw object of refresh details.
         """
         return {
             PowerBIDatasetRefreshFields.REQUEST_ID.value: 
str(refresh_details.get("requestId")),
             PowerBIDatasetRefreshFields.STATUS.value: (
-                "In Progress"
-                if str(refresh_details.get("status")) == "Unknown"
+                PowerBIDatasetRefreshStatus.IN_PROGRESS
+                if refresh_details.get("status")
+                in PowerBIDatasetRefreshStatus.ACTIVE_EXTENDED_STATUSES | 
{"Unknown"}
                 else str(refresh_details.get("status"))
             ),
             PowerBIDatasetRefreshFields.ERROR.value: 
str(refresh_details.get("serviceExceptionJson")),
+            PowerBIDatasetRefreshFields.REFRESH_TYPE.value: 
str(refresh_details.get("refreshType")),
         }
 
     async def get_refresh_details_by_refresh_id(
@@ -187,6 +196,47 @@ class PowerBIHook(KiotaRequestAdapterHook):
 
         refresh_details = refresh_histories[refresh_ids.index(refresh_id)]
 
+        if refresh_details.get(PowerBIDatasetRefreshFields.REFRESH_TYPE.value) 
== self.VIA_ENHANCED_API:
+            try:
+                execution_details = await self.run(
+                    
url="myorg/groups/{group_id}/datasets/{dataset_id}/refreshes/{refresh_id}",
+                    path_parameters={
+                        "group_id": group_id,
+                        "dataset_id": dataset_id,
+                        "refresh_id": refresh_id,
+                    },
+                )
+            except AirflowException as error:
+                raise PowerBIDatasetRefreshException(
+                    "Failed to retrieve refresh execution details"
+                ) from error
+            status = execution_details.get("extendedStatus")
+            if status not in (
+                PowerBIDatasetRefreshStatus.TERMINAL_STATUSES
+                | PowerBIDatasetRefreshStatus.ACTIVE_EXTENDED_STATUSES
+            ):
+                status = execution_details.get("status")
+            errors = [
+                message["message"]
+                for message in execution_details.get("messages") or []
+                if message.get("message") and message.get("type") != "Warning"
+            ]
+            if execution_details.get("serviceExceptionJson"):
+                errors.append(execution_details["serviceExceptionJson"])
+            errors.extend(
+                attempt["serviceExceptionJson"]
+                for attempt in execution_details.get("refreshAttempts") or []
+                if attempt.get("serviceExceptionJson")
+            )
+            return self.raw_to_refresh_details(
+                {
+                    "requestId": refresh_id,
+                    "status": status,
+                    "refreshType": 
refresh_details[PowerBIDatasetRefreshFields.REFRESH_TYPE.value],
+                    "serviceExceptionJson": "; ".join(errors) if errors else 
None,
+                }
+            )
+
         return refresh_details
 
     async def trigger_dataset_refresh(
diff --git 
a/providers/microsoft/azure/src/airflow/providers/microsoft/azure/operators/powerbi.py
 
b/providers/microsoft/azure/src/airflow/providers/microsoft/azure/operators/powerbi.py
index 01d416fe1bc..8ae2b979389 100644
--- 
a/providers/microsoft/azure/src/airflow/providers/microsoft/azure/operators/powerbi.py
+++ 
b/providers/microsoft/azure/src/airflow/providers/microsoft/azure/operators/powerbi.py
@@ -158,11 +158,18 @@ class PowerBIDatasetRefreshOperator(ResumableJobMixin, 
BaseOperator):
         refresh_histories = self.hook.run_sync(
             self.hook.get_refresh_history(dataset_id=self.dataset_id, 
group_id=self.group_id)
         )
-        for refresh_details in refresh_histories:
-            if refresh_details[PowerBIDatasetRefreshFields.REQUEST_ID.value] 
== external_id:
-                return 
refresh_details[PowerBIDatasetRefreshFields.STATUS.value]
-        # Power BI keeps a limited refresh history; a refresh that dropped out 
of it is not resumable.
-        return _REFRESH_NOT_IN_HISTORY
+        if not any(
+            details[PowerBIDatasetRefreshFields.REQUEST_ID.value] == 
external_id
+            for details in refresh_histories
+        ):
+            # Power BI keeps a limited refresh history; a refresh that dropped 
out of it is not resumable.
+            return _REFRESH_NOT_IN_HISTORY
+        refresh_details = self.hook.run_sync(
+            self.hook.get_refresh_details_by_refresh_id(
+                dataset_id=self.dataset_id, group_id=self.group_id, 
refresh_id=str(external_id)
+            )
+        )
+        return refresh_details[PowerBIDatasetRefreshFields.STATUS.value]
 
     def is_job_active(self, status: str) -> bool:
         return status == PowerBIDatasetRefreshStatus.IN_PROGRESS
diff --git 
a/providers/microsoft/azure/tests/unit/microsoft/azure/hooks/test_powerbi.py 
b/providers/microsoft/azure/tests/unit/microsoft/azure/hooks/test_powerbi.py
index b0569a84b35..d2d8bbe9202 100644
--- a/providers/microsoft/azure/tests/unit/microsoft/azure/hooks/test_powerbi.py
+++ b/providers/microsoft/azure/tests/unit/microsoft/azure/hooks/test_powerbi.py
@@ -16,6 +16,7 @@
 # under the License.
 from __future__ import annotations
 
+from os.path import dirname
 from unittest import mock
 
 import pytest
@@ -29,24 +30,29 @@ from airflow.providers.microsoft.azure.hooks.powerbi import 
(
     PowerBIHook,
 )
 
+from tests_common.test_utils.file_loading import load_json_from_resources
+
 FORMATTED_RESPONSE = [
     # Completed refresh
     {
         PowerBIDatasetRefreshFields.REQUEST_ID.value: 
"5e2d9921-e91b-491f-b7e1-e7d8db49194c",
         PowerBIDatasetRefreshFields.STATUS.value: 
PowerBIDatasetRefreshStatus.COMPLETED,
         PowerBIDatasetRefreshFields.ERROR.value: "None",
+        PowerBIDatasetRefreshFields.REFRESH_TYPE.value: "None",
     },
     # In-progress refresh
     {
         PowerBIDatasetRefreshFields.REQUEST_ID.value: 
"6b6536c1-cfcb-4148-9c21-402c3f5241e4",
         PowerBIDatasetRefreshFields.STATUS.value: 
PowerBIDatasetRefreshStatus.IN_PROGRESS,
         PowerBIDatasetRefreshFields.ERROR.value: "None",
+        PowerBIDatasetRefreshFields.REFRESH_TYPE.value: "None",
     },
     # Failed refresh
     {
         PowerBIDatasetRefreshFields.REQUEST_ID.value: 
"11bf290a-346b-48b7-8973-c5df149337ff",
         PowerBIDatasetRefreshFields.STATUS.value: 
PowerBIDatasetRefreshStatus.FAILED,
         PowerBIDatasetRefreshFields.ERROR.value: 
'{"errorCode":"ModelRefreshFailed_CredentialsNotSpecified"}',
+        PowerBIDatasetRefreshFields.REFRESH_TYPE.value: "None",
     },
 ]
 
@@ -56,6 +62,184 @@ DATASET_ID = "dataset_id"
 
 
 class TestPowerBIHook:
+    @pytest.mark.asyncio
+    @mock.patch.object(KiotaRequestAdapterHook, "run", autospec=True)
+    async def test_completed_enhanced_refresh_observation(self, mock_run, 
powerbi_hook):
+        fixture = load_json_from_resources(
+            dirname(__file__), "..", "resources", 
"powerbi_completed_refresh.json"
+        )
+        history = fixture["history"]
+        execution = fixture["execution"]
+        refresh_id = history["value"][0]["requestId"]
+        mock_run.side_effect = [history, execution]
+
+        result = await 
powerbi_hook.get_refresh_details_by_refresh_id(DATASET_ID, GROUP_ID, refresh_id)
+
+        assert result == {
+            "request_id": refresh_id,
+            "status": "Completed",
+            "error": "None",
+            "refresh_type": "ViaEnhancedApi",
+        }
+        assert mock_run.call_count == 2
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize(
+        ("message", "expected_error"),
+        [
+            ({"type": "Error", "code": "SyntheticMissingText"}, "None"),
+            ({"type": "Error", "message": None}, "None"),
+            ({"type": "Error", "message": ""}, "None"),
+            ({"type": "Warning", "message": "Synthetic warning"}, "None"),
+            ({"message": "Synthetic untyped error"}, "Synthetic untyped 
error"),
+            ({"type": "Error", "message": "Synthetic error"}, "Synthetic 
error"),
+        ],
+    )
+    @mock.patch.object(KiotaRequestAdapterHook, "run", autospec=True)
+    async def test_enhanced_refresh_optional_message_text(
+        self, mock_run, powerbi_hook, message, expected_error
+    ):
+        mock_run.side_effect = [
+            {"value": [{"requestId": "1234", "refreshType": "ViaEnhancedApi", 
"status": "Unknown"}]},
+            {"status": "Unknown", "extendedStatus": "Failed", "messages": 
[message]},
+        ]
+
+        result = await 
powerbi_hook.get_refresh_details_by_refresh_id(DATASET_ID, GROUP_ID, "1234")
+
+        assert result["status"] == "Failed"
+        assert result["error"] == expected_error
+
+    @pytest.mark.asyncio
+    @mock.patch.object(KiotaRequestAdapterHook, "run", autospec=True)
+    async def test_enhanced_refresh_execution_request_error(self, mock_run, 
powerbi_hook):
+        error = AirflowException("Synthetic request failure")
+        mock_run.side_effect = [
+            {"value": [{"requestId": "1234", "refreshType": "ViaEnhancedApi", 
"status": "Unknown"}]},
+            error,
+        ]
+
+        with pytest.raises(
+            PowerBIDatasetRefreshException, match="Failed to retrieve refresh 
execution details"
+        ) as exc:
+            await powerbi_hook.get_refresh_details_by_refresh_id(DATASET_ID, 
GROUP_ID, "1234")
+
+        assert exc.value.__cause__ is error
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize(
+        ("extended_status", "status", "expected_status"),
+        [
+            ("Failed", "Unknown", "Failed"),
+            ("Completed", "Unknown", "Completed"),
+            ("TimedOut", "Unknown", "TimedOut"),
+            ("Cancelled", "Unknown", "Cancelled"),
+            ("Disabled", "Unknown", "Disabled"),
+            ("InProgress", "Failed", "In Progress"),
+            ("NotStarted", "Unknown", "In Progress"),
+            (None, "Completed", "Completed"),
+            (None, "InProgress", "In Progress"),
+            (None, "NotStarted", "In Progress"),
+            ("", "Failed", "Failed"),
+            ("Unknown", "Failed", "Failed"),
+            ("Unknown", "Unknown", "In Progress"),
+            ("FutureStatus", "Unknown", "In Progress"),
+        ],
+    )
+    @mock.patch.object(KiotaRequestAdapterHook, "run", autospec=True)
+    async def test_enhanced_refresh_execution_status(
+        self, mock_run, powerbi_hook, extended_status, status, expected_status
+    ):
+        mock_run.side_effect = [
+            {
+                "value": [
+                    {"requestId": "other-refresh", "refreshType": 
"ViaEnhancedApi", "status": "Completed"},
+                    {"requestId": "submitted-refresh", "refreshType": 
"ViaEnhancedApi", "status": "Unknown"},
+                ]
+            },
+            {"status": status, "extendedStatus": extended_status},
+        ]
+
+        result = await powerbi_hook.get_refresh_details_by_refresh_id(
+            dataset_id=DATASET_ID, group_id=GROUP_ID, 
refresh_id="submitted-refresh"
+        )
+
+        assert result == {
+            "request_id": "submitted-refresh",
+            "status": expected_status,
+            "error": "None",
+            "refresh_type": "ViaEnhancedApi",
+        }
+        assert mock_run.call_count == 2
+        mock_run.assert_called_with(
+            powerbi_hook,
+            
url="myorg/groups/{group_id}/datasets/{dataset_id}/refreshes/{refresh_id}",
+            path_parameters={
+                "group_id": GROUP_ID,
+                "dataset_id": DATASET_ID,
+                "refresh_id": "submitted-refresh",
+            },
+        )
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize(
+        ("null_fields", "expected_errors"),
+        [
+            ((), ["Synthetic engine failure", "SyntheticRefreshError", 
"Synthetic attempt failure"]),
+            (("messages",), ["SyntheticRefreshError", "Synthetic attempt 
failure"]),
+            (("refreshAttempts",), ["Synthetic engine failure", 
"SyntheticRefreshError"]),
+            (("messages", "refreshAttempts"), ["SyntheticRefreshError"]),
+        ],
+    )
+    @mock.patch.object(KiotaRequestAdapterHook, "run", autospec=True)
+    async def test_enhanced_refresh_execution_errors(
+        self, mock_run, powerbi_hook, null_fields, expected_errors
+    ):
+        execution = {
+            "status": "Unknown",
+            "extendedStatus": "Failed",
+            "messages": [{"type": "Error", "message": "Synthetic engine 
failure"}],
+            "serviceExceptionJson": '{"errorCode":"SyntheticRefreshError"}',
+            "refreshAttempts": [
+                {"serviceExceptionJson": '{"errorDescription":"Synthetic 
attempt failure"}'},
+                {"attemptId": 2},
+            ],
+        }
+        for field in null_fields:
+            execution[field] = None
+        mock_run.side_effect = [
+            {"value": [{"requestId": "1234", "refreshType": "ViaEnhancedApi", 
"status": "Unknown"}]},
+            execution,
+        ]
+
+        result = await 
powerbi_hook.get_refresh_details_by_refresh_id(DATASET_ID, GROUP_ID, "1234")
+
+        assert result["status"] == "Failed"
+        errors = {
+            "Synthetic engine failure": "Synthetic engine failure",
+            "SyntheticRefreshError": '{"errorCode":"SyntheticRefreshError"}',
+            "Synthetic attempt failure": '{"errorDescription":"Synthetic 
attempt failure"}',
+        }
+        assert result["error"] == "; ".join(errors[error] for error in 
expected_errors)
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize("status", ["Unknown", "Completed", "Failed", 
"Disabled"])
+    @pytest.mark.parametrize("refresh_type", ["ViaApi", "OnDemand", 
"WebModeling", None])
+    @mock.patch.object(KiotaRequestAdapterHook, "run", autospec=True)
+    async def test_standard_refresh_uses_only_history(self, mock_run, 
powerbi_hook, status, refresh_type):
+        mock_run.return_value = {
+            "value": [{"requestId": "1234", "refreshType": refresh_type, 
"status": status}]
+        }
+
+        result = await 
powerbi_hook.get_refresh_details_by_refresh_id(DATASET_ID, GROUP_ID, "1234")
+
+        assert result == {
+            "request_id": "1234",
+            "status": "In Progress" if status == "Unknown" else status,
+            "error": "None",
+            "refresh_type": str(refresh_type),
+        }
+        mock_run.assert_called_once()
+
     @pytest.mark.asyncio
     async def test_get_refresh_history(self, powerbi_hook):
         response_data = {"value": [{"requestId": "1234", "status": 
"Completed", "serviceExceptionJson": ""}]}
@@ -64,7 +248,7 @@ class TestPowerBIHook:
             mock_run.return_value = response_data
             result = await powerbi_hook.get_refresh_history(DATASET_ID, 
GROUP_ID)
 
-            expected = [{"request_id": "1234", "status": "Completed", "error": 
""}]
+            expected = [{"request_id": "1234", "status": "Completed", "error": 
"", "refresh_type": "None"}]
             assert result == expected
 
     @pytest.mark.asyncio
@@ -86,6 +270,7 @@ class TestPowerBIHook:
                     PowerBIDatasetRefreshFields.REQUEST_ID.value: "1234",
                     PowerBIDatasetRefreshFields.STATUS.value: "Completed",
                     PowerBIDatasetRefreshFields.ERROR.value: "",
+                    PowerBIDatasetRefreshFields.REFRESH_TYPE.value: "None",
                 },
             ),
             (
@@ -94,6 +279,7 @@ class TestPowerBIHook:
                     PowerBIDatasetRefreshFields.REQUEST_ID.value: "5678",
                     PowerBIDatasetRefreshFields.STATUS.value: "In Progress",
                     PowerBIDatasetRefreshFields.ERROR.value: "Some error",
+                    PowerBIDatasetRefreshFields.REFRESH_TYPE.value: "None",
                 },
             ),
             (
@@ -102,6 +288,7 @@ class TestPowerBIHook:
                     PowerBIDatasetRefreshFields.REQUEST_ID.value: "None",
                     PowerBIDatasetRefreshFields.STATUS.value: "None",
                     PowerBIDatasetRefreshFields.ERROR.value: "None",
+                    PowerBIDatasetRefreshFields.REFRESH_TYPE.value: "None",
                 },
             ),
             (
@@ -110,6 +297,7 @@ class TestPowerBIHook:
                     PowerBIDatasetRefreshFields.REQUEST_ID.value: "None",
                     PowerBIDatasetRefreshFields.STATUS.value: "None",
                     PowerBIDatasetRefreshFields.ERROR.value: "None",
+                    PowerBIDatasetRefreshFields.REFRESH_TYPE.value: "None",
                 },
             ),
         ],
@@ -136,6 +324,7 @@ class TestPowerBIHook:
             PowerBIDatasetRefreshFields.REQUEST_ID.value: 
"5e2d9921-e91b-491f-b7e1-e7d8db49194c",
             PowerBIDatasetRefreshFields.STATUS.value: "Completed",
             PowerBIDatasetRefreshFields.ERROR.value: "None",
+            PowerBIDatasetRefreshFields.REFRESH_TYPE.value: "None",
         }
 
         # Call the function with an invalid request ID
diff --git 
a/providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_powerbi.py
 
b/providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_powerbi.py
index bda158c7329..5a0dcb781e0 100644
--- 
a/providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_powerbi.py
+++ 
b/providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_powerbi.py
@@ -23,6 +23,7 @@ from unittest.mock import MagicMock
 import pytest
 
 from airflow.providers.common.compat.sdk import AirflowException, BaseHook, 
TaskDeferred, timezone
+from airflow.providers.microsoft.azure.hooks.msgraph import 
KiotaRequestAdapterHook
 from airflow.providers.microsoft.azure.hooks.powerbi import (
     PowerBIDatasetRefreshException,
     PowerBIDatasetRefreshFields,
@@ -389,6 +390,100 @@ class TestPowerBIDatasetRefreshOperator:
         assert exc.value.trigger.dataset_refresh_id == NEW_REFRESH_REQUEST_ID
         assert task_state_store.values == {REFRESH_ID_KEY: 
NEW_REFRESH_REQUEST_ID}
 
+    @pytest.mark.skipif(not AIRFLOW_V_3_3_PLUS, reason="The task state store 
arrived in Airflow 3.3")
+    @pytest.mark.parametrize(
+        "execution_status",
+        ["Failed", "Completed", "InProgress", "NotStarted"],
+    )
+    @mock.patch.object(KiotaRequestAdapterHook, "run", autospec=True)
+    @mock.patch.object(
+        PowerBIHook, "trigger_dataset_refresh", autospec=True, 
return_value=NEW_REFRESH_REQUEST_ID
+    )
+    def test_execute_uses_enhanced_refresh_status(
+        self, mock_trigger_dataset_refresh, mock_run, execution_status
+    ):
+        history = {
+            "value": [
+                {
+                    "requestId": PREVIOUS_REFRESH_REQUEST_ID,
+                    "status": "Unknown",
+                    "refreshType": PowerBIHook.VIA_ENHANCED_API,
+                }
+            ]
+        }
+        mock_run.side_effect = [history, history, {"status": "Unknown", 
"extendedStatus": execution_status}]
+        operator = PowerBIDatasetRefreshOperator(**CONFIG)
+        task_state_store = TaskStateStore(**{REFRESH_ID_KEY: 
PREVIOUS_REFRESH_REQUEST_ID})
+        context = {
+            "ti": MagicMock(spec=["xcom_push", "stats_tags"], stats_tags={}),
+            "task_state_store": task_state_store,
+        }
+
+        if execution_status == "Completed":
+            assert operator.execute(context) is None
+            context["ti"].xcom_push.assert_any_call(
+                key=f"{TASK_ID}.powerbi_dataset_refresh_status", 
value=PowerBIDatasetRefreshStatus.COMPLETED
+            )
+        else:
+            with pytest.raises(TaskDeferred) as exc:
+                operator.execute(context)
+            assert exc.value.trigger.dataset_refresh_id == (
+                NEW_REFRESH_REQUEST_ID if execution_status == "Failed" else 
PREVIOUS_REFRESH_REQUEST_ID
+            )
+            assert exc.value.trigger.cancel_on_error is False
+
+        if execution_status == "Failed":
+            mock_trigger_dataset_refresh.assert_awaited_once_with(
+                operator.hook, dataset_id=DATASET_ID, group_id=GROUP_ID, 
request_body=REQUEST_BODY
+            )
+            assert task_state_store.values == {REFRESH_ID_KEY: 
NEW_REFRESH_REQUEST_ID}
+        else:
+            mock_trigger_dataset_refresh.assert_not_awaited()
+            assert task_state_store.values == {REFRESH_ID_KEY: 
PREVIOUS_REFRESH_REQUEST_ID}
+        assert mock_run.await_count == 3
+        mock_run.assert_awaited_with(
+            operator.hook,
+            
url="myorg/groups/{group_id}/datasets/{dataset_id}/refreshes/{refresh_id}",
+            path_parameters={
+                "group_id": GROUP_ID,
+                "dataset_id": DATASET_ID,
+                "refresh_id": PREVIOUS_REFRESH_REQUEST_ID,
+            },
+        )
+
+    @pytest.mark.skipif(not AIRFLOW_V_3_3_PLUS, reason="The task state store 
arrived in Airflow 3.3")
+    @mock.patch.object(KiotaRequestAdapterHook, "run", autospec=True)
+    @mock.patch.object(PowerBIHook, "trigger_dataset_refresh", autospec=True)
+    @mock.patch.object(PowerBIHook, "cancel_dataset_refresh", autospec=True)
+    def test_execute_preserves_refresh_when_execution_details_fail(
+        self, mock_cancel_dataset_refresh, mock_trigger_dataset_refresh, 
mock_run
+    ):
+        history = {
+            "value": [
+                {
+                    "requestId": PREVIOUS_REFRESH_REQUEST_ID,
+                    "status": "Unknown",
+                    "refreshType": PowerBIHook.VIA_ENHANCED_API,
+                }
+            ]
+        }
+        mock_run.side_effect = [history, history, AirflowException("Execution 
details unavailable")]
+        operator = PowerBIDatasetRefreshOperator(**CONFIG)
+        task_state_store = TaskStateStore(**{REFRESH_ID_KEY: 
PREVIOUS_REFRESH_REQUEST_ID})
+        context = {
+            "ti": MagicMock(spec=["xcom_push", "stats_tags"], stats_tags={}),
+            "task_state_store": task_state_store,
+        }
+
+        with pytest.raises(
+            PowerBIDatasetRefreshException, match="Failed to retrieve refresh 
execution details"
+        ):
+            operator.execute(context)
+
+        mock_trigger_dataset_refresh.assert_not_awaited()
+        mock_cancel_dataset_refresh.assert_not_awaited()
+        assert task_state_store.values == {REFRESH_ID_KEY: 
PREVIOUS_REFRESH_REQUEST_ID}
+
     @mock.patch.object(PowerBIHook, "trigger_dataset_refresh", 
return_value=NEW_REFRESH_REQUEST_ID)
     def test_execute_not_durable_starts_new_refresh_and_cancels_on_error(self, 
mock_trigger_dataset_refresh):
         operator = PowerBIDatasetRefreshOperator(**CONFIG, durable=False)
diff --git 
a/providers/microsoft/azure/tests/unit/microsoft/azure/resources/powerbi_completed_refresh.json
 
b/providers/microsoft/azure/tests/unit/microsoft/azure/resources/powerbi_completed_refresh.json
new file mode 100644
index 00000000000..1a574eabf19
--- /dev/null
+++ 
b/providers/microsoft/azure/tests/unit/microsoft/azure/resources/powerbi_completed_refresh.json
@@ -0,0 +1,122 @@
+{
+  "history": {
+    "@odata.context": 
"https://wabi-north-europe-h-primary-redirect.analysis.windows.net/v1.0/myorg/groups/00000000-0000-4000-8000-000000000001/$metadata#refreshes";,
+    "value": [
+      {
+        "requestId": "00000000-0000-4000-8000-000000000003",
+        "id": 1001,
+        "refreshType": "ViaEnhancedApi",
+        "startTime": "2026-10-12T14:09:43.34Z",
+        "endTime": "2026-10-12T14:09:46.763Z",
+        "status": "Completed",
+        "extendedStatus": "Completed",
+        "refreshAttempts": [
+          {
+            "attemptId": 1,
+            "startTime": "2026-10-12T14:09:43.9804475Z",
+            "endTime": "2026-10-12T14:09:46.7631279Z",
+            "type": "Data",
+            "executionMetrics": []
+          }
+        ]
+      },
+      {
+        "requestId": "00000000-0000-4000-8000-000000000004",
+        "id": 1002,
+        "refreshType": "OnDemand",
+        "startTime": "2026-10-12T13:34:26.643Z",
+        "endTime": "2026-10-12T13:34:29.503Z",
+        "status": "Completed",
+        "refreshAttempts": [
+          {
+            "attemptId": 1,
+            "startTime": "2026-10-12T13:34:26.6758493Z",
+            "endTime": "2026-10-12T13:34:28.6290889Z",
+            "type": "Data",
+            "executionMetrics": []
+          },
+          {
+            "attemptId": 1,
+            "startTime": "2026-10-12T13:34:28.8166028Z",
+            "endTime": "2026-10-12T13:34:29.0509883Z",
+            "type": "Query",
+            "executionMetrics": []
+          }
+        ]
+      },
+      {
+        "requestId": "00000000-0000-4000-8000-000000000005",
+        "id": 1003,
+        "refreshType": "WebModeling",
+        "startTime": "2026-10-12T13:30:56.287Z",
+        "endTime": "2026-10-12T13:31:01.023Z",
+        "status": "Completed",
+        "extendedStatus": "Completed",
+        "refreshAttempts": [
+          {
+            "attemptId": 1,
+            "startTime": "2026-10-12T13:30:56.6609601Z",
+            "endTime": "2026-10-12T13:31:01.0399565Z",
+            "type": "Data",
+            "executionMetrics": []
+          }
+        ]
+      }
+    ]
+  },
+  "execution": {
+    "startTime": "2026-10-12T14:09:43.34",
+    "endTime": "2026-10-12T14:09:46.763",
+    "type": "Full",
+    "commitMode": "Transactional",
+    "status": "Completed",
+    "extendedStatus": "Completed",
+    "currentRefreshType": "Full",
+    "numberOfAttempts": 1,
+    "objects": [
+      {"table": "ExampleTable", "partition": "ExampleTable", "status": 
"Completed"},
+      {
+        "table": "DateTableTemplate_00000000-0000-4000-8000-000000000006",
+        "partition": "DateTableTemplate_00000000-0000-4000-8000-000000000006",
+        "status": "Completed"
+      },
+      {
+        "table": "LocalDateTable_00000000-0000-4000-8000-000000000007",
+        "partition": "LocalDateTable_00000000-0000-4000-8000-000000000007",
+        "status": "Completed"
+      }
+    ],
+    "refreshAttempts": [
+      {
+        "attemptId": 1,
+        "startTime": "2026-10-12T14:09:43.9804475Z",
+        "endTime": "2026-10-12T14:09:46.7631279Z",
+        "type": "Data",
+        "executionMetrics": [
+          {
+            "timeStart": "2026-10-12T14:09:44.653Z",
+            "timeEnd": "2026-10-12T14:09:45.919Z",
+            "durationMs": 1266,
+            "externalQueryExecutionTimeMs": 32,
+            "vertipaqJobCpuTimeMs": 31,
+            "mEngineCpuTimeMs": 47,
+            "queryProcessingCpuTimeMs": 156,
+            "totalCpuTimeMs": 703,
+            "executionDelayMs": 19,
+            "approximatePeakMemConsumptionKB": 137951,
+            "mEnginePeakMemoryKB": 136228,
+            "tabularConnectionTimeoutMs": 17999000,
+            "commandType": "Batch",
+            "discoverType": 136,
+            "queryDialect": 4,
+            "refreshParallelism": 16,
+            "vertipaqTotalRows": 2563,
+            "intendedUsage": 2,
+            "qsoReplicaVersion": 1004
+          }
+        ]
+      }
+    ],
+    "initiatedBy": "ViaEnhancedApi"
+  }
+}
diff --git 
a/providers/microsoft/azure/tests/unit/microsoft/azure/resources/powerbi_completed_refresh.md
 
b/providers/microsoft/azure/tests/unit/microsoft/azure/resources/powerbi_completed_refresh.md
new file mode 100644
index 00000000000..cf656dac93a
--- /dev/null
+++ 
b/providers/microsoft/azure/tests/unit/microsoft/azure/resources/powerbi_completed_refresh.md
@@ -0,0 +1,36 @@
+<!--
+ 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.
+ -->
+
+<!-- SPDX-License-Identifier: Apache-2.0
+     https://www.apache.org/licenses/LICENSE-2.0 -->
+
+`powerbi_completed_refresh.json` contains sanitized response bodies from a
+user-supplied, post-completion observation on 2026-10-12. Both the refresh 
history
+and execution-details requests returned HTTP 200. The matching enhanced refresh
+has `status: Completed` and `extendedStatus: Completed` in both responses, with
+no engine messages or service exceptions.
+
+Workspace, request, history-entry, replica-version, and object identifiers are
+replaced consistently. Statuses, refresh types, timestamps, attempts, and other
+execution metrics are preserved. The dataset ID only appeared in the request
+URLs, which are not included in the fixture.
+
+This pair validates normal completion. It does not capture an active refresh,
+a failed refresh, or history remaining `Unknown` after execution becomes 
terminal.
+Those status-divergence and failure regressions use synthetic inputs.
diff --git 
a/providers/microsoft/azure/tests/unit/microsoft/azure/triggers/test_powerbi.py 
b/providers/microsoft/azure/tests/unit/microsoft/azure/triggers/test_powerbi.py
index d462ec9e6d6..f58c037ce9f 100644
--- 
a/providers/microsoft/azure/tests/unit/microsoft/azure/triggers/test_powerbi.py
+++ 
b/providers/microsoft/azure/tests/unit/microsoft/azure/triggers/test_powerbi.py
@@ -97,6 +97,100 @@ def powerbi_workspace_list_trigger(timeout=TIMEOUT) -> 
PowerBIWorkspaceListTrigg
 
 
 class TestPowerBITrigger:
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize("status", ["Completed", "Failed", "TimedOut", 
"Cancelled", "Disabled"])
+    @mock.patch.object(PowerBIHook, "run", autospec=True)
+    async def test_enhanced_refresh_terminal_event(self, mock_run, 
powerbi_trigger, status):
+        history = {
+            "value": [{"requestId": DATASET_REFRESH_ID, "refreshType": 
"ViaEnhancedApi", "status": "Unknown"}]
+        }
+        details = {
+            "status": "Unknown",
+            "extendedStatus": status,
+            "messages": [{"type": "Error", "message": "Synthetic engine 
message"}],
+            "serviceExceptionJson": '{"errorCode":"SyntheticRefreshError"}',
+        }
+        mock_run.side_effect = [history, details, history, details]
+
+        events = [event async for event in powerbi_trigger.run()]
+
+        assert len(events) == 1
+        assert events[0].payload["status"] == ("success" if status == 
"Completed" else "error")
+        assert events[0].payload["dataset_refresh_status"] == status
+        assert events[0].payload["dataset_refresh_id"] == DATASET_REFRESH_ID
+        if status != "Completed":
+            assert "Synthetic engine message" in events[0].payload["message"]
+            assert "SyntheticRefreshError" in events[0].payload["message"]
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize(
+        "null_fields", [(), ("messages",), ("refreshAttempts",), ("messages", 
"refreshAttempts")]
+    )
+    @pytest.mark.parametrize("status", ["InProgress", "NotStarted", "Unknown"])
+    @mock.patch.object(PowerBIHook, "cancel_dataset_refresh", autospec=True)
+    
@mock.patch("airflow.providers.microsoft.azure.triggers.powerbi.asyncio.sleep", 
autospec=True)
+    @mock.patch.object(PowerBIHook, "run", autospec=True)
+    async def test_enhanced_refresh_messages_do_not_end_polling(
+        self, mock_run, mock_sleep, mock_cancel, powerbi_trigger, status, 
null_fields
+    ):
+        history = {
+            "value": [{"requestId": DATASET_REFRESH_ID, "refreshType": 
"ViaEnhancedApi", "status": "Unknown"}]
+        }
+        active = {
+            "status": "Unknown",
+            "extendedStatus": status,
+            "messages": [
+                {"type": "Error", "message": "Synthetic retried attempt 
error"},
+                {"type": "Error", "code": "SyntheticMessageWithoutText"},
+            ],
+        }
+        for field in null_fields:
+            active[field] = None
+        mock_run.side_effect = [
+            history,
+            active,
+            history,
+            active,
+            history,
+            {"status": "Completed", "extendedStatus": "Completed"},
+        ]
+
+        events = [event async for event in powerbi_trigger.run()]
+
+        assert len(events) == 1
+        assert events[0].payload["status"] == "success"
+        assert events[0].payload["dataset_refresh_status"] == "Completed"
+        mock_sleep.assert_awaited_once_with(CHECK_INTERVAL)
+        mock_cancel.assert_not_awaited()
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize("status", ["Unknown", "NotStarted", "InProgress"])
+    
@mock.patch("airflow.providers.microsoft.azure.triggers.powerbi.time.monotonic",
 autospec=True)
+    
@mock.patch("airflow.providers.microsoft.azure.triggers.powerbi.asyncio.sleep", 
autospec=True)
+    @mock.patch.object(PowerBIHook, "run", autospec=True)
+    async def test_enhanced_refresh_active_times_out(
+        self, mock_run, mock_sleep, mock_monotonic, powerbi_trigger, status
+    ):
+        history = {
+            "value": [{"requestId": DATASET_REFRESH_ID, "refreshType": 
"ViaEnhancedApi", "status": "Unknown"}]
+        }
+        details = {"status": "Unknown", "extendedStatus": status}
+        mock_run.side_effect = [history, details, history, details]
+        mock_monotonic.return_value = 0
+
+        async def advance_clock(delay):
+            mock_monotonic.return_value = TIMEOUT + 1
+
+        mock_sleep.side_effect = advance_clock
+
+        events = [event async for event in powerbi_trigger.run()]
+
+        assert len(events) == 1
+        assert events[0].payload["status"] == "error"
+        assert events[0].payload["dataset_refresh_status"] == "In Progress"
+        assert "Timeout occurred" in events[0].payload["message"]
+        mock_sleep.assert_awaited_once_with(CHECK_INTERVAL)
+
     @mock.patch.object(PowerBIHook, "get_connection", 
side_effect=get_airflow_connection)
     def test_powerbi_trigger_serialization(self, connection):
         """Asserts that the PowerBI Trigger correctly serializes its arguments 
and classpath."""

Reply via email to