Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Deleting a pipeline's Airflow DAG stops its active run instead of failing

- **Status:** Accepted
- **Revisions:** v1 2026-10-29 (initial)
- **Deciders:** Sonika Shah
- **Guard:** `test_delete_stops_a_running_dag_and_removes_it`, `test_failed_delete_leaves_active_runs_untouched` in `openmetadata-airflow-apis/tests/integration/operations/test_dag_lifecycle.py`
- **Related:** #36350, #36349, #36267

## Context

Airflow's `delete_dag` refuses while any task instance of the DAG is running. The server commits
the hard delete of an ingestion pipeline (`cleanup()`) before `postDelete` asks the runner to
remove the DAG, so a refusal cannot keep the pipeline: returning 409 from the plugin left the
pipeline deleted and the DAG in Airflow, still scheduled, with nothing in OpenMetadata to manage it.

## Decision

When `delete_dag` raises because a task instance is running, the plugin's delete operation fails
the DAG's unfinished runs and task instances (as `kill` does) and deletes again, in one
transaction: if the retried delete also fails, nothing is committed, so the runs stay as they were
and the DAG files stay on disk. Any other Airflow error propagates the same way.

## Consequences

- Every delete path (direct, by name, async, force, service recursive cascade, app uninstall)
removes the DAG, because all of them reach this one plugin endpoint.
- Deleting a pipeline mid-run ends that run as failed; the running task is terminated by Airflow.
- A task that starts running between the stop and the retry makes the retry fail; the delete then
fails as it did before this record, with the run left untouched.
- Revisit only if the server moves the runner teardown ahead of its DB commit; then refusing the
delete would become a viable alternative.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
from pathlib import Path

from airflow import settings
from airflow.exceptions import DagNotFound
from airflow.exceptions import AirflowException, DagNotFound
from airflow.models import TaskInstance
from airflow.utils.state import TaskInstanceState
from flask import Response

try:
Expand All @@ -29,6 +31,10 @@
DAG_GENERATED_CONFIGS,
)
from openmetadata_managed_apis.api.response import ApiResponse
from openmetadata_managed_apis.operations.kill_all import (
fail_unfinished_runs,
fail_unfinished_task_instances,
)
from openmetadata_managed_apis.utils.logger import operations_logger

logger = operations_logger()
Expand All @@ -43,11 +49,9 @@ def delete_dag_id(dag_id: str) -> Response:
- DAG metadata, versions, runs and task history in airflow db

