Skip to content

ForeignKeyViolation when doing airflow db clean (dag table) #71864

Open

Description

@igorlovich

Under which category would you file this issue?

Airflow Core

Apache Airflow version

3.3.0

What happened and how to reproduce it?

Creating a new issue as asked by @ephraimbuddy in #56192

Running

exec airflow db clean --clean-before-timestamp "${CLEAN_TS}" --yes --skip-archive --verbose

results in the following exception when cleaning the dag table

Checking table dag 
Found 31 rows meeting deletion criteria. 
Performing Delete... 
Moving data to table _airflow_deleted__dag__20260816000010 
    self.dialect.do_execute( 
  File "/home/airflow/.local/lib/python3.12/site-packages/sqlalchemy/engine/default.py", line 952, in do_execute 
    cursor.execute(statement, parameters) 
psycopg2.errors.RestrictViolation: update or delete on table "dag_version" violates RESTRICT setting of foreign key constraint "task_instance_dag_version_id_fkey" on table "task_instance" 
DETAIL:  Key (id)=(019a2639-6675-74ec-bafd-a4f6b7a58a07) is referenced from table "task_instance". 
 
 
The above exception was the direct cause of the following exception: 
 
Traceback (most recent call last): 
  File "/home/airflow/.local/bin/airflow", line 6, in <module> 
    sys.exit(main()) 
             ^^^^^^ 
  File "/home/airflow/.local/lib/python3.12/site-packages/airflow/__main__.py", line 55, in main 
    args.func(args) 
  File "/home/airflow/.local/lib/python3.12/site-packages/airflow/cli/cli_config.py", line 49, in command 
    return func(*args, **kwargs) 
           ^^^^^^^^^^^^^^^^^^^^^ 
  File "/home/airflow/.local/lib/python3.12/site-packages/airflow/utils/cli.py", line 113, in wrapper 
    return f(*args, **kwargs) 
           ^^^^^^^^^^^^^^^^^^ 
  File "/home/airflow/.local/lib/python3.12/site-packages/airflow/utils/providers_configuration_loader.py", line 54, in wrapped_function 
    return func(*args, **kwargs) 
           ^^^^^^^^^^^^^^^^^^^^^ 
  File "/home/airflow/.local/lib/python3.12/site-packages/airflow/cli/commands/db_command.py", line 358, in cleanup_tables 
    run_cleanup( 
  File "/home/airflow/.local/lib/python3.12/site-packages/airflow/utils/session.py", line 100, in wrapper 
    return func(*args, session=session, **kwargs)  # type: ignore[arg-type] 
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
  File "/home/airflow/.local/lib/python3.12/site-packages/airflow/utils/db_cleanup.py", line 689, in run_cleanup 
    _cleanup_table( 
  File "/home/airflow/.local/lib/python3.12/site-packages/airflow/utils/db_cleanup.py", line 486, in _cleanup_table 
    _do_delete( 
  File "/home/airflow/.local/lib/python3.12/site-packages/airflow/utils/db_cleanup.py", line 327, in _do_delete 
    raise e 
  File "/home/airflow/.local/lib/python3.12/site-packages/airflow/utils/db_cleanup.py", line 323, in _do_delete 
    session.execute(delete) 
  File "/home/airflow/.local/lib/python3.12/site-packages/sqlalchemy/orm/session.py", line 2373, in execute 
    return self._execute_internal( 
           ^^^^^^^^^^^^^^^^^^^^^^^ 
  File "/home/airflow/.local/lib/python3.12/site-packages/sqlalchemy/orm/session.py", line 2280, in _execute_internal 
    result = conn.execute( 
             ^^^^^^^^^^^^^ 
  File "/home/airflow/.local/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1421, in execute 
    return meth( 
           ^^^^^ 
  File "/home/airflow/.local/lib/python3.12/site-packages/sqlalchemy/sql/elements.py", line 526, in _execute_on_connection 
    return connection._execute_clauseelement( 
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
  File "/home/airflow/.local/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1643, in _execute_clauseelement 
    ret = self._execute_context( 
          ^^^^^^^^^^^^^^^^^^^^^^ 
  File "/home/airflow/.local/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1848, in _execute_context 
    return self._exec_single_context( 
           ^^^^^^^^^^^^^^^^^^^^^^^^^^ 
  File "/home/airflow/.local/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1988, in _exec_single_context 
    self._handle_dbapi_exception( 
  File "/home/airflow/.local/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 2365, in _handle_dbapi_exception 
    raise sqlalchemy_exception.with_traceback(exc_info[2]) from e 
  File "/home/airflow/.local/lib/python3.12/site-packages/sqlalchemy/engine/base.py", line 1969, in _exec_single_context 
    self.dialect.do_execute( 
  File "/home/airflow/.local/lib/python3.12/site-packages/sqlalchemy/engine/default.py", line 952, in do_execute 
    cursor.execute(statement, parameters) 
sqlalchemy.exc.IntegrityError: (psycopg2.errors.RestrictViolation) update or delete on table "dag_version" violates RESTRICT setting of foreign key constraint "task_instance_dag_version_id_fkey" on table "task_instance" 
DETAIL:  Key (id)=(019a2639-6675-74ec-bafd-a4f6b7a58a07) is referenced from table "task_instance". 
 
[SQL: DELETE FROM dag USING _airflow_deleted__dag__20260816000010 WHERE dag.dag_id = _airflow_deleted__dag__20260816000010.dag_id] 
(Background on this error at: https://sqlalche.me/e/20/gkpj) 

What you think should happen instead?

The clean job should run without errors

Operating System

Debian GNU/Linux 12 (bookworm)

Deployment

Official Apache Airflow Helm Chart

Apache Airflow Provider(s)

No response

Versions of Apache Airflow Providers

No response

Official Helm Chart version

1.22.0 (latest released)

Kubernetes Version

No response

Helm Chart configuration

No response

Docker Image customizations

No response

Anything else?

No response

Are you willing to submit PR?

  • Yes I am willing to submit a PR!

Code of Conduct

Activity

  1. added
    kind:bug
    needs-triage
    on Aug 20, 2026
  2. boring-cyborg commented on Aug 20, 2026

    @boring-cyborg

    Thanks for opening your first issue here! Be sure to follow the issue template! If you are willing to raise PR to address this issue please do so, no need to wait for approval.

  3. metabsd commented on Sep 15, 2026

    @metabsd

    I have the same bug

  4. fernando-luiz-effecti commented on Oct 13, 2026

    @fernando-luiz-effecti

    Same issue here on Airflow 3.3.1 (official chart 1.22.0, PostgreSQL 17).
    I found the cause and was able to reproduce it on a fresh install.

    Root cause

    The rows that block the delete are task instances that never started: state IS NULL, start_date IS NULL.
    They belong to a DAG that is paused and later becomes stale (its file was removed).

    1. The task_instance cleanup filters on start_date.
      It is NULL for these rows, so they are never eligible.
      The same happens to their dag_run, which stays queued with start_date NULL.
    2. The dag cleanup picks stale DAGs by last_parsed_time.
      Deleting those rows cascades to dag_version (dag_version_dag_id_fkey ... ON DELETE CASCADE).
    3. task_instance_dag_version_id_fkey is ON DELETE RESTRICT, so the whole DELETE FROM dag fails.
      Nothing checks whether the DAG's versions are still referenced before deleting.

    Once a DAG reaches this state, every later run of db clean fails on the dag table.
    Each failed run also leaves an _airflow_deleted__dag__* table behind.

    In production, 76 DAGs were eligible for deletion.
    2 of them had 7 task instances in this state, and that was enough to block the dag table for every run.

    Reproduction (fresh 3.3.1 DB, chart 1.22.0, dags_are_paused_at_creation=True)

    1. Add this DAG file and wait until it is parsed. It is created paused.

      from datetime import datetime
      from airflow.providers.standard.operators.empty import EmptyOperator
      from airflow.sdk import DAG
      
      with DAG(dag_id="repro_never_started", schedule=None,
               start_date=datetime(2026, 1, 1), catchup=False):
          EmptyOperator(task_id="a") >> EmptyOperator(task_id="b")
    2. Trigger it while it is still paused: airflow dags trigger repro_never_started.
      The result is a dag_run with state=queued and start_date NULL, plus 2 task instances with state NULL and start_date NULL.

    3. Delete the DAG file and wait for is_stale = true.

    4. Run airflow db clean --clean-before-timestamp "$(date -u +%Y-%m-%dT%H:%M:%S)" --yes --verbose:

      Checking table task_instance
      Found 0 rows meeting deletion criteria.
      ...
      Checking table dag_run
      Found 0 rows meeting deletion criteria.
      Checking table dag_version
      Found 0 rows meeting deletion criteria.
      Checking table dag
      Found 1 rows meeting deletion criteria.
      Moving data to table _airflow_deleted__dag__20261013115501
      sqlalchemy.exc.IntegrityError: (psycopg2.errors.ForeignKeyViolation) update or delete on table "dag_version" violates foreign key constraint "task_instance_dag_version_id_fkey" on table "task_instance"
      DETAIL:  Key (id)=(01a1351c-...) is still referenced from table "task_instance".
      [SQL: DELETE FROM dag USING _airflow_deleted__dag__20261013115501 WHERE dag.dag_id = _airflow_deleted__dag__20261013115501.dag_id]
      

    Workaround (verified)

    Delete the never-started task instances of the stale DAGs, then run db clean again.
    With this, the run completes with exit 0:

    DELETE FROM task_instance ti
    USING dag_version v, dag d
    WHERE v.id = ti.dag_version_id AND d.dag_id = v.dag_id
      AND d.is_stale AND d.last_parsed_time < '<clean_before_ts>'
      AND ti.start_date IS NULL;

    The queued dag_run is left behind as an orphan, because nothing cleans runs with a NULL start_date.

  5. ucaeon commented on Oct 14, 2026

    @ucaeon
    Contributor

    I've opened #74659 to address this issue!
    The change preserves Dags that still have task instances referencing them, preventing foreign-key errors caused by cascading version deletion during cleanup. Thank you ☺️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:corekind:bugneeds-triage

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions