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

[PR] fix(task-sdk): handle missing DAG in TriggerDagRunOperator gracefully [airflow]

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

   ## Problem
   
   `TriggerDagRunOperator` crashes with `UnboundLocalError: cannot access local variable 'state'` when targeting a non-existent DAG. The API server returns 404, which `SUPERVISOR_COMMS.send()` re-raises as `ServerResponseError` — but this propagates past all exception handlers in `run()` into the `finally` block where `state` was declared but never assigned.
   
   ## Root Cause
   
   Two issues:
   
   1. `state: TaskInstanceState` in `run()` is declared without a default value. Any unhandled exception reaching the `finally` block causes `UnboundLocalError` when accessing `state.value` for stats.
   
   2. The `DagRunOperations.trigger()` client method only handles 409 (conflict) — a 404 from the API server is re-raised as `ServerResponseError`, which isn't caught by `_handle_trigger_dag_run`.
   
   ## Fix
   
   - Initialize `state = TaskInstanceState.FAILED` as a safe default so the `finally` block always works, regardless of what exception propagates.
   - Add `DAG_NOT_FOUND` to `ErrorType` enum.
   - Handle 404 in `DagRunOperations.trigger()`, returning `ErrorResponse(error=ErrorType.DAG_NOT_FOUND)`.
   - Handle `DAG_NOT_FOUND` in `_handle_trigger_dag_run`, failing the task gracefully instead of crashing.
   
   Tests added for both the client-side 404 handling and the task runner DAG-not-found path.
   
   Closes: #63089
   
   <!-- SPDX-License-Identifier: Apache-2.0
         https://www.apache.org/licenses/LICENSE-2.0 -->
   
   ---
   
   ##### Was generative AI tooling used to co-author this PR?
   
   - [X] Yes — Claude Code
   
   Generated-by: Claude Code following [the guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions)
   
   ---
   
   * Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)** for more information. Note: commit author/co-author name and email in commits become permanently public when merged.
   * For fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
   * When adding dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
   * For significant user-facing changes create newsfragment: `{pr_number}.significant.rst`, in [airflow-core/newsfragments](https://github.com/apache/airflow/tree/main/airflow-core/newsfragments). You can add this file in a follow-up commit after the PR is created so you know the PR number.
   


-- 
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(task-sdk): handle missing DAG in TriggerDagRunOperator gracefully [airflow]

Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk closed pull request #63207: fix(task-sdk): handle missing DAG in TriggerDagRunOperator gracefully
URL: https://github.com/apache/airflow/pull/63207


-- 
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(task-sdk): handle missing DAG in TriggerDagRunOperator gracefully [airflow]

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

   @YoannAbriel This draft PR has had no activity for 2 weeks. Closing to keep the queue clean.
   
   You are welcome to reopen and continue when you're ready. If you'd like to pick it back up, please rebase onto the current `main` branch first.
   
   ---
   
   _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(task-sdk): handle missing DAG in TriggerDagRunOperator gracefully [airflow]

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


##########
task-sdk/tests/task_sdk/execution_time/test_task_runner.py:
##########
@@ -4448,6 +4448,25 @@ def test_handle_trigger_dag_run_conflict(
         ]
         mock_supervisor_comms.assert_has_calls(expected_calls)
 
+    @time_machine.travel("2025-01-01 00:00:00", tick=False)
+    def test_handle_trigger_dag_run_dag_not_found(self, create_runtime_ti, mock_supervisor_comms):
+        """Test that TriggerDagRunOperator fails gracefully when the target DAG doesn't exist."""
+        from airflow.providers.standard.operators.trigger_dagrun import TriggerDagRunOperator
+
+        task = TriggerDagRunOperator(
+            task_id="test_task",
+            trigger_dag_id="nonexistent_dag",
+            trigger_run_id="test_run_id",
+        )
+        ti = create_runtime_ti(dag_id="test_handle_trigger_dag_run_not_found", run_id="test_run", task=task)
+
+        log = mock.MagicMock()
+        mock_supervisor_comms.send.return_value = ErrorResponse(error=ErrorType.DAG_NOT_FOUND)
+        state, msg, _ = run(ti, ti.get_template_context(), log)

Review Comment:
   New test introduces an unspecced `mock.MagicMock()` for `log`. Airflow’s testing guidelines prefer mocks with `spec`/`autospec` to avoid silently accepting unexpected attributes; consider using a real `structlog.get_logger(...)` or `mock.Mock(spec=...)` for the logger instead.



##########
task-sdk/src/airflow/sdk/api/client.py:
##########
@@ -724,6 +724,9 @@ def trigger(
                 f"dag-runs/{dag_id}/{run_id}", content=body.model_dump_json(exclude_defaults=True)
             )
         except ServerResponseError as e:
+            if e.response.status_code == HTTPStatus.NOT_FOUND:
+                log.error("Dag not found.", dag_id=dag_id)
+                return ErrorResponse(error=ErrorType.DAG_NOT_FOUND)

Review Comment:
   The new 404 handling logs only a generic "Dag not found" message and doesn’t include available response context (`e.detail`, `status_code`). Consider logging those fields (and/or returning them in `ErrorResponse.detail`) for easier debugging, consistent with other client methods’ 404 handling.
   ```suggestion
                   log.error(
                       "Dag not found.",
                       dag_id=dag_id,
                       status_code=e.response.status_code,
                       detail=e.detail,
                   )
                   return ErrorResponse(error=ErrorType.DAG_NOT_FOUND, detail=e.detail)
   ```



-- 
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(task-sdk): handle missing DAG in TriggerDagRunOperator gracefully [airflow]

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

   @YoannAbriel — Removing the `ready for maintainer review` label and converting back to draft. **The branch now has merge conflicts with `main`** that surfaced after the label was added.
   
   The label's contract is that the PR is ready for maintainer review — a regression like this means the PR temporarily isn't. Rebase your branch onto the latest `main`, resolve conflicts, then mark "Ready for review" again to re-enter the queue.
   
   `git fetch upstream main && git rebase upstream/main`, resolve, `git push --force-with-lease`. See the [working-with-git docs](https://github.com/apache/airflow/blob/main/contributing-docs/10_working_with_git.rst).
   
   No rush.
   
   ---
   
   _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