You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "aurangzaib048 (via GitHub)" <gi...@apache.org> on 2026/04/06 15:47:33 UTC
[PR] Fix EMR container job not cancelled on deferral timeout [airflow]
aurangzaib048 opened a new pull request, #64770:
URL: https://github.com/apache/airflow/pull/64770
When `EmrContainerOperator` runs in deferrable mode and the trigger
times out or the task is killed, the EMR job keeps running on the
cluster. This leads to orphaned jobs consuming resources and duplicate
executions on retry.
This PR adds cancel-on-kill support to `EmrContainerTrigger` following
the same proven pattern as `EmrServerlessStartJobTrigger` (PR #51883):
- Override `run()` in `EmrContainerTrigger` to catch
`asyncio.CancelledError` and cancel the EMR job via
`hook.stop_query()` when safe to do so
- Add `safe_to_cancel()` check to distinguish user-initiated kills
from triggerer restarts (avoids cancelling jobs during triggerer
restart)
- Add `cancel_on_kill` parameter (default `True`) for opt-out
- Update `EmrContainerOperator.execute_complete()` to cancel the job
when the trigger reports a failure/timeout event
- All cancellation paths are wrapped in try/except to ensure proper
error propagation (CancelledError is always re-raised, original
AirflowException is preserved)
closes: #60517
---
##### Was generative AI tooling used to co-author this PR?
- [ ] No
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3067095943
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,9 +199,131 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
- return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ return EmrContainerHook(aws_conn_id=self.aws_conn_id, virtual_cluster_id=self.virtual_cluster_id)
+
+ if not AIRFLOW_V_3_0_PLUS:
+
+ @provide_session
+ def get_task_instance(self, session: Session) -> TaskInstance:
+ """Get the task instance for the current trigger (Airflow 2.x compatibility)."""
+ query = select(TaskInstance).where(
+ TaskInstance.dag_id == self.task_instance.dag_id,
+ TaskInstance.task_id == self.task_instance.task_id,
+ TaskInstance.run_id == self.task_instance.run_id,
+ TaskInstance.map_index == self.task_instance.map_index,
+ )
+ task_instance = session.scalars(query).one_or_none()
+ if task_instance is None:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ )
+ return task_instance
+
+ async def get_task_state(self):
+ """Get the current state of the task instance (Airflow 3.x)."""
+ from airflow.sdk.execution_time.task_runner import RuntimeTaskInstance
+
+ task_states_response = await sync_to_async(RuntimeTaskInstance.get_task_states)(
+ dag_id=self.task_instance.dag_id,
+ task_ids=[self.task_instance.task_id],
+ run_ids=[self.task_instance.run_id],
+ map_index=self.task_instance.map_index,
+ )
+ try:
+ task_state = task_states_response[self.task_instance.run_id][self.task_instance.task_id]
+ except (KeyError, TypeError) as e:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ ) from e
+ return task_state
+
+ async def safe_to_cancel(self) -> bool:
+ """
+ Whether it is safe to cancel the EMR container job.
+
+ Returns True if task is NOT DEFERRED (user-initiated cancellation).
+ Returns False if task is DEFERRED (triggerer restart - don't cancel job).
+ """
+ if AIRFLOW_V_3_0_PLUS:
+ task_state = await self.get_task_state()
+ else:
+ task_instance = await sync_to_async(self.get_task_instance)() # type: ignore[call-arg]
+ task_state = task_instance.state
+ return task_state != TaskInstanceState.DEFERRED
+
+ async def run(self) -> AsyncIterator[TriggerEvent]:
+ """
+ Run the trigger and wait for the job to complete.
+
+ If the task is cancelled while waiting, attempt to cancel the EMR container job
+ if cancel_on_kill is enabled and it's safe to do so.
+ """
+ hook: EmrContainerHook = self.hook() # type: ignore[assignment]
+ try:
+ async with await hook.get_async_conn() as client:
+ waiter = hook.get_waiter(
+ self.waiter_name,
+ deferrable=True,
+ client=client,
+ config_overrides=self.waiter_config_overrides,
+ )
+ await async_wait(
+ waiter,
+ self.waiter_delay,
+ self.attempts,
+ self.waiter_args,
+ self.failure_message,
+ self.status_message,
+ self.status_queries,
+ )
+ yield TriggerEvent({"status": "success", self.return_key: self.return_value})
+ except asyncio.CancelledError:
+ try:
+ if self.job_id and self.cancel_on_kill and await self.safe_to_cancel():
+ self.log.info(
+ "Task was cancelled. Cancelling EMR container job. "
+ "Virtual Cluster ID: %s, Job ID: %s",
+ self.virtual_cluster_id,
+ self.job_id,
+ )
+ try:
+ await sync_to_async(hook.stop_query)(self.job_id)
+ self.log.info("EMR container job %s cancelled successfully.", self.job_id)
+ except Exception:
+ self.log.exception(
+ "Failed to cancel EMR container job %s. The job may still be running.",
+ self.job_id,
+ )
+ else:
+ self.log.info(
+ "Trigger may have shutdown or cancel_on_kill is disabled. "
+ "Skipping job cancellation. Virtual Cluster ID: %s, Job ID: %s",
+ self.virtual_cluster_id,
+ self.job_id,
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ self.log.exception(
+ "Error during cancellation check for EMR container job %s. The job may still be running.",
+ self.job_id,
+ )
+ raise
+ except AirflowException as e:
+ yield TriggerEvent({"status": "error", "message": str(e), self.return_key: self.return_value})
Review Comment:
`except AirflowException` and the following `except Exception` yield identical error events, so the first branch is redundant. Consider removing the `AirflowException` handler (or differentiate the payload) to reduce duplication and keep the trigger's error handling simpler.
```suggestion
```
##########
providers/amazon/tests/unit/amazon/aws/triggers/test_emr.py:
##########
@@ -152,8 +155,175 @@ def test_serialization_default_max_attempts(self):
"waiter_delay": 30,
"waiter_max_attempts": sys.maxsize,
"aws_conn_id": "aws_default",
+ "cancel_on_kill": True,
}
+ def test_serialization_includes_cancel_on_kill(self):
+ """Test that cancel_on_kill=True is correctly serialized."""
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+ classpath, kwargs = trigger.serialize()
+ assert classpath == "airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger"
+ assert kwargs["cancel_on_kill"] is True
+
Review Comment:
`test_serialization()` already asserts the default `cancel_on_kill=True` is serialized, so `test_serialization_includes_cancel_on_kill` is redundant. Consider removing it (keeping the `cancel_on_kill=False` serialization test) to avoid duplicate coverage.
```suggestion
```
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "aurangzaib048 (via GitHub)" <gi...@apache.org>.
aurangzaib048 commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3067088726
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,9 +197,133 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
- return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ return EmrContainerHook(aws_conn_id=self.aws_conn_id, virtual_cluster_id=self.virtual_cluster_id)
+
+ if not AIRFLOW_V_3_0_PLUS:
+
+ @provide_session
+ def get_task_instance(self, session: Session) -> TaskInstance:
+ """Get the task instance for the current trigger (Airflow 2.x compatibility)."""
+ from sqlalchemy import select
+
+ query = select(TaskInstance).where(
Review Comment:
Fixed. Moved `from sqlalchemy import select` to the module-level `if not AIRFLOW_V_3_0_PLUS:` block alongside the other conditional imports.
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,9 +197,133 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
- return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ return EmrContainerHook(aws_conn_id=self.aws_conn_id, virtual_cluster_id=self.virtual_cluster_id)
+
+ if not AIRFLOW_V_3_0_PLUS:
+
+ @provide_session
+ def get_task_instance(self, session: Session) -> TaskInstance:
+ """Get the task instance for the current trigger (Airflow 2.x compatibility)."""
+ from sqlalchemy import select
+
+ query = select(TaskInstance).where(
+ TaskInstance.dag_id == self.task_instance.dag_id,
+ TaskInstance.task_id == self.task_instance.task_id,
+ TaskInstance.run_id == self.task_instance.run_id,
+ TaskInstance.map_index == self.task_instance.map_index,
+ )
+ task_instance = session.scalars(query).one_or_none()
+ if task_instance is None:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ )
+ return task_instance
+
+ async def get_task_state(self):
+ """Get the current state of the task instance (Airflow 3.x)."""
+ from airflow.sdk.execution_time.task_runner import RuntimeTaskInstance
+
+ task_states_response = await sync_to_async(RuntimeTaskInstance.get_task_states)(
+ dag_id=self.task_instance.dag_id,
Review Comment:
This import is intentionally lazy — `RuntimeTaskInstance` is a heavy Task SDK import that should not be loaded at module level in the triggerer process (worker isolation boundary). Same pattern used in the reference `EmrServerlessStartJobTrigger`.
##########
providers/amazon/tests/unit/amazon/aws/triggers/test_emr.py:
##########
@@ -152,8 +154,179 @@ def test_serialization_default_max_attempts(self):
"waiter_delay": 30,
"waiter_max_attempts": sys.maxsize,
"aws_conn_id": "aws_default",
+ "cancel_on_kill": True,
}
+ def test_serialization_includes_cancel_on_kill(self):
+ """Test that cancel_on_kill=True is correctly serialized."""
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+ classpath, kwargs = trigger.serialize()
+ assert classpath == "airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger"
+ assert kwargs["cancel_on_kill"] is True
+
+ def test_serialization_cancel_on_kill_false(self):
+ """Test that cancel_on_kill=False is correctly serialized."""
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=False,
+ )
+ classpath, kwargs = trigger.serialize()
+ assert classpath == "airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger"
+ assert kwargs["cancel_on_kill"] is False
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger.safe_to_cancel")
+ async def test_run_cancels_job_on_killed_when_safe(self, mock_safe_to_cancel, mock_async_wait):
+ """
+ Test that EmrContainerTrigger cancels the job when task is killed
+ and safe_to_cancel returns True.
+ """
+ mock_safe_to_cancel.return_value = True
+ mock_async_wait.side_effect = asyncio.CancelledError()
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+ mock_hook.stop_query.return_value = {"ResponseMetadata": {"HTTPStatusCode": 200}}
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
Review Comment:
Fixed. All `MagicMock()` instances now use `spec=EmrContainerHook` to catch attribute typos.
##########
providers/amazon/tests/unit/amazon/aws/triggers/test_emr.py:
##########
@@ -152,8 +154,179 @@ def test_serialization_default_max_attempts(self):
"waiter_delay": 30,
"waiter_max_attempts": sys.maxsize,
"aws_conn_id": "aws_default",
+ "cancel_on_kill": True,
}
+ def test_serialization_includes_cancel_on_kill(self):
+ """Test that cancel_on_kill=True is correctly serialized."""
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+ classpath, kwargs = trigger.serialize()
+ assert classpath == "airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger"
+ assert kwargs["cancel_on_kill"] is True
+
+ def test_serialization_cancel_on_kill_false(self):
+ """Test that cancel_on_kill=False is correctly serialized."""
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=False,
+ )
+ classpath, kwargs = trigger.serialize()
+ assert classpath == "airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger"
+ assert kwargs["cancel_on_kill"] is False
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger.safe_to_cancel")
+ async def test_run_cancels_job_on_killed_when_safe(self, mock_safe_to_cancel, mock_async_wait):
+ """
+ Test that EmrContainerTrigger cancels the job when task is killed
+ and safe_to_cancel returns True.
+ """
+ mock_safe_to_cancel.return_value = True
+ mock_async_wait.side_effect = asyncio.CancelledError()
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+ mock_hook.stop_query.return_value = {"ResponseMetadata": {"HTTPStatusCode": 200}}
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
+ mock_async_cm.__aenter__ = mock.AsyncMock(return_value=mock_client)
+ mock_async_cm.__aexit__ = mock.AsyncMock(return_value=None)
+ mock_hook.get_async_conn = mock.AsyncMock(return_value=mock_async_cm)
+
+ with mock.patch.object(trigger, "hook", return_value=mock_hook):
+ with pytest.raises(asyncio.CancelledError):
+ async for _ in trigger.run():
+ pass
+
+ mock_hook.stop_query.assert_called_once_with("test_job")
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger.safe_to_cancel")
+ async def test_run_no_cancel_when_unsafe(self, mock_safe_to_cancel, mock_async_wait):
+ """
+ Test that EmrContainerTrigger does NOT cancel the job when
+ safe_to_cancel returns False (e.g., triggerer shutdown).
+ """
+ mock_safe_to_cancel.return_value = False
+ mock_async_wait.side_effect = asyncio.CancelledError()
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
+ mock_async_cm.__aenter__ = mock.AsyncMock(return_value=mock_client)
+ mock_async_cm.__aexit__ = mock.AsyncMock(return_value=None)
+ mock_hook.get_async_conn = mock.AsyncMock(return_value=mock_async_cm)
+
Review Comment:
Fixed in the same commit — all four async test methods now use specced mocks.
##########
providers/amazon/tests/unit/amazon/aws/triggers/test_emr.py:
##########
@@ -152,8 +154,179 @@ def test_serialization_default_max_attempts(self):
"waiter_delay": 30,
"waiter_max_attempts": sys.maxsize,
"aws_conn_id": "aws_default",
+ "cancel_on_kill": True,
}
+ def test_serialization_includes_cancel_on_kill(self):
+ """Test that cancel_on_kill=True is correctly serialized."""
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+ classpath, kwargs = trigger.serialize()
+ assert classpath == "airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger"
+ assert kwargs["cancel_on_kill"] is True
+
+ def test_serialization_cancel_on_kill_false(self):
+ """Test that cancel_on_kill=False is correctly serialized."""
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=False,
+ )
+ classpath, kwargs = trigger.serialize()
+ assert classpath == "airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger"
+ assert kwargs["cancel_on_kill"] is False
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger.safe_to_cancel")
+ async def test_run_cancels_job_on_killed_when_safe(self, mock_safe_to_cancel, mock_async_wait):
+ """
+ Test that EmrContainerTrigger cancels the job when task is killed
+ and safe_to_cancel returns True.
+ """
+ mock_safe_to_cancel.return_value = True
+ mock_async_wait.side_effect = asyncio.CancelledError()
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+ mock_hook.stop_query.return_value = {"ResponseMetadata": {"HTTPStatusCode": 200}}
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
+ mock_async_cm.__aenter__ = mock.AsyncMock(return_value=mock_client)
+ mock_async_cm.__aexit__ = mock.AsyncMock(return_value=None)
+ mock_hook.get_async_conn = mock.AsyncMock(return_value=mock_async_cm)
+
+ with mock.patch.object(trigger, "hook", return_value=mock_hook):
+ with pytest.raises(asyncio.CancelledError):
+ async for _ in trigger.run():
+ pass
+
+ mock_hook.stop_query.assert_called_once_with("test_job")
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger.safe_to_cancel")
+ async def test_run_no_cancel_when_unsafe(self, mock_safe_to_cancel, mock_async_wait):
+ """
+ Test that EmrContainerTrigger does NOT cancel the job when
+ safe_to_cancel returns False (e.g., triggerer shutdown).
+ """
+ mock_safe_to_cancel.return_value = False
+ mock_async_wait.side_effect = asyncio.CancelledError()
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
+ mock_async_cm.__aenter__ = mock.AsyncMock(return_value=mock_client)
+ mock_async_cm.__aexit__ = mock.AsyncMock(return_value=None)
+ mock_hook.get_async_conn = mock.AsyncMock(return_value=mock_async_cm)
+
+ with mock.patch.object(trigger, "hook", return_value=mock_hook):
+ with pytest.raises(asyncio.CancelledError):
+ async for _ in trigger.run():
+ pass
+
+ mock_hook.stop_query.assert_not_called()
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger.safe_to_cancel")
+ async def test_run_no_cancel_when_disabled(self, mock_safe_to_cancel, mock_async_wait):
+ """
+ Test that EmrContainerTrigger does NOT cancel the job when
+ cancel_on_kill=False.
+ """
+ mock_safe_to_cancel.return_value = True
+ mock_async_wait.side_effect = asyncio.CancelledError()
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=False,
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
+ mock_async_cm.__aenter__ = mock.AsyncMock(return_value=mock_client)
+ mock_async_cm.__aexit__ = mock.AsyncMock(return_value=None)
+ mock_hook.get_async_conn = mock.AsyncMock(return_value=mock_async_cm)
+
Review Comment:
Fixed — same change applied across all tests.
##########
providers/amazon/tests/unit/amazon/aws/triggers/test_emr.py:
##########
@@ -152,8 +154,179 @@ def test_serialization_default_max_attempts(self):
"waiter_delay": 30,
"waiter_max_attempts": sys.maxsize,
"aws_conn_id": "aws_default",
+ "cancel_on_kill": True,
}
+ def test_serialization_includes_cancel_on_kill(self):
+ """Test that cancel_on_kill=True is correctly serialized."""
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+ classpath, kwargs = trigger.serialize()
+ assert classpath == "airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger"
+ assert kwargs["cancel_on_kill"] is True
+
+ def test_serialization_cancel_on_kill_false(self):
+ """Test that cancel_on_kill=False is correctly serialized."""
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=False,
+ )
+ classpath, kwargs = trigger.serialize()
+ assert classpath == "airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger"
+ assert kwargs["cancel_on_kill"] is False
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger.safe_to_cancel")
+ async def test_run_cancels_job_on_killed_when_safe(self, mock_safe_to_cancel, mock_async_wait):
+ """
+ Test that EmrContainerTrigger cancels the job when task is killed
+ and safe_to_cancel returns True.
+ """
+ mock_safe_to_cancel.return_value = True
+ mock_async_wait.side_effect = asyncio.CancelledError()
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+ mock_hook.stop_query.return_value = {"ResponseMetadata": {"HTTPStatusCode": 200}}
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
+ mock_async_cm.__aenter__ = mock.AsyncMock(return_value=mock_client)
+ mock_async_cm.__aexit__ = mock.AsyncMock(return_value=None)
+ mock_hook.get_async_conn = mock.AsyncMock(return_value=mock_async_cm)
+
+ with mock.patch.object(trigger, "hook", return_value=mock_hook):
+ with pytest.raises(asyncio.CancelledError):
+ async for _ in trigger.run():
+ pass
+
+ mock_hook.stop_query.assert_called_once_with("test_job")
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger.safe_to_cancel")
+ async def test_run_no_cancel_when_unsafe(self, mock_safe_to_cancel, mock_async_wait):
+ """
+ Test that EmrContainerTrigger does NOT cancel the job when
+ safe_to_cancel returns False (e.g., triggerer shutdown).
+ """
+ mock_safe_to_cancel.return_value = False
+ mock_async_wait.side_effect = asyncio.CancelledError()
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
+ mock_async_cm.__aenter__ = mock.AsyncMock(return_value=mock_client)
+ mock_async_cm.__aexit__ = mock.AsyncMock(return_value=None)
+ mock_hook.get_async_conn = mock.AsyncMock(return_value=mock_async_cm)
+
+ with mock.patch.object(trigger, "hook", return_value=mock_hook):
+ with pytest.raises(asyncio.CancelledError):
+ async for _ in trigger.run():
+ pass
+
+ mock_hook.stop_query.assert_not_called()
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger.safe_to_cancel")
+ async def test_run_no_cancel_when_disabled(self, mock_safe_to_cancel, mock_async_wait):
+ """
+ Test that EmrContainerTrigger does NOT cancel the job when
+ cancel_on_kill=False.
+ """
+ mock_safe_to_cancel.return_value = True
+ mock_async_wait.side_effect = asyncio.CancelledError()
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=False,
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
+ mock_async_cm.__aenter__ = mock.AsyncMock(return_value=mock_client)
+ mock_async_cm.__aexit__ = mock.AsyncMock(return_value=None)
+ mock_hook.get_async_conn = mock.AsyncMock(return_value=mock_async_cm)
+
+ with mock.patch.object(trigger, "hook", return_value=mock_hook):
+ with pytest.raises(asyncio.CancelledError):
+ async for _ in trigger.run():
+ pass
+
+ mock_hook.stop_query.assert_not_called()
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ async def test_run_yields_error_on_airflow_exception(self, mock_async_wait):
+ """Test that an AirflowException yields an error TriggerEvent."""
+ mock_async_wait.side_effect = AirflowException("Something went wrong")
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
+ mock_async_cm.__aenter__ = mock.AsyncMock(return_value=mock_client)
+ mock_async_cm.__aexit__ = mock.AsyncMock(return_value=None)
+ mock_hook.get_async_conn = mock.AsyncMock(return_value=mock_async_cm)
+
Review Comment:
Fixed — all test mocks now specced consistently.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck merged PR #64770:
URL: https://github.com/apache/airflow/pull/64770
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "aurangzaib048 (via GitHub)" <gi...@apache.org>.
aurangzaib048 commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3122898348
##########
providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py:
##########
@@ -604,10 +610,19 @@ def check_failure(self, query_status):
def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str:
validated_event = validate_execute_complete_event(event)
- if validated_event["status"] != "success":
- raise AirflowException(f"Error while running job: {validated_event}")
-
- return validated_event["job_id"]
+ if validated_event["status"] == "success":
+ return validated_event["job_id"]
+ job_id = validated_event.get("job_id")
+ if job_id:
+ self.log.info("Cancelling EMR container job %s", job_id)
+ try:
+ self.hook.stop_query(job_id)
Review Comment:
Fixed in c0fc64c. Added `and self.cancel_on_kill` guard so cancellation in `execute_complete()` is skipped when `cancel_on_kill=False`, matching the trigger-side behavior.
##########
providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py:
##########
@@ -604,10 +610,19 @@ def check_failure(self, query_status):
def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str:
validated_event = validate_execute_complete_event(event)
- if validated_event["status"] != "success":
- raise AirflowException(f"Error while running job: {validated_event}")
-
- return validated_event["job_id"]
+ if validated_event["status"] == "success":
+ return validated_event["job_id"]
+ job_id = validated_event.get("job_id")
+ if job_id:
Review Comment:
Good point. Fixed in 88172f4 — `execute_complete` now only cancels on explicit `status == "error"` instead of an else branch, so any future trigger status won't silently fall into the cancel path.
##########
providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py:
##########
@@ -604,10 +610,19 @@ def check_failure(self, query_status):
def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str:
validated_event = validate_execute_complete_event(event)
- if validated_event["status"] != "success":
- raise AirflowException(f"Error while running job: {validated_event}")
-
- return validated_event["job_id"]
+ if validated_event["status"] == "success":
+ return validated_event["job_id"]
+ job_id = validated_event.get("job_id")
+ if job_id:
+ self.log.info("Cancelling EMR container job %s", job_id)
+ try:
+ self.hook.stop_query(job_id)
Review Comment:
Addressed in c0fc64c — `execute_complete` now respects `cancel_on_kill` before invoking `stop_query`.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "aurangzaib048 (via GitHub)" <gi...@apache.org>.
aurangzaib048 commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3122898942
##########
providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py:
##########
@@ -604,10 +610,19 @@ def check_failure(self, query_status):
def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str:
validated_event = validate_execute_complete_event(event)
- if validated_event["status"] != "success":
- raise AirflowException(f"Error while running job: {validated_event}")
-
- return validated_event["job_id"]
+ if validated_event["status"] == "success":
+ return validated_event["job_id"]
+ job_id = validated_event.get("job_id")
+ if job_id:
Review Comment:
Good point, `execute_complete` now only cancels on explicit `status == "error"` instead of an else branch, so any future trigger status won't silently fall into the cancel path.
##########
providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py:
##########
@@ -604,10 +610,19 @@ def check_failure(self, query_status):
def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str:
validated_event = validate_execute_complete_event(event)
- if validated_event["status"] != "success":
- raise AirflowException(f"Error while running job: {validated_event}")
-
- return validated_event["job_id"]
+ if validated_event["status"] == "success":
+ return validated_event["job_id"]
+ job_id = validated_event.get("job_id")
+ if job_id:
+ self.log.info("Cancelling EMR container job %s", job_id)
+ try:
+ self.hook.stop_query(job_id)
Review Comment:
Addressed in c0fc64c — `execute_complete` now respects `cancel_on_kill` before invoking `stop_query`.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3074900854
##########
providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py:
##########
@@ -604,10 +610,19 @@ def check_failure(self, query_status):
def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str:
validated_event = validate_execute_complete_event(event)
- if validated_event["status"] != "success":
- raise AirflowException(f"Error while running job: {validated_event}")
-
- return validated_event["job_id"]
+ if validated_event["status"] == "success":
+ return validated_event["job_id"]
+ job_id = validated_event.get("job_id")
+ if job_id:
+ self.log.info("Cancelling EMR container job %s", job_id)
+ try:
+ self.hook.stop_query(job_id)
Review Comment:
You seem to cancel the job regardless of `cancel_on_kill` value?
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "aurangzaib048 (via GitHub)" <gi...@apache.org>.
aurangzaib048 commented on PR #64770:
URL: https://github.com/apache/airflow/pull/64770#issuecomment-4388376524
Adopted the BaseTrigger.on_kill() pattern from #65590, this removed safe_to_cancel / get_task_state / get_task_instance from EmrContainerTrigger entirely.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "o-nikolas (via GitHub)" <gi...@apache.org>.
o-nikolas commented on PR #64770:
URL: https://github.com/apache/airflow/pull/64770#issuecomment-4330544975
> Something we might want to leverage? #65590
Yes, let's definitely make use of this if we can here!
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #64770:
URL: https://github.com/apache/airflow/pull/64770#issuecomment-4299452232
@aurangzaib048 Thanks for working through all the review feedback — every thread on the PR is resolved. This PR has a small issue that needs to be addressed before it can be reviewed — please see our [Pull Request quality criteria](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-quality-criteria).
**Issues found:**
- :x: **Pre-commit / static checks**: `CI image checks / Static checks` is failing. Run `prek run --from-ref main --stage pre-commit` locally, fix whatever it flags, and push.
**What to do next:**
- Make sure static checks pass locally: `prek run --from-ref main --stage pre-commit`.
- Once CI goes green, the PR is ready for re-review.
Leaving the PR open (not converting to draft) since you have clearly worked through the earlier reviewer feedback — all 20 review threads are resolved. Just this one CI fix left. There is no rush — take your time.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "aurangzaib048 (via GitHub)" <gi...@apache.org>.
aurangzaib048 commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3067057834
##########
providers/amazon/tests/unit/amazon/aws/operators/test_emr_containers.py:
##########
@@ -162,6 +162,19 @@ def test_operator_defer_with_timeout(self, mock_submit_job, mock_check_query_sta
assert trigger.waiter_delay == self.emr_container.poll_interval
assert trigger.attempts == self.emr_container.max_polling_attempts
+ @mock.patch.object(EmrContainerHook, "stop_query")
+ def test_execute_complete_cancels_job_on_failure(self, mock_stop_query):
+ self.emr_container.job_id = "test_job_id"
+ event = {"status": "error", "message": "Job timed out", "job_id": "test_job_id"}
+ with pytest.raises(AirflowException):
+ self.emr_container.execute_complete(context=None, event=event)
+ mock_stop_query.assert_called_once_with("test_job_id")
+
Review Comment:
Added `test_execute_complete_raises_original_error_when_cancel_fails`, mocks `stop_query` to raise and asserts the original `AirflowException` is still propagated.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "aurangzaib048 (via GitHub)" <gi...@apache.org>.
aurangzaib048 commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3067498382
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,9 +199,131 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
- return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ return EmrContainerHook(aws_conn_id=self.aws_conn_id, virtual_cluster_id=self.virtual_cluster_id)
+
+ if not AIRFLOW_V_3_0_PLUS:
+
+ @provide_session
+ def get_task_instance(self, session: Session) -> TaskInstance:
+ """Get the task instance for the current trigger (Airflow 2.x compatibility)."""
+ query = select(TaskInstance).where(
+ TaskInstance.dag_id == self.task_instance.dag_id,
+ TaskInstance.task_id == self.task_instance.task_id,
+ TaskInstance.run_id == self.task_instance.run_id,
+ TaskInstance.map_index == self.task_instance.map_index,
+ )
+ task_instance = session.scalars(query).one_or_none()
+ if task_instance is None:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ )
+ return task_instance
+
+ async def get_task_state(self):
+ """Get the current state of the task instance (Airflow 3.x)."""
+ from airflow.sdk.execution_time.task_runner import RuntimeTaskInstance
+
+ task_states_response = await sync_to_async(RuntimeTaskInstance.get_task_states)(
+ dag_id=self.task_instance.dag_id,
+ task_ids=[self.task_instance.task_id],
+ run_ids=[self.task_instance.run_id],
+ map_index=self.task_instance.map_index,
+ )
+ try:
+ task_state = task_states_response[self.task_instance.run_id][self.task_instance.task_id]
+ except (KeyError, TypeError) as e:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ ) from e
+ return task_state
+
+ async def safe_to_cancel(self) -> bool:
+ """
+ Whether it is safe to cancel the EMR container job.
+
+ Returns True if task is NOT DEFERRED (user-initiated cancellation).
+ Returns False if task is DEFERRED (triggerer restart - don't cancel job).
+ """
+ if AIRFLOW_V_3_0_PLUS:
+ task_state = await self.get_task_state()
+ else:
+ task_instance = await sync_to_async(self.get_task_instance)() # type: ignore[call-arg]
+ task_state = task_instance.state
+ return task_state != TaskInstanceState.DEFERRED
+
+ async def run(self) -> AsyncIterator[TriggerEvent]:
+ """
+ Run the trigger and wait for the job to complete.
+
+ If the task is cancelled while waiting, attempt to cancel the EMR container job
+ if cancel_on_kill is enabled and it's safe to do so.
+ """
+ hook: EmrContainerHook = self.hook() # type: ignore[assignment]
+ try:
+ async with await hook.get_async_conn() as client:
+ waiter = hook.get_waiter(
+ self.waiter_name,
+ deferrable=True,
+ client=client,
+ config_overrides=self.waiter_config_overrides,
+ )
+ await async_wait(
+ waiter,
+ self.waiter_delay,
+ self.attempts,
+ self.waiter_args,
+ self.failure_message,
+ self.status_message,
+ self.status_queries,
+ )
+ yield TriggerEvent({"status": "success", self.return_key: self.return_value})
+ except asyncio.CancelledError:
+ try:
+ if self.job_id and self.cancel_on_kill and await self.safe_to_cancel():
+ self.log.info(
+ "Task was cancelled. Cancelling EMR container job. "
+ "Virtual Cluster ID: %s, Job ID: %s",
+ self.virtual_cluster_id,
+ self.job_id,
+ )
+ try:
+ await sync_to_async(hook.stop_query)(self.job_id)
+ self.log.info("EMR container job %s cancelled successfully.", self.job_id)
+ except Exception:
+ self.log.exception(
+ "Failed to cancel EMR container job %s. The job may still be running.",
+ self.job_id,
+ )
+ else:
+ self.log.info(
+ "Trigger may have shutdown or cancel_on_kill is disabled. "
+ "Skipping job cancellation. Virtual Cluster ID: %s, Job ID: %s",
+ self.virtual_cluster_id,
+ self.job_id,
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ self.log.exception(
+ "Error during cancellation check for EMR container job %s. The job may still be running.",
+ self.job_id,
+ )
+ raise
+ except AirflowException as e:
+ yield TriggerEvent({"status": "error", "message": str(e), self.return_key: self.return_value})
Review Comment:
Good point. Merged both handlers into a single `except Exception` since they yield identical events. Also removed the now-unused `AirflowException` import.
##########
providers/amazon/tests/unit/amazon/aws/triggers/test_emr.py:
##########
@@ -152,8 +155,175 @@ def test_serialization_default_max_attempts(self):
"waiter_delay": 30,
"waiter_max_attempts": sys.maxsize,
"aws_conn_id": "aws_default",
+ "cancel_on_kill": True,
}
+ def test_serialization_includes_cancel_on_kill(self):
+ """Test that cancel_on_kill=True is correctly serialized."""
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+ classpath, kwargs = trigger.serialize()
+ assert classpath == "airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger"
+ assert kwargs["cancel_on_kill"] is True
+
Review Comment:
Agreed. Removed `test_serialization_includes_cancel_on_kill` — the existing `test_serialization` already asserts the default `cancel_on_kill=True`.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3073359387
##########
providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py:
##########
@@ -604,10 +610,19 @@ def check_failure(self, query_status):
def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str:
validated_event = validate_execute_complete_event(event)
- if validated_event["status"] != "success":
- raise AirflowException(f"Error while running job: {validated_event}")
-
- return validated_event["job_id"]
+ if validated_event["status"] == "success":
+ return validated_event["job_id"]
+ job_id = validated_event.get("job_id") or self.job_id
Review Comment:
Never use `self.job_id` in `execute_complete`. The worker/machine running `execute` and `execute_complete` could be very different, hence you should not assume `self.job_id` is defined
```suggestion
job_id = validated_event.get("job_id")
```
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3067509583
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,9 +198,129 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
- return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ return EmrContainerHook(aws_conn_id=self.aws_conn_id, virtual_cluster_id=self.virtual_cluster_id)
+
+ if not AIRFLOW_V_3_0_PLUS:
+
+ @provide_session
+ def get_task_instance(self, session: Session) -> TaskInstance:
+ """Get the task instance for the current trigger (Airflow 2.x compatibility)."""
+ query = select(TaskInstance).where(
+ TaskInstance.dag_id == self.task_instance.dag_id,
+ TaskInstance.task_id == self.task_instance.task_id,
+ TaskInstance.run_id == self.task_instance.run_id,
+ TaskInstance.map_index == self.task_instance.map_index,
+ )
+ task_instance = session.scalars(query).one_or_none()
+ if task_instance is None:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ )
+ return task_instance
+
+ async def get_task_state(self):
+ """Get the current state of the task instance (Airflow 3.x)."""
+ from airflow.sdk.execution_time.task_runner import RuntimeTaskInstance
+
+ task_states_response = await sync_to_async(RuntimeTaskInstance.get_task_states)(
+ dag_id=self.task_instance.dag_id,
+ task_ids=[self.task_instance.task_id],
+ run_ids=[self.task_instance.run_id],
+ map_index=self.task_instance.map_index,
+ )
+ try:
+ task_state = task_states_response[self.task_instance.run_id][self.task_instance.task_id]
Review Comment:
In Airflow 3.x, `RuntimeTaskInstance.get_task_states(..., map_index=...)` returns a mapping where mapped task instances use keys like `"{task_id}_{map_index}"` (see execution API `task_instances.get_task_instance_states`). This code always indexes with just `task_id`, so mapped tasks will raise `KeyError` and be treated as "not found", which prevents cancellation for mapped deferrable EMR container jobs. Update the lookup key to include `map_index` when `self.task_instance.map_index >= 0` (or adjust the API call/response handling accordingly).
```suggestion
task_instance_key = self.task_instance.task_id
if self.task_instance.map_index >= 0:
task_instance_key = f"{self.task_instance.task_id}_{self.task_instance.map_index}"
try:
task_state = task_states_response[self.task_instance.run_id][task_instance_key]
```
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "boring-cyborg[bot] (via GitHub)" <gi...@apache.org>.
boring-cyborg[bot] commented on PR #64770:
URL: https://github.com/apache/airflow/pull/64770#issuecomment-4398351101
Awesome work, congrats on your first merged pull request! You are invited to check our [Issue Tracker](https://github.com/apache/airflow/issues) for additional contributions.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3067064733
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,10 +197,134 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ if not AIRFLOW_V_3_0_PLUS:
+
+ @provide_session
+ def get_task_instance(self, session: Session) -> TaskInstance:
+ """Get the task instance for the current trigger (Airflow 2.x compatibility)."""
+ from sqlalchemy import select
+
+ query = select(TaskInstance).where(
+ TaskInstance.dag_id == self.task_instance.dag_id,
+ TaskInstance.task_id == self.task_instance.task_id,
+ TaskInstance.run_id == self.task_instance.run_id,
+ TaskInstance.map_index == self.task_instance.map_index,
+ )
+ task_instance = session.scalars(query).one_or_none()
+ if task_instance is None:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ )
+ return task_instance
+
+ async def get_task_state(self):
+ """Get the current state of the task instance (Airflow 3.x)."""
+ from airflow.sdk.execution_time.task_runner import RuntimeTaskInstance
+
+ task_states_response = await sync_to_async(RuntimeTaskInstance.get_task_states)(
+ dag_id=self.task_instance.dag_id,
+ task_ids=[self.task_instance.task_id],
+ run_ids=[self.task_instance.run_id],
+ map_index=self.task_instance.map_index,
+ )
+ try:
+ task_state = task_states_response[self.task_instance.run_id][self.task_instance.task_id]
+ except (KeyError, TypeError) as e:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ ) from e
+ return task_state
+
+ async def safe_to_cancel(self) -> bool:
+ """
+ Whether it is safe to cancel the EMR container job.
+
+ Returns True if task is NOT DEFERRED (user-initiated cancellation).
+ Returns False if task is DEFERRED (triggerer restart - don't cancel job).
+ """
+ if AIRFLOW_V_3_0_PLUS:
+ task_state = await self.get_task_state()
+ else:
+ task_instance = await sync_to_async(self.get_task_instance)() # type: ignore[call-arg]
+ task_state = task_instance.state
+ return task_state != TaskInstanceState.DEFERRED
+
+ async def run(self) -> AsyncIterator[TriggerEvent]:
+ """
+ Run the trigger and wait for the job to complete.
+
+ If the task is cancelled while waiting, attempt to cancel the EMR container job
+ if cancel_on_kill is enabled and it's safe to do so.
+ """
+ hook: EmrContainerHook = self.hook() # type: ignore[assignment]
+ try:
+ async with await hook.get_async_conn() as client:
+ waiter = hook.get_waiter(
+ self.waiter_name,
Review Comment:
`EmrContainerHook.stop_query()` requires `virtual_cluster_id` (it calls `cancel_job_run(virtualClusterId=self.virtual_cluster_id, ...)`), but this trigger builds the hook via `self.hook()` which currently passes only `aws_conn_id`. As a result, the new cancel-on-kill path will call the EMR Containers API with `virtualClusterId=None` and fail to cancel the job. Update `hook()` (or the instantiation here) to pass `virtual_cluster_id=self.virtual_cluster_id` so cancellation works.
##########
providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py:
##########
@@ -604,10 +610,18 @@ def check_failure(self, query_status):
def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str:
validated_event = validate_execute_complete_event(event)
- if validated_event["status"] != "success":
- raise AirflowException(f"Error while running job: {validated_event}")
-
- return validated_event["job_id"]
+ if validated_event["status"] == "success":
+ return validated_event["job_id"]
+ if self.job_id:
+ self.log.info("Cancelling EMR container job %s", self.job_id)
+ try:
+ self.hook.stop_query(self.job_id)
+ except Exception:
+ self.log.exception(
+ "Failed to cancel EMR container job %s. The job may still be running.",
+ self.job_id,
Review Comment:
In deferrable mode the operator instance is reconstructed on resume, so runtime fields like `self.job_id` may be `None` in `execute_complete`. This new cancellation logic uses `self.job_id`, which can skip cancellation even though the trigger event contains the real `job_id`. Use `validated_event["job_id"]` (and/or persist `job_id` explicitly) when cancelling so deferral timeout/failure reliably cancels the correct EMR job.
```suggestion
job_id = validated_event.get("job_id") or self.job_id
if job_id:
self.log.info("Cancelling EMR container job %s", job_id)
try:
self.hook.stop_query(job_id)
except Exception:
self.log.exception(
"Failed to cancel EMR container job %s. The job may still be running.",
job_id,
```
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "aurangzaib048 (via GitHub)" <gi...@apache.org>.
aurangzaib048 commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3067057016
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,10 +197,132 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ if not AIRFLOW_V_3_0_PLUS:
+
+ @provide_session
+ def get_task_instance(self, session: Session) -> TaskInstance:
+ """Get the task instance for the current trigger (Airflow 2.x compatibility)."""
+ from sqlalchemy import select
+
+ query = select(TaskInstance).where(
+ TaskInstance.dag_id == self.task_instance.dag_id,
+ TaskInstance.task_id == self.task_instance.task_id,
+ TaskInstance.run_id == self.task_instance.run_id,
+ TaskInstance.map_index == self.task_instance.map_index,
+ )
+ task_instance = session.scalars(query).one_or_none()
+ if task_instance is None:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ )
+ return task_instance
+
+ async def get_task_state(self):
+ """Get the current state of the task instance (Airflow 3.x)."""
+ from airflow.sdk.execution_time.task_runner import RuntimeTaskInstance
+
+ task_states_response = await sync_to_async(RuntimeTaskInstance.get_task_states)(
+ dag_id=self.task_instance.dag_id,
+ task_ids=[self.task_instance.task_id],
+ run_ids=[self.task_instance.run_id],
+ map_index=self.task_instance.map_index,
+ )
+ try:
+ task_state = task_states_response[self.task_instance.run_id][self.task_instance.task_id]
+ except (KeyError, TypeError) as e:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ ) from e
+ return task_state
+
+ async def safe_to_cancel(self) -> bool:
+ """
+ Whether it is safe to cancel the EMR container job.
+
+ Returns True if task is NOT DEFERRED (user-initiated cancellation).
+ Returns False if task is DEFERRED (triggerer restart - don't cancel job).
+ """
+ if AIRFLOW_V_3_0_PLUS:
+ task_state = await self.get_task_state()
+ else:
+ task_instance = self.get_task_instance() # type: ignore[call-arg]
+ task_state = task_instance.state
+ return task_state != TaskInstanceState.DEFERRED
+
+ async def run(self) -> AsyncIterator[TriggerEvent]:
+ """
+ Run the trigger and wait for the job to complete.
+
+ If the task is cancelled while waiting, attempt to cancel the EMR container job
+ if cancel_on_kill is enabled and it's safe to do so.
+ """
+ hook: EmrContainerHook = self.hook() # type: ignore[assignment]
+ try:
+ async with await hook.get_async_conn() as client:
+ waiter = hook.get_waiter(
+ self.waiter_name,
+ deferrable=True,
+ client=client,
+ config_overrides=self.waiter_config_overrides,
+ )
+ await async_wait(
+ waiter,
+ self.waiter_delay,
+ self.attempts,
+ self.waiter_args,
+ self.failure_message,
+ self.status_message,
+ self.status_queries,
+ )
+ yield TriggerEvent({"status": "success", self.return_key: self.return_value})
+ except asyncio.CancelledError:
+ try:
+ if self.job_id and self.cancel_on_kill and await self.safe_to_cancel():
+ self.log.info(
+ "Task was cancelled. Cancelling EMR container job. "
+ "Virtual Cluster ID: %s, Job ID: %s",
+ self.virtual_cluster_id,
+ self.job_id,
+ )
+ try:
+ hook.stop_query(self.job_id)
Review Comment:
Addressed together with the previous comment — both sync calls now go through `sync_to_async`.
##########
providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py:
##########
@@ -567,13 +567,15 @@ def execute(self, context: Context) -> str | None:
aws_conn_id=self.aws_conn_id,
waiter_delay=self.poll_interval,
waiter_max_attempts=self.max_polling_attempts,
+ cancel_on_kill=True,
)
if self.max_polling_attempts
else EmrContainerTrigger(
virtual_cluster_id=self.virtual_cluster_id,
job_id=self.job_id,
aws_conn_id=self.aws_conn_id,
waiter_delay=self.poll_interval,
+ cancel_on_kill=True,
),
Review Comment:
Good point. Added `cancel_on_kill: bool = True` parameter to `EmrContainerOperator` and pass it through to the trigger, so users can opt out with `cancel_on_kill=False`.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3124747034
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,9 +198,132 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
- return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ return EmrContainerHook(aws_conn_id=self.aws_conn_id, virtual_cluster_id=self.virtual_cluster_id)
+
+ if not AIRFLOW_V_3_0_PLUS:
Review Comment:
We usually do not do that, do not define a method only if Airflow version is XXX. Define it regardless, you might use it only for a given set of versions but defining methods conditionally feels wrong to me.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "o-nikolas (via GitHub)" <gi...@apache.org>.
o-nikolas commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3096872099
##########
providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py:
##########
@@ -604,10 +610,19 @@ def check_failure(self, query_status):
def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str:
validated_event = validate_execute_complete_event(event)
- if validated_event["status"] != "success":
- raise AirflowException(f"Error while running job: {validated_event}")
-
- return validated_event["job_id"]
+ if validated_event["status"] == "success":
+ return validated_event["job_id"]
+ job_id = validated_event.get("job_id")
+ if job_id:
Review Comment:
Also we look for the state success above, but attempt to cancel on every other possible status. In the future another status might get swallowed into this path? I wonder if we should make it more explicit.
##########
providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py:
##########
@@ -604,10 +610,19 @@ def check_failure(self, query_status):
def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str:
validated_event = validate_execute_complete_event(event)
- if validated_event["status"] != "success":
- raise AirflowException(f"Error while running job: {validated_event}")
-
- return validated_event["job_id"]
+ if validated_event["status"] == "success":
+ return validated_event["job_id"]
+ job_id = validated_event.get("job_id")
+ if job_id:
+ self.log.info("Cancelling EMR container job %s", job_id)
+ try:
+ self.hook.stop_query(job_id)
Review Comment:
+1
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "aurangzaib048 (via GitHub)" <gi...@apache.org>.
aurangzaib048 commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3067964843
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,9 +198,129 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
- return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ return EmrContainerHook(aws_conn_id=self.aws_conn_id, virtual_cluster_id=self.virtual_cluster_id)
+
+ if not AIRFLOW_V_3_0_PLUS:
+
+ @provide_session
+ def get_task_instance(self, session: Session) -> TaskInstance:
+ """Get the task instance for the current trigger (Airflow 2.x compatibility)."""
+ query = select(TaskInstance).where(
+ TaskInstance.dag_id == self.task_instance.dag_id,
+ TaskInstance.task_id == self.task_instance.task_id,
+ TaskInstance.run_id == self.task_instance.run_id,
+ TaskInstance.map_index == self.task_instance.map_index,
+ )
+ task_instance = session.scalars(query).one_or_none()
+ if task_instance is None:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ )
+ return task_instance
+
+ async def get_task_state(self):
+ """Get the current state of the task instance (Airflow 3.x)."""
+ from airflow.sdk.execution_time.task_runner import RuntimeTaskInstance
+
+ task_states_response = await sync_to_async(RuntimeTaskInstance.get_task_states)(
+ dag_id=self.task_instance.dag_id,
+ task_ids=[self.task_instance.task_id],
+ run_ids=[self.task_instance.run_id],
+ map_index=self.task_instance.map_index,
+ )
+ try:
+ task_state = task_states_response[self.task_instance.run_id][self.task_instance.task_id]
Review Comment:
Valid observation, but this is a pre-existing pattern, the reference `EmrServerlessStartJobTrigger.get_task_state()` has the identical lookup. Fixing this for mapped tasks would be a separate improvement across all triggers that use this pattern. Our `except (KeyError, TypeError)` already handles this gracefully by logging the error rather than crashing.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "aurangzaib048 (via GitHub)" <gi...@apache.org>.
aurangzaib048 commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3067964843
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,9 +198,129 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
- return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ return EmrContainerHook(aws_conn_id=self.aws_conn_id, virtual_cluster_id=self.virtual_cluster_id)
+
+ if not AIRFLOW_V_3_0_PLUS:
+
+ @provide_session
+ def get_task_instance(self, session: Session) -> TaskInstance:
+ """Get the task instance for the current trigger (Airflow 2.x compatibility)."""
+ query = select(TaskInstance).where(
+ TaskInstance.dag_id == self.task_instance.dag_id,
+ TaskInstance.task_id == self.task_instance.task_id,
+ TaskInstance.run_id == self.task_instance.run_id,
+ TaskInstance.map_index == self.task_instance.map_index,
+ )
+ task_instance = session.scalars(query).one_or_none()
+ if task_instance is None:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ )
+ return task_instance
+
+ async def get_task_state(self):
+ """Get the current state of the task instance (Airflow 3.x)."""
+ from airflow.sdk.execution_time.task_runner import RuntimeTaskInstance
+
+ task_states_response = await sync_to_async(RuntimeTaskInstance.get_task_states)(
+ dag_id=self.task_instance.dag_id,
+ task_ids=[self.task_instance.task_id],
+ run_ids=[self.task_instance.run_id],
+ map_index=self.task_instance.map_index,
+ )
+ try:
+ task_state = task_states_response[self.task_instance.run_id][self.task_instance.task_id]
Review Comment:
Valid observation, but this is a pre-existing pattern — the reference `EmrServerlessStartJobTrigger.get_task_state()` has the identical lookup. Fixing this for mapped tasks would be a separate improvement across all triggers that use this pattern. Our `except (KeyError, TypeError)` already handles this gracefully by logging the error rather than crashing.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3067080788
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,9 +197,133 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
- return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ return EmrContainerHook(aws_conn_id=self.aws_conn_id, virtual_cluster_id=self.virtual_cluster_id)
+
+ if not AIRFLOW_V_3_0_PLUS:
+
+ @provide_session
+ def get_task_instance(self, session: Session) -> TaskInstance:
+ """Get the task instance for the current trigger (Airflow 2.x compatibility)."""
+ from sqlalchemy import select
+
+ query = select(TaskInstance).where(
Review Comment:
Imports are being done inside method bodies (`from sqlalchemy import select`). Per Airflow codebase guidelines, imports should be at module scope unless there is a strong circular/lazy-load reason. Consider moving this import to the existing `if not AIRFLOW_V_3_0_PLUS:` module-level block to avoid repeated imports and keep import behavior consistent.
##########
providers/amazon/tests/unit/amazon/aws/triggers/test_emr.py:
##########
@@ -152,8 +154,179 @@ def test_serialization_default_max_attempts(self):
"waiter_delay": 30,
"waiter_max_attempts": sys.maxsize,
"aws_conn_id": "aws_default",
+ "cancel_on_kill": True,
}
+ def test_serialization_includes_cancel_on_kill(self):
+ """Test that cancel_on_kill=True is correctly serialized."""
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+ classpath, kwargs = trigger.serialize()
+ assert classpath == "airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger"
+ assert kwargs["cancel_on_kill"] is True
+
+ def test_serialization_cancel_on_kill_false(self):
+ """Test that cancel_on_kill=False is correctly serialized."""
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=False,
+ )
+ classpath, kwargs = trigger.serialize()
+ assert classpath == "airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger"
+ assert kwargs["cancel_on_kill"] is False
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger.safe_to_cancel")
+ async def test_run_cancels_job_on_killed_when_safe(self, mock_safe_to_cancel, mock_async_wait):
+ """
+ Test that EmrContainerTrigger cancels the job when task is killed
+ and safe_to_cancel returns True.
+ """
+ mock_safe_to_cancel.return_value = True
+ mock_async_wait.side_effect = asyncio.CancelledError()
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+ mock_hook.stop_query.return_value = {"ResponseMetadata": {"HTTPStatusCode": 200}}
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
+ mock_async_cm.__aenter__ = mock.AsyncMock(return_value=mock_client)
+ mock_async_cm.__aexit__ = mock.AsyncMock(return_value=None)
+ mock_hook.get_async_conn = mock.AsyncMock(return_value=mock_async_cm)
+
+ with mock.patch.object(trigger, "hook", return_value=mock_hook):
+ with pytest.raises(asyncio.CancelledError):
+ async for _ in trigger.run():
+ pass
+
+ mock_hook.stop_query.assert_called_once_with("test_job")
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger.safe_to_cancel")
+ async def test_run_no_cancel_when_unsafe(self, mock_safe_to_cancel, mock_async_wait):
+ """
+ Test that EmrContainerTrigger does NOT cancel the job when
+ safe_to_cancel returns False (e.g., triggerer shutdown).
+ """
+ mock_safe_to_cancel.return_value = False
+ mock_async_wait.side_effect = asyncio.CancelledError()
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
+ mock_async_cm.__aenter__ = mock.AsyncMock(return_value=mock_client)
+ mock_async_cm.__aexit__ = mock.AsyncMock(return_value=None)
+ mock_hook.get_async_conn = mock.AsyncMock(return_value=mock_async_cm)
+
+ with mock.patch.object(trigger, "hook", return_value=mock_hook):
+ with pytest.raises(asyncio.CancelledError):
+ async for _ in trigger.run():
+ pass
+
+ mock_hook.stop_query.assert_not_called()
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger.safe_to_cancel")
+ async def test_run_no_cancel_when_disabled(self, mock_safe_to_cancel, mock_async_wait):
+ """
+ Test that EmrContainerTrigger does NOT cancel the job when
+ cancel_on_kill=False.
+ """
+ mock_safe_to_cancel.return_value = True
+ mock_async_wait.side_effect = asyncio.CancelledError()
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=False,
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
+ mock_async_cm.__aenter__ = mock.AsyncMock(return_value=mock_client)
+ mock_async_cm.__aexit__ = mock.AsyncMock(return_value=None)
+ mock_hook.get_async_conn = mock.AsyncMock(return_value=mock_async_cm)
+
+ with mock.patch.object(trigger, "hook", return_value=mock_hook):
+ with pytest.raises(asyncio.CancelledError):
+ async for _ in trigger.run():
+ pass
+
+ mock_hook.stop_query.assert_not_called()
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ async def test_run_yields_error_on_airflow_exception(self, mock_async_wait):
+ """Test that an AirflowException yields an error TriggerEvent."""
+ mock_async_wait.side_effect = AirflowException("Something went wrong")
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
+ mock_async_cm.__aenter__ = mock.AsyncMock(return_value=mock_client)
+ mock_async_cm.__aexit__ = mock.AsyncMock(return_value=None)
+ mock_hook.get_async_conn = mock.AsyncMock(return_value=mock_async_cm)
+
Review Comment:
This new test also relies on unspecced `MagicMock` instances for the hook/client/context manager. Using autospecced mocks would better validate the `EmrContainerHook` API and avoid silent passes if production method names/signatures change.
##########
providers/amazon/tests/unit/amazon/aws/triggers/test_emr.py:
##########
@@ -152,8 +154,179 @@ def test_serialization_default_max_attempts(self):
"waiter_delay": 30,
"waiter_max_attempts": sys.maxsize,
"aws_conn_id": "aws_default",
+ "cancel_on_kill": True,
}
+ def test_serialization_includes_cancel_on_kill(self):
+ """Test that cancel_on_kill=True is correctly serialized."""
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+ classpath, kwargs = trigger.serialize()
+ assert classpath == "airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger"
+ assert kwargs["cancel_on_kill"] is True
+
+ def test_serialization_cancel_on_kill_false(self):
+ """Test that cancel_on_kill=False is correctly serialized."""
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=False,
+ )
+ classpath, kwargs = trigger.serialize()
+ assert classpath == "airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger"
+ assert kwargs["cancel_on_kill"] is False
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger.safe_to_cancel")
+ async def test_run_cancels_job_on_killed_when_safe(self, mock_safe_to_cancel, mock_async_wait):
+ """
+ Test that EmrContainerTrigger cancels the job when task is killed
+ and safe_to_cancel returns True.
+ """
+ mock_safe_to_cancel.return_value = True
+ mock_async_wait.side_effect = asyncio.CancelledError()
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+ mock_hook.stop_query.return_value = {"ResponseMetadata": {"HTTPStatusCode": 200}}
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
Review Comment:
These tests create `mock.MagicMock()` objects without a `spec`/`autospec`, which can hide attribute/typo bugs (e.g., `stop_query`/`get_async_conn` naming). Prefer `mock.create_autospec(EmrContainerHook, instance=True)` (or `MagicMock(spec=...)`) and `autospec=True` patches so the test fails if the production API changes.
```suggestion
mock_hook = mock.MagicMock(spec=["get_waiter", "stop_query", "get_async_conn"])
mock_hook.get_waiter.return_value = mock.MagicMock(spec=[])
mock_hook.stop_query.return_value = {"ResponseMetadata": {"HTTPStatusCode": 200}}
mock_client = object()
mock_async_cm = mock.MagicMock(spec=["__aenter__", "__aexit__"])
```
##########
providers/amazon/tests/unit/amazon/aws/triggers/test_emr.py:
##########
@@ -152,8 +154,179 @@ def test_serialization_default_max_attempts(self):
"waiter_delay": 30,
"waiter_max_attempts": sys.maxsize,
"aws_conn_id": "aws_default",
+ "cancel_on_kill": True,
}
+ def test_serialization_includes_cancel_on_kill(self):
+ """Test that cancel_on_kill=True is correctly serialized."""
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+ classpath, kwargs = trigger.serialize()
+ assert classpath == "airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger"
+ assert kwargs["cancel_on_kill"] is True
+
+ def test_serialization_cancel_on_kill_false(self):
+ """Test that cancel_on_kill=False is correctly serialized."""
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=False,
+ )
+ classpath, kwargs = trigger.serialize()
+ assert classpath == "airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger"
+ assert kwargs["cancel_on_kill"] is False
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger.safe_to_cancel")
+ async def test_run_cancels_job_on_killed_when_safe(self, mock_safe_to_cancel, mock_async_wait):
+ """
+ Test that EmrContainerTrigger cancels the job when task is killed
+ and safe_to_cancel returns True.
+ """
+ mock_safe_to_cancel.return_value = True
+ mock_async_wait.side_effect = asyncio.CancelledError()
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+ mock_hook.stop_query.return_value = {"ResponseMetadata": {"HTTPStatusCode": 200}}
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
+ mock_async_cm.__aenter__ = mock.AsyncMock(return_value=mock_client)
+ mock_async_cm.__aexit__ = mock.AsyncMock(return_value=None)
+ mock_hook.get_async_conn = mock.AsyncMock(return_value=mock_async_cm)
+
+ with mock.patch.object(trigger, "hook", return_value=mock_hook):
+ with pytest.raises(asyncio.CancelledError):
+ async for _ in trigger.run():
+ pass
+
+ mock_hook.stop_query.assert_called_once_with("test_job")
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger.safe_to_cancel")
+ async def test_run_no_cancel_when_unsafe(self, mock_safe_to_cancel, mock_async_wait):
+ """
+ Test that EmrContainerTrigger does NOT cancel the job when
+ safe_to_cancel returns False (e.g., triggerer shutdown).
+ """
+ mock_safe_to_cancel.return_value = False
+ mock_async_wait.side_effect = asyncio.CancelledError()
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
+ mock_async_cm.__aenter__ = mock.AsyncMock(return_value=mock_client)
+ mock_async_cm.__aexit__ = mock.AsyncMock(return_value=None)
+ mock_hook.get_async_conn = mock.AsyncMock(return_value=mock_async_cm)
+
+ with mock.patch.object(trigger, "hook", return_value=mock_hook):
+ with pytest.raises(asyncio.CancelledError):
+ async for _ in trigger.run():
+ pass
+
+ mock_hook.stop_query.assert_not_called()
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger.safe_to_cancel")
+ async def test_run_no_cancel_when_disabled(self, mock_safe_to_cancel, mock_async_wait):
+ """
+ Test that EmrContainerTrigger does NOT cancel the job when
+ cancel_on_kill=False.
+ """
+ mock_safe_to_cancel.return_value = True
+ mock_async_wait.side_effect = asyncio.CancelledError()
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=False,
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
+ mock_async_cm.__aenter__ = mock.AsyncMock(return_value=mock_client)
+ mock_async_cm.__aexit__ = mock.AsyncMock(return_value=None)
+ mock_hook.get_async_conn = mock.AsyncMock(return_value=mock_async_cm)
+
Review Comment:
`mock.MagicMock()` objects here are not specced/autospecced. Consider using `autospec=True`/`create_autospec` for the hook and context manager to ensure the test catches API mismatches (e.g. signature/name changes on `get_async_conn`, `get_waiter`).
##########
providers/amazon/tests/unit/amazon/aws/triggers/test_emr.py:
##########
@@ -152,8 +154,179 @@ def test_serialization_default_max_attempts(self):
"waiter_delay": 30,
"waiter_max_attempts": sys.maxsize,
"aws_conn_id": "aws_default",
+ "cancel_on_kill": True,
}
+ def test_serialization_includes_cancel_on_kill(self):
+ """Test that cancel_on_kill=True is correctly serialized."""
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+ classpath, kwargs = trigger.serialize()
+ assert classpath == "airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger"
+ assert kwargs["cancel_on_kill"] is True
+
+ def test_serialization_cancel_on_kill_false(self):
+ """Test that cancel_on_kill=False is correctly serialized."""
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=False,
+ )
+ classpath, kwargs = trigger.serialize()
+ assert classpath == "airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger"
+ assert kwargs["cancel_on_kill"] is False
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger.safe_to_cancel")
+ async def test_run_cancels_job_on_killed_when_safe(self, mock_safe_to_cancel, mock_async_wait):
+ """
+ Test that EmrContainerTrigger cancels the job when task is killed
+ and safe_to_cancel returns True.
+ """
+ mock_safe_to_cancel.return_value = True
+ mock_async_wait.side_effect = asyncio.CancelledError()
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+ mock_hook.stop_query.return_value = {"ResponseMetadata": {"HTTPStatusCode": 200}}
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
+ mock_async_cm.__aenter__ = mock.AsyncMock(return_value=mock_client)
+ mock_async_cm.__aexit__ = mock.AsyncMock(return_value=None)
+ mock_hook.get_async_conn = mock.AsyncMock(return_value=mock_async_cm)
+
+ with mock.patch.object(trigger, "hook", return_value=mock_hook):
+ with pytest.raises(asyncio.CancelledError):
+ async for _ in trigger.run():
+ pass
+
+ mock_hook.stop_query.assert_called_once_with("test_job")
+
+ @pytest.mark.asyncio
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.async_wait")
+ @mock.patch("airflow.providers.amazon.aws.triggers.emr.EmrContainerTrigger.safe_to_cancel")
+ async def test_run_no_cancel_when_unsafe(self, mock_safe_to_cancel, mock_async_wait):
+ """
+ Test that EmrContainerTrigger does NOT cancel the job when
+ safe_to_cancel returns False (e.g., triggerer shutdown).
+ """
+ mock_safe_to_cancel.return_value = False
+ mock_async_wait.side_effect = asyncio.CancelledError()
+
+ trigger = EmrContainerTrigger(
+ virtual_cluster_id="test_cluster",
+ job_id="test_job",
+ waiter_delay=30,
+ waiter_max_attempts=60,
+ aws_conn_id="aws_default",
+ cancel_on_kill=True,
+ )
+
+ mock_hook = mock.MagicMock()
+ mock_hook.get_waiter.return_value = mock.MagicMock()
+
+ mock_client = mock.MagicMock()
+ mock_async_cm = mock.MagicMock()
+ mock_async_cm.__aenter__ = mock.AsyncMock(return_value=mock_client)
+ mock_async_cm.__aexit__ = mock.AsyncMock(return_value=None)
+ mock_hook.get_async_conn = mock.AsyncMock(return_value=mock_async_cm)
+
Review Comment:
`mock.MagicMock()` is used here without `spec`/`autospec`, which makes the test permissive to wrong method names and missing attributes. Using an autospecced `EmrContainerHook`/async context manager mock would keep this test aligned with the real hook interface.
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,9 +197,133 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
- return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ return EmrContainerHook(aws_conn_id=self.aws_conn_id, virtual_cluster_id=self.virtual_cluster_id)
+
+ if not AIRFLOW_V_3_0_PLUS:
+
+ @provide_session
+ def get_task_instance(self, session: Session) -> TaskInstance:
+ """Get the task instance for the current trigger (Airflow 2.x compatibility)."""
+ from sqlalchemy import select
+
+ query = select(TaskInstance).where(
+ TaskInstance.dag_id == self.task_instance.dag_id,
+ TaskInstance.task_id == self.task_instance.task_id,
+ TaskInstance.run_id == self.task_instance.run_id,
+ TaskInstance.map_index == self.task_instance.map_index,
+ )
+ task_instance = session.scalars(query).one_or_none()
+ if task_instance is None:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ )
+ return task_instance
+
+ async def get_task_state(self):
+ """Get the current state of the task instance (Airflow 3.x)."""
+ from airflow.sdk.execution_time.task_runner import RuntimeTaskInstance
+
+ task_states_response = await sync_to_async(RuntimeTaskInstance.get_task_states)(
+ dag_id=self.task_instance.dag_id,
Review Comment:
`get_task_state()` imports `RuntimeTaskInstance` inside the function. If this import is only needed for Airflow 3, prefer a module-level conditional import (e.g. under `if AIRFLOW_V_3_0_PLUS:`) so the import happens once and avoids function-scope imports in hot paths.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "aurangzaib048 (via GitHub)" <gi...@apache.org>.
aurangzaib048 commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3067055882
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,10 +197,132 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ if not AIRFLOW_V_3_0_PLUS:
+
+ @provide_session
+ def get_task_instance(self, session: Session) -> TaskInstance:
+ """Get the task instance for the current trigger (Airflow 2.x compatibility)."""
+ from sqlalchemy import select
+
+ query = select(TaskInstance).where(
+ TaskInstance.dag_id == self.task_instance.dag_id,
+ TaskInstance.task_id == self.task_instance.task_id,
+ TaskInstance.run_id == self.task_instance.run_id,
+ TaskInstance.map_index == self.task_instance.map_index,
+ )
+ task_instance = session.scalars(query).one_or_none()
+ if task_instance is None:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ )
+ return task_instance
+
+ async def get_task_state(self):
+ """Get the current state of the task instance (Airflow 3.x)."""
+ from airflow.sdk.execution_time.task_runner import RuntimeTaskInstance
+
+ task_states_response = await sync_to_async(RuntimeTaskInstance.get_task_states)(
+ dag_id=self.task_instance.dag_id,
+ task_ids=[self.task_instance.task_id],
+ run_ids=[self.task_instance.run_id],
+ map_index=self.task_instance.map_index,
+ )
+ try:
+ task_state = task_states_response[self.task_instance.run_id][self.task_instance.task_id]
+ except (KeyError, TypeError) as e:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ ) from e
+ return task_state
+
+ async def safe_to_cancel(self) -> bool:
+ """
+ Whether it is safe to cancel the EMR container job.
+
+ Returns True if task is NOT DEFERRED (user-initiated cancellation).
+ Returns False if task is DEFERRED (triggerer restart - don't cancel job).
+ """
+ if AIRFLOW_V_3_0_PLUS:
+ task_state = await self.get_task_state()
+ else:
+ task_instance = self.get_task_instance() # type: ignore[call-arg]
+ task_state = task_instance.state
+ return task_state != TaskInstanceState.DEFERRED
+
+ async def run(self) -> AsyncIterator[TriggerEvent]:
+ """
+ Run the trigger and wait for the job to complete.
+
+ If the task is cancelled while waiting, attempt to cancel the EMR container job
+ if cancel_on_kill is enabled and it's safe to do so.
+ """
+ hook: EmrContainerHook = self.hook() # type: ignore[assignment]
+ try:
+ async with await hook.get_async_conn() as client:
+ waiter = hook.get_waiter(
+ self.waiter_name,
+ deferrable=True,
+ client=client,
+ config_overrides=self.waiter_config_overrides,
+ )
+ await async_wait(
+ waiter,
+ self.waiter_delay,
+ self.attempts,
+ self.waiter_args,
+ self.failure_message,
+ self.status_message,
+ self.status_queries,
+ )
+ yield TriggerEvent({"status": "success", self.return_key: self.return_value})
+ except asyncio.CancelledError:
+ try:
+ if self.job_id and self.cancel_on_kill and await self.safe_to_cancel():
+ self.log.info(
+ "Task was cancelled. Cancelling EMR container job. "
+ "Virtual Cluster ID: %s, Job ID: %s",
+ self.virtual_cluster_id,
+ self.job_id,
+ )
+ try:
+ hook.stop_query(self.job_id)
+ self.log.info("EMR container job %s cancelled successfully.", self.job_id)
+ except Exception:
+ self.log.exception(
+ "Failed to cancel EMR container job %s. The job may still be running.",
+ self.job_id,
+ )
+ else:
+ self.log.info(
+ "Trigger may have shutdown or cancel_on_kill is disabled. "
+ "Skipping job cancellation. Virtual Cluster ID: %s, Job ID: %s",
+ self.virtual_cluster_id,
+ self.job_id,
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ self.log.exception(
+ "Error during cancellation check for EMR container job %s. The job may still be running.",
+ self.job_id,
+ )
+ raise
+ except AirflowException as e:
+ yield TriggerEvent({"status": "error", "message": str(e), self.return_key: self.return_value})
Review Comment:
Good catch. Added `except Exception` fallback after `AirflowException` to match the base class behavior — both now yield an error TriggerEvent.
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,10 +197,132 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ if not AIRFLOW_V_3_0_PLUS:
+
+ @provide_session
+ def get_task_instance(self, session: Session) -> TaskInstance:
+ """Get the task instance for the current trigger (Airflow 2.x compatibility)."""
+ from sqlalchemy import select
+
+ query = select(TaskInstance).where(
+ TaskInstance.dag_id == self.task_instance.dag_id,
+ TaskInstance.task_id == self.task_instance.task_id,
+ TaskInstance.run_id == self.task_instance.run_id,
+ TaskInstance.map_index == self.task_instance.map_index,
+ )
+ task_instance = session.scalars(query).one_or_none()
+ if task_instance is None:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ )
+ return task_instance
+
+ async def get_task_state(self):
+ """Get the current state of the task instance (Airflow 3.x)."""
+ from airflow.sdk.execution_time.task_runner import RuntimeTaskInstance
+
+ task_states_response = await sync_to_async(RuntimeTaskInstance.get_task_states)(
+ dag_id=self.task_instance.dag_id,
+ task_ids=[self.task_instance.task_id],
+ run_ids=[self.task_instance.run_id],
+ map_index=self.task_instance.map_index,
+ )
+ try:
+ task_state = task_states_response[self.task_instance.run_id][self.task_instance.task_id]
+ except (KeyError, TypeError) as e:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ ) from e
+ return task_state
+
+ async def safe_to_cancel(self) -> bool:
+ """
+ Whether it is safe to cancel the EMR container job.
+
+ Returns True if task is NOT DEFERRED (user-initiated cancellation).
+ Returns False if task is DEFERRED (triggerer restart - don't cancel job).
+ """
+ if AIRFLOW_V_3_0_PLUS:
+ task_state = await self.get_task_state()
+ else:
+ task_instance = self.get_task_instance() # type: ignore[call-arg]
Review Comment:
Fixed. Wrapped `get_task_instance()` with `sync_to_async()` and `stop_query()` with `await sync_to_async(hook.stop_query)()` to avoid blocking the triggerer event loop.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "aurangzaib048 (via GitHub)" <gi...@apache.org>.
aurangzaib048 commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3072573005
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,9 +198,129 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
- return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ return EmrContainerHook(aws_conn_id=self.aws_conn_id, virtual_cluster_id=self.virtual_cluster_id)
+
+ if not AIRFLOW_V_3_0_PLUS:
+
+ @provide_session
+ def get_task_instance(self, session: Session) -> TaskInstance:
+ """Get the task instance for the current trigger (Airflow 2.x compatibility)."""
+ query = select(TaskInstance).where(
+ TaskInstance.dag_id == self.task_instance.dag_id,
+ TaskInstance.task_id == self.task_instance.task_id,
+ TaskInstance.run_id == self.task_instance.run_id,
+ TaskInstance.map_index == self.task_instance.map_index,
+ )
+ task_instance = session.scalars(query).one_or_none()
+ if task_instance is None:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ )
+ return task_instance
+
+ async def get_task_state(self):
+ """Get the current state of the task instance (Airflow 3.x)."""
+ from airflow.sdk.execution_time.task_runner import RuntimeTaskInstance
+
+ task_states_response = await sync_to_async(RuntimeTaskInstance.get_task_states)(
+ dag_id=self.task_instance.dag_id,
+ task_ids=[self.task_instance.task_id],
+ run_ids=[self.task_instance.run_id],
+ map_index=self.task_instance.map_index,
+ )
+ try:
+ task_state = task_states_response[self.task_instance.run_id][self.task_instance.task_id]
Review Comment:
Fixed. Now using `f"{task_id}_{map_index}"` as the lookup key when `map_index >= 0`, matching the execution API response format for mapped task instances.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "aurangzaib048 (via GitHub)" <gi...@apache.org>.
aurangzaib048 commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3074881021
##########
providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py:
##########
@@ -604,10 +610,19 @@ def check_failure(self, query_status):
def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str:
validated_event = validate_execute_complete_event(event)
- if validated_event["status"] != "success":
- raise AirflowException(f"Error while running job: {validated_event}")
-
- return validated_event["job_id"]
+ if validated_event["status"] == "success":
+ return validated_event["job_id"]
+ job_id = validated_event.get("job_id") or self.job_id
Review Comment:
Fixed. Now using only `validated_event.get("job_id")` — dropped the `self.job_id` fallback since the worker may be different after deferral.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #64770:
URL: https://github.com/apache/airflow/pull/64770#issuecomment-4382640229
@aurangzaib048 — Your unresolved review thread(s) from @o-nikolas, @vincbeck appear to have been addressed (post-review commits and/or in-thread replies on every thread, with the latest commit pushed after the most recent thread). I've added the `ready for maintainer review` label so the PR re-enters the maintainer review queue.
@o-nikolas, @vincbeck — could you take another look when you have a chance? If you agree the feedback was addressed, please mark the threads as resolved so the queue signal stays accurate. If a thread still needs work, please reply in-line — @aurangzaib048 will follow up.
---
_Note: This comment was drafted by an AI-assisted triage tool and may contain mistakes. Once you have addressed the points above, an Apache Airflow maintainer — a real person — will take the next look at your PR. We use this [two-stage triage process](https://github.com/apache/airflow/blob/main/contributing-docs/25_maintainer_pr_triage.md#why-the-first-pass-is-automated) so that our maintainers' limited time is spent where it matters most: the conversation with you._
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on PR #64770:
URL: https://github.com/apache/airflow/pull/64770#issuecomment-4383002448
Still waiting this comment to be addressed: https://github.com/apache/airflow/pull/64770/changes#r3124747034
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "boring-cyborg[bot] (via GitHub)" <gi...@apache.org>.
boring-cyborg[bot] commented on PR #64770:
URL: https://github.com/apache/airflow/pull/64770#issuecomment-4193277763
Congratulations on your first Pull Request and welcome to the Apache Airflow community! If you have any issues or are unsure about any anything please check our Contributors' Guide (https://github.com/apache/airflow/blob/main/contributing-docs/README.rst)
Here are some useful points:
- Pay attention to the quality of your code (ruff, mypy and type annotations). Our [prek-hooks]( https://github.com/apache/airflow/blob/main/contributing-docs/08_static_code_checks.rst#prerequisites-for-prek-hooks) will help you with that.
- In case of a new feature add useful documentation (in docstrings or in `docs/` directory). Adding a new operator? Check this short [guide](https://github.com/apache/airflow/blob/main/airflow-core/docs/howto/custom-operator.rst) Consider adding an example DAG that shows how users should use it.
- Consider using [Breeze environment](https://github.com/apache/airflow/blob/main/dev/breeze/doc/README.rst) for testing locally, it's a heavy docker but it ships with a working Airflow and a lot of integrations.
- Be patient and persistent. It might take some time to get a review or get the final approval from Committers.
- Please follow [ASF Code of Conduct](https://www.apache.org/foundation/policies/conduct) for all communication including (but not limited to) comments on Pull Requests, Mailing list and Slack.
- Be sure to read the [Airflow Coding style]( https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#coding-style-and-best-practices).
- Always keep your Pull Requests rebased, otherwise your build might fail due to changes not related to your commits.
Apache Airflow is a community-driven project and together we are making it better 🚀.
In case of doubts contact the developers at:
Mailing List: dev@airflow.apache.org
Slack: https://s.apache.org/airflow-slack
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "aurangzaib048 (via GitHub)" <gi...@apache.org>.
aurangzaib048 commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3122898348
##########
providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py:
##########
@@ -604,10 +610,19 @@ def check_failure(self, query_status):
def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str:
validated_event = validate_execute_complete_event(event)
- if validated_event["status"] != "success":
- raise AirflowException(f"Error while running job: {validated_event}")
-
- return validated_event["job_id"]
+ if validated_event["status"] == "success":
+ return validated_event["job_id"]
+ job_id = validated_event.get("job_id")
+ if job_id:
+ self.log.info("Cancelling EMR container job %s", job_id)
+ try:
+ self.hook.stop_query(job_id)
Review Comment:
Added `and self.cancel_on_kill` guard so cancellation in `execute_complete()` is skipped when `cancel_on_kill=False`, matching the trigger-side behavior.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on PR #64770:
URL: https://github.com/apache/airflow/pull/64770#issuecomment-4305725803
Something we might want to leverage? https://github.com/apache/airflow/pull/65590
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3066476162
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,10 +197,132 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ if not AIRFLOW_V_3_0_PLUS:
+
+ @provide_session
+ def get_task_instance(self, session: Session) -> TaskInstance:
+ """Get the task instance for the current trigger (Airflow 2.x compatibility)."""
+ from sqlalchemy import select
+
+ query = select(TaskInstance).where(
+ TaskInstance.dag_id == self.task_instance.dag_id,
+ TaskInstance.task_id == self.task_instance.task_id,
+ TaskInstance.run_id == self.task_instance.run_id,
+ TaskInstance.map_index == self.task_instance.map_index,
+ )
+ task_instance = session.scalars(query).one_or_none()
+ if task_instance is None:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ )
+ return task_instance
+
+ async def get_task_state(self):
+ """Get the current state of the task instance (Airflow 3.x)."""
+ from airflow.sdk.execution_time.task_runner import RuntimeTaskInstance
+
+ task_states_response = await sync_to_async(RuntimeTaskInstance.get_task_states)(
+ dag_id=self.task_instance.dag_id,
+ task_ids=[self.task_instance.task_id],
+ run_ids=[self.task_instance.run_id],
+ map_index=self.task_instance.map_index,
+ )
+ try:
+ task_state = task_states_response[self.task_instance.run_id][self.task_instance.task_id]
+ except (KeyError, TypeError) as e:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ ) from e
+ return task_state
+
+ async def safe_to_cancel(self) -> bool:
+ """
+ Whether it is safe to cancel the EMR container job.
+
+ Returns True if task is NOT DEFERRED (user-initiated cancellation).
+ Returns False if task is DEFERRED (triggerer restart - don't cancel job).
+ """
+ if AIRFLOW_V_3_0_PLUS:
+ task_state = await self.get_task_state()
+ else:
+ task_instance = self.get_task_instance() # type: ignore[call-arg]
+ task_state = task_instance.state
+ return task_state != TaskInstanceState.DEFERRED
+
+ async def run(self) -> AsyncIterator[TriggerEvent]:
+ """
+ Run the trigger and wait for the job to complete.
+
+ If the task is cancelled while waiting, attempt to cancel the EMR container job
+ if cancel_on_kill is enabled and it's safe to do so.
+ """
+ hook: EmrContainerHook = self.hook() # type: ignore[assignment]
+ try:
+ async with await hook.get_async_conn() as client:
+ waiter = hook.get_waiter(
+ self.waiter_name,
+ deferrable=True,
+ client=client,
+ config_overrides=self.waiter_config_overrides,
+ )
+ await async_wait(
+ waiter,
+ self.waiter_delay,
+ self.attempts,
+ self.waiter_args,
+ self.failure_message,
+ self.status_message,
+ self.status_queries,
+ )
+ yield TriggerEvent({"status": "success", self.return_key: self.return_value})
+ except asyncio.CancelledError:
+ try:
+ if self.job_id and self.cancel_on_kill and await self.safe_to_cancel():
+ self.log.info(
+ "Task was cancelled. Cancelling EMR container job. "
+ "Virtual Cluster ID: %s, Job ID: %s",
+ self.virtual_cluster_id,
+ self.job_id,
+ )
+ try:
+ hook.stop_query(self.job_id)
+ self.log.info("EMR container job %s cancelled successfully.", self.job_id)
+ except Exception:
+ self.log.exception(
+ "Failed to cancel EMR container job %s. The job may still be running.",
+ self.job_id,
+ )
+ else:
+ self.log.info(
+ "Trigger may have shutdown or cancel_on_kill is disabled. "
+ "Skipping job cancellation. Virtual Cluster ID: %s, Job ID: %s",
+ self.virtual_cluster_id,
+ self.job_id,
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ self.log.exception(
+ "Error during cancellation check for EMR container job %s. The job may still be running.",
+ self.job_id,
+ )
+ raise
+ except AirflowException as e:
+ yield TriggerEvent({"status": "error", "message": str(e), self.return_key: self.return_value})
Review Comment:
Overriding `run()` narrows error handling to only `AirflowException`. Any other exception from `get_async_conn()`, `get_waiter()`, or `async_wait()` (e.g., boto/connection errors that are not wrapped as `AirflowException`) will now bubble out of the trigger instead of producing an error `TriggerEvent`, changing behavior from the base waiter trigger. Add a final `except Exception as e:` branch that yields an `{\"status\": \"error\"...}` event (while keeping `CancelledError` re-raised) to preserve expected deferrable error propagation.
```suggestion
yield TriggerEvent({"status": "error", "message": str(e), self.return_key: self.return_value})
except Exception as e:
yield TriggerEvent({"status": "error", "message": str(e), self.return_key: self.return_value})
```
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,10 +197,132 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ if not AIRFLOW_V_3_0_PLUS:
+
+ @provide_session
+ def get_task_instance(self, session: Session) -> TaskInstance:
+ """Get the task instance for the current trigger (Airflow 2.x compatibility)."""
+ from sqlalchemy import select
+
+ query = select(TaskInstance).where(
+ TaskInstance.dag_id == self.task_instance.dag_id,
+ TaskInstance.task_id == self.task_instance.task_id,
+ TaskInstance.run_id == self.task_instance.run_id,
+ TaskInstance.map_index == self.task_instance.map_index,
+ )
+ task_instance = session.scalars(query).one_or_none()
+ if task_instance is None:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ )
+ return task_instance
+
+ async def get_task_state(self):
+ """Get the current state of the task instance (Airflow 3.x)."""
+ from airflow.sdk.execution_time.task_runner import RuntimeTaskInstance
+
+ task_states_response = await sync_to_async(RuntimeTaskInstance.get_task_states)(
+ dag_id=self.task_instance.dag_id,
+ task_ids=[self.task_instance.task_id],
+ run_ids=[self.task_instance.run_id],
+ map_index=self.task_instance.map_index,
+ )
+ try:
+ task_state = task_states_response[self.task_instance.run_id][self.task_instance.task_id]
+ except (KeyError, TypeError) as e:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ ) from e
+ return task_state
+
+ async def safe_to_cancel(self) -> bool:
+ """
+ Whether it is safe to cancel the EMR container job.
+
+ Returns True if task is NOT DEFERRED (user-initiated cancellation).
+ Returns False if task is DEFERRED (triggerer restart - don't cancel job).
+ """
+ if AIRFLOW_V_3_0_PLUS:
+ task_state = await self.get_task_state()
+ else:
+ task_instance = self.get_task_instance() # type: ignore[call-arg]
+ task_state = task_instance.state
+ return task_state != TaskInstanceState.DEFERRED
+
+ async def run(self) -> AsyncIterator[TriggerEvent]:
+ """
+ Run the trigger and wait for the job to complete.
+
+ If the task is cancelled while waiting, attempt to cancel the EMR container job
+ if cancel_on_kill is enabled and it's safe to do so.
+ """
+ hook: EmrContainerHook = self.hook() # type: ignore[assignment]
+ try:
+ async with await hook.get_async_conn() as client:
+ waiter = hook.get_waiter(
+ self.waiter_name,
+ deferrable=True,
+ client=client,
+ config_overrides=self.waiter_config_overrides,
+ )
+ await async_wait(
+ waiter,
+ self.waiter_delay,
+ self.attempts,
+ self.waiter_args,
+ self.failure_message,
+ self.status_message,
+ self.status_queries,
+ )
+ yield TriggerEvent({"status": "success", self.return_key: self.return_value})
+ except asyncio.CancelledError:
+ try:
+ if self.job_id and self.cancel_on_kill and await self.safe_to_cancel():
+ self.log.info(
+ "Task was cancelled. Cancelling EMR container job. "
+ "Virtual Cluster ID: %s, Job ID: %s",
+ self.virtual_cluster_id,
+ self.job_id,
+ )
+ try:
+ hook.stop_query(self.job_id)
Review Comment:
`safe_to_cancel()` calls a synchronous DB query (`get_task_instance()`) from an async context (Airflow 2.x path), and the cancellation path calls synchronous `hook.stop_query()` from the trigger event loop. Both can block the triggerer loop and degrade reliability under load. Prefer running these sync operations via `sync_to_async(...)` (or an async-capable hook/client method) so cancellation checks and stop calls don't block other triggers.
```suggestion
await sync_to_async(hook.stop_query)(self.job_id)
```
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,10 +197,132 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ if not AIRFLOW_V_3_0_PLUS:
+
+ @provide_session
+ def get_task_instance(self, session: Session) -> TaskInstance:
+ """Get the task instance for the current trigger (Airflow 2.x compatibility)."""
+ from sqlalchemy import select
+
+ query = select(TaskInstance).where(
+ TaskInstance.dag_id == self.task_instance.dag_id,
+ TaskInstance.task_id == self.task_instance.task_id,
+ TaskInstance.run_id == self.task_instance.run_id,
+ TaskInstance.map_index == self.task_instance.map_index,
+ )
+ task_instance = session.scalars(query).one_or_none()
+ if task_instance is None:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ )
+ return task_instance
+
+ async def get_task_state(self):
+ """Get the current state of the task instance (Airflow 3.x)."""
+ from airflow.sdk.execution_time.task_runner import RuntimeTaskInstance
+
+ task_states_response = await sync_to_async(RuntimeTaskInstance.get_task_states)(
+ dag_id=self.task_instance.dag_id,
+ task_ids=[self.task_instance.task_id],
+ run_ids=[self.task_instance.run_id],
+ map_index=self.task_instance.map_index,
+ )
+ try:
+ task_state = task_states_response[self.task_instance.run_id][self.task_instance.task_id]
+ except (KeyError, TypeError) as e:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ ) from e
+ return task_state
+
+ async def safe_to_cancel(self) -> bool:
+ """
+ Whether it is safe to cancel the EMR container job.
+
+ Returns True if task is NOT DEFERRED (user-initiated cancellation).
+ Returns False if task is DEFERRED (triggerer restart - don't cancel job).
+ """
+ if AIRFLOW_V_3_0_PLUS:
+ task_state = await self.get_task_state()
+ else:
+ task_instance = self.get_task_instance() # type: ignore[call-arg]
Review Comment:
`safe_to_cancel()` calls a synchronous DB query (`get_task_instance()`) from an async context (Airflow 2.x path), and the cancellation path calls synchronous `hook.stop_query()` from the trigger event loop. Both can block the triggerer loop and degrade reliability under load. Prefer running these sync operations via `sync_to_async(...)` (or an async-capable hook/client method) so cancellation checks and stop calls don't block other triggers.
```suggestion
task_instance = await sync_to_async(self.get_task_instance, thread_sensitive=True)() # type: ignore[call-arg]
```
##########
providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py:
##########
@@ -567,13 +567,15 @@ def execute(self, context: Context) -> str | None:
aws_conn_id=self.aws_conn_id,
waiter_delay=self.poll_interval,
waiter_max_attempts=self.max_polling_attempts,
+ cancel_on_kill=True,
)
if self.max_polling_attempts
else EmrContainerTrigger(
virtual_cluster_id=self.virtual_cluster_id,
job_id=self.job_id,
aws_conn_id=self.aws_conn_id,
waiter_delay=self.poll_interval,
+ cancel_on_kill=True,
),
Review Comment:
The PR description states a new `cancel_on_kill` parameter is added \"for opt-out\", but `EmrContainerOperator` hard-codes `cancel_on_kill=True` when instantiating the trigger, leaving no opt-out path for operator users. To match the stated behavior, consider adding an operator parameter (e.g., `cancel_on_kill: bool = True`) and pass it through to `EmrContainerTrigger`.
##########
providers/amazon/tests/unit/amazon/aws/operators/test_emr_containers.py:
##########
@@ -162,6 +162,19 @@ def test_operator_defer_with_timeout(self, mock_submit_job, mock_check_query_sta
assert trigger.waiter_delay == self.emr_container.poll_interval
assert trigger.attempts == self.emr_container.max_polling_attempts
+ @mock.patch.object(EmrContainerHook, "stop_query")
+ def test_execute_complete_cancels_job_on_failure(self, mock_stop_query):
+ self.emr_container.job_id = "test_job_id"
+ event = {"status": "error", "message": "Job timed out", "job_id": "test_job_id"}
+ with pytest.raises(AirflowException):
+ self.emr_container.execute_complete(context=None, event=event)
+ mock_stop_query.assert_called_once_with("test_job_id")
+
Review Comment:
Current coverage verifies `stop_query()` is invoked on failure, but does not cover the branch where `stop_query()` raises and the operator should still raise the original `AirflowException` (i.e., cancellation failure must not mask the task failure). Add a unit test where `mock_stop_query.side_effect = Exception(...)` and assert `execute_complete()` still raises `AirflowException` while logging the cancellation error.
```suggestion
@mock.patch.object(EmrContainerHook, "stop_query")
def test_execute_complete_raises_original_error_when_cancel_fails(self, mock_stop_query, caplog):
self.emr_container.job_id = "test_job_id"
mock_stop_query.side_effect = Exception("Failed to cancel job")
event = {"status": "error", "message": "Job timed out", "job_id": "test_job_id"}
with pytest.raises(AirflowException):
self.emr_container.execute_complete(context=None, event=event)
mock_stop_query.assert_called_once_with("test_job_id")
assert "Failed to cancel job" in caplog.text
```
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "aurangzaib048 (via GitHub)" <gi...@apache.org>.
aurangzaib048 commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3067071531
##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/emr.py:
##########
@@ -190,10 +197,134 @@ def __init__(
waiter_max_attempts=waiter_max_attempts,
aws_conn_id=aws_conn_id,
)
+ self.virtual_cluster_id = virtual_cluster_id
+ self.job_id = job_id
+ self.cancel_on_kill = cancel_on_kill
def hook(self) -> AwsGenericHook:
return EmrContainerHook(aws_conn_id=self.aws_conn_id)
+ if not AIRFLOW_V_3_0_PLUS:
+
+ @provide_session
+ def get_task_instance(self, session: Session) -> TaskInstance:
+ """Get the task instance for the current trigger (Airflow 2.x compatibility)."""
+ from sqlalchemy import select
+
+ query = select(TaskInstance).where(
+ TaskInstance.dag_id == self.task_instance.dag_id,
+ TaskInstance.task_id == self.task_instance.task_id,
+ TaskInstance.run_id == self.task_instance.run_id,
+ TaskInstance.map_index == self.task_instance.map_index,
+ )
+ task_instance = session.scalars(query).one_or_none()
+ if task_instance is None:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ )
+ return task_instance
+
+ async def get_task_state(self):
+ """Get the current state of the task instance (Airflow 3.x)."""
+ from airflow.sdk.execution_time.task_runner import RuntimeTaskInstance
+
+ task_states_response = await sync_to_async(RuntimeTaskInstance.get_task_states)(
+ dag_id=self.task_instance.dag_id,
+ task_ids=[self.task_instance.task_id],
+ run_ids=[self.task_instance.run_id],
+ map_index=self.task_instance.map_index,
+ )
+ try:
+ task_state = task_states_response[self.task_instance.run_id][self.task_instance.task_id]
+ except (KeyError, TypeError) as e:
+ raise ValueError(
+ f"TaskInstance with dag_id: {self.task_instance.dag_id}, "
+ f"task_id: {self.task_instance.task_id}, "
+ f"run_id: {self.task_instance.run_id} and "
+ f"map_index: {self.task_instance.map_index} is not found"
+ ) from e
+ return task_state
+
+ async def safe_to_cancel(self) -> bool:
+ """
+ Whether it is safe to cancel the EMR container job.
+
+ Returns True if task is NOT DEFERRED (user-initiated cancellation).
+ Returns False if task is DEFERRED (triggerer restart - don't cancel job).
+ """
+ if AIRFLOW_V_3_0_PLUS:
+ task_state = await self.get_task_state()
+ else:
+ task_instance = await sync_to_async(self.get_task_instance)() # type: ignore[call-arg]
+ task_state = task_instance.state
+ return task_state != TaskInstanceState.DEFERRED
+
+ async def run(self) -> AsyncIterator[TriggerEvent]:
+ """
+ Run the trigger and wait for the job to complete.
+
+ If the task is cancelled while waiting, attempt to cancel the EMR container job
+ if cancel_on_kill is enabled and it's safe to do so.
+ """
+ hook: EmrContainerHook = self.hook() # type: ignore[assignment]
+ try:
+ async with await hook.get_async_conn() as client:
+ waiter = hook.get_waiter(
+ self.waiter_name,
Review Comment:
Good catch — fixed. Now passing `virtual_cluster_id=self.virtual_cluster_id` to `EmrContainerHook` in `hook()` so `stop_query()` has the cluster ID it needs.
##########
providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py:
##########
@@ -604,10 +610,18 @@ def check_failure(self, query_status):
def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str:
validated_event = validate_execute_complete_event(event)
- if validated_event["status"] != "success":
- raise AirflowException(f"Error while running job: {validated_event}")
-
- return validated_event["job_id"]
+ if validated_event["status"] == "success":
+ return validated_event["job_id"]
+ if self.job_id:
+ self.log.info("Cancelling EMR container job %s", self.job_id)
+ try:
+ self.hook.stop_query(self.job_id)
+ except Exception:
+ self.log.exception(
+ "Failed to cancel EMR container job %s. The job may still be running.",
+ self.job_id,
Review Comment:
Fixed. Now using `validated_event.get("job_id") or self.job_id` so the cancellation works even when the operator is reconstructed after deferral and `self.job_id` is None.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Fix EMR container job not cancelled on deferral timeout [airflow]
Posted by "aurangzaib048 (via GitHub)" <gi...@apache.org>.
aurangzaib048 commented on code in PR #64770:
URL: https://github.com/apache/airflow/pull/64770#discussion_r3067057834
##########
providers/amazon/tests/unit/amazon/aws/operators/test_emr_containers.py:
##########
@@ -162,6 +162,19 @@ def test_operator_defer_with_timeout(self, mock_submit_job, mock_check_query_sta
assert trigger.waiter_delay == self.emr_container.poll_interval
assert trigger.attempts == self.emr_container.max_polling_attempts
+ @mock.patch.object(EmrContainerHook, "stop_query")
+ def test_execute_complete_cancels_job_on_failure(self, mock_stop_query):
+ self.emr_container.job_id = "test_job_id"
+ event = {"status": "error", "message": "Job timed out", "job_id": "test_job_id"}
+ with pytest.raises(AirflowException):
+ self.emr_container.execute_complete(context=None, event=event)
+ mock_stop_query.assert_called_once_with("test_job_id")
+
Review Comment:
Added `test_execute_complete_raises_original_error_when_cancel_fails` — mocks `stop_query` to raise and asserts the original `AirflowException` is still propagated.
--
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: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org