This is an automated email from the ASF dual-hosted git repository.

vincbeck pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git


The following commit(s) were added to refs/heads/main by this push:
     new aa34596bab4 Speed up the scheduler selection query when many tasks are 
waiting (#77545)
aa34596bab4 is described below

commit aa34596bab41aa10af66281568e718d5ccaacc98
Author: Vincent <[email protected]>
AuthorDate: Fri Nov 27 09:35:36 2026 -0500

    Speed up the scheduler selection query when many tasks are waiting (#77545)
    
    Each scheduler loop picks the task instances to queue with a selection 
query,
    in the critical section that only one scheduler can hold at a time. The 
query
    carried every column of every SCHEDULED task instance through its ranking 
and
    only cut the result to the batch size after joining back to task_instance.
    With 70,000 task instances waiting, it took about 1 s on PostgreSQL (three
    sorts spilled to disk) and on MySQL in a local test, whatever the batch 
size.
    
    Candidates that another transaction holds locked must still be skipped and
    replaced by the next ones, so the query keeps a few batches of candidates, 
and
    a single Dag run takes at most half of them.
---
 .../src/airflow/jobs/scheduler_job_runner.py       |  59 ++++++++--
 airflow-core/tests/unit/jobs/test_scheduler_job.py | 121 +++++++++++++++++++++
 2 files changed, 170 insertions(+), 10 deletions(-)

diff --git a/airflow-core/src/airflow/jobs/scheduler_job_runner.py 
b/airflow-core/src/airflow/jobs/scheduler_job_runner.py
index f904316deaf..d1920864614 100644
--- a/airflow-core/src/airflow/jobs/scheduler_job_runner.py
+++ b/airflow-core/src/airflow/jobs/scheduler_job_runner.py
@@ -213,6 +213,20 @@ still selects at least one runnable task instance queued 
behind blocked ones.
 :meta private:
 """
 
+CANDIDATE_BATCHES = 4
+"""
+How many batches of ranked candidates the selection query keeps before joining 
full rows and locking them.
+
+One batch is selected and the others are spares: the caller locks rows with 
``SKIP LOCKED``, so
+candidates that other transactions hold locked are skipped and replaced from 
the spares. A Dag run takes at
+most half of the candidates: one whose rows are all locked leaves spares for 
the others, and up to a batch of
+locked rows at the top of a Dag run is still replaced from that Dag run. Must 
be at least 2, or that cap would
+be smaller than a batch and change selections without locked rows. A larger 
value joins and sorts more full
+rows on every selection.
+
+:meta private:
+"""
+
 
 def _eager_load_dag_run_for_validation() -> tuple[LoaderOption, LoaderOption]:
     """
@@ -1401,6 +1415,8 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
         don't re-appear in the candidate set.  Row-number windowing enforces
         ``max_active_tasks`` per DagRun.  The returned query is ready to be 
wrapped
         with ``with_row_locks`` and executed by the caller; no session is 
required here.
+        It keeps at most ``CANDIDATE_BATCHES * max_tis`` candidates, so with 
the caller's ``SKIP LOCKED``
+        it can return fewer than ``max_tis`` rows while other transactions 
hold candidates locked.
 
         This behaves the same as calling ``concurrency_map.load()`` followed by
         ``_get_current_dr_task_concurrency``, with the difference that the 
subquery
@@ -1410,7 +1426,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
         dr_task_concurrency_subquery = 
_get_current_dr_task_concurrency(states=EXECUTION_STATES)
 
         query = (
-            select(TI)
+            select(TI.id)
             .with_hint(TI, "USE INDEX (ti_state)", dialect_name="mysql")
             .join(TI.dag_run)
             .where(DR.state == DagRunState.RUNNING)
@@ -1427,7 +1443,6 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
                 isouter=True,
             )
             
.where(func.coalesce(dr_task_concurrency_subquery.c.task_per_dr_count, 0) < 
DM.max_active_tasks)
-            .order_by(-TI.priority_weight, DR.logical_date, TI.region_index)
         )
 
         # Starvation filters should be applied before computing the row_num 
based on the
@@ -1470,20 +1485,44 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
             )
         ).subquery()
 
-        # Select only rows where row_number <= max_active_tasks.
+        # Select only rows where row_number <= max_active_tasks. Keep only ids 
and ordering columns, and
+        # only CANDIDATE_BATCHES batches of them, before joining back to 
task_instance: ranking full rows
+        # would sort the full row of every waiting task instance.
+        candidates_query = (
+            select(
+                ranked_query.c.id,
+                ranked_query.c.priority_weight_for_ordering,
+                ranked_query.c.logical_date_for_ordering,
+                ranked_query.c.region_index_for_ordering,
+            )
+            .where(
+                ranked_query.c.row_num <= ranked_query.c.dr_max_active_tasks,
+                # A Dag run has at most max_tis rows in the result, so this 
per-Dag-run cap only matters
+                # when candidates are locked (see CANDIDATE_BATCHES).
+                ranked_query.c.row_num <= max_tis * CANDIDATE_BATCHES // 2,
+            )
+            .order_by(
+                -ranked_query.c.priority_weight_for_ordering,
+                ranked_query.c.logical_date_for_ordering,
+                ranked_query.c.region_index_for_ordering,
+            )
+            .limit(max_tis * CANDIDATE_BATCHES)
+            .subquery("candidates")
+        )
+
         return (
+            # A join rather than TI.id.in_(candidates): MySQL rejects LIMIT in 
IN subqueries (error 1235).
             select(TI)
-            .select_from(ranked_query)
+            .select_from(candidates_query)
             .join(
                 TI,
-                TI.id == ranked_query.c.id,
+                TI.id == candidates_query.c.id,
             )
-            .where(ranked_query.c.row_num <= 
ranked_query.c.dr_max_active_tasks)
-            # Add the order_by columns from the ranked query for sqlite.
+            # Add the order_by columns from the candidates subquery for sqlite.
             .order_by(
-                -ranked_query.c.priority_weight_for_ordering,
-                ranked_query.c.logical_date_for_ordering,
-                ranked_query.c.region_index_for_ordering,
+                -candidates_query.c.priority_weight_for_ordering,
+                candidates_query.c.logical_date_for_ordering,
+                candidates_query.c.region_index_for_ordering,
             )
             .options(selectinload(TI.dag_model))
             # Eager-load the run's pinned DagVersion 
(dag_run.created_dag_version): TIs become
diff --git a/airflow-core/tests/unit/jobs/test_scheduler_job.py 
b/airflow-core/tests/unit/jobs/test_scheduler_job.py
index f2e0ca33a71..f2969bbb918 100644
--- a/airflow-core/tests/unit/jobs/test_scheduler_job.py
+++ b/airflow-core/tests/unit/jobs/test_scheduler_job.py
@@ -44,6 +44,7 @@ from sqlalchemy import Delete, delete, event as sa_event, 
func, inspect, select,
 from sqlalchemy.dialects import mysql
 from sqlalchemy.exc import IntegrityError, InvalidRequestError, 
OperationalError
 from sqlalchemy.orm import joinedload
+from sqlalchemy.sql import Subquery, visitors
 
 from airflow import settings
 from airflow._shared.module_loading import qualname
@@ -74,6 +75,7 @@ from airflow.executors.workloads import ExecuteTask, 
WorkloadType
 from airflow.executors.workloads.types import TaskInstanceUuid
 from airflow.jobs.job import EXECUTOR_JOB_TYPE, Job, JobState, run_job
 from airflow.jobs.scheduler_job_runner import (
+    CANDIDATE_BATCHES,
     MAX_TI_REFILL_QUERIES_PER_LOOP,
     TASK_STUCK_IN_QUEUED_RESCHEDULE_EVENT,
     TI_METRIC_STATES,
@@ -4232,6 +4234,125 @@ class TestSchedulerJob:
 
             assert future.result(timeout=30) == ["unchanged"]
 
+    def 
test_build_schedulable_tis_query_joins_full_rows_to_a_few_batches_of_ids(self):
+        query = 
SchedulerJobRunner(job=Job())._build_schedulable_tis_query(set(), set(), set(), 
set(), 7)
+
+        (candidates,) = {
+            element
+            for element in visitors.iterate(query)
+            if isinstance(element, Subquery) and element.name == "candidates"
+        }
+        (ranked,) = candidates.element.get_final_froms()
+        assert set(ranked.c.keys()) == {
+            "id",
+            "row_num",
+            "dr_max_active_tasks",
+            "priority_weight_for_ordering",
+            "logical_date_for_ordering",
+            "region_index_for_ordering",
+        }
+        sql = str(candidates.element.compile(compile_kwargs={"literal_binds": 
True}))
+        assert re.search(rf"LIMIT {7 * CANDIDATE_BATCHES}$", sql)
+
+    @staticmethod
+    def _schedule_one_task_per_dag_run(dag_maker, session, 
dag_ids_and_priorities):
+        for dag_id, priority in dag_ids_and_priorities:
+            with dag_maker(dag_id=dag_id, session=session):
+                EmptyOperator(task_id="task", priority_weight=priority)
+            dag_run = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED)
+            dag_run.get_task_instance("task", session=session).state = 
State.SCHEDULED
+
+    def 
test_build_schedulable_tis_query_keeps_the_highest_priority_candidates(self, 
dag_maker, session):
+        # Dag ids sort lowest priority first, the order in which the ranking 
returns its rows (by Dag
+        # run), so a LIMIT without the candidates subquery's ORDER BY would 
keep the lowest priorities.
+        priorities = range(1, CANDIDATE_BATCHES + 2)
+        self._schedule_one_task_per_dag_run(dag_maker, session, ((f"p{p:03d}", 
p) for p in priorities))
+        session.flush()
+
+        query = 
SchedulerJobRunner(job=Job())._build_schedulable_tis_query(set(), set(), set(), 
set(), 1)
+
+        assert [ti.dag_id for ti in session.scalars(query)] == 
[f"p{priorities[-1]:03d}"]
+
+    def 
test_build_schedulable_tis_query_keeps_the_top_task_instances_of_a_dag_run(self,
 dag_maker, session):
+        with dag_maker(dag_id="one_run", session=session):
+            for priority in range(1, 7):
+                EmptyOperator(task_id=f"p{priority}", priority_weight=priority)
+        dag_run = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED)
+        for ti in dag_run.get_task_instances(session=session):
+            ti.state = State.SCHEDULED
+        session.flush()
+
+        query = 
SchedulerJobRunner(job=Job())._build_schedulable_tis_query(set(), set(), set(), 
set(), 3)
+
+        assert [ti.task_id for ti in session.scalars(query)] == ["p6", "p5", 
"p4"]
+
+    @staticmethod
+    def _select_while_locked(query, locked_ti_ids, attribute: str = "dag_id") 
-> list[str]:
+        """Run the selection in another thread while another transaction holds 
``locked_ti_ids`` locked."""
+
+        def select_candidates():
+            with create_session(scoped=False) as selecting:
+                locked_query = with_row_locks(query, of=TaskInstance, 
session=selecting, skip_locked=True)
+                return [getattr(ti, attribute) for ti in 
selecting.scalars(locked_query)]
+
+        with ThreadPoolExecutor(max_workers=1) as pool, 
create_session(scoped=False) as locker:
+            locker.execute(
+                
select(TaskInstance.id).where(TaskInstance.id.in_(locked_ti_ids)).with_for_update()
+            ).all()
+            future = pool.submit(select_candidates)
+            try:
+                # Fails instead of hanging if the selection waits for the 
locked rows.
+                return future.result(timeout=10)
+            finally:
+                locker.rollback()
+
+    @pytest.mark.backend("postgres", "mysql")
+    def 
test_build_schedulable_tis_query_replaces_candidates_locked_by_other_transactions(
+        self, dag_maker, session
+    ):
+        # CANDIDATE_BATCHES Dag runs of one candidate each (one batch of 
candidates per locked one, plus
+        # the replacement), all locked but the lowest-priority one.
+        priorities = range(CANDIDATE_BATCHES, 0, -1)
+        self._schedule_one_task_per_dag_run(dag_maker, session, ((f"p{p}", p) 
for p in priorities))
+        session.commit()
+        locked = 
session.scalars(select(TaskInstance.id).where(TaskInstance.dag_id != 
"p1")).all()
+        query = 
SchedulerJobRunner(job=Job())._build_schedulable_tis_query(set(), set(), set(), 
set(), 1)
+
+        assert self._select_while_locked(query, locked) == ["p1"]
+
+    @pytest.mark.backend("postgres", "mysql")
+    def 
test_build_schedulable_tis_query_replaces_a_locked_candidate_from_the_same_dag_run(
+        self, dag_maker, session
+    ):
+        with dag_maker(dag_id="one_run", session=session):
+            EmptyOperator(task_id="p2", priority_weight=2)
+            EmptyOperator(task_id="p1", priority_weight=1)
+        dag_run = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED)
+        for ti in dag_run.get_task_instances(session=session):
+            ti.state = State.SCHEDULED
+        session.commit()
+        query = 
SchedulerJobRunner(job=Job())._build_schedulable_tis_query(set(), set(), set(), 
set(), 1)
+
+        locked = [dag_run.get_task_instance("p2", session=session).id]
+        assert self._select_while_locked(query, locked, attribute="task_id") 
== ["p1"]
+
+    @pytest.mark.backend("postgres", "mysql")
+    def 
test_build_schedulable_tis_query_leaves_candidates_for_other_dag_runs_when_one_is_locked(
+        self, dag_maker, session
+    ):
+        with dag_maker(dag_id="locked", session=session):
+            for i in range(CANDIDATE_BATCHES):
+                EmptyOperator(task_id=f"task_{i}", priority_weight=2)
+        locked_run = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED)
+        locked = locked_run.get_task_instances(session=session)
+        for ti in locked:
+            ti.state = State.SCHEDULED
+        self._schedule_one_task_per_dag_run(dag_maker, session, [("unlocked", 
1)])
+        session.commit()
+        query = 
SchedulerJobRunner(job=Job())._build_schedulable_tis_query(set(), set(), set(), 
set(), 1)
+
+        assert self._select_while_locked(query, [ti.id for ti in locked]) == 
["unlocked"]
+
     def 
test_find_executable_task_instances_task_concurrency_per_dagrun_for_first(self, 
dag_maker):
         scheduler_job = Job()
         self.job_runner = SchedulerJobRunner(job=scheduler_job)

Reply via email to