Repository navigation
Fix dagrun starvation - #64109
Fix dagrun starvation#64109Nataneljpwd wants to merge 44 commits into
Conversation
|
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, Assume dags a, b A
|
6b09818 to
fe5462d
Compare
|
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 |
There was a problem hiding this comment.
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 arow_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
left a comment
There was a problem hiding this comment.
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.
Sure, no problem |
a9c77cd to
c47e216
Compare
d9df73e to
3162697
Compare
|
Hello, is there any blocker that needs to be addressed before the PR can be merged? |
| ) | ||
| .label("rn"), | ||
| ) | ||
| .where(DagRun.state == DagRunState.QUEUED) |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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.
| .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, | ||
| ) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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"), |
There was a problem hiding this comment.
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.
| [{"inputs": 1}, {"inputs": 2}] | ||
| [ | ||
| {"inputs": 1}, | ||
| {"inputs": 2}, | ||
| ] |
|
@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 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 Repro against this PR's head ( 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: Fix: func.row_number().over(
partition_by=(DagRun.dag_id, DagRun.backfill_id),
order_by=(BackfillDagRun.sort_ordinal, DagRun.run_after, DagRun.id),
)
I ran this ordering on a branch off |
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?
{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 UTCHelpful heads-up from the maintainers — please address before this PR can be reviewed (see our Pull Request quality criteria):
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.