Order matters: run Airflow's own delete FIRST so that its FK ordering
(a task instance pins the DAG version it ran, so deleting the DAG first
is refused when a task is still running) is enforced BEFORE the files
are removed. When Airflow refuses (raises AirflowException / RuntimeError
on running task instances), the files stay on disk and Airflow's next
parse can restore the DAG rather than leaving an orphan.
(a task instance pins the DAG version it ran) is enforced BEFORE the
files are removed. If that delete still fails, the files stay on disk
and Airflow's next parse can restore the DAG rather than leaving an orphan.
:param dag_id: DAG to delete
:return: API Response
"""
Expand All @@ -56,10 +60,7 @@ def delete_dag_id(dag_id: str) -> Response:
config_file = Path(DAG_GENERATED_CONFIGS) / f"{dag_id}.json"

with settings.Session() as session:
try:
deleted_dags = airflow_delete_dag(dag_id, session=session)
except DagNotFound:
deleted_dags = 0
deleted_dags = _delete_dag_records(dag_id, session)
session.commit()

deleted_file = False
Expand All @@ -83,3 +84,27 @@ def delete_dag_id(dag_id: str) -> Response:
deleted_config,
)
return ApiResponse.server_error()


def _delete_dag_records(dag_id: str, session) -> int:
try:
return airflow_delete_dag(dag_id, session=session)
except DagNotFound:
return 0
except AirflowException:
# Airflow refuses while a task is running (e.g. a scheduled run); the caller is deleting
# the pipeline for good, so stop the run the same way kill does and delete again
# (ADR:2026-10-29-deleting-a-pipeline-dag-stops-its-active-run)
if not _has_running_task_instances(dag_id, session):
raise
logger.info("Stopping the active run of DAG %s before deleting it", dag_id)
if not fail_unfinished_runs(dag_id, session):
fail_unfinished_task_instances(dag_id, session)
return airflow_delete_dag(dag_id, session=session)
Comment thread
gitar-bot[bot] marked this conversation as resolved.
Resolved
Comment thread
gitar-bot[bot] marked this conversation as resolved.
Resolved


def _has_running_task_instances(dag_id: str, session) -> bool:
running = session.query(TaskInstance).filter(
TaskInstance.dag_id == dag_id, TaskInstance.state == TaskInstanceState.RUNNING
)
return session.query(running.exists()).scalar()
Original file line number Diff line number Diff line change
Expand Up @@ -34,29 +34,55 @@ def kill_all(dag_id: str) -> Response:
if not dag_model:
return ApiResponse.not_found(f"DAG {dag_id} not found.")

runs: list[DagRun] = (
session.query(DagRun)
.filter(
DagRun.dag_id == dag_id,
DagRun.state.in_((DagRunState.RUNNING, DagRunState.QUEUED)),
)
.all()
)
if not fail_unfinished_runs(dag_id, session):
return ApiResponse.not_found(f"Workflow [{dag_id}] has no running or pending runs nor tasks")

instances: list[TaskInstance] = session.query(TaskInstance).filter(
TaskInstance.dag_id == dag_id,
TaskInstance.state.notin_((TaskInstanceState.SUCCESS, TaskInstanceState.FAILED)),
session.commit()

return ApiResponse.success({"message": f"Workflow [{dag_id}] has been killed"})


def fail_unfinished_runs(dag_id: str, session) -> bool:
"""
Mark the DAG's running or queued runs and their unfinished task instances as failed.
:param dag_id: DAG whose runs to stop
:param session: Airflow DB session; the caller commits
:return: whether there was a run to stop
"""
runs: list[DagRun] = (
session.query(DagRun)
.filter(
DagRun.dag_id == dag_id,
DagRun.state.in_((DagRunState.RUNNING, DagRunState.QUEUED)),
)
.all()
)

if not runs or not instances:
return ApiResponse.not_found(f"Workflow [{dag_id}] has no running or pending runs nor tasks")
if not runs:
return False

for dag_run in runs:
dag_run.set_state(DagRunState.FAILED)
for dag_run in runs:
dag_run.set_state(DagRunState.FAILED)

for instance in instances:
instance.set_state(TaskInstanceState.FAILED)
fail_unfinished_task_instances(dag_id, session)

session.commit()
return True

return ApiResponse.success({"message": f"Workflow [{dag_id}] has been killed"})

def fail_unfinished_task_instances(dag_id: str, session) -> None:
"""
Mark every unfinished task instance of the DAG as failed, whatever the state of its run.
:param dag_id: DAG whose task instances to stop
:param session: Airflow DB session; the caller commits
"""
instances: list[TaskInstance] = (
session.query(TaskInstance)
.filter(
TaskInstance.dag_id == dag_id,
TaskInstance.state.notin_((TaskInstanceState.SUCCESS, TaskInstanceState.FAILED)),
)
.all()
)

for instance in instances:
instance.set_state(TaskInstanceState.FAILED, session=session)
Original file line number Diff line number Diff line change
Expand Up @@ -102,20 +102,45 @@ def test_delete_dag_with_versioned_task_history(stored_dag):
assert session.query(model).filter_by(dag_id=name).count() == 0


def test_running_dag_keeps_its_files_when_deletion_is_rejected(stored_dag):
name, dag_file, config_file, _ = stored_dag
@pytest.mark.parametrize("run_state", [DagRunState.RUNNING, DagRunState.SUCCESS])
def test_delete_stops_a_running_dag_and_removes_it(stored_dag, run_state):
name, dag_file, config_file, version_model = stored_dag
with settings.Session() as session:
session.query(DagRun).filter_by(dag_id=name).update({"state": run_state})
session.query(TaskInstance).filter_by(dag_id=name).update({"state": TaskInstanceState.RUNNING})
session.commit()

with (
Flask(__name__).app_context(),
pytest.raises(AirflowException, match="TaskInstances still running"),
):
with Flask(__name__).app_context():
response = delete.delete_dag_id(name)

assert response.status_code == 200
assert not dag_file.exists()
assert not config_file.exists()
with settings.Session() as session:
for model in (TaskInstance, DagRun, version_model, DagModel):
assert session.query(model).filter_by(dag_id=name).count() == 0


@pytest.mark.parametrize("ti_state", [TaskInstanceState.QUEUED, TaskInstanceState.RUNNING])
def test_failed_delete_leaves_active_runs_untouched(stored_dag, monkeypatch, ti_state):
name, dag_file, config_file, _ = stored_dag
with settings.Session() as session:
session.query(DagRun).filter_by(dag_id=name).update({"state": DagRunState.RUNNING})
session.query(TaskInstance).filter_by(dag_id=name).update({"state": ti_state})
session.commit()

def refuse(dag_id, session=None):
raise AirflowException("refused")

monkeypatch.setattr(delete, "airflow_delete_dag", refuse)
with Flask(__name__).app_context(), pytest.raises(AirflowException, match="refused"):
delete.delete_dag_id(name)

assert dag_file.exists()
assert config_file.exists()
with settings.Session() as session:
assert session.query(DagRun).filter_by(dag_id=name).one().state == DagRunState.RUNNING
assert session.query(TaskInstance).filter_by(dag_id=name).one().state == ti_state


def test_invalid_dag_does_not_report_success(tmp_path, monkeypatch):
Expand Down
Loading