You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "Leondon9 (via GitHub)" <gi...@apache.org> on 2026/09/25 03:31:09 UTC

[PR] Stop AWS Glue job run when a deferred task is cleared [airflow]

Leondon9 opened a new pull request, #73702:
URL: https://github.com/apache/airflow/pull/73702

   This makes `GlueJobOperator`'s `stop_job_run_on_kill` work on the deferrable path: when a deferred Glue task is killed (for example, cleared while running), the trigger now stops the running Glue job run instead of leaving it running.
   
   ## Motivation
   
   Today `stop_job_run_on_kill` is only honoured by the operator's synchronous `on_kill`, which does not run for a deferred task (the task lives in the triggerer, not on a worker). So a cleared deferrable Glue task left its Spark job running. `EmrServerlessStartJobOperator`'s trigger already cancels the AWS job on kill, so the two Spark-submitting operators behaved differently on the same user action. This brings Glue into line.
   
   `GlueJobCompleteTrigger` now honours `stop_job_run_on_kill`:
   
   - **Airflow 3.3+** — via the trigger's `on_kill()` hook, which the triggerer calls only for user-initiated kills.
   - **Older Airflow** — via a `CancelledError` handler in `run()`, guarded by a task-state check (`safe_to_cancel`) so that a triggerer restart does not stop a still-healthy run.
   
   The behaviour is opt-in and unchanged by default (`stop_job_run_on_kill=False`).
   
   ## Context
   
   This is the second of two PRs aligning EMR Serverless and Glue deferrable behaviour so both Spark-submitting operators expose the same knobs:
   
   - durable reconnect on EMR Serverless (mirrors Glue's `durable`) — #73701.
   - this PR: `stop_job_run_on_kill` on Glue's deferrable path (mirrors EMR's `cancel_on_kill`).
   
   Paired with `durable`, `stop_job_run_on_kill=True` gives "stop the old run, submit fresh" on clear; leaving it `False` keeps the reconnect-on-clear behaviour.
   
   ## Testing
   
   - New trigger unit tests: serialization, `on_kill` (enabled/disabled), `run()` cancellation (safe → stop, unsafe → skip, 3.3+ sentinel → skip), and the `safe_to_cancel` task-state check.
   - New operator test: the deferred trigger receives `stop_job_run_on_kill`.
   - Full `test_glue.py` trigger + operator suites green (138 passed).
   - Provider `mypy` and other Docker-dependent prek hooks were not run locally (Docker unavailable); CI will validate them.
   
   ---
   
   ##### Was generative AI tooling used to co-author this PR?
   
   - [X] Yes — Claude Code (Opus 4.8)
   
   Generated-by: Claude Code (Opus 4.8) following [the guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-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] Stop AWS Glue job run when a deferred task is cleared [airflow]

Posted by "Leondon9 (via GitHub)" <gi...@apache.org>.
Leondon9 commented on code in PR #73702:
URL: https://github.com/apache/airflow/pull/73702#discussion_r4171661989


##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/glue.py:
##########
@@ -85,8 +103,114 @@ def __init__(
         self.job_name = job_name
         self.run_id = run_id
         self.verbose = verbose
+        self.stop_job_run_on_kill = stop_job_run_on_kill
+
+    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
+
+            ti = self.task_instance
+            if ti is None:
+                raise RuntimeError("task_instance is not set on the trigger")
+            query = select(TaskInstance).where(
+                TaskInstance.dag_id == ti.dag_id,
+                TaskInstance.task_id == ti.task_id,
+                TaskInstance.run_id == ti.run_id,
+                TaskInstance.map_index == ti.map_index,
+            )
+            task_instance = session.scalars(query).one_or_none()
+            if task_instance is None:
+                raise ValueError(
+                    f"TaskInstance with dag_id: {ti.dag_id}, "
+                    f"task_id: {ti.task_id}, "
+                    f"run_id: {ti.run_id} and "
+                    f"map_index: {ti.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 Exception:
+            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_state
+
+    async def safe_to_cancel(self) -> bool:
+        """
+        Whether it is safe to stop the Glue job run.
+
+        Returns True if the task is NOT DEFERRED (a user-initiated clear/kill). Returns False if the
+        task is still DEFERRED, which means the triggerer is merely restarting and the job must keep
+        running.
+        """
+        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]:
+        """
+        Watch the Glue job run to completion.
+
+        If the task is killed while waiting, stop the Glue job run when ``stop_job_run_on_kill`` is
+        enabled and it is safe to do so.
+        """
+        try:
+            async for event in self._watch():
+                yield event
+        except asyncio.CancelledError as e:

Review Comment:
   Agreed, dropped the `CancelledError` handler and the `safe_to_cancel`/`get_task_state` helpers; the trigger now relies on `on_kill()` only, like `EmrContainerTrigger`, and the hook is inert below 3.3 (noted in the docstring). Thanks for catching the mapped-task key. The same `[run_id][task_id]` lookup is in `EmrServerlessStartJobTrigger` and a few Google triggers, so I'll look at that separately.
   
   ---
   Drafted-by: Claude Code (Opus 5.5); reviewed by @Leondon9 before posting



##########
providers/amazon/src/airflow/providers/amazon/aws/operators/glue.py:
##########
@@ -260,6 +267,21 @@ def __init__(
         self.deferrable = deferrable
         self.job_poll_interval = job_poll_interval
         self.stop_job_run_on_kill = stop_job_run_on_kill
+        # In deferrable mode durable reconnects to the still-running job on clear, while
+        # stop_job_run_on_kill stops it via the trigger: the two are mutually exclusive there. Because
+        # the worker re-executes before the trigger's on_kill runs, a durable retry would reconnect to
+        # a run that on_kill is about to stop and then fail, so reject the contradiction and keep
+        # durable off when the caller asked to stop on kill. (In synchronous mode there is no such
+        # race -- on_kill runs on the worker before the retry -- so the combination is allowed.)
+        if self.deferrable and self.stop_job_run_on_kill and self.durable:

Review Comment:
   Removed. The operator change is now just passing `stop_job_run_on_kill` to the trigger, so the `durable` default and parsing behaviour are untouched. You're right that it didn't give a fresh run either: the retry submits while the old run is still RUNNING/STOPPING. I've noted that as out of scope in the description; stopping the prior run on the worker and waiting for STOPPED before submitting looks like the right fix, and I'll take that up separately.
   
   ---
   Drafted-by: Claude Code (Opus 5.5); reviewed by @Leondon9 before posting



##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/glue.py:
##########
@@ -85,8 +103,114 @@ def __init__(
         self.job_name = job_name
         self.run_id = run_id
         self.verbose = verbose
+        self.stop_job_run_on_kill = stop_job_run_on_kill
+
+    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
+
+            ti = self.task_instance
+            if ti is None:
+                raise RuntimeError("task_instance is not set on the trigger")
+            query = select(TaskInstance).where(
+                TaskInstance.dag_id == ti.dag_id,
+                TaskInstance.task_id == ti.task_id,
+                TaskInstance.run_id == ti.run_id,
+                TaskInstance.map_index == ti.map_index,
+            )
+            task_instance = session.scalars(query).one_or_none()
+            if task_instance is None:
+                raise ValueError(
+                    f"TaskInstance with dag_id: {ti.dag_id}, "
+                    f"task_id: {ti.task_id}, "
+                    f"run_id: {ti.run_id} and "
+                    f"map_index: {ti.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 Exception:
+            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_state
+
+    async def safe_to_cancel(self) -> bool:
+        """
+        Whether it is safe to stop the Glue job run.
+
+        Returns True if the task is NOT DEFERRED (a user-initiated clear/kill). Returns False if the
+        task is still DEFERRED, which means the triggerer is merely restarting and the job must keep
+        running.
+        """
+        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]:
+        """
+        Watch the Glue job run to completion.
+
+        If the task is killed while waiting, stop the Glue job run when ``stop_job_run_on_kill`` is
+        enabled and it is safe to do so.
+        """
+        try:
+            async for event in self._watch():
+                yield event
+        except asyncio.CancelledError as e:
+            # TODO: Remove this handler once the minimum supported Airflow version is 3.3+.
+            # On Airflow 3.3+ the triggerer passes a sentinel via task.cancel(msg) for
+            # user-initiated kills and calls on_kill() separately -- skip here to avoid stopping
+            # the job twice. On older Airflow there is no sentinel, so we handle it here.
+            if not (e.args and e.args[0] == "__airflow_user_action__"):
+                if self.run_id and self.stop_job_run_on_kill and await self.safe_to_cancel():
+                    self.log.info(
+                        "Task was cancelled. Stopping AWS Glue job %s run %s.", self.job_name, self.run_id
+                    )
+                    self.hook().conn.batch_stop_job_run(JobName=self.job_name, JobRunIds=[self.run_id])
+                else:
+                    self.log.info(
+                        "Trigger may have shut down or stop_job_run_on_kill is disabled. "
+                        "Skipping stop of AWS Glue job %s run %s.",
+                        self.job_name,
+                        self.run_id,
+                    )
+            raise
+
+    async def on_kill(self) -> None:
+        """
+        Stop the Glue job run when the trigger is cancelled by a user action.
+
+        Available on Airflow 3.3+ via ``BaseTrigger.on_kill()``. On older Airflow the
+        ``CancelledError`` handler in ``run()`` provides the same behaviour.
+        """
+        if self.run_id and self.stop_job_run_on_kill:
+            self.log.info("Stopping AWS Glue job %s run %s.", self.job_name, self.run_id)
+            await sync_to_async(self.hook().conn.batch_stop_job_run)(

Review Comment:
   Done: `on_kill` now uses `get_async_conn()` and logs the `Errors` from `batch_stop_job_run`. Added a docstring note that released 3.3.x cores also call it on triggerer failover (fixed in #73454).
   
   ---
   Drafted-by: Claude Code (Opus 5.5); reviewed by @Leondon9 before posting



-- 
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] Stop AWS Glue job run when a deferred task is cleared [airflow]

Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on PR #73702:
URL: https://github.com/apache/airflow/pull/73702#issuecomment-5832921494

   @seanghaeli @ramitkataria 


-- 
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] Stop AWS Glue job run when a deferred task is cleared [airflow]

Posted by "ramitkataria (via GitHub)" <gi...@apache.org>.
ramitkataria commented on code in PR #73702:
URL: https://github.com/apache/airflow/pull/73702#discussion_r4128155346


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/glue.py:
##########
@@ -260,6 +267,21 @@ def __init__(
         self.deferrable = deferrable
         self.job_poll_interval = job_poll_interval
         self.stop_job_run_on_kill = stop_job_run_on_kill
+        # In deferrable mode durable reconnects to the still-running job on clear, while
+        # stop_job_run_on_kill stops it via the trigger: the two are mutually exclusive there. Because
+        # the worker re-executes before the trigger's on_kill runs, a durable retry would reconnect to
+        # a run that on_kill is about to stop and then fail, so reject the contradiction and keep
+        # durable off when the caller asked to stop on kill. (In synchronous mode there is no such
+        # race -- on_kill runs on the worker before the retry -- so the combination is allowed.)
+        if self.deferrable and self.stop_job_run_on_kill and self.durable:

Review Comment:
   Could this move to a separate PR? It overrides the 9.35.0 `durable` default, and the `ValueError` breaks Dags that parse today (e.g. `durable=True` via `default_args`). It also won't give a fresh run: the retry starts before `on_kill`, so with `MaxConcurrentRuns=1` it hits `ConcurrentRunsExceededException`. Handling it on the worker (stop the old run, wait for STOPPED, then submit) would cover sync mode too.



##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/glue.py:
##########
@@ -85,8 +103,114 @@ def __init__(
         self.job_name = job_name
         self.run_id = run_id
         self.verbose = verbose
+        self.stop_job_run_on_kill = stop_job_run_on_kill
+
+    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
+
+            ti = self.task_instance
+            if ti is None:
+                raise RuntimeError("task_instance is not set on the trigger")
+            query = select(TaskInstance).where(
+                TaskInstance.dag_id == ti.dag_id,
+                TaskInstance.task_id == ti.task_id,
+                TaskInstance.run_id == ti.run_id,
+                TaskInstance.map_index == ti.map_index,
+            )
+            task_instance = session.scalars(query).one_or_none()
+            if task_instance is None:
+                raise ValueError(
+                    f"TaskInstance with dag_id: {ti.dag_id}, "
+                    f"task_id: {ti.task_id}, "
+                    f"run_id: {ti.run_id} and "
+                    f"map_index: {ti.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 Exception:
+            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_state
+
+    async def safe_to_cancel(self) -> bool:
+        """
+        Whether it is safe to stop the Glue job run.
+
+        Returns True if the task is NOT DEFERRED (a user-initiated clear/kill). Returns False if the
+        task is still DEFERRED, which means the triggerer is merely restarting and the job must keep
+        running.
+        """
+        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]:
+        """
+        Watch the Glue job run to completion.
+
+        If the task is killed while waiting, stop the Glue job run when ``stop_job_run_on_kill`` is
+        enabled and it is safe to do so.
+        """
+        try:
+            async for event in self._watch():
+                yield event
+        except asyncio.CancelledError as e:

Review Comment:
   I'd drop this handler and the helpers above, and keep only `on_kill` like `EmrContainerTrigger` does. The copied logic breaks for mapped tasks (`get_task_states` keys by `f"{task_id}_{map_index}"`, so the lookup raises and fails the task on failover). It also still runs on 3.3+ reassignment cancels and calls `self.hook().conn` synchronously on the event loop.



##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/glue.py:
##########
@@ -85,8 +103,114 @@ def __init__(
         self.job_name = job_name
         self.run_id = run_id
         self.verbose = verbose
+        self.stop_job_run_on_kill = stop_job_run_on_kill
+
+    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
+
+            ti = self.task_instance
+            if ti is None:
+                raise RuntimeError("task_instance is not set on the trigger")
+            query = select(TaskInstance).where(
+                TaskInstance.dag_id == ti.dag_id,
+                TaskInstance.task_id == ti.task_id,
+                TaskInstance.run_id == ti.run_id,
+                TaskInstance.map_index == ti.map_index,
+            )
+            task_instance = session.scalars(query).one_or_none()
+            if task_instance is None:
+                raise ValueError(
+                    f"TaskInstance with dag_id: {ti.dag_id}, "
+                    f"task_id: {ti.task_id}, "
+                    f"run_id: {ti.run_id} and "
+                    f"map_index: {ti.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 Exception:
+            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_state
+
+    async def safe_to_cancel(self) -> bool:
+        """
+        Whether it is safe to stop the Glue job run.
+
+        Returns True if the task is NOT DEFERRED (a user-initiated clear/kill). Returns False if the
+        task is still DEFERRED, which means the triggerer is merely restarting and the job must keep
+        running.
+        """
+        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]:
+        """
+        Watch the Glue job run to completion.
+
+        If the task is killed while waiting, stop the Glue job run when ``stop_job_run_on_kill`` is
+        enabled and it is safe to do so.
+        """
+        try:
+            async for event in self._watch():
+                yield event
+        except asyncio.CancelledError as e:
+            # TODO: Remove this handler once the minimum supported Airflow version is 3.3+.
+            # On Airflow 3.3+ the triggerer passes a sentinel via task.cancel(msg) for
+            # user-initiated kills and calls on_kill() separately -- skip here to avoid stopping
+            # the job twice. On older Airflow there is no sentinel, so we handle it here.
+            if not (e.args and e.args[0] == "__airflow_user_action__"):
+                if self.run_id and self.stop_job_run_on_kill and await self.safe_to_cancel():
+                    self.log.info(
+                        "Task was cancelled. Stopping AWS Glue job %s run %s.", self.job_name, self.run_id
+                    )
+                    self.hook().conn.batch_stop_job_run(JobName=self.job_name, JobRunIds=[self.run_id])
+                else:
+                    self.log.info(
+                        "Trigger may have shut down or stop_job_run_on_kill is disabled. "
+                        "Skipping stop of AWS Glue job %s run %s.",
+                        self.job_name,
+                        self.run_id,
+                    )
+            raise
+
+    async def on_kill(self) -> None:
+        """
+        Stop the Glue job run when the trigger is cancelled by a user action.
+
+        Available on Airflow 3.3+ via ``BaseTrigger.on_kill()``. On older Airflow the
+        ``CancelledError`` handler in ``run()`` provides the same behaviour.
+        """
+        if self.run_id and self.stop_job_run_on_kill:
+            self.log.info("Stopping AWS Glue job %s run %s.", self.job_name, self.run_id)
+            await sync_to_async(self.hook().conn.batch_stop_job_run)(

Review Comment:
   Could this use `get_async_conn()` like `_watch`, and check `Errors` in the response? `sync_to_async(self.hook().conn...)` still builds the client on the loop thread. A docstring note would help too: released 3.3.x cores also send the user-action cancel on triggerer failover (fixed in #73454, main only).



-- 
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] Stop AWS Glue job run when a deferred task is cleared [airflow]

Posted by "Leondon9 (via GitHub)" <gi...@apache.org>.
Leondon9 commented on code in PR #73702:
URL: https://github.com/apache/airflow/pull/73702#discussion_r4171662047


##########
providers/amazon/src/airflow/providers/amazon/aws/operators/glue.py:
##########
@@ -260,6 +267,21 @@ def __init__(
         self.deferrable = deferrable
         self.job_poll_interval = job_poll_interval
         self.stop_job_run_on_kill = stop_job_run_on_kill
+        # In deferrable mode durable reconnects to the still-running job on clear, while
+        # stop_job_run_on_kill stops it via the trigger: the two are mutually exclusive there. Because
+        # the worker re-executes before the trigger's on_kill runs, a durable retry would reconnect to
+        # a run that on_kill is about to stop and then fail, so reject the contradiction and keep
+        # durable off when the caller asked to stop on kill. (In synchronous mode there is no such
+        # race -- on_kill runs on the worker before the retry -- so the combination is allowed.)
+        if self.deferrable and self.stop_job_run_on_kill and self.durable:

Review Comment:
   Removed. The operator change is now just passing `stop_job_run_on_kill` to the trigger, so the `durable` default and parsing behaviour are untouched. You're right that it didn't give a fresh run either: the retry submits while the old run is still RUNNING/STOPPING. I've noted that as out of scope in the description; stopping the prior run on the worker and waiting for STOPPED before submitting looks like the right fix, and I'll take that up separately.



##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/glue.py:
##########
@@ -85,8 +103,114 @@ def __init__(
         self.job_name = job_name
         self.run_id = run_id
         self.verbose = verbose
+        self.stop_job_run_on_kill = stop_job_run_on_kill
+
+    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
+
+            ti = self.task_instance
+            if ti is None:
+                raise RuntimeError("task_instance is not set on the trigger")
+            query = select(TaskInstance).where(
+                TaskInstance.dag_id == ti.dag_id,
+                TaskInstance.task_id == ti.task_id,
+                TaskInstance.run_id == ti.run_id,
+                TaskInstance.map_index == ti.map_index,
+            )
+            task_instance = session.scalars(query).one_or_none()
+            if task_instance is None:
+                raise ValueError(
+                    f"TaskInstance with dag_id: {ti.dag_id}, "
+                    f"task_id: {ti.task_id}, "
+                    f"run_id: {ti.run_id} and "
+                    f"map_index: {ti.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 Exception:
+            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_state
+
+    async def safe_to_cancel(self) -> bool:
+        """
+        Whether it is safe to stop the Glue job run.
+
+        Returns True if the task is NOT DEFERRED (a user-initiated clear/kill). Returns False if the
+        task is still DEFERRED, which means the triggerer is merely restarting and the job must keep
+        running.
+        """
+        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]:
+        """
+        Watch the Glue job run to completion.
+
+        If the task is killed while waiting, stop the Glue job run when ``stop_job_run_on_kill`` is
+        enabled and it is safe to do so.
+        """
+        try:
+            async for event in self._watch():
+                yield event
+        except asyncio.CancelledError as e:

Review Comment:
   Agreed, dropped the `CancelledError` handler and the `safe_to_cancel`/`get_task_state` helpers; the trigger now relies on `on_kill()` only, like `EmrContainerTrigger`, and the hook is inert below 3.3 (noted in the docstring). Thanks for catching the mapped-task key. The same `[run_id][task_id]` lookup is in `EmrServerlessStartJobTrigger` and a few Google triggers, so I'll look at that separately.



##########
providers/amazon/src/airflow/providers/amazon/aws/operators/glue.py:
##########
@@ -260,6 +267,21 @@ def __init__(
         self.deferrable = deferrable
         self.job_poll_interval = job_poll_interval
         self.stop_job_run_on_kill = stop_job_run_on_kill
+        # In deferrable mode durable reconnects to the still-running job on clear, while
+        # stop_job_run_on_kill stops it via the trigger: the two are mutually exclusive there. Because
+        # the worker re-executes before the trigger's on_kill runs, a durable retry would reconnect to
+        # a run that on_kill is about to stop and then fail, so reject the contradiction and keep
+        # durable off when the caller asked to stop on kill. (In synchronous mode there is no such
+        # race -- on_kill runs on the worker before the retry -- so the combination is allowed.)
+        if self.deferrable and self.stop_job_run_on_kill and self.durable:

Review Comment:
   Removed. The operator change is now just passing `stop_job_run_on_kill` to the trigger, so the `durable` default and parsing behaviour are untouched. You're right that it didn't give a fresh run either: the retry submits while the old run is still RUNNING/STOPPING. I've noted that as out of scope in the description; stopping the prior run on the worker and waiting for STOPPED before submitting looks like the right fix, and I'll take that up separately.



##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/glue.py:
##########
@@ -85,8 +103,114 @@ def __init__(
         self.job_name = job_name
         self.run_id = run_id
         self.verbose = verbose
+        self.stop_job_run_on_kill = stop_job_run_on_kill
+
+    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
+
+            ti = self.task_instance
+            if ti is None:
+                raise RuntimeError("task_instance is not set on the trigger")
+            query = select(TaskInstance).where(
+                TaskInstance.dag_id == ti.dag_id,
+                TaskInstance.task_id == ti.task_id,
+                TaskInstance.run_id == ti.run_id,
+                TaskInstance.map_index == ti.map_index,
+            )
+            task_instance = session.scalars(query).one_or_none()
+            if task_instance is None:
+                raise ValueError(
+                    f"TaskInstance with dag_id: {ti.dag_id}, "
+                    f"task_id: {ti.task_id}, "
+                    f"run_id: {ti.run_id} and "
+                    f"map_index: {ti.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 Exception:
+            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_state
+
+    async def safe_to_cancel(self) -> bool:
+        """
+        Whether it is safe to stop the Glue job run.
+
+        Returns True if the task is NOT DEFERRED (a user-initiated clear/kill). Returns False if the
+        task is still DEFERRED, which means the triggerer is merely restarting and the job must keep
+        running.
+        """
+        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]:
+        """
+        Watch the Glue job run to completion.
+
+        If the task is killed while waiting, stop the Glue job run when ``stop_job_run_on_kill`` is
+        enabled and it is safe to do so.
+        """
+        try:
+            async for event in self._watch():
+                yield event
+        except asyncio.CancelledError as e:
+            # TODO: Remove this handler once the minimum supported Airflow version is 3.3+.
+            # On Airflow 3.3+ the triggerer passes a sentinel via task.cancel(msg) for
+            # user-initiated kills and calls on_kill() separately -- skip here to avoid stopping
+            # the job twice. On older Airflow there is no sentinel, so we handle it here.
+            if not (e.args and e.args[0] == "__airflow_user_action__"):
+                if self.run_id and self.stop_job_run_on_kill and await self.safe_to_cancel():
+                    self.log.info(
+                        "Task was cancelled. Stopping AWS Glue job %s run %s.", self.job_name, self.run_id
+                    )
+                    self.hook().conn.batch_stop_job_run(JobName=self.job_name, JobRunIds=[self.run_id])
+                else:
+                    self.log.info(
+                        "Trigger may have shut down or stop_job_run_on_kill is disabled. "
+                        "Skipping stop of AWS Glue job %s run %s.",
+                        self.job_name,
+                        self.run_id,
+                    )
+            raise
+
+    async def on_kill(self) -> None:
+        """
+        Stop the Glue job run when the trigger is cancelled by a user action.
+
+        Available on Airflow 3.3+ via ``BaseTrigger.on_kill()``. On older Airflow the
+        ``CancelledError`` handler in ``run()`` provides the same behaviour.
+        """
+        if self.run_id and self.stop_job_run_on_kill:
+            self.log.info("Stopping AWS Glue job %s run %s.", self.job_name, self.run_id)
+            await sync_to_async(self.hook().conn.batch_stop_job_run)(

Review Comment:
   Done: `on_kill` now uses `get_async_conn()` and logs the `Errors` from `batch_stop_job_run`. Added a docstring note that released 3.3.x cores also call it on triggerer failover (fixed in #73454).
   



##########
providers/amazon/src/airflow/providers/amazon/aws/triggers/glue.py:
##########
@@ -85,8 +103,114 @@ def __init__(
         self.job_name = job_name
         self.run_id = run_id
         self.verbose = verbose
+        self.stop_job_run_on_kill = stop_job_run_on_kill
+
+    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
+
+            ti = self.task_instance
+            if ti is None:
+                raise RuntimeError("task_instance is not set on the trigger")
+            query = select(TaskInstance).where(
+                TaskInstance.dag_id == ti.dag_id,
+                TaskInstance.task_id == ti.task_id,
+                TaskInstance.run_id == ti.run_id,
+                TaskInstance.map_index == ti.map_index,
+            )
+            task_instance = session.scalars(query).one_or_none()
+            if task_instance is None:
+                raise ValueError(
+                    f"TaskInstance with dag_id: {ti.dag_id}, "
+                    f"task_id: {ti.task_id}, "
+                    f"run_id: {ti.run_id} and "
+                    f"map_index: {ti.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 Exception:
+            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_state
+
+    async def safe_to_cancel(self) -> bool:
+        """
+        Whether it is safe to stop the Glue job run.
+
+        Returns True if the task is NOT DEFERRED (a user-initiated clear/kill). Returns False if the
+        task is still DEFERRED, which means the triggerer is merely restarting and the job must keep
+        running.
+        """
+        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]:
+        """
+        Watch the Glue job run to completion.
+
+        If the task is killed while waiting, stop the Glue job run when ``stop_job_run_on_kill`` is
+        enabled and it is safe to do so.
+        """
+        try:
+            async for event in self._watch():
+                yield event
+        except asyncio.CancelledError as e:
+            # TODO: Remove this handler once the minimum supported Airflow version is 3.3+.
+            # On Airflow 3.3+ the triggerer passes a sentinel via task.cancel(msg) for
+            # user-initiated kills and calls on_kill() separately -- skip here to avoid stopping
+            # the job twice. On older Airflow there is no sentinel, so we handle it here.
+            if not (e.args and e.args[0] == "__airflow_user_action__"):
+                if self.run_id and self.stop_job_run_on_kill and await self.safe_to_cancel():
+                    self.log.info(
+                        "Task was cancelled. Stopping AWS Glue job %s run %s.", self.job_name, self.run_id
+                    )
+                    self.hook().conn.batch_stop_job_run(JobName=self.job_name, JobRunIds=[self.run_id])
+                else:
+                    self.log.info(
+                        "Trigger may have shut down or stop_job_run_on_kill is disabled. "
+                        "Skipping stop of AWS Glue job %s run %s.",
+                        self.job_name,
+                        self.run_id,
+                    )
+            raise
+
+    async def on_kill(self) -> None:
+        """
+        Stop the Glue job run when the trigger is cancelled by a user action.
+
+        Available on Airflow 3.3+ via ``BaseTrigger.on_kill()``. On older Airflow the
+        ``CancelledError`` handler in ``run()`` provides the same behaviour.
+        """
+        if self.run_id and self.stop_job_run_on_kill:
+            self.log.info("Stopping AWS Glue job %s run %s.", self.job_name, self.run_id)
+            await sync_to_async(self.hook().conn.batch_stop_job_run)(

Review Comment:
   Done: `on_kill` now uses `get_async_conn()` and logs the `Errors` from `batch_stop_job_run`. Added a docstring note that released 3.3.x cores also call it on triggerer failover (fixed in #73454).
   



-- 
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] Stop AWS Glue job run when a deferred task is cleared [airflow]

Posted by "seanghaeli (via GitHub)" <gi...@apache.org>.
seanghaeli commented on PR #73702:
URL: https://github.com/apache/airflow/pull/73702#issuecomment-6226541701

   On my machine I'm seeing a problem arise with this PR when a deferred task is cleared. `clear` instructs the task to run again, and on 3.3+ the re-run looks for an existing Glue job from the same task. It finds the old one still running, and decides to just wait on that one. But clearing also triggers this PR's "on kill" step, which stops that same old Glue job. So the re-run ends up waiting on a stopped job and fails with `STOPPED`. On main, the re-run reattached and succeeded.
   
   Could the re-run start a fresh Glue job when `stop_job_run_on_kill=True`, instead of reattaching?


-- 
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] Stop AWS Glue job run when a deferred task is cleared [airflow]

Posted by "Leondon9 (via GitHub)" <gi...@apache.org>.
Leondon9 commented on PR #73702:
URL: https://github.com/apache/airflow/pull/73702#issuecomment-6229757648

   > On my machine I'm seeing a problem arise with this PR when a deferred task is cleared. `clear` instructs the task to run again, and on 3.3+ the re-run looks for an existing Glue job from the same task. It finds the old one still running, and decides to just wait on that one. But clearing also triggers this PR's "on kill" step, which stops that same old Glue job. So the re-run ends up waiting on a stopped job and fails with `STOPPED`. On main, the re-run reattached and succeeded.
   > 
   > Could the re-run start a fresh Glue job when `stop_job_run_on_kill=True`, instead of reattaching?
   
   Thanks for reproducing this, you're right. on_kill fires on any user action and can't tell a clear from mark failed/success, so the re-run reattached to the run it was stopping.
   Fixed in db0041cde4: with stop_job_run_on_kill=True in deferrable mode, a retried try no longer reattaches. It stops the previous run itself, waits for it to reach a terminal state (a STOPPING run still counts toward MaxConcurrentRuns), then submits a fresh one.
   If the run doesn't stop within 10 minutes, the try fails instead of starting a second run.
   durable and its default are unchanged, so stop_job_run_on_kill=False still reattaches as before. 
   Would you mind re-running your clear scenario?


-- 
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] Stop AWS Glue job run when a deferred task is cleared [airflow]

Posted by "o-nikolas (via GitHub) via commits" <co...@airflow.apache.org>.
o-nikolas merged PR #73702:
URL: https://github.com/apache/airflow/pull/73702


-- 
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