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 70294c21740 Speed up scheduler concurrency counts with many running 
tasks (#77548)
70294c21740 is described below

commit 70294c217409641935a7dbffa594b49ec5c16c0a
Author: Vincent <[email protected]>
AuthorDate: Fri Nov 27 14:39:59 2026 -0500

    Speed up scheduler concurrency counts with many running tasks (#77548)
    
    Each time the scheduler looked for task instances to queue, it counted
    active task instances with a query grouped by Dag, task, Dag run and state.
    That returns about one row per active task instance of an unmapped task, so
    with tens of thousands of running task instances the scheduler read tens of
    thousands of rows just to add them up, although the per-task counts are only
    needed for the Dags that define task concurrency limits. In a profile with
    70,000 running task instances this was 13 % of the scheduler's time.
    
    The running and queued task instances per Dag run are now counted by the
    database, one row per Dag run, from the same definition as the candidate
    query's per-run subquery. The per-task counts are read through an accessor
    that loads them per Dag on first use, and are prefetched in one query for
    the Dags with task limits among each batch of candidates.
---
 .../src/airflow/jobs/scheduler_job_runner.py       | 129 +++++++++++++-------
 airflow-core/tests/unit/jobs/test_scheduler_job.py | 133 ++++++++++++++++++++-
 2 files changed, 213 insertions(+), 49 deletions(-)

diff --git a/airflow-core/src/airflow/jobs/scheduler_job_runner.py 
b/airflow-core/src/airflow/jobs/scheduler_job_runner.py
index d1920864614..822c26e31b7 100644
--- a/airflow-core/src/airflow/jobs/scheduler_job_runner.py
+++ b/airflow-core/src/airflow/jobs/scheduler_job_runner.py
@@ -290,37 +290,71 @@ def _ensure_ti_has_dag_version_id(ti: TaskInstance, 
session: Session, log: Logge
 
 class ConcurrencyMap:
     """
-    Dataclass to represent concurrency maps.
+    Counts of task instances used to enforce concurrency limits while 
selecting task instances.
 
-    It contains a map from (dag_id, task_id) to # of task instances, a map 
from (dag_id, task_id)
-    to # of task instances in the given state list and a map from (dag_id, 
run_id, task_id)
-    to # of task instances in the given state list in each DAG run.
+    ``dag_run_active_tasks_map`` maps (dag_id, run_id) to the number of 
running and queued task instances
+    of every Dag run, from ``load``. Per-task counts, for 
``max_active_tis_per_dag`` and
+    ``max_active_tis_per_dagrun``, are read through ``get_task_counts``, which 
loads them per Dag on first
+    use. Task instances selected to be queued are counted with 
``add_selected_task_instance``.
     """
 
     def __init__(self):
         self.dag_run_active_tasks_map: Counter[tuple[str, str]] = Counter()
-        self.task_concurrency_map: Counter[tuple[str, str]] = Counter()
-        self.task_dagrun_concurrency_map: Counter[tuple[str, str, str]] = 
Counter()
+        self._task_counts: Counter[tuple[str, str]] = Counter()
+        self._task_dagrun_counts: Counter[tuple[str, str, str]] = Counter()
+        self._dags_with_task_counts: set[str] = set()
 
-    def load(self, session: Session) -> None:
+    def load(self, *, session: Session) -> None:
+        """Load the running and queued task instances per Dag run, and forget 
the per-task counts."""
         self.dag_run_active_tasks_map.clear()
-        self.task_concurrency_map.clear()
-        self.task_dagrun_concurrency_map.clear()
-        query = session.execute(
-            select(TI.dag_id, TI.task_id, TI.run_id, TI.state, func.count("*"))
-            .where(TI.state.in_(ACTIVE_STATES))
-            .group_by(TI.dag_id, TI.task_id, TI.run_id, TI.state)
+        self._task_counts.clear()
+        self._task_dagrun_counts.clear()
+        self._dags_with_task_counts.clear()
+        # Without the hint, MySQL can pick ``ti_dag_run`` to group in index 
order and read every task
+        # instance, finished ones included, instead of the active ones only.
+        query = _select_current_dr_task_concurrency().with_hint(
+            TI, "USE INDEX (ti_state)", dialect_name="mysql"
         )
-        for dag_id, task_id, run_id, state, count in query:
-            # Always count towards task-level concurrency 
(max_active_tis_per_dag /
-            # max_active_tis_per_dagrun), including DEFERRED.
-            self.task_concurrency_map[(dag_id, task_id)] += count
-            self.task_dagrun_concurrency_map[(dag_id, run_id, task_id)] += 
count
-            # Only count states that hold a worker slot towards DAG-run active 
tasks
-            # (max_active_tasks / worker slot accounting). DEFERRED and 
AWAITING_INPUT
-            # are in-flight but parked, holding no worker slot.
-            if state not in (TaskInstanceState.DEFERRED, 
TaskInstanceState.AWAITING_INPUT):
-                self.dag_run_active_tasks_map[dag_id, run_id] += count
+        for dag_id, run_id, count in session.execute(query):
+            self.dag_run_active_tasks_map[dag_id, run_id] = count
+
+    def load_task_counts(self, dag_ids: Collection[str], *, session: Session) 
-> None:
+        """
+        Load the per-task counts of the Dags in ``dag_ids`` not loaded since 
the last ``load``, in one query.
+
+        Callers pass the Dags whose limits may be checked, because the query 
returns one row per task and
+        Dag run with active task instances. The database counts are added to 
the task instances already
+        counted with ``add_selected_task_instance``.
+        """
+        dag_ids = set(dag_ids) - self._dags_with_task_counts
+        if not dag_ids:
+            return
+        for dag_id, task_id, run_id, count in session.execute(
+            select(TI.dag_id, TI.task_id, TI.run_id, func.count("*"))
+            .where(TI.dag_id.in_(dag_ids), TI.state.in_(ACTIVE_STATES))
+            .group_by(TI.dag_id, TI.task_id, TI.run_id)
+        ):
+            self._task_counts[dag_id, task_id] += count
+            self._task_dagrun_counts[dag_id, run_id, task_id] += count
+        self._dags_with_task_counts.update(dag_ids)
+
+    def get_task_counts(self, dag_id: str, task_id: str, run_id: str, *, 
session: Session) -> tuple[int, int]:
+        """
+        Return the active task instances of a task in all runs of its Dag, and 
in one Dag run.
+
+        Active includes DEFERRED and AWAITING_INPUT, and the task instances 
counted with
+        ``add_selected_task_instance``. The Dag's counts are loaded first if 
needed.
+        """
+        if dag_id not in self._dags_with_task_counts:
+            self.load_task_counts((dag_id,), session=session)
+        return self._task_counts[dag_id, task_id], 
self._task_dagrun_counts[dag_id, run_id, task_id]
+
+    def add_selected_task_instance(self, task_instance: TI) -> None:
+        """Count a task instance selected to be queued, which the database 
does not count yet."""
+        dag_id, task_id, run_id = task_instance.dag_id, task_instance.task_id, 
task_instance.run_id
+        self.dag_run_active_tasks_map[dag_id, run_id] += 1
+        self._task_counts[dag_id, task_id] += 1
+        self._task_dagrun_counts[dag_id, run_id, task_id] += 1
 
 
 def _is_parent_process() -> bool:
@@ -425,13 +459,17 @@ def _has_default_asset_event_grouping(timetable: 
Timetable) -> bool:
     return type(timetable).group_asset_events is Timetable.group_asset_events
 
 
-def _get_current_dr_task_concurrency(states: Iterable[TaskInstanceState]) -> 
Subquery:
-    """Get the dag_run IDs and how many tasks are in the provided states for 
each one."""
+def _select_current_dr_task_concurrency() -> Select[str, str, int]:
+    """
+    Count the task instances of each Dag run that count towards its 
``max_active_tasks``.
+
+    Only states that hold a worker slot count (``EXECUTION_STATES``); DEFERRED 
and AWAITING_INPUT are
+    in-flight but parked. ``ConcurrencyMap.load`` and the candidate query 
share this definition.
+    """
     return (
         select(TI.dag_id, TI.run_id, 
func.count("*").label("task_per_dr_count"))
-        .where(TI.state.in_(states))
+        .where(TI.state.in_(EXECUTION_STATES))
         .group_by(TI.dag_id, TI.run_id)
-        .subquery()
     )
 
 
@@ -995,10 +1033,15 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
         task = serialized_dag.get_task(task_id)
 
         task_concurrency_limit = task.max_active_tis_per_dag
+        task_dagrun_concurrency_limit = task.max_active_tis_per_dagrun
+        if task_concurrency_limit is None and task_dagrun_concurrency_limit is 
None:
+            return True
 
-        if task_concurrency_limit is not None:
-            current_task_concurrency = 
concurrency_map.task_concurrency_map[(dag_id, task_id)]
+        current_task_concurrency, current_task_dagrun_concurrency = 
concurrency_map.get_task_counts(
+            dag_id, task_id, run_id, session=session
+        )
 
+        if task_concurrency_limit is not None:
             if current_task_concurrency >= task_concurrency_limit:
                 self.log.info(
                     "Not executing %s since the task concurrency for this task 
has been reached.",
@@ -1008,13 +1051,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
                 starved_tasks.add((dag_id, task_id))
                 return False
 
-        task_dagrun_concurrency_limit = task.max_active_tis_per_dagrun
-
         if task_dagrun_concurrency_limit is not None:
-            current_task_dagrun_concurrency = 
concurrency_map.task_dagrun_concurrency_map[
-                (dag_id, run_id, task_id)
-            ]
-
             if current_task_dagrun_concurrency >= 
task_dagrun_concurrency_limit:
                 self.log.info(
                     "Not executing %s since the task concurrency per DAG run 
for this task has been reached.",
@@ -1105,7 +1142,6 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
         if self._multi_team:
             pool_to_team_name = 
Pool.get_name_to_team_name_mapping(list(pools.keys()), session=session)
 
-        # dag_id to # of running tasks and (dag_id, task_id) to # of running 
tasks.
         concurrency_map = ConcurrencyMap()
         concurrency_map.load(session=session)
 
@@ -1205,6 +1241,12 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
                     if team := dag_id_to_team_name.get(ti.dag_id):
                         ti.dag_run._team_name = team
 
+            # One query for the Dags of this batch instead of one per Dag from 
``get_task_counts``.
+            concurrency_map.load_task_counts(
+                {ti.dag_id for ti in task_instances_to_examine if 
ti.dag_model.has_task_concurrency_limits},
+                session=session,
+            )
+
             for task_instance in task_instances_to_examine:
                 pool_name = task_instance.pool
 
@@ -1340,11 +1382,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
 
                 executable_tis.append(task_instance)
                 open_slots -= task_instance.pool_slots
-                concurrency_map.dag_run_active_tasks_map[dag_run_key] += 1
-                concurrency_map.task_concurrency_map[(task_instance.dag_id, 
task_instance.task_id)] += 1
-                concurrency_map.task_dagrun_concurrency_map[
-                    (task_instance.dag_id, task_instance.run_id, 
task_instance.task_id)
-                ] += 1
+                concurrency_map.add_selected_task_instance(task_instance)
 
                 pool_stats["open"] = open_slots
 
@@ -1418,12 +1456,11 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
         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
-        object is built here and executed as part of the main query, so any 
state
-        changes between construction and execution are naturally ignored.
+        The per-Dag-run count of running and queued task instances comes from
+        ``_select_current_dr_task_concurrency``, the definition 
``ConcurrencyMap.load`` also uses,
+        evaluated here as a subquery of this query.
         """
-        dr_task_concurrency_subquery = 
_get_current_dr_task_concurrency(states=EXECUTION_STATES)
+        dr_task_concurrency_subquery = 
_select_current_dr_task_concurrency().subquery()
 
         query = (
             select(TI.id)
diff --git a/airflow-core/tests/unit/jobs/test_scheduler_job.py 
b/airflow-core/tests/unit/jobs/test_scheduler_job.py
index cea327eabcb..869c585e125 100644
--- a/airflow-core/tests/unit/jobs/test_scheduler_job.py
+++ b/airflow-core/tests/unit/jobs/test_scheduler_job.py
@@ -43,7 +43,7 @@ import time_machine
 from sqlalchemy import Delete, delete, event as sa_event, func, inspect, 
select, text, update
 from sqlalchemy.dialects import mysql
 from sqlalchemy.exc import IntegrityError, InvalidRequestError, 
OperationalError
-from sqlalchemy.orm import joinedload
+from sqlalchemy.orm import Session, joinedload
 from sqlalchemy.sql import Subquery, visitors
 
 from airflow import settings
@@ -79,6 +79,7 @@ from airflow.jobs.scheduler_job_runner import (
     MAX_TI_REFILL_QUERIES_PER_LOOP,
     TASK_STUCK_IN_QUEUED_RESCHEDULE_EVENT,
     TI_METRIC_STATES,
+    ConcurrencyMap,
     SchedulerJobRunner,
     _associate_asset_events_with_dag_run,
 )
@@ -210,8 +211,6 @@ from unit.listeners import dag_listener
 from unit.models import TEST_DAGS_FOLDER
 
 if TYPE_CHECKING:
-    from sqlalchemy.orm.session import Session
-
     from tests_common.pytest_plugin import DagMaker
 
 pytestmark = pytest.mark.db_test
@@ -3677,6 +3676,134 @@ class TestSchedulerJob:
         assert ("task_a", 1) not in queued_task_ids
         session.rollback()
 
+    def test_concurrency_map_counts(self, dag_maker, session):
+        states_in_first_run = {
+            "running": TaskInstanceState.RUNNING,
+            "queued": TaskInstanceState.QUEUED,
+            "deferred": TaskInstanceState.DEFERRED,
+            "awaiting_input": TaskInstanceState.AWAITING_INPUT,
+            "scheduled": TaskInstanceState.SCHEDULED,
+            "success": TaskInstanceState.SUCCESS,
+        }
+        with dag_maker(dag_id="limited", session=session):
+            for task_id in states_in_first_run:
+                EmptyOperator(task_id=task_id, max_active_tis_per_dag=16)
+        first_run = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED, 
run_id="first", session=session)
+        second_run = dag_maker.create_dagrun_after(
+            first_run, run_type=DagRunType.SCHEDULED, run_id="second", 
session=session
+        )
+        for ti in first_run.get_task_instances(session=session):
+            ti.state = states_in_first_run[ti.task_id]
+        second_run.get_task_instance("running", session=session).state = 
TaskInstanceState.RUNNING
+        selected = second_run.get_task_instance("queued", session=session)
+        selected.state = TaskInstanceState.SCHEDULED
+        with dag_maker(dag_id="other", session=session):
+            EmptyOperator(task_id="running")
+        other_run = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED, 
run_id="other", session=session)
+        other_run.get_task_instance("running", session=session).state = 
TaskInstanceState.RUNNING
+        session.flush()
+        concurrency_map = ConcurrencyMap()
+        concurrency_map.load(session=session)
+
+        # Only running and queued task instances count for their Dag run.
+        assert concurrency_map.dag_run_active_tasks_map == {
+            ("limited", "first"): 2,
+            ("limited", "second"): 1,
+            ("other", "other"): 1,
+        }
+
+        # Counted before the Dag's counts are loaded: still SCHEDULED in the 
database.
+        concurrency_map.add_selected_task_instance(selected)
+
+        assert concurrency_map.dag_run_active_tasks_map["limited", "second"] 
== 2
+        # Loaded on first use. Deferred and awaiting input task instances 
count for their task, as well as
+        # the selected one.
+        assert {
+            task_id: concurrency_map.get_task_counts("limited", task_id, 
"first", session=session)
+            for task_id in states_in_first_run
+        } == {
+            "running": (2, 1),
+            "queued": (2, 1),
+            "deferred": (1, 1),
+            "awaiting_input": (1, 1),
+            "scheduled": (0, 0),
+            "success": (0, 0),
+        }
+        assert concurrency_map.get_task_counts("limited", "queued", "second", 
session=session) == (2, 1)
+
+        # A refill candidate query can bring back a Dag already loaded: its 
counts are not added again.
+        concurrency_map.load_task_counts(["limited", "other"], session=session)
+
+        assert concurrency_map.get_task_counts("limited", "queued", "second", 
session=session) == (2, 1)
+        assert concurrency_map.get_task_counts("other", "running", "other", 
session=session) == (1, 1)
+
+        concurrency_map.load(session=session)
+
+        assert concurrency_map.get_task_counts("limited", "queued", "second", 
session=session) == (1, 0)
+
+    def test_concurrency_map_load_hints_ti_state_index_on_mysql(self):
+        session = mock.create_autospec(Session, instance=True)
+
+        ConcurrencyMap().load(session=session)
+
+        statement = session.execute.call_args.args[0]
+        assert "FROM task_instance USE INDEX (ti_state)" in 
str(statement.compile(dialect=mysql.dialect()))
+
+    @pytest.mark.parametrize(
+        ("task_limit", "expected_queued", "expected_counted_dags"),
+        [
+            pytest.param(
+                1,
+                ["no_limits", "refill_a", "refill_b"],
+                [{"first_a", "first_b"}, {"refill_a", "refill_b"}],
+                id="limited",
+            ),
+            pytest.param(None, ["first_a", "first_b", "no_limits"], [], 
id="unlimited"),
+        ],
+    )
+    def 
test_select_task_instances_to_queue_counts_tasks_at_most_once_per_candidate_query(
+        self, dag_maker, session, task_limit, expected_queued, 
expected_counted_dags
+    ):
+        # The first candidate query brings "first_*" and "no_limits"; with a 
limit, "first_*" are at it, so
+        # the batch of 3 is refilled with "refill_*", which have limits too 
but room left.
+        dag_ids = ("first_a", "first_b", "no_limits", "refill_a", "refill_b")
+        for dag_id, priority_weight in zip(dag_ids, (10, 10, 10, 1, 1)):
+            with dag_maker(dag_id=dag_id, session=session):
+                EmptyOperator(
+                    task_id="task",
+                    priority_weight=priority_weight,
+                    max_active_tis_per_dag=None if dag_id == "no_limits" else 
task_limit,
+                )
+            dag_run = dag_maker.create_dagrun(run_type=DagRunType.SCHEDULED, 
session=session)
+            dag_run.get_task_instance("task", session=session).state = 
TaskInstanceState.SCHEDULED
+            if dag_id.startswith("first"):
+                running_run = dag_maker.create_dagrun_after(
+                    dag_run, run_type=DagRunType.SCHEDULED, session=session
+                )
+                running_run.get_task_instance("task", session=session).state = 
TaskInstanceState.RUNNING
+        session.flush()
+        self.job_runner = SchedulerJobRunner(job=Job())
+
+        with capture_orm_selects("task_instance") as statements:
+            queued_tis = self.job_runner._select_task_instances_to_queue(
+                3, make_pool_stats(), set(), session=session
+            )
+
+        assert sorted(ti.dag_id for ti in queued_tis) == expected_queued
+        task_count_statements = [
+            statement
+            for statement in statements
+            if "GROUP BY task_instance.dag_id, task_instance.task_id, 
task_instance.run_id" in statement
+        ]
+        counted_dags = []
+        for statement in task_count_statements:
+            dag_ids_in = re.search(r"task_instance\.dag_id IN \(([^)]*)\)", 
statement)
+            counted_dags.append(
+                {dag_id.strip("'") for dag_id in dag_ids_in[1].split(", ")} if 
dag_ids_in else set()
+            )
+        assert counted_dags == expected_counted_dags
+        session.rollback()
+
     def 
test_find_executable_task_instances_deferred_does_not_affect_max_active_tasks(
         self, dag_maker, session
     ):

Reply via email to