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 db88e8cfd95 Drain executor events without scanning all tracked tasks 
in Python (#77549)
db88e8cfd95 is described below

commit db88e8cfd951847faec910b495d36374ccd4587e
Author: Vincent <[email protected]>
AuthorDate: Mon Nov 30 12:00:31 2026 -0500

    Drain executor events without scanning all tracked tasks in Python (#77549)
    
    Every scheduler loop drained each executor's events by copying the
    executor's table of task identities, one entry per queued or running
    task attempt, and by walking it again to forget the entries no longer
    referenced. With 70,000 running tasks that took 50 to 70 ms per loop
    and per executor, even when no task had finished: about 10 % of the
    scheduler's time. The copy and the full scan came with the attempt
    UUID correlation of executor events (#73916), first released in 3.4.0.
    
    Which identities are known at any time, and which attempt each event
    is attributed to, do not change.
---
 airflow-core/docs/core-concepts/executor/index.rst |   2 +-
 .../src/airflow/executors/base_executor.py         | 129 ++++++++++++----
 .../tests/unit/executors/test_base_executor.py     | 163 +++++++++++++++++++++
 3 files changed, 267 insertions(+), 27 deletions(-)

diff --git a/airflow-core/docs/core-concepts/executor/index.rst 
b/airflow-core/docs/core-concepts/executor/index.rst
index 1e112836c0d..4af0f8e20ed 100644
--- a/airflow-core/docs/core-concepts/executor/index.rst
+++ b/airflow-core/docs/core-concepts/executor/index.rst
@@ -298,7 +298,7 @@ These methods don't require overriding to implement your 
own executor, but are u
 
 * ``heartbeat``: The Airflow scheduler Job loop will periodically call 
heartbeat on the executor. This is one of the main points of interaction 
between the Airflow scheduler and the executor. This method updates some 
metrics, triggers newly queued tasks to execute and updates state of 
running/completed tasks.
 * ``queue_workload``: The Airflow Executor will call this method of the 
BaseExecutor to provide tasks to be run by the executor. The BaseExecutor 
simply adds the *workloads* (check section above to understand) to an internal 
list of queued workloads to run within the executor. All executors present in 
the repository use this method. An override must only buffer the workload: do 
not send it and do not commit the session; writes to the session (the 
``EdgeExecutor`` writes its ``edge_job``  [...]
-* ``get_event_buffer``: The Airflow scheduler calls this method to retrieve 
the current state of the TaskInstances the executor is executing.
+* ``get_event_buffer``: The Airflow scheduler calls this method to retrieve 
the current state of the TaskInstances the executor is executing. It also 
forgets the executor's record of the tasks that left ``running``, the queued 
workloads and ``event_buffer``, so change those only on the thread that calls 
this method, and call ``super().get_event_buffer()`` if you override it.
 * ``has_task``: The scheduler uses this BaseExecutor method to determine if an 
executor already has a specific task instance queued or running.
 * ``send_callback``: Sends any callbacks to the sink configured on the 
executor.
 
diff --git a/airflow-core/src/airflow/executors/base_executor.py 
b/airflow-core/src/airflow/executors/base_executor.py
index 681a20e5a10..5062beee3df 100644
--- a/airflow-core/src/airflow/executors/base_executor.py
+++ b/airflow-core/src/airflow/executors/base_executor.py
@@ -25,7 +25,7 @@ from collections import defaultdict, deque
 from collections.abc import Sequence
 from dataclasses import dataclass, field
 from functools import cached_property, wraps
-from typing import TYPE_CHECKING, Any, ClassVar
+from typing import TYPE_CHECKING, Any, ClassVar, cast
 
 import pendulum
 
@@ -339,7 +339,18 @@ class BaseExecutor(LoggingMixin):
         )
         self.running: set[WorkloadKey] = set()
         self.event_buffer: dict[WorkloadKey, EventBufferValueType] = {}
+        # Only ``_register_task`` adds entries and only 
``_forget_unreferenced_tasks`` removes them: the
+        # reverse index and the sweep rely on it.
         self._task_coordinates: dict[TaskInstanceUuid, TaskInstanceKey] = {}
+        # Reverse index of ``_task_coordinates``, so events keyed by 
coordinates resolve without a scan.
+        # Tuples: coordinates almost always have a single attempt, and a set 
costs 4x the memory.
+        self._coordinate_task_ids: dict[TaskInstanceKey, 
tuple[TaskInstanceUuid, ...]] = {}
+        # Identities registered since the last sweep, and the container keys 
it saw (see
+        # ``_forget_unreferenced_tasks``).
+        self._unswept_task_ids: set[TaskInstanceUuid] = set()
+        self._keys_at_last_sweep: tuple[set[WorkloadKey], ...] = (set(), 
set(), set())
+        # Identities forgotten by the sweep of the drain in progress in 
``_drain_events_with_task_ids``.
+        self._task_coordinates_forgotten_by_drain: dict[TaskInstanceUuid, 
TaskInstanceKey] | None = None
         self._task_event_logs: deque[Log] = deque()
         self.conf = ExecutorConf(team_name)
 
@@ -424,8 +435,76 @@ class BaseExecutor(LoggingMixin):
         )
 
     def _register_task(self, ti: TaskInstance | TaskInstanceDTO) -> None:
-        """Snapshot identity before provider submission or adoption can emit 
events."""
-        self._task_coordinates[TaskInstanceUuid(ti.id)] = ti.key
+        """
+        Snapshot identity before provider submission or adoption can emit 
events.
+
+        Overrides must call ``super()._register_task(ti)``: the reverse index 
and the sweep of unreferenced
+        identities depend on it.
+        """
+        task_id = TaskInstanceUuid(ti.id)
+        coordinates = ti.key
+        previous = self._task_coordinates.get(task_id)
+        self._task_coordinates[task_id] = coordinates
+        if previous != coordinates:
+            if previous is not None:
+                self._discard_coordinate_owner(previous, task_id)
+            self._coordinate_task_ids[coordinates] = (
+                *self._coordinate_task_ids.get(coordinates, ()),
+                task_id,
+            )
+        self._unswept_task_ids.add(task_id)
+
+    def _discard_coordinate_owner(self, coordinates: TaskInstanceKey, task_id: 
TaskInstanceUuid) -> None:
+        # Tolerates identities missing from the index (added without 
``_register_task``): the sweep runs
+        # after get_event_buffer() took the events, so raising here would lose 
them.
+        if owners := tuple(
+            owner for owner in self._coordinate_task_ids.get(coordinates, ()) 
if owner != task_id
+        ):
+            self._coordinate_task_ids[coordinates] = owners
+        else:
+            self._coordinate_task_ids.pop(coordinates, None)
+
+    def _forget_unreferenced_tasks(self) -> None:
+        """
+        Forget the identities of tasks no longer in the running set, the task 
queue or the event buffer.
+
+        An identity can only have become unreferenced since the last sweep if 
it was registered since,
+        or if one of its keys (attempt UUID or coordinates) left one of those 
containers since. Only
+        those identities are checked, so the result is the same as checking 
every identity, without a
+        Python-level pass over every task the executor tracks on each 
scheduler loop.
+
+        An identity added to ``_task_coordinates`` directly is missing from 
the reverse index, and one
+        deleted directly leaves a stale owner in it.
+
+        The containers are expected to change only on the thread that calls 
``get_event_buffer()``. The
+        references are checked against the same copies that are diffed, so 
every identity kept is in the
+        latest copy, and its departure shows in the next diff even if another 
thread changed a container
+        during a sweep.
+        """
+        task_queue = self.executor_queues.get(WorkloadType.EXECUTE_TASK, {})
+        keys_now = tuple(set(container) for container in (self.running, 
task_queue, self.event_buffer))
+        candidates = self._unswept_task_ids
+        for keys_before, keys_after in zip(self._keys_at_last_sweep, keys_now):
+            # Matched by equality, like the check below: a key equal to an 
attempt id or to coordinates (the
+            # Task SDK's TaskInstanceKey, a plain tuple) references them 
whatever its type, and a key of any
+            # other kind matches nothing.
+            for key in keys_before - keys_after:
+                if key in self._task_coordinates:
+                    candidates.add(key)
+                
candidates.update(self._coordinate_task_ids.get(cast("TaskInstanceKey", key), 
()))
+        forgotten = self._task_coordinates_forgotten_by_drain
+        for task_id in candidates:
+            coordinates = self._task_coordinates.get(task_id)
+            if coordinates is None or any(
+                key in container_keys for key in (task_id, coordinates) for 
container_keys in keys_now
+            ):
+                continue
+            del self._task_coordinates[task_id]
+            self._discard_coordinate_owner(coordinates, task_id)
+            if forgotten is not None:
+                forgotten[task_id] = coordinates
+        self._unswept_task_ids = set()
+        self._keys_at_last_sweep = keys_now
 
     @classmethod
     def get_task_key(cls, ti: TaskInstance | TaskInstanceDTO) -> 
TaskInstanceUuid | TaskInstanceKey:
@@ -745,44 +824,42 @@ class BaseExecutor(LoggingMixin):
                 ):
                     cleared_events[key] = self.event_buffer.pop(key)
 
-        task_queue = self.executor_queues.get(WorkloadType.EXECUTE_TASK, {})
-        for task_id, coordinates in list(self._task_coordinates.items()):
-            if not any(
-                key in container
-                for key in (task_id, coordinates)
-                for container in (self.running, task_queue, self.event_buffer)
-            ):
-                del self._task_coordinates[task_id]
-
+        self._forget_unreferenced_tasks()
         return cleared_events
 
     def _drain_events_with_task_ids(
         self, dag_ids=None
     ) -> tuple[dict[WorkloadKey, EventBufferValueType], dict[TaskInstanceUuid, 
TaskInstanceKey]]:
         """Drain events with captured attempt identities and coordinates."""
-        captured_coordinates = self._task_coordinates.copy()
-        task_ids: dict[TaskInstanceKey, TaskInstanceUuid | None] = {}
-        for task_id, coordinates in captured_coordinates.items():
-            task_ids[coordinates] = None if coordinates in task_ids else 
task_id
+        # The sweep in get_event_buffer() forgets the identities of the tasks 
whose events it drains:
+        # they are kept aside, so events resolve against the identities known 
before the drain.
+        forgotten: dict[TaskInstanceUuid, TaskInstanceKey] = {}
+        self._task_coordinates_forgotten_by_drain = forgotten
+        try:
+            drained = self.get_event_buffer(dag_ids)
+        finally:
+            self._task_coordinates_forgotten_by_drain = None
+        forgotten_owners: defaultdict[TaskInstanceKey, list[TaskInstanceUuid]] 
= defaultdict(list)
+        for task_id, coordinates in forgotten.items():
+            forgotten_owners[coordinates].append(task_id)
         events: dict[WorkloadKey, EventBufferValueType] = {}
         event_coordinates: dict[TaskInstanceUuid, TaskInstanceKey] = {}
-        for key, value in self.get_event_buffer(dag_ids).items():
+        for key, value in drained.items():
             if isinstance(key, TaskInstanceKey):
-                captured_id = task_ids.get(key)
-                if captured_id is None:
+                owners = [*self._coordinate_task_ids.get(key, ()), 
*forgotten_owners.get(key, ())]
+                if len(owners) != 1:
                     self.log.warning(
                         "Discarding executor event without a unique captured 
task identity: %s", key
                     )
                     continue
-                events[captured_id] = value
-                event_coordinates[captured_id] = key
+                events[owners[0]] = value
+                event_coordinates[owners[0]] = key
             else:
                 events[key] = value
-                if (
-                    isinstance(key, TaskInstanceUuid)
-                    and (captured := captured_coordinates.get(key)) is not None
-                ):
-                    event_coordinates[key] = captured
+                if isinstance(key, TaskInstanceUuid):
+                    captured = self._task_coordinates.get(key, 
forgotten.get(key))
+                    if captured is not None:
+                        event_coordinates[key] = captured
         return events, event_coordinates
 
     def get_task_log(self, ti: TaskInstance, try_number: int) -> 
tuple[list[str], list[str]]:
diff --git a/airflow-core/tests/unit/executors/test_base_executor.py 
b/airflow-core/tests/unit/executors/test_base_executor.py
index a10534813b4..fbd825c7161 100644
--- a/airflow-core/tests/unit/executors/test_base_executor.py
+++ b/airflow-core/tests/unit/executors/test_base_executor.py
@@ -18,7 +18,9 @@
 from __future__ import annotations
 
 import logging
+import random
 import warnings
+from collections import defaultdict
 from datetime import timedelta
 from pathlib import Path
 from textwrap import dedent
@@ -48,6 +50,7 @@ from airflow.models.connection_test import ConnectionTestKey, 
ConnectionTestStat
 from airflow.models.taskinstance import TaskInstance, TaskInstanceKey
 from airflow.sdk import BaseOperator
 from airflow.sdk.execution_time.callback_supervisor import execute_callback
+from airflow.sdk.types import TaskInstanceKey as SdkTaskInstanceKey
 from airflow.serialization.definitions.baseoperator import 
SerializedBaseOperator
 from airflow.utils.state import CallbackState, State, TaskInstanceState
 
@@ -433,6 +436,166 @@ def 
test_task_workloads_with_matching_coordinates_keep_distinct_attempts(next_tr
     assert executor.has_task(second.ti)
 
 
+def test_event_drain_does_not_scan_every_tracked_task():
+    class UnscannableDict(dict):
+        def scan(self, *args, **kwargs):
+            raise AssertionError("scanned every tracked task")
+
+        __iter__ = keys = values = items = copy = scan
+
+    executor = BaseExecutor()
+    # Swapped in while empty, so entries are still only added by 
_register_task.
+    executor._task_coordinates = UnscannableDict()
+    executor._coordinate_task_ids = UnscannableDict()
+    tasks = [
+        mock.Mock(spec=TaskInstance, id=uuid4(), key=TaskInstanceKey("dag", 
f"task_{i}", "run", 1))
+        for i in range(3)
+    ]
+    for ti in tasks:
+        executor._register_task(ti)
+        executor.running.add(ti.key)
+    executor.get_event_buffer()
+
+    executor.success(tasks[0].key)
+
+    assert executor._drain_events_with_task_ids() == (
+        {TaskInstanceUuid(tasks[0].id): (TaskInstanceState.SUCCESS, None)},
+        {TaskInstanceUuid(tasks[0].id): tasks[0].key},
+    )
+    assert len(executor._task_coordinates) == 2
+    assert TaskInstanceUuid(tasks[0].id) not in executor._task_coordinates
+
+
+def test_sweep_tolerates_identity_missing_from_reverse_index():
+    executor = BaseExecutor()
+    unindexed = TaskInstanceUuid(uuid4())
+    executor._task_coordinates[unindexed] = TaskInstanceKey("dag", 
"unindexed", "run", 1)
+    executor.running.add(unindexed)
+    executor._drain_events_with_task_ids()
+    other = TaskInstanceUuid(uuid4())
+
+    executor.running.discard(unindexed)
+    executor.success(other)
+
+    assert executor._drain_events_with_task_ids() == ({other: 
(TaskInstanceState.SUCCESS, None)}, {})
+    assert executor._task_coordinates == {}
+    assert executor._coordinate_task_ids == {}
+
+
+class FullScanExecutor(BaseExecutor):
+    """Reference: the previous identity bookkeeping, ported onto the new hooks 
(without the warning log)."""
+
+    def _register_task(self, ti):
+        self._task_coordinates[TaskInstanceUuid(ti.id)] = ti.key
+
+    def _forget_unreferenced_tasks(self):
+        task_queue = self.executor_queues.get(WorkloadType.EXECUTE_TASK, {})
+        for task_id, coordinates in list(self._task_coordinates.items()):
+            if not any(
+                key in container
+                for key in (task_id, coordinates)
+                for container in (self.running, task_queue, self.event_buffer)
+            ):
+                del self._task_coordinates[task_id]
+
+    def _drain_events_with_task_ids(self, dag_ids=None):
+        captured_coordinates = self._task_coordinates.copy()
+        task_ids = {}
+        for task_id, coordinates in captured_coordinates.items():
+            task_ids[coordinates] = None if coordinates in task_ids else 
task_id
+        events, event_coordinates = {}, {}
+        for key, value in self.get_event_buffer(dag_ids).items():
+            if isinstance(key, TaskInstanceKey):
+                if (captured_id := task_ids.get(key)) is not None:
+                    events[captured_id] = value
+                    event_coordinates[captured_id] = key
+            else:
+                events[key] = value
+                if (
+                    isinstance(key, TaskInstanceUuid)
+                    and (captured := captured_coordinates.get(key)) is not None
+                ):
+                    event_coordinates[key] = captured
+        return events, event_coordinates
+
+
+OPERATIONS = {
+    "register": lambda executor, key, ti, dag_ids: executor._register_task(ti),
+    "add to running": lambda executor, key, ti, dag_ids: 
executor.running.add(key),
+    "remove from running": lambda executor, key, ti, dag_ids: 
executor.running.discard(key),
+    "queue": lambda executor, key, ti, dag_ids: 
executor.executor_queues[WorkloadType.EXECUTE_TASK].update(
+        {key: None}
+    ),
+    "dequeue": lambda executor, key, ti, dag_ids: 
executor.executor_queues[WorkloadType.EXECUTE_TASK].pop(
+        key, None
+    ),
+    "replace task queue": lambda executor, key, ti, dag_ids: 
executor.executor_queues.update(
+        {WorkloadType.EXECUTE_TASK: {}}
+    ),
+    "replace running": lambda executor, key, ti, dag_ids: setattr(executor, 
"running", set()),
+    "report success": lambda executor, key, ti, dag_ids: executor.change_state(
+        key, TaskInstanceState.SUCCESS
+    ),
+    "pop event": lambda executor, key, ti, dag_ids: 
executor.event_buffer.pop(key, None),
+    "report running": lambda executor, key, ti, dag_ids: executor.change_state(
+        key, TaskInstanceState.RUNNING, remove_running=False
+    ),
+    "drain events": lambda executor, key, ti, dag_ids: 
executor._drain_events_with_task_ids(dag_ids),
+    "get event buffer": lambda executor, key, ti, dag_ids: 
executor.get_event_buffer(dag_ids),
+}
+
+
[email protected]("seed", range(10))
+def 
test_identity_bookkeeping_matches_checking_every_identity_on_each_drain(seed):
+    # Few attempts and coordinates, so attempts share coordinates and keys 
come and go often.
+    rng = random.Random(seed)
+    task_ids = [TaskInstanceUuid(UUID(int=rng.getrandbits(128))) for _ in 
range(12)]
+    coordinates = [
+        TaskInstanceKey(dag_id, f"task_{i}", "run", try_number)
+        for dag_id in ("dag_a", "dag_b")
+        for i in range(2)
+        for try_number in (1, 2)
+    ]
+    tis = {
+        (task_id, ti_coordinates): mock.Mock(spec=TaskInstance, id=task_id.id, 
key=ti_coordinates)
+        for task_id in task_ids
+        for ti_coordinates in coordinates
+    }
+    callback_key = CallbackKey(id=str(UUID(int=rng.getrandbits(128))))
+    operation_names = sorted(OPERATIONS)
+    actual, expected = BaseExecutor(), FullScanExecutor()
+
+    for _ in range(2000):
+        task_id = rng.choice(task_ids)
+        task_coordinates = rng.choice(coordinates)
+        # Keys equal to coordinates reference identities whatever their type, 
e.g. the Task SDK's
+        # TaskInstanceKey or a plain tuple.
+        key = rng.choice(
+            [
+                task_id,
+                task_coordinates,
+                SdkTaskInstanceKey(*task_coordinates),
+                tuple(task_coordinates),
+                callback_key,
+            ]
+        )
+        ti = tis[task_id, rng.choice(coordinates)]
+        dag_ids = rng.choice([None, ["dag_a"]])
+        operation = OPERATIONS[rng.choice(operation_names)]
+
+        assert operation(actual, key, ti, dag_ids) == operation(expected, key, 
ti, dag_ids)
+        assert actual._task_coordinates == expected._task_coordinates
+        reverse_index: defaultdict[TaskInstanceKey, list[TaskInstanceUuid]] = 
defaultdict(list)
+        for known_id, known_coordinates in actual._task_coordinates.items():
+            reverse_index[known_coordinates].append(known_id)
+        assert {
+            known_coordinates: sorted(owners, key=str)
+            for known_coordinates, owners in 
actual._coordinate_task_ids.items()
+        } == {
+            known_coordinates: sorted(owners, key=str) for known_coordinates, 
owners in reverse_index.items()
+        }
+
+
 @pytest.mark.parametrize(
     ("team_name", "expected_tags"),
     [

Reply via email to