Skip to content

Fix dagrun starvation - #64109

Open
Nataneljpwd wants to merge 44 commits into
apache:mainfrom
Nataneljpwd:bugfix/fix-dagrun-starvation
Open

Nataneljpwd wants to merge 44 commits into
apache:mainfrom
Nataneljpwd:bugfix/fix-dagrun-starvation

Conversation

@Nataneljpwd

@Nataneljpwd Nataneljpwd commented Mar 23, 2026 •

Copy link
Copy Markdown
Contributor

We have been experiencing severe dagrun starvation at our cluster, where when there were a lot of dagruns, and a low max_active_runs limit (hundreds to thousands runs with a limit in the 10s) this caused a lot of dags to get stuck in queued state without moving to running, causing those dagruns to timeout.
After investigation, we found that the reason was due to the _start_queued_dagruns method, where the query was returning dagruns which cannot be set to running due to the max_active_runs limit, meaning that other dagruns where starved.

A similar issue occurs when new dagruns are created in large batches (due to the nulls first), yet this is out of scope for the given pr, I will submit an additional PR soon.

closes #49508


Was generative AI tooling used to co-author this PR?
  • Yes (please specify the tool below)

  • Read the 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) is needed.
  • When adding dependency, check compliance with the ASF 3rd Party License Policy.
  • For significant user-facing changes create newsfragment: {pr_number}.significant.rst, in airflow-core/newsfragments. You can add this file in a follow-up commit after the PR is created so you know the PR number.

Important

🛠️ Maintainer triage note for @Nataneljpwd · by @potiuk · 2026-07-11 14:59 UTC

Helpful heads-up from the maintainers — please address before this PR can be reviewed (see our Pull Request quality criteria):

  • ❌ Other failing CI checks. See docs.

The ball is in your court — you've been assigned to this PR. Fix the above, then mark it Ready for review.

Automated triage — may be imperfect; a maintainer takes the next look.

@Nataneljpwd
Nataneljpwd marked this pull request as draft March 23, 2026 16:48
@collinmcnulty

Copy link
Copy Markdown
Contributor

I'm struggling to understand how the problem has been solved from reading the code. Can you explain your solution for preventing the starvation?

@Nataneljpwd

Copy link
Copy Markdown
Contributor Author

I'm struggling to understand how the problem has been solved from reading the code. Can you explain your solution for preventing the starvation?

Sure,
Instead of (as of now) querying N first runs, and then filtering on the max active runs, we query the first N runs where we (in SQL) check the the max active runs (before the limit is applied)
And so we skip a lot of runs which cannot be scheduled

Assume dags a, b
a - 3 max active runs
b - no limit (default to 16 from config)
If now the query result looked like so (small letter is schedulable, capital letter is schedulable according to ) where each row represents a run (the - determine the limit, all runs before the - are selected, all other are ignored) where the max dagruns to schedule per loop (the limit) is 5

A
A
A
a
a

B
B
B

Here (as of now) the last 3 dagruns are ommitted and ignored (starving runs from b)

After the change it will look like so:

A
A
A
B
B

B

Now we do schedule everything we queried without dagruns from a limiting us (the limit now becomes the max dagruns per loop to schedule configuration) and it is guaranteed that the runs queried will be able to run

Hope this explained it, if anything is not clear feel free to let me know, I will write a better explanation.

@Nataneljpwd
Nataneljpwd force-pushed the bugfix/fix-dagrun-starvation branch from 6b09818 to fe5462d Compare March 23, 2026 19:21
@Nataneljpwd
Nataneljpwd marked this pull request as ready for review March 23, 2026 21:01
@eladkal
eladkal requested a review from kaxil March 24, 2026 10:05
@kaxil
kaxil requested a review from Copilot March 24, 2026 12:15
@kaxil kaxil added this to the Airflow 3.2.1 milestone Mar 24, 2026
@kaxil

kaxil commented Mar 24, 2026

Copy link
Copy Markdown
Member

This will have to wait until 3.2.0 -- This touches the core and I don't want to hurry until 3.2.0 is out.

We have 1200+ commits in 3.2.0

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR addresses scheduler DAG run starvation by changing how queued DagRuns are selected for transition to RUNNING when max_active_runs is low and there are large backlogs of queued runs.

Changes:

  • Update DagRun.get_queued_dag_runs_to_set_running() to limit queued candidates per DAG/backfill using a row_number() window so the scheduler doesn’t spend its per-loop budget examining non-runnable runs from a single DAG.
  • Adjust scheduler unit tests to validate the improved fairness/scheduling behavior under backlog conditions.
  • Remove a max-active guard/logging in _create_dag_runs() and add a TODO note around _set_exceeds_max_active_runs.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.

File Description
airflow-core/src/airflow/models/dagrun.py Changes queued dagrun selection query to avoid starvation by limiting per DAG/backfill candidates.
airflow-core/src/airflow/jobs/scheduler_job_runner.py Removes a creation-time max-active skip and adds a TODO comment near _set_exceeds_max_active_runs.
airflow-core/tests/unit/jobs/test_scheduler_job.py Updates/reshapes scheduling tests to assert non-starved behavior and updated run counts.

@kaxil kaxil left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The core idea — using row_number() to cap how many queued runs per DAG/backfill pass through the query — is a reasonable approach to solving the starvation problem in get_queued_dag_runs_to_set_running. However, this PR bundles in unrelated and incorrect changes to the DagRun creation path (_create_dag_runs), which is a separate concern from the QUEUED→RUNNING promotion path.

See inline comments for details.

@Nataneljpwd

Copy link
Copy Markdown
Contributor Author

This will have to wait until 3.2.0 -- This touches the core and I don't want to hurry until 3.2.0 is out.

We have 1200+ commits in 3.2.0

Sure, no problem

@eladkal eladkal added the type:bug-fix Changelog: Bug Fixes label Mar 24, 2026
@Nataneljpwd
Nataneljpwd force-pushed the bugfix/fix-dagrun-starvation branch from a9c77cd to c47e216 Compare March 24, 2026 19:35
@Nataneljpwd

Copy link
Copy Markdown
Contributor Author

@kaxil, @eladkal I have addressed the review comments and would appreciate another review

@Nataneljpwd
Nataneljpwd marked this pull request as ready for review July 26, 2026 19:15
@Nataneljpwd
Nataneljpwd requested review from ashb and uranusjr July 26, 2026 19:16
@Nataneljpwd
Nataneljpwd force-pushed the bugfix/fix-dagrun-starvation branch from d9df73e to 3162697 Compare September 11, 2026 18:18
@eladkal
eladkal requested a review from uranusjr September 13, 2026 06:41
@Nataneljpwd

Copy link
Copy Markdown
Contributor Author

Hello, is there any blocker that needs to be addressed before the PR can be merged?
Thank you.

)
.label("rn"),
)
.where(DagRun.state == DagRunState.QUEUED)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The window ranks every queued run in the partition, but run_after <= now() is only applied on the outer query (line 888), after rn <= cap - num_running. So a run that isn't due yet can take a slot and then get dropped, and the ready run ranked after it never comes back.

That's reachable on main today: a reverse backfill on a partitioned timetable can have to_date in the future (validation in backfill.py only rejects when both bounds are in the future, and _get_info_list keeps future partitions for partitioned timetables). Reversing gives those future partitions sort_ordinal 1..N, which is the first window key. With the default backfill max_active_runs=10 and ten or more future partitions, the backfill returns nothing until they mature, where main starts the newest past partitions right away.

Moving the run_after filter into this subquery fixes it, and the comment at line 873 would then be true. Since you'd be touching the subquery anyway, I'd move the paused/stale DagModel join in here as well. I don't think the planner can push a join condition into a subquery that computes a window function, so as written the ranking also runs over queued runs of paused Dags.

),
isouter=True,
)
.order_by(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On main the outer ORDER BY started with sort_ordinal NULLS FIRST so backfill runs sort after every non-backfill run. That key now only lives in the window, so it no longer orders anything across partitions. Backfill runs usually have an older run_after, so they now win the 20-row limit over scheduled runs. In a breeze run with one backfill (cap 3) and a regular Dag with 30 queued runs, main's query started 20 scheduled runs and this one started 3 backfill plus 17 scheduled.

Could you select sort_ordinal from the subquery and put it back as the first key here? test_backfill_runs_are_started_with_lower_priority_catchup_true can't catch this as rewritten, since 1 + 3 + 16 startable runs exactly fill the limit. It needs more startable runs than DEFAULT_DAGRUNS_TO_EXAMINE, and dag2's max_active_runs set explicitly instead of relying on the 16 from config.

self.job_runner._start_queued_dagruns(session)
session.flush()

# after running the scheduler one time, observe that only one dag run is started

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still says only one dag run is started, but the assert below is now 20. The session.flush() right after session.commit() on line 7883 doesn't do anything either.

dag_runs = DagRun.find(dag_id=dag.dag_id, session=session)
assert len(dag_runs) == 2

def test_runs_are_not_starved_by_max_active_runs_limit(self, dag_maker, session):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one also passes with dagrun.py reverted to main (checked in breeze), same as @ashb 's point on the test below. The three Dags share start_date and schedule, so their queued runs interleave by run_after, main's top 20 holds about 7 per Dag, and the Python guard still starts 3 of each.

To fail on main, one Dag's backlog has to sort entirely ahead of a Dag that has capacity. For example: Dag A with max_active_runs=1 and 25 queued runs, Dag B starting a day later with max_active_runs=3 and 5 queued runs, then assert {A: 1, B: 3} running. Main gives {A: 1} and this branch passes.

Comment on lines +866 to +870
.order_by(
nulls_first(cast("ColumnElement[Any]", cls.last_scheduling_decision), session=session),
nulls_first(available_dagruns_rn.c.num_running, session=session),
DagRun.run_after,
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On main, the first sort key is nulls_first(BackfillDagRun.sort_ordinal), putting every non-backfill run ahead of every backfill run before the LIMIT is applied. sort_ordinal is now used only inside the window, which orders runs within a single (dag_id, backfill_id) partition. This does nothing for ranking across partitions.

One possible fix is to select BackfillDagRun.sort_ordinal in available_dagruns_rn and put nulls_first(available_dagruns_rn.c.sort_ordinal) first. A test where the capped candidates exceed the query’s limit is also needed. No current tests cover this.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A separate minor issue: This order_by probably should be moved to after .where() to follow SQL conventions. (SQLAlchemy doesn’t actually care, so this is more of a readability issue.)

<= coalesce(
Backfill.max_active_runs,
DagModel.max_active_runs,
airflow_conf.getint("core", "max_active_runs_per_dag"),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This reads conf on every scheduler loop. It should be at the class level simialr to DEFAULT_DAGRUNS_TO_EXAMINE.

It is also inconsistent with `_start_queued_dagruns, which treats None as unlimited. SQL now caps at the config default, and Python applies no cap. Both are defensible, but they should agree.

Comment on lines -3018 to +3021
[{"inputs": 1}, {"inputs": 2}]
[
{"inputs": 1},
{"inputs": 2},
]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unrelated?

@seunggabi

Copy link
Copy Markdown
Contributor

@Nataneljpwd @kaxil @eladkal This PR still leaves a deadlock in place, and I think it needs fixing before merge.

The window ranks runs inside a dag by last_scheduling_decision NULLS FIRST before run_after:

order_by=[
    nulls_first(BackfillDagRun.sort_ordinal, session=session),
    nulls_first(cls.last_scheduling_decision, session=session),  # <- per-dag rank ignores date order
    DagRun.run_after,
],

So whenever the earliest queued run of a dag already has a last_scheduling_decision (it was cleared, or marked queued again; see #77603) and a later run doesn't, the later run gets rn = 1 and is the one that starts. With depends_on_past=True + max_active_runs=1, that's a deadlock: the later run is running and waits on the earlier one, and the earlier one stays queued forever because the only slot is taken. We hit this in production.

Repro against this PR's head (3af7b2af7a): add this test to test_scheduler_job.py:

def test_start_queued_dagruns_starts_earliest_run_of_dag_first(self, dag_maker, session):
    with dag_maker("test_dag", max_active_runs=1, session=session):
        EmptyOperator(task_id="mytask", depends_on_past=True)
    for i in range(3):
        dag_maker.create_dagrun(
            run_id=f"dagrun_{i}",
            run_type=DagRunType.SCHEDULED,
            state=State.QUEUED,
            logical_date=DEFAULT_DATE + timedelta(days=i),
            session=session,
        )
    session.execute(
        update(DagRun).where(DagRun.run_id == "dagrun_0").values(last_scheduling_decision=timezone.utcnow())
    )
    session.flush()

    self.job_runner = SchedulerJobRunner(job=Job(), executors=[MockExecutor(do_update=False)])
    self.job_runner._start_queued_dagruns(session)
    session.flush()

    states = dict(session.execute(select(DagRun.run_id, DagRun.state)).all())
    assert states == {
        "dagrun_0": DagRunState.RUNNING,
        "dagrun_1": DagRunState.QUEUED,
        "dagrun_2": DagRunState.QUEUED,
    }

Result:

FAILED ...::test_start_queued_dagruns_starts_earliest_run_of_dag_first
E      -  'dagrun_0': 'queued',     +  'dagrun_0': 'running',
E      -  'dagrun_1': 'running',    +  'dagrun_1': 'queued',

Fix: last_scheduling_decision is a fairness key across dags. It should stay in the outer ORDER BY and come out of the per-dag window. Inside a dag, the order should only be the order the runs are meant to start in:

func.row_number().over(
    partition_by=(DagRun.dag_id, DagRun.backfill_id),
    order_by=(BackfillDagRun.sort_ordinal, DagRun.run_after, DagRun.id),
)
  • sort_ordinal keeps reverse backfills correct (@kaxil's point about sort_ordinal=1 being the latest date).
  • run_after is never NULL, unlike logical_date for partitioned backfills, and id breaks ties so the ranking is deterministic.

I ran this ordering on a branch off main (SQLite): the test above passes, and so do the existing _start_queued_dagruns, backfill and max_active_runs scheduler tests. I can push it as a suggestion or a follow-up commit if that helps get this merged.

This branch has not been deployed

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

Labels

area:scheduler type:bug-fix Changelog: Bug Fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DAG Runs from a single DAG can prevent scheduler from seeing other DAG's runs

10 participants