xBis7 opened a new pull request, #77600:
URL: https://github.com/apache/airflow/pull/77600

    <!-- SPDX-License-Identifier: Apache-2.0
         https://www.apache.org/licenses/LICENSE-2.0 -->
   
   <!--
   Thank you for contributing!
   
   Please provide above a brief description of the changes made in this pull 
request.
   Write a good git commit message following this guide: 
https://chris.beams.io/posts/git-commit/
   
   Please make sure that your code changes are covered with tests.
   And in case of new features or big changes remember to adjust the 
documentation.
   
   For user-facing UI changes, please attach before/after screenshots (or a 
short
   screen recording) so reviewers can assess the visual impact.
   
   Feel free to ping (in general) for the review if you do not see reaction for 
a few days
   (72 Hours is the minimum reaction time you can expect from volunteers) - we 
sometimes miss notifications.
   
   In case of an existing issue, reference it using one of the following:
   
   * closes: #ISSUE
   * related: #ISSUE
   -->
   
   
   ## The issue
   
   When a Dag run has a mapped task group, the group is copied once per input 
item. For example:
   
   ```python
   @task_group
   def group(item):
       b(a(item))
   
   group.expand(item=["x", "y", "z"])
   ```
   
   creates 3 copies of the group, each with its own `a` and `b` task instance:
   
   ```
   copy 0: a[0] → b[0]
   copy 1: a[1] → b[1]
   copy 2: a[2] → b[2]
   ```
   
   `b[1]` waits only on `a[1]`, not on `a[0]` or `a[2]`. To pick out `a[1]`, 
`TriggerRuleDep` needs to know
   how many copies the group has, which is 3.
   
   In one scheduling pass over the Dag run, the scheduler checks the waiting 
task instances one by one.
   Say every `a` has finished and `b[0]`, `b[1]` and `b[2]` are waiting:
   
   ```
   b[0]: copy count for b[0] itself  → database → 3
         copy count for upstream a   → database → 3
   b[1]: the same two lookups        → database → 3, 3
   b[2]: the same two lookups        → database → 3, 3
   ```
   
   `b[0]`'s two lookups already give every count the pass needs. `b[1]` and 
`b[2]` repeat them and get the same answers,
   so the pass makes 6 database lookups where 2 would do, two more for every 
additional waiting copy.
   
   Now imagine 10 stages chained in the group and 10 copies per stage, 100 task 
instances in total.
   While stage 1 runs, the 90 copies of stages 2–10 are all waiting,
   and each makes the same two lookups: 180 database lookups per pass,
   where 10 would do (one per stage - 9 waiting, plus one for the group).
   The scheduler repeats this pass for every running Dag run, in every loop.
   
   ## Optimization
   
   We can optimize this with memoization. This PR adds a dictionary to 
`DepContext` that keeps each copy count
   it looks up for the rest of the scheduling pass, so every later copy that 
needs the same count gets it
   from the memo instead of the database. For the same example:
   
   ```
   b[0]: copy count for b[0] itself  → database → 3, kept
         copy count for upstream a   → database → 3, kept
   b[1]: the same two counts         → memo     → 3, 3
   b[2]: the same two counts         → memo     → 3, 3
   ```
   
   The pass makes 2 database lookups instead of 6, regardless of how many 
copies are waiting.
   With 10 stages and 10 copies per stage, it makes 10 lookups instead of 180.
   
   The memo lasts only one pass, so the next pass looks the counts up again. A 
count that can't be computed yet isn't
   kept, and if a task expands during the pass, then the memo is dropped so 
that later copies look up the new count.
   
   
   ### For one scheduler loop iteration
   
   1. For each running Dag run, one scheduling pass: fetch its task instances 
and check the dependencies of each
      waiting one.
   2. Inside that check, `TriggerRuleDep` looks up the group's copy count for 
each waiting copy. In the example
      above, with `b[0]`, `b[1]` and `b[2]` waiting:
      - Before: each copy looks up both counts in the database, 6 lookups.
      - After: `b[0]` looks up both counts in the database and `b[1]` and 
`b[2]` get them from the memo, 2 lookups.
   3. Queue up to `max_tis_per_query` (16) scheduled task instances and send 
them to the executor.
   
   
   The 16-per-loop cap doesn't change, so before and after take about the same 
number of loops (221 and 223);
   each loop is 4.7× shorter.
   
   
   ## Testing
   
   This patch doesn't introduce any behavioral changes.
   I've added new unit tests and I've also run manual tests using the setup 
here:
   
   
https://github.com/apache/airflow/blob/main/airflow-core/tests/integration/performance/test_perf.py
   
   I adjusted it to create 5 Dag runs with 70 copies per group and used this Dag
   
   ```python
   from __future__ import annotations
   
   from datetime import datetime
   from typing import Any
   
   from airflow.sdk import DAG, task, task_group
   
   STAGE_COUNT = 9
   
   
   @task
   def get_mapped_task_indexes(**context: Any) -> list[int]:
       """Return [0, ..., (mapped_task_count - 1)], one element per mapped copy 
of the stage group."""
       # The run's conf overrides the Dag's params; the test sets the count 
there.
       return list(range(int(context["params"]["mapped_task_count"])))
   
   
   @task
   def run_stage(parameter: int) -> None:
       """Do nothing."""
       # Empty on purpose: any work here would measure the workers, not the 
scheduler.
   
   
   @task_group
   def run_stages(parameter: int) -> None:
       previous = None
       for stage in range(1, STAGE_COUNT + 1):
           current = 
run_stage.override(task_id=f"stage_{stage}")(parameter=parameter)
           # Each stage instance waits only for the previous stage's instance 
in the same copy.
           if previous is not None:
               previous >> current
           previous = current
   
   
   with DAG(
       dag_id="perf_task_group_dag",
       schedule=None,
       start_date=datetime(2024, 1, 1),
       catchup=False,
       default_args={"retries": 0},
       params={"mapped_task_count": 20},  # overridden by each run's conf
       tags=["perf"],
   ):
       # Same stages and sizes as perf_dag, but the group expands once, so 
every stage's copies exist
       # as soon as the list is ready, instead of each stage expanding when the 
previous one finishes.
       run_stages.expand(parameter=get_mapped_task_indexes())
   ```
   
   So basically, it ran a mapped task group of 9 sequential stages expanded to 
70 copies, 631 task instances per Dag
   run, 5 Dag runs (3,155 task instances in total) once with the patch and once 
without.
   The DB backend was Postgres, and it also had 3 Celery workers with 54 slots, 
default `max_tis_per_query` (16).
   
   With the above setup, although the load isn't too much, the scheduler is 
almost unusable in `main`.
   
   | `main` | Without the patch | With the patch | Change |
   |---|---|---|---|
   | Time to finish all 5 Dag runs | 2,037 s (34.0 min) | 442 s (7.4 min) | 
−78% (4.6×) |
   | Dag run duration, mean | 2,033 s | 438 s | −78% |
   | Task instances queued per minute | 93 | 429 | +361% |
   | Scheduler loop, mean | 9,183 ms | 1,942 ms | −79% (4.7×) |
   | Dependency check per Dag run, mean | 1,986 ms | 402 ms | −80% (4.9×) |
   | Copy-count lookups from the database | 511,619 | 6,376 | −99% |
   | Copy-count lookups from the memo | 0 | 505,717 | |
   | Copy-count lookup time per loop | 7,086 ms | 117 ms | −98% |
   | Scheduler SQL statements per loop | 7,021 | 2,423 | −65% |
   | Scheduler SQL time per loop | 3,533 ms | 621 ms | −82% |
   
   
   ### Performance degradation in main
   
   I also ran the same test with `main` and `3.2.2` without the new patch and 
performance has degraded a lot.
   Each lookup has become way more expensive. On `3.2.2` a lookup is one query 
on `task_map`. On `main`, #73005
   removed `task_map`, so the count comes from `xcom.mapped_length` through a 
join, and the dynamic regions from
   #74275 and #74346 added a producer check to it, so each lookup is now two 
SQL statements. Here are some numbers:
   
   | Without the patch | `3.2.2` | `main` | Change |
   |---|---|---|---|
   | Time to finish all 5 Dag runs | 505 s (8.4 min) | 2,037 s (34.0 min) | 
+303% (4.0×) |
   | Dag run duration, mean | 499 s | 2,033 s | +308% (4.1×) |
   | Task instances queued per minute | 375 | 93 | −75% |
   | Scheduler loop, mean | 2,144 ms | 9,183 ms | +328% (4.3×) |
   | Dependency check per Dag run, mean | 444 ms | 1,986 ms | +347% (4.5×) |
   | Copy-count lookups from the database | 513,616 | 511,619 | about the same |
   | One copy-count lookup | 0.23 ms | 3.06 ms | +1,217% (13×) |
   | Copy-count lookup time per loop | 523 ms | 7,086 ms | +1,254% (13.5×) |
   | Copy-count lookups' share of the loop | 24% | 77% | |
   | Scheduler SQL statements per loop | 4,557 | 7,021 | +54% |
   | Scheduler SQL time per loop | 564 ms | 3,533 ms | +526% (6.3×) |
   
   The `3.2.2` run includes #71737, which `main` already has.
   
   ---
   
   ##### Was generative AI tooling used to co-author this PR?
   
   <!--
   If generative AI tooling has been used in the process of authoring this PR, 
please
   change below checkbox to `[X]` followed by the name of the tool, uncomment 
the "Generated-by".
   -->
   
   - [X] Yes (please specify the tool below)
   
   Claude Code Opus 5.5
   
   <!--
   Generated-by: [Tool Name] following [the 
guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions)
   -->
   
   ---
   
   * Read the **[Pull Request 
Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#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](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals))
 is needed.
   * When adding dependency, check compliance with the [ASF 3rd Party License 
Policy](https://www.apache.org/legal/resolved.html#category-x).
   * For significant user-facing changes create newsfragment: 
`{pr_number}.significant.rst`, in 
[airflow-core/newsfragments](https://github.com/apache/airflow/tree/main/airflow-core/newsfragments).
 You can add this file in a follow-up commit after the PR is created so you 
know the PR number.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to