This is an automated email from the ASF dual-hosted git repository.
shahar1 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 b36792ff7df Add an integration test for performance and regression
testing (#77032)
b36792ff7df is described below
commit b36792ff7df3b2ff1f476674e47751ed702851c0
Author: Christos Bisias <[email protected]>
AuthorDate: Sat Nov 21 19:55:50 2026 +0200
Add an integration test for performance and regression testing (#77032)
---
.../skills/airflow-performance-harness/SKILL.md | 67 +++
airflow-core/tests/integration/otel/test_otel.py | 57 +--
.../tests/integration/performance/README.md | 104 +++++
.../tests/integration/performance/__init__.py | 16 +
.../tests/integration/performance/conftest.py | 38 ++
.../tests/integration/performance/dags/__init__.py | 16 +
.../tests/integration/performance/dags/perf_dag.py | 58 +++
.../tests/integration/performance/poll_usage.py | 210 +++++++++
.../tests/integration/performance/test_perf.py | 280 ++++++++++++
contributing-docs/testing/integration_tests.rst | 11 +
.../tests_common/test_utils/integration_setup.py | 448 +++++++++++++++++--
.../apache/kafka/plugins/test_event_producer.py | 4 +-
.../grafana/volume/dashboards/scheduler_perf.json | 480 +++++++++++++++++++++
scripts/ci/prek/check_tests_in_right_folders.py | 1 +
14 files changed, 1710 insertions(+), 80 deletions(-)
diff --git a/.agents/skills/airflow-performance-harness/SKILL.md
b/.agents/skills/airflow-performance-harness/SKILL.md
new file mode 100644
index 00000000000..6c51aea5906
--- /dev/null
+++ b/.agents/skills/airflow-performance-harness/SKILL.md
@@ -0,0 +1,67 @@
+---
+name: airflow-performance-harness
+description: Measure a scheduler or executor-path change under load with the
performance harness in airflow-core/tests/integration/performance. Use when
asked to benchmark, load test or compare the performance of a change to the
scheduler, the executors or task scheduling. Covers putting the change behind
the flag, shaping the load, running the harness in breeze, reading its
dashboard, and dropping the scratch changes afterwards.
+---
+
+<!-- SPDX-License-Identifier: Apache-2.0
+ https://www.apache.org/licenses/LICENSE-2.0 -->
+
+# Measure a change with the performance harness
+
+The harness in
[`airflow-core/tests/integration/performance`](../../../airflow-core/tests/integration/performance/README.md)
+is a scratch environment, not a test suite. It runs the Airflow processes
inside breeze against a
+backlog of Dag runs, once with the original code and once with the change, and
the comparison is
+how long each took plus what the dashboard shows. Read its README first.
+
+## Workflow
+
+1. **Put the change behind the flag.** The test sets `PERF_TEST__NEW_CODE` to
`false` for the first
+ test case and `true` for the second, before starting the processes. In the
code under test:
+
+ ```python
+ if os.environ.get("PERF_TEST__NEW_CODE", "").lower() == "true":
+ ... # new code with changes
+ else:
+ ... # original code, e.g. code from main
+ ```
+
+ Code that is purely additive only needs the first branch of the if-else
statement. The
+ `else` branch must be exactly what `main` does. Do not add a config option
or anything else
+ for the flag; the environment variable is enough and leaves nothing to
clean up.
+
+2. **Shape the load.** The test function chooses its load at its top, in
`test_perf.py`. Edit the
+ numbers there, or override one for a single run with its
`PERF_TEST__<NAME>` variable in the
+ shell. Start small to check the plumbing, then scale to what the change is
about. The README
+ says how to change the Dags or the runs.
+
+3. **Run it.** Breeze needs Docker. If breeze cannot run, stop and say which
call failed; do not
+ build a substitute environment.
+
+ ```bash
+ breeze shell --backend postgres --integration otel --integration redis
+ # inside the shell
+ pytest airflow-core/tests/integration/performance/test_perf.py -s
+ ```
+
+ Without a terminal, for example when an agent runs it, add `-s` so that
output is not held
+ back by pytest's capture. Run a single test case with `-k original_code` or
`-k new_code`. The
+ first run on a machine raises the Postgres connection limit the profile
needs, persists it in
+ the breeze volume and restarts the container from inside breeze. If the
restart is not
+ possible, the test fails with the command to run on the host; ask for it
and run again.
+
+4. **Read the results.** Progress lines are printed in the terminal every 15
seconds, and the
+ elapsed time at the end of each test case; that elapsed time is the
headline. The "Scheduler
+ performance" dashboard at `http://localhost:23000` says whether the
scheduler or the workers
+ were the constraint and where a task's time went; a scheduler change should
move the
+ scheduler's share and leave the workers' alone. Prometheus scrapes every 30
seconds, so a run
+ needs several minutes before the rate panels say anything. Report both test
cases side by side
+ with the load you used, and treat the numbers as invalid if the machine was
oversubscribed,
+ which shows as the mean running time per task climbing with the load.
+
+5. **Clean up.** The flag belongs to the scratch change: nothing in the
harness depends on it, so
+ drop it together with the rest when you are done. Never commit a
`PERF_TEST__NEW_CODE` read.
+
+The test setup isn't meant to run in the CI. The folder is collected only when
its path is named
+on the pytest command line; do not change `conftest.py` or any workflow to
select it. The test
+only fails when a process dies, a run fails or the environment is missing; it
is not where the
+measurement is read.
diff --git a/airflow-core/tests/integration/otel/test_otel.py
b/airflow-core/tests/integration/otel/test_otel.py
index 5be887bbdfa..aa0b43bbc09 100644
--- a/airflow-core/tests/integration/otel/test_otel.py
+++ b/airflow-core/tests/integration/otel/test_otel.py
@@ -18,7 +18,6 @@ from __future__ import annotations
import logging
import os
-import socket
import subprocess
import time
from typing import TYPE_CHECKING, Any
@@ -32,11 +31,14 @@ from airflow.utils.session import create_session
from airflow.utils.state import State
from tests_common.test_utils.integration_setup import (
+ OTEL_COLLECTOR_HOST,
+ OTEL_COLLECTOR_PORT,
serialize_and_get_dags,
start_scheduler,
terminate_process,
unpause_trigger_dag_and_get_run_id,
- wait_for_dag_run,
+ wait_for_dag_runs,
+ wait_for_otel_collector,
)
from tests_common.test_utils.otel_utils import (
dump_airflow_metadata_db,
@@ -49,44 +51,6 @@ if TYPE_CHECKING:
log = logging.getLogger("integration.otel.test_otel")
-def wait_for_otel_collector(host: str, port: int, timeout: int = 120) -> None:
- """
- Wait for the OTel collector to be reachable before running tests.
-
- This prevents flaky test failures caused by transient DNS resolution issues
- (e.g., 'Temporary failure in name resolution' for breeze-otel-collector).
-
- Note: If the collector is not reachable after timeout, logs a warning but
- does not fail - allows tests to run and fail naturally if needed.
- """
- deadline = time.monotonic() + timeout
- last_error = None
- while time.monotonic() < deadline:
- try:
- # Test DNS resolution and TCP connectivity
- with socket.create_connection((host, port), timeout=5):
- pass
- log.info("OTel collector at %s:%d is reachable.", host, port)
- return
- except (socket.gaierror, TimeoutError, OSError) as e:
- last_error = e
- log.debug(
- "OTel collector at %s:%d not reachable: %s. Retrying...",
- host,
- port,
- e,
- )
- time.sleep(2)
- log.warning(
- "OTel collector at %s:%d is not reachable after %ds. Last error: %s. "
- "Tests will proceed but may fail if collector is required.",
- host,
- port,
- timeout,
- last_error,
- )
-
-
def print_ti_output_for_dag_run(dag_id: str, run_id: str):
breeze_logs_dir = "/root/airflow/logs"
@@ -138,13 +102,10 @@ class TestOtelIntegration:
@classmethod
def setup_class(cls):
- otel_host = "breeze-otel-collector"
- otel_port = 4318
-
# Wait for OTel collector to be reachable before running tests.
# This prevents flaky test failures caused by transient DNS resolution
issues
# during scheduler handoff (see
https://github.com/apache/airflow/issues/61070).
- wait_for_otel_collector(otel_host, otel_port)
+ wait_for_otel_collector(OTEL_COLLECTOR_HOST, OTEL_COLLECTOR_PORT)
# The pytest plugin strips AIRFLOW__*__* env vars (including the JWT
secret set
# by Breeze). Both the scheduler and api-server subprocesses must
share the same
@@ -210,10 +171,10 @@ class TestOtelIntegration:
run_id = unpause_trigger_dag_and_get_run_id(dag_id=dag_id)
- state = wait_for_dag_run(dag_id=dag_id, run_id=run_id,
max_wait_time=90)
+ state = wait_for_dag_runs([(dag_id, run_id)],
max_wait_time=90)[(dag_id, run_id)]
assert state == State.SUCCESS, f"Dag run did not complete
successfully. Final state: {state}."
- # wait_for_dag_run returns on the dag_run DB state, but OTel
metrics are exported
+ # wait_for_dag_runs returns on the dag_run DB state, but OTel
metrics are exported
# asynchronously, so wait for them to reach stdout before we
capture it below.
time.sleep(10)
@@ -380,9 +341,9 @@ class TestOtelIntegration:
run_id = unpause_trigger_dag_and_get_run_id(dag_id=dag_id,
conf=conf)
- wait_for_dag_run(dag_id=dag_id, run_id=run_id, max_wait_time=90)
+ wait_for_dag_runs([(dag_id, run_id)], max_wait_time=90)
- # wait_for_dag_run returns on the dag_run DB state, but spans
reach Jaeger
+ # wait_for_dag_runs returns on the dag_run DB state, but spans
reach Jaeger
# asynchronously via the BatchSpanProcessor, so wait before
querying the trace below.
time.sleep(10)
diff --git a/airflow-core/tests/integration/performance/README.md
b/airflow-core/tests/integration/performance/README.md
new file mode 100644
index 00000000000..367d72325b7
--- /dev/null
+++ b/airflow-core/tests/integration/performance/README.md
@@ -0,0 +1,104 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+# Performance harness
+
+A scratch environment for measuring a scheduler or executor-path change under
load, inside
+breeze. The test starts an API server, Celery workers and a scheduler as its
own subprocesses,
+creates a backlog of queued Dag runs and measures how long the deployment
takes to finish running them,
+once with the new code under test and once with the original code. While the
Dag runs are active,
+metrics are captured which can then be examined in Grafana. Apart from the
internal Airflow metrics,
+there are usage metrics for the scheduler and the workers which are captured
and exported by a
+`poll_usage.py` script that runs for as long as the services are running.
+
+The test setup isn't meant to run in the CI. The folder is collected only when
its path is named on the pytest command line.
+
+## Running it
+
+Start breeze with Postgres and the two integrations the harness needs, and
then run the test:
+
+```bash
+breeze shell --backend postgres --integration otel --integration redis
+pytest airflow-core/tests/integration/performance/test_perf.py
+```
+
+Progress lines are printed in the terminal every 15 seconds, and the elapsed
time at the end of each test case.
+Without a terminal, for example when an agent runs it, add `-s` so that output
is not held back
+by pytest's capture.
+
+Watch the run from the host: Grafana at <http://localhost:23000>, dashboard
"Scheduler
+performance"; Jaeger at <http://localhost:26686>; Prometheus at
<http://localhost:29090>.
+
+The first run on a machine raises the Postgres connection limit the profile
needs, persists it
+in the breeze volume and restarts the container from inside breeze. If the
restart is not
+possible, the test fails with the command to run on the host.
+
+## Comparing new code with the original
+
+The test runs two test cases, `original_code` and then `new_code`, and sets
`PERF_TEST__NEW_CODE` to `false`
+or `true` before starting the processes. Put the change in the code under test
behind the flag:
+
+```python
+if os.environ.get("PERF_TEST__NEW_CODE", "").lower() == "true":
+ ... # new code with changes
+else:
+ ... # original code, e.g. code from main
+```
+
+Code that is purely additive only needs the first branch of the if-else
statement.
+The flag belongs to the scratch change:
+nothing in the harness depends on it, so drop it together with the rest when
you are done.
+
+Run a single test case with `-k original_code` or `-k new_code`.
+
+`AIRFLOW__*` variables exported in the shell do not reach the processes,
because the test plugin
+strips them. Pass `--keep-env-variables` to pytest to keep them.
+
+## Shaping the load
+
+The test function chooses its load at its top, in `test_perf.py`. Edit the
numbers there, or
+override one for a single run with its `PERF_TEST__<NAME>` variable in the
shell. The profile is the one
+class-level choice, because it sizes the deployment before the database is
created.
+
+| Setting | Default | Override | Effect
|
+|-----------------------|-----------|----------------------------|------------------------------------------------------------------------|
+| `dag_run_count` | `5` | `PERF_TEST__DAG_RUN_COUNT`
| Queued runs created up front, before the scheduler starts. |
+| `mapped_task_count` | `20` | `PERF_TEST__MAPPED_TASK_COUNT` |
Mapped instances per stage, passed to every run in its `conf`. |
+| `timeout_seconds` | `3600` | `PERF_TEST__TIMEOUT_SECONDS` | Give
up on a test case after this; unfinished runs compare with nothing. |
+| `profile` | `dynamic` | `PERF_TEST__PROFILE` |
Concurrency profile, see below. |
+
+The Dag is fixed: a first task producing a list, then nine mapped stages that
expand over it,
+each depending on the whole previous stage. Only the size of a run changes,
through its `conf`.
+The total mapped task instances per test case are `dag_run_count * 9 *
mapped_task_count`.
+
+To adjust:
+
+- The load: edit the numbers at the top of the test function, or override them
in the shell.
+- The Dags, the runs or their `conf`: add a test function that picks them and
calls
+ `execute_dag_runs`.
+- The shape: add a Dag file in `dags/` that reads its sizes from `params`. The
class serializes
+ every Dag in the folder. Keep task bodies empty, or the run turns into a
worker throughput test.
+
+## Profiles
+
+`dynamic` checks the available CPU cores and sets the required configs based
on the machine size.
+
+`custom` is the `custom` entry of `PROFILES` in `test_perf.py`. Fill in what
the machine or the experiment needs
+and select it with `profile = "custom"` or `PERF_TEST__PROFILE=custom`.
+The current values set all configs at their Airflow default.
diff --git a/airflow-core/tests/integration/performance/__init__.py
b/airflow-core/tests/integration/performance/__init__.py
new file mode 100644
index 00000000000..13a83393a91
--- /dev/null
+++ b/airflow-core/tests/integration/performance/__init__.py
@@ -0,0 +1,16 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
diff --git a/airflow-core/tests/integration/performance/conftest.py
b/airflow-core/tests/integration/performance/conftest.py
new file mode 100644
index 00000000000..2d64c286700
--- /dev/null
+++ b/airflow-core/tests/integration/performance/conftest.py
@@ -0,0 +1,38 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ import pytest
+
+PERF_DIR = Path(__file__).resolve().parent
+
+
+def pytest_ignore_collect(config: pytest.Config) -> bool | None:
+ """Collect this folder only when it is named on the pytest command line."""
+ invocation_dir = Path(config.invocation_params.dir)
+ for arg in config.args:
+ target = Path(str(arg).split("::", 1)[0])
+ if not target.is_absolute():
+ target = invocation_dir / target
+ target = target.resolve()
+ if target == PERF_DIR or PERF_DIR in target.parents:
+ return None
+ return True
diff --git a/airflow-core/tests/integration/performance/dags/__init__.py
b/airflow-core/tests/integration/performance/dags/__init__.py
new file mode 100644
index 00000000000..13a83393a91
--- /dev/null
+++ b/airflow-core/tests/integration/performance/dags/__init__.py
@@ -0,0 +1,16 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
diff --git a/airflow-core/tests/integration/performance/dags/perf_dag.py
b/airflow-core/tests/integration/performance/dags/perf_dag.py
new file mode 100644
index 00000000000..3f09153f814
--- /dev/null
+++ b/airflow-core/tests/integration/performance/dags/perf_dag.py
@@ -0,0 +1,58 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+
+from airflow.sdk import DAG, task
+
+STAGE_COUNT = 9
+
+
+@task
+def get_mapped_task_indexes(**context: Any) -> list[int]:
+ """Return [0, ..., (mapped_task_count - 1)], one element per mapped task
instance of a stage."""
+ # 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.
+
+
+with DAG(
+ dag_id="perf_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"],
+):
+ # expand() needs a list at run time, one element per instance; only a task
can build it from
+ # the run's conf.
+ mapped_task_indexes = get_mapped_task_indexes()
+ previous = None
+ for stage in range(1, STAGE_COUNT + 1):
+ current =
run_stage.override(task_id=f"stage_{stage}").expand(parameter=mapped_task_indexes)
+ # Each stage waits for every instance of the previous one: a barrier
per stage.
+ if previous is not None:
+ previous >> current
+ previous = current
diff --git a/airflow-core/tests/integration/performance/poll_usage.py
b/airflow-core/tests/integration/performance/poll_usage.py
new file mode 100644
index 00000000000..491711dfc3f
--- /dev/null
+++ b/airflow-core/tests/integration/performance/poll_usage.py
@@ -0,0 +1,210 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+This file runs along with the processes in the performance integration test.
+Calculates the CPU and memory usage of the processes, and the number of
occupied worker slots,
+and pushes the values over OTLP. Exits on its own once every sampled process
is gone.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import logging
+import os
+import sys
+import time
+import urllib.request
+
+import psutil
+from celery import Celery
+
+from airflow.configuration import conf
+
+log = logging.getLogger(__name__)
+
+OTLP_METRICS_URL = os.environ.get(
+ "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
"http://breeze-otel-collector:4318/v1/metrics"
+)
+SERVICE_NAME = "perf-harness"
+
+
+def parse_roles(pairs: list[str]) -> dict[str, int]:
+ roles: dict[str, int] = {}
+ for pair in pairs:
+ role, _, pid = pair.partition("=")
+ if not role or not pid.isdigit():
+ raise SystemExit(f"expected ROLE=PID, got {pair!r}")
+ roles[role] = int(pid)
+ return roles
+
+
+def sample_tree(pid: int) -> tuple[float, int] | None:
+ """Return ``(cpu_seconds, rss_bytes)`` summed over ``pid`` and its live
descendants."""
+ try:
+ root = psutil.Process(pid)
+ processes = [root, *root.children(recursive=True)]
+ except psutil.NoSuchProcess:
+ return None
+ cpu_seconds = 0.0
+ rss_bytes = 0
+ for process in processes:
+ try:
+ times = process.cpu_times()
+ # cpu_times deltas rather than Process.cpu_percent: Celery and the
task supervisor fork
+ # per task, so the tree changes between samples and a new child's
first cpu_percent
+ # always reads zero. The children_* fields count reaped children
through their parent,
+ # so a task process that lived and died between two samples is not
lost.
+ cpu_seconds += times.user + times.system + times.children_user +
times.children_system
+ # Summed over the tree, so pages shared with forked children count
more than once: it
+ # tracks growth and compares test cases, it is not an absolute
footprint.
+ rss_bytes += process.memory_info().rss
+ except (psutil.NoSuchProcess, psutil.ZombieProcess,
psutil.AccessDenied):
+ continue
+ return cpu_seconds, rss_bytes
+
+
+def sample_roles(roles: dict[str, int]) -> dict[str, tuple[float, int]]:
+ samples: dict[str, tuple[float, int]] = {}
+ for role, pid in roles.items():
+ if (sample := sample_tree(pid)) is not None:
+ samples[role] = sample
+ return samples
+
+
+def count_occupied_slots(app: Celery) -> int | None:
+ """Celery's own count of held slots across all workers, or None when no
worker answered."""
+ # pool.running_slots only covers execution, about half of a slot's
occupancy.
+ try:
+ active = app.control.inspect(timeout=2.0).active()
+ except Exception:
+ log.exception("celery inspect failed")
+ return None
+ if active is None:
+ return None
+ return sum(len(tasks) for tasks in active.values())
+
+
+def build_data_point(value: float | int, now_ns: int, role: str | None = None)
-> dict:
+ point: dict = {"timeUnixNano": str(now_ns), "attributes": []}
+ if role is not None:
+ point["attributes"].append({"key": "role", "value": {"stringValue":
role}})
+ if isinstance(value, float):
+ point["asDouble"] = value
+ else:
+ point["asInt"] = str(value)
+ return point
+
+
+def build_gauge(name: str, points: list[dict]) -> dict:
+ return {"name": name, "gauge": {"dataPoints": points}}
+
+
+def build_payload(gauges: list[dict]) -> dict:
+ return {
+ "resourceMetrics": [
+ {
+ "resource": {"attributes": [{"key": "service.name", "value":
{"stringValue": SERVICE_NAME}}]},
+ "scopeMetrics": [{"scope": {"name": "perf.poller"}, "metrics":
gauges}],
+ }
+ ]
+ }
+
+
+def push(payload: dict) -> None:
+ request = urllib.request.Request(
+ OTLP_METRICS_URL,
+ data=json.dumps(payload).encode(),
+ headers={"Content-Type": "application/json"},
+ )
+ urllib.request.urlopen(request, timeout=5).read()
+
+
+def main(argv: list[str] | None = None) -> None:
+ parser = argparse.ArgumentParser(
+ description="Push CPU, memory and worker slot usage of the harness
processes to the OTel collector."
+ )
+ parser.add_argument("roles", nargs="+", metavar="ROLE=PID")
+ parser.add_argument(
+ "--slot-budget",
+ type=int,
+ required=True,
+ help="worker slots the harness configured, pushed next to the occupied
count",
+ )
+ parser.add_argument("--interval", type=float, default=5.0, help="seconds
between samples")
+ parser.add_argument(
+ "--once", action="store_true", help="print one sample as JSON to
stdout and exit without pushing"
+ )
+ args = parser.parse_args(argv)
+ roles = parse_roles(args.roles)
+ app = Celery(broker=conf.get("celery", "broker_url"))
+
+ previous_at = time.monotonic()
+ previous = sample_roles(roles)
+ interval = 1.0 if args.once else args.interval
+ while True:
+ time.sleep(interval)
+ now_at = time.monotonic()
+ current = sample_roles(roles)
+ elapsed = now_at - previous_at
+ cpu_percent = {
+ role: max(0.0, (cpu - previous[role][0]) / elapsed * 100.0)
+ for role, (cpu, _) in current.items()
+ if role in previous
+ }
+ rss_bytes = {role: rss for role, (_, rss) in current.items()}
+ slots_occupied = count_occupied_slots(app)
+ if args.once:
+ sample = {
+ "cpu_percent": cpu_percent,
+ "rss_bytes": rss_bytes,
+ "slots_occupied": slots_occupied,
+ "slot_budget": args.slot_budget,
+ }
+ json.dump(sample, sys.stdout, indent=2)
+ print()
+ return
+
+ now_ns = time.time_ns()
+ gauges = [
+ build_gauge(
+ "perf.process.cpu_percent",
+ [build_data_point(value, now_ns, role) for role, value in
cpu_percent.items()],
+ ),
+ build_gauge(
+ "perf.process.rss_bytes",
+ [build_data_point(value, now_ns, role) for role, value in
rss_bytes.items()],
+ ),
+ build_gauge("perf.worker.slot_budget",
[build_data_point(args.slot_budget, now_ns)]),
+ ]
+ if slots_occupied is not None:
+ gauges.append(
+ build_gauge("perf.worker.slots_occupied",
[build_data_point(slots_occupied, now_ns)])
+ )
+ try:
+ push(build_payload([g for g in gauges if
g["gauge"]["dataPoints"]]))
+ except Exception:
+ log.exception("push to the OTel collector failed; retrying next
interval")
+ if not current:
+ log.info("every sampled process is gone; exiting")
+ return
+ previous, previous_at = current, now_at
+
+
+if __name__ == "__main__":
+ logging.basicConfig(level=logging.INFO)
+ main()
diff --git a/airflow-core/tests/integration/performance/test_perf.py
b/airflow-core/tests/integration/performance/test_perf.py
new file mode 100644
index 00000000000..d148fe38c6a
--- /dev/null
+++ b/airflow-core/tests/integration/performance/test_perf.py
@@ -0,0 +1,280 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Performance integration test for the scheduler.
+Creates a backlog of Dag runs, starts the Airflow processes and measures how
long they take to
+finish it, once per test case of the code under test. See README.md.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import subprocess
+import sys
+import time
+from typing import TYPE_CHECKING, Any
+
+import pytest
+
+from airflow.configuration import conf
+from airflow.utils.state import State
+
+from tests_common.test_utils.integration_setup import (
+ OTEL_COLLECTOR_HOST,
+ OTEL_COLLECTOR_PORT,
+ ProgressReporter,
+ compute_usable_cpu_count,
+ create_queued_dag_runs,
+ ensure_postgres_max_connections,
+ export_setting,
+ print_to_terminal,
+ serialize_and_get_dags,
+ start_process,
+ start_processes,
+ terminate_processes,
+ wait_for_dag_runs,
+ wait_for_otel_collector,
+)
+
+if TYPE_CHECKING:
+ from airflow.serialization.definitions.dag import SerializedDAG
+
+log = logging.getLogger("integration.perf.test_perf")
+
+TEST_DIR = os.path.dirname(os.path.abspath(__file__))
+DAG_FOLDER = os.path.join(TEST_DIR, "dags")
+POLL_USAGE_SCRIPT = os.path.join(TEST_DIR, "poll_usage.py")
+
+# "true" or "false" per test case, read by the code under test.
+NEW_CODE_ENV_VAR = "PERF_TEST__NEW_CODE"
+
+# Per Airflow process; Airflow's defaults times the API server workers exceed
Postgres's limit.
+DB_POOL_SIZE = 3
+DB_MAX_OVERFLOW = 5
+# Per Celery child, which runs one task at a time.
+RESULT_BACKEND_POOL_SIZE = 1
+RESULT_BACKEND_MAX_OVERFLOW = 1
+# psql, the test process and the usage poller.
+DB_CONNECTION_HEADROOM = 20
+
+CPUS = compute_usable_cpu_count()
+
+# The first three are process counts; the rest are Airflow settings, None
keeps Airflow's default.
+PROFILES: dict[str, dict[str, Any]] = {
+ # Sized so the scheduler is the only constraint: every other cap is far
above what the workers
+ # can execute.
+ "dynamic": {
+ # More slots per worker rather than more workers: each worker process
costs connections.
+ "worker_count": 3,
+ "worker_concurrency": max(2, CPUS * 2 // 3),
+ # One worker saturates well before the scheduler does.
+ "api_server_workers": max(4, CPUS // 3),
+ "parallelism": 4096,
+ "default_pool_task_slot_count": 4096,
+ "max_active_tasks_per_dag": 4096,
+ # Many runs of one Dag; the default of 16 would throttle them.
+ "max_active_runs_per_dag": 4096,
+ "max_tis_per_query": None,
+ },
+ # Fill in as needed; the process counts start at the tools' defaults.
+ "custom": {
+ "worker_count": 1,
+ "worker_concurrency": CPUS,
+ "api_server_workers": conf.getint("api", "workers"),
+ "parallelism": None,
+ "default_pool_task_slot_count": None,
+ "max_active_tasks_per_dag": None,
+ "max_active_runs_per_dag": None,
+ "max_tis_per_query": None,
+ },
+}
+
+
+def compute_required_db_connections(sizing: dict[str, Any]) -> int:
+ """Peak connections the deployment can open against the metadata DB."""
+ # Tasks use the Execution API and never connect.
+ scheduler = 1
+ airflow_processes = scheduler + sizing["api_server_workers"] +
sizing["worker_count"]
+ per_airflow_process = DB_POOL_SIZE + DB_MAX_OVERFLOW
+ # One result-backend pool per Celery child.
+ celery_children = sizing["worker_count"] * sizing["worker_concurrency"]
+ per_celery_child = RESULT_BACKEND_POOL_SIZE + RESULT_BACKEND_MAX_OVERFLOW
+ return (
+ airflow_processes * per_airflow_process + celery_children *
per_celery_child + DB_CONNECTION_HEADROOM
+ )
+
+
[email protected]("otel")
[email protected]("redis")
[email protected]("postgres")
+class TestPerformance:
+ """One environment per class, one deployment per test case."""
+
+ profile = os.environ.get("PERF_TEST__PROFILE", "dynamic") # key of
PROFILES; sizes the deployment
+ sizing: dict[str, Any]
+ dags: dict[str, SerializedDAG] = {}
+
+ @classmethod
+ def setup_class(cls):
+ if cls.profile not in PROFILES:
+ pytest.fail(f"profile {cls.profile!r} is not one of
{sorted(PROFILES)}")
+ cls.sizing = PROFILES[cls.profile]
+ log.info("profile %s: %s", cls.profile, cls.sizing)
+
+ wait_for_otel_collector(OTEL_COLLECTOR_HOST, OTEL_COLLECTOR_PORT)
+ # Exceeding the limit kills the scheduler mid-run.
+
ensure_postgres_max_connections(compute_required_db_connections(cls.sizing))
+
+ # The pytest plugin strips AIRFLOW__* variables; scheduler and API
server must share the secret.
+ os.environ["AIRFLOW__API_AUTH__JWT_SECRET"] =
"test-secret-key-for-testing"
+ os.environ["AIRFLOW__API_AUTH__JWT_ISSUER"] = "airflow"
+
+ os.environ["AIRFLOW__CORE__EXECUTOR"] = "CeleryExecutor"
+ os.environ["AIRFLOW__CORE__DAGS_FOLDER"] = DAG_FOLDER
+ os.environ["AIRFLOW__CORE__LOAD_EXAMPLES"] = "False"
+ os.environ["AIRFLOW__CORE__PLUGINS_FOLDER"] = "/dev/null"
+ os.environ["AIRFLOW__CORE__UNIT_TEST_MODE"] = "False"
+
+ os.environ["AIRFLOW__DATABASE__SQL_ALCHEMY_POOL_SIZE"] =
str(DB_POOL_SIZE)
+ os.environ["AIRFLOW__DATABASE__SQL_ALCHEMY_MAX_OVERFLOW"] =
str(DB_MAX_OVERFLOW)
+
os.environ["AIRFLOW__CELERY__RESULT_BACKEND_SQLALCHEMY_ENGINE_OPTIONS"] =
json.dumps(
+ {"pool_size": RESULT_BACKEND_POOL_SIZE, "max_overflow":
RESULT_BACKEND_MAX_OVERFLOW}
+ )
+ # The default spawns a ProcessPoolExecutor per publish batch, on the
scheduler's heartbeat.
+ os.environ["AIRFLOW__CELERY__SYNC_PARALLELISM"] = "1"
+ # The default of one second fails publishes behind a busy broker.
+ os.environ["AIRFLOW__CELERY__OPERATION_TIMEOUT"] = "300"
+
+ # Before db migrate, which creates the default pool with this slot
count.
+ export_setting("AIRFLOW__CORE__PARALLELISM", cls.sizing["parallelism"])
+ export_setting(
+ "AIRFLOW__CORE__DEFAULT_POOL_TASK_SLOT_COUNT",
cls.sizing["default_pool_task_slot_count"]
+ )
+ export_setting("AIRFLOW__CORE__MAX_ACTIVE_TASKS_PER_DAG",
cls.sizing["max_active_tasks_per_dag"])
+ export_setting("AIRFLOW__CORE__MAX_ACTIVE_RUNS_PER_DAG",
cls.sizing["max_active_runs_per_dag"])
+ export_setting("AIRFLOW__SCHEDULER__MAX_TIS_PER_QUERY",
cls.sizing["max_tis_per_query"])
+
+ os.environ["AIRFLOW__METRICS__OTEL_ON"] = "True"
+ os.environ["AIRFLOW__METRICS__OTEL_HOST"] = OTEL_COLLECTOR_HOST
+ os.environ["AIRFLOW__METRICS__OTEL_PORT"] = str(OTEL_COLLECTOR_PORT)
+ # breeze's OTEL_METRIC_EXPORT_INTERVAL=30000 overrides the Airflow
option; Prometheus still
+ # scrapes every 30s.
+ os.environ["AIRFLOW__METRICS__OTEL_INTERVAL_MILLISECONDS"] = "1000"
+ os.environ["OTEL_METRIC_EXPORT_INTERVAL"] = "1000"
+ # The dashboard reads the tagged names; legacy names add one series
family per task.
+ os.environ["AIRFLOW__METRICS__LEGACY_NAMES_ON"] = "False"
+ os.environ["AIRFLOW__TRACES__OTEL_ON"] = "True"
+ os.environ["OTEL_EXPORTER_OTLP_PROTOCOL"] = "http/protobuf"
+ os.environ["OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"] = (
+ f"http://{OTEL_COLLECTOR_HOST}:{OTEL_COLLECTOR_PORT}/v1/traces"
+ )
+
+ # Once per class: the scheduler ignores finished runs, and run ids
carry the test case.
+ subprocess.run(["airflow", "db", "reset", "--yes"], check=True,
env=os.environ.copy())
+ subprocess.run(["airflow", "db", "migrate"], check=True,
env=os.environ.copy())
+
+ # Every Dag in the folder; the test picks by id.
+ cls.dags = serialize_and_get_dags(dag_folder=DAG_FOLDER)
+ assert cls.dags, f"no Dags found in {DAG_FOLDER}"
+
+ def start_usage_poller(self, processes: dict[str, subprocess.Popen]) ->
subprocess.Popen:
+ """Start poll_usage.py, which pushes CPU, memory and worker slot
gauges for ``processes``."""
+ slot_budget = self.sizing["worker_count"] *
self.sizing["worker_concurrency"]
+ command = [sys.executable, POLL_USAGE_SCRIPT, "--slot-budget",
str(slot_budget)]
+ for role, process in processes.items():
+ command.append(f"{role}={process.pid}")
+ # Own process group, or terminate_processes would kill pytest with it.
+ return start_process(command)
+
+ def execute_dag_runs(
+ self,
+ *,
+ run_id_prefix: str,
+ dag_ids: list[str],
+ dag_run_count: int,
+ run_conf: dict[str, Any],
+ timeout_seconds: int,
+ ) -> None:
+ """Create the Dag runs, start the processes, wait for the runs to
finish, stop the processes."""
+ dags = {dag_id: self.dags[dag_id] for dag_id in dag_ids}
+ # Created before any process exists, so every test case starts from
the same rows, all
+ # eligible at once, and CLI triggering cannot cap the live runs at its
own rate. This is the
+ # scheduler under full load, not a production trickle.
+ runs = create_queued_dag_runs(
+ dags, run_id_prefix=run_id_prefix, dag_run_count=dag_run_count,
run_conf=run_conf
+ )
+ processes, started_at = start_processes(
+ worker_count=self.sizing["worker_count"],
+ worker_concurrency=self.sizing["worker_concurrency"],
+ api_server_workers=self.sizing["api_server_workers"],
+ )
+ try:
+ processes["usage_poller"] = self.start_usage_poller(processes)
+ # A guard only: unfinished runs fail below.
+ with ProgressReporter(runs):
+ states = wait_for_dag_runs(runs, max_wait_time=timeout_seconds)
+ elapsed_seconds = time.monotonic() - started_at
+
+ exited = {}
+ for role, process in processes.items():
+ if process.poll() is not None:
+ exited[role] = process.returncode
+ assert not exited, f"processes exited, with these codes: {exited}"
+
+ not_succeeded = {run: state for run, state in states.items() if
state != State.SUCCESS}
+ assert not not_succeeded, (
+ f"{len(not_succeeded)} of {len(runs)} Dag runs are not
successful after {timeout_seconds}s: "
+ f"{not_succeeded}"
+ )
+ finally:
+ terminate_processes(processes)
+ # After the processes are stopped, so their shutdown logging does not
bury it.
+ print_to_terminal(f"\n{run_id_prefix}: {len(runs)} Dag runs finished
in {elapsed_seconds:.0f}s\n")
+
+ @pytest.mark.parametrize(
+ "new_code",
+ [
+ pytest.param(False, id="original_code"),
+ pytest.param(True, id="new_code"),
+ ],
+ )
+ def test_scheduler_load(self, new_code: bool):
+ """Run many Dag runs of the fan-out Dag at once, with the original
code and then the new code."""
+ test_case = "new_code" if new_code else "original_code"
+ # Inherited by every process started below.
+ os.environ[NEW_CODE_ENV_VAR] = str(new_code).lower()
+
+ # The load; each variable overrides its default for one run.
+ dag_run_count = int(os.environ.get("PERF_TEST__DAG_RUN_COUNT", "5"))
# queued runs created up front
+ mapped_task_count = int(os.environ.get("PERF_TEST__MAPPED_TASK_COUNT",
"20")) # instances per stage
+ # Give up on the test case after this.
+ timeout_seconds = int(os.environ.get("PERF_TEST__TIMEOUT_SECONDS",
"3600"))
+ print_to_terminal(
+ f"\n\n{test_case}: {dag_run_count} runs of perf_dag,
{mapped_task_count} mapped instances per stage, "
+ f"timeout {timeout_seconds}s, profile {self.profile}\n"
+ )
+
+ self.execute_dag_runs(
+ # Run ids carry the test case name.
+ run_id_prefix=test_case,
+ dag_ids=["perf_dag"],
+ dag_run_count=dag_run_count,
+ run_conf={"mapped_task_count": mapped_task_count},
+ timeout_seconds=timeout_seconds,
+ )
diff --git a/contributing-docs/testing/integration_tests.rst
b/contributing-docs/testing/integration_tests.rst
index 93217348f3b..a2e615ccaf3 100644
--- a/contributing-docs/testing/integration_tests.rst
+++ b/contributing-docs/testing/integration_tests.rst
@@ -320,6 +320,17 @@ Kerberos is active for ``trino`` integration tests, the
following code has been
+Performance Harness
+-------------------
+
+``airflow-core/tests/integration/performance`` holds a load harness for the
scheduler and the executor
+path. It starts the Airflow components as subprocesses against the ``otel``
and ``redis``
+integrations on Postgres, runs a backlog of fan-out Dag runs to completion and
shows the numbers on the
+"Scheduler performance" Grafana dashboard. It never runs in the CI: the folder
is collected only when
+its path is named on the pytest command line. See its
+`README <../../airflow-core/tests/integration/performance/README.md>`__ for
how to run it and how to
+compare a change with the original code.
+
-----
For other kinds of tests look at `Testing document <../09_testing.rst>`__
diff --git a/devel-common/src/tests_common/test_utils/integration_setup.py
b/devel-common/src/tests_common/test_utils/integration_setup.py
index 511c87223ce..eba3be760cc 100644
--- a/devel-common/src/tests_common/test_utils/integration_setup.py
+++ b/devel-common/src/tests_common/test_utils/integration_setup.py
@@ -16,28 +16,47 @@
# under the License.
from __future__ import annotations
+import contextlib
+import datetime
import json
import logging
import os
+import signal
+import socket
import subprocess
+import threading
import time
+import urllib.error
+import urllib.request
+from collections.abc import Sequence
+from typing import Any
-from sqlalchemy import func, select
+from sqlalchemy import func, select, tuple_, update
-from airflow.dag_processing.bundles.manager import DagBundlesManager
+from airflow.dag_processing.bundles.manager import DagBundlesManager,
_load_bundle_config_snapshot
from airflow.dag_processing.dagbag import DagBag
-from airflow.models import DagRun
+from airflow.models import DagModel, DagRun, TaskInstance
from airflow.models.serialized_dag import SerializedDagModel
from airflow.sdk import timezone
from airflow.serialization.definitions.dag import SerializedDAG
from airflow.utils.session import create_session
-from airflow.utils.state import State
+from airflow.utils.state import DagRunState, State
+from airflow.utils.types import DagRunTriggeredByType, DagRunType
from tests_common.test_utils.dag import create_scheduler_dag
from tests_common.test_utils.version_compat import AIRFLOW_V_3_0_PLUS,
AIRFLOW_V_3_1_PLUS
log = logging.getLogger(__name__)
+# Breeze service names and ports.
+# The otel-collector is assigned a fixed container_name in the compose file,
+# so the name is the same in every worktree.
+OTEL_COLLECTOR_HOST = "breeze-otel-collector"
+OTEL_COLLECTOR_PORT = 4318
+API_SERVER_PORT = 8080
+
+FINISHED_TI_STATES = frozenset(state.value for state in State.finished)
+
def unpause_trigger_dag_and_get_run_id(dag_id: str, conf: dict | None = None)
-> str:
unpause_command = ["airflow", "dags", "unpause", dag_id]
@@ -68,6 +87,44 @@ def unpause_trigger_dag_and_get_run_id(dag_id: str, conf:
dict | None = None) ->
return run_id
+def wait_for_otel_collector(host: str, port: int, timeout: int = 120) -> None:
+ """
+ Wait for the OTel collector to be reachable before running tests.
+
+ This prevents flaky test failures caused by transient DNS resolution issues
+ (e.g., 'Temporary failure in name resolution' for breeze-otel-collector).
+
+ Note: If the collector is not reachable after timeout, logs a warning but
+ does not fail - allows tests to run and fail naturally if needed.
+ """
+ deadline = time.monotonic() + timeout
+ last_error = None
+ while time.monotonic() < deadline:
+ try:
+ # Test DNS resolution and TCP connectivity
+ with socket.create_connection((host, port), timeout=5):
+ pass
+ log.info("OTel collector at %s:%d is reachable.", host, port)
+ return
+ except (socket.gaierror, TimeoutError, OSError) as e:
+ last_error = e
+ log.debug(
+ "OTel collector at %s:%d not reachable: %s. Retrying...",
+ host,
+ port,
+ e,
+ )
+ time.sleep(2)
+ log.warning(
+ "OTel collector at %s:%d is not reachable after %ds. Last error: %s. "
+ "Tests will proceed but may fail if collector is required.",
+ host,
+ port,
+ timeout,
+ last_error,
+ )
+
+
def start_scheduler(capture_output: bool = False):
stdout = None if capture_output else subprocess.DEVNULL
stderr = None if capture_output else subprocess.DEVNULL
@@ -155,43 +212,374 @@ def serialize_and_get_dags(dag_folder) -> dict[str,
SerializedDAG]:
]
os.environ["AIRFLOW__DAG_PROCESSOR__DAG_BUNDLE_CONFIG_LIST"] =
json.dumps(TESTING_BUNDLE_CONFIG)
- # Initial add
+ # The manager caches the bundle config per process, and the pytest plugin
already loaded it with
+ # the default list; without this the sync below deactivates the "testing"
bundle just added, and
+ # the scheduler marks its Dags stale a minute later.
+ _load_bundle_config_snapshot.cache_clear()
manager = DagBundlesManager()
manager.sync_bundles_to_db()
return dag_dict
-def wait_for_dag_run(dag_id: str, run_id: str, max_wait_time: int):
- # max_wait_time, is the timeout for the DAG run to complete. The value is
in seconds.
- start_time = timezone.utcnow().timestamp()
-
- while timezone.utcnow().timestamp() - start_time < max_wait_time:
+def wait_for_dag_runs(runs: list[tuple[str, str]], max_wait_time: int) ->
dict[tuple[str, str], str | None]:
+ """Wait until every ``(dag_id, run_id)`` in ``runs`` finishes or
``max_wait_time`` elapses; return the states."""
+ # One budget for all runs, not one per run.
+ deadline = time.monotonic() + max_wait_time
+ states: dict[tuple[str, str], str | None] = dict.fromkeys(runs)
+ while True:
with create_session() as session:
- dag_run = session.scalar(
- select(DagRun).where(
- DagRun.dag_id == dag_id,
- DagRun.run_id == run_id,
+ rows = session.execute(
+ select(DagRun.dag_id, DagRun.run_id, DagRun.state).where(
+ tuple_(DagRun.dag_id, DagRun.run_id).in_(runs)
)
- )
+ ).all()
+ for dag_id, run_id, state in rows:
+ states[(dag_id, run_id)] = state
+ if all(state in (State.SUCCESS, State.FAILED) for state in
states.values()):
+ break
+ if time.monotonic() >= deadline:
+ break
+ # Otherwise the loop spins and loads the database under test.
+ time.sleep(2)
+ return states
+
+
+def is_process_group_alive(pgid: int) -> bool:
+ """Whether any process of the group ``pgid`` still exists."""
+ try:
+ os.killpg(pgid, 0)
+ except ProcessLookupError:
+ return False
+ return True
+
+
+def terminate_process(proc: subprocess.Popen, timeout: int = 30, *,
process_group: bool = False) -> None:
+ """Stop ``proc``, with SIGKILL as the fallback if it is still alive after
``timeout``."""
+
+ def send(sig: signal.Signals) -> None:
+ # Children (uvicorn workers, prefork pool) would be orphaned if only
the parent was signalled.
+ if process_group:
+ # proc is the group leader (start_new_session), so the group id
equals proc.pid. Signalling
+ # the group reaches the children even when proc has already exited
and been reaped.
+ with contextlib.suppress(ProcessLookupError):
+ os.killpg(proc.pid, sig)
+ else:
+ proc.send_signal(sig)
+
+ deadline = time.monotonic() + timeout
+ send(signal.SIGTERM)
+ try:
+ proc.wait(timeout=timeout)
+ except subprocess.TimeoutExpired:
+ send(signal.SIGKILL)
+ proc.wait()
+ if not process_group:
+ return
+ # wait() only checks the leader. If a child is still alive, it will occupy
the port and the broker queue.
+ while is_process_group_alive(proc.pid) and time.monotonic() < deadline:
+ time.sleep(0.5)
+ if is_process_group_alive(proc.pid):
+ send(signal.SIGKILL)
+ while is_process_group_alive(proc.pid):
+ time.sleep(0.5)
+
+
+def print_to_terminal(text: str) -> None:
+ """Write ``text`` as plain text to the controlling terminal, or to stdout
when there is none."""
+ # Plain text past pytest's capture, distinct from the processes' logging.
+ try:
+ with open("/dev/tty", "w") as tty:
+ tty.write(text + "\n")
+ except OSError:
+ # No terminal: stdout, shown live by pytest -s.
+ print(text, flush=True)
+
+
+def compute_usable_cpu_count() -> int:
+ """CPUs this process may actually run on."""
+ # Honours a cpuset, which os.cpu_count() does not. Linux only.
+ if hasattr(os, "sched_getaffinity"):
+ return len(os.sched_getaffinity(0))
+ # The whole host.
+ return os.cpu_count() or 8
+
+
+def export_setting(env_var: str, value: int | None) -> None:
+ """Export an Airflow setting for the subprocesses; ``None`` keeps
Airflow's default."""
+ if value is not None:
+ os.environ[env_var] = str(value)
+
+
+def run_psql(sql: str) -> str:
+ """Run ``sql`` against the breeze Postgres as its superuser and return the
output."""
+ result = subprocess.run(
+ ["psql", "-h", "postgres", "-U", "postgres", "-d", "postgres", "-tAc",
sql],
+ env={**os.environ, "PGPASSWORD": "airflow"},
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ return result.stdout.strip()
+
- if dag_run is None:
- time.sleep(5)
- continue
+def run_docker_command(*args: str) -> str:
+ """Run a ``docker`` command and return its output; breeze mounts the CLI
and the socket."""
+ result = subprocess.run(["docker", *args], capture_output=True, text=True,
check=True)
+ return result.stdout.strip()
- dag_run_state = dag_run.state
- log.debug("DAG Run state: %s.", dag_run_state)
- if dag_run_state in [State.SUCCESS, State.FAILED]:
- break
- return dag_run_state
+def find_postgres_container() -> str | None:
+ """Return the name of the Postgres container in this breeze container's
Compose project, or None when unknown."""
+ # Postgres has no fixed container_name, so it is <project>-postgres-1 and
the project differs per
+ # worktree. This container's labels carry the project, and its id is the
hostname.
+ try:
+ project = run_docker_command(
+ "inspect",
+ "--format",
+ '{{ index .Config.Labels "com.docker.compose.project" }}',
+ socket.gethostname(),
+ )
+ names = run_docker_command(
+ "ps",
+ "--filter",
+ f"label=com.docker.compose.project={project}",
+ "--filter",
+ "label=com.docker.compose.service=postgres",
+ "--format",
+ "{{.Names}}",
+ )
+ except (FileNotFoundError, subprocess.CalledProcessError):
+ # No Docker CLI or socket: another environment.
+ return None
+ return names.splitlines()[0] if project and names else None
+
+
+def restart_postgres_container(postgres_container: str) -> bool:
+ """Restart ``container``; False when that is not possible from here."""
+ try:
+ run_docker_command("restart", postgres_container)
+ except (FileNotFoundError, subprocess.CalledProcessError):
+ return False
+ return True
-def terminate_process(proc: subprocess.Popen, timeout: int = 30) -> None:
- # SIGKILL is the fallback if the process is still alive after timeout.
- proc.terminate()
+def ensure_postgres_max_connections(required: int) -> None:
+ """Raise the metadata DB's ``max_connections`` to ``required`` if it is
lower, restarting it once."""
try:
- proc.wait(timeout=timeout)
- except subprocess.TimeoutExpired:
- proc.kill()
- proc.wait()
+ current = int(run_psql("show max_connections"))
+ except FileNotFoundError:
+ raise RuntimeError("psql not found: this helper runs inside the breeze
environment")
+ if current >= required:
+ return
+
+ # Persisted in the data volume; takes effect at server start, hence the
restart.
+ run_psql(f"ALTER SYSTEM SET max_connections = {required}")
+ postgres_container = find_postgres_container()
+ log.info(
+ "Raised postgres max_connections from %s to %s; restarting %s",
current, required, postgres_container
+ )
+ if postgres_container is not None and
restart_postgres_container(postgres_container):
+ deadline = time.monotonic() + 60
+ while time.monotonic() < deadline:
+ with contextlib.suppress(subprocess.CalledProcessError):
+ if int(run_psql("show max_connections")) >= required:
+ return
+ time.sleep(2)
+ raise RuntimeError(
+ f"postgres max_connections={current} is below the {required} needed.
The new value is "
+ "persisted and applies after a restart, which could not be done from
here: run "
+ f"`docker restart {postgres_container or '<breeze
project>-postgres-1'}` on the host, then re-run the test."
+ )
+
+
+def start_process(command: list[str]) -> subprocess.Popen:
+ """Start ``command`` with the current environment, as the leader of its
own process group."""
+ # Children (uvicorn workers, prefork pool) are signalled with the parent.
+ return subprocess.Popen(command, env=os.environ.copy(),
start_new_session=True)
+
+
+def wait_for_api_server(process: subprocess.Popen, port: int =
API_SERVER_PORT, timeout: int = 120) -> None:
+ """Block until the API server answers its execution health route, or
``timeout`` passes."""
+ # uvicorn accepts connections before its workers can answer; a task
starting in that gap times
+ # out and fails.
+ health_url = f"http://localhost:{port}/execution/health"
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if process.poll() is not None:
+ raise RuntimeError(f"api_server exited early with code
{process.returncode}")
+ with contextlib.suppress(urllib.error.URLError, TimeoutError,
ConnectionError):
+ with urllib.request.urlopen(health_url, timeout=5) as response:
+ if response.status == 200:
+ return
+ time.sleep(1)
+ raise RuntimeError(f"api_server did not answer {health_url} within
{timeout}s")
+
+
+def build_api_server_command(*, port: int, workers: int) -> list[str]:
+ """The ``airflow api-server`` command line for ``start_process``."""
+ # --daemon would detach the real server from Popen and let it outlive the
test.
+ return ["airflow", "api-server", "--port", str(port), "--workers",
str(workers)]
+
+
+def build_celery_worker_command(*, hostname: str, concurrency: int) ->
list[str]:
+ """The ``celery worker`` command line for ``start_process``."""
+ return [
+ "celery",
+ "--app",
+ "airflow.providers.celery.executors.celery_executor.app",
+ "worker",
+ "--pool",
+ "prefork",
+ "--loglevel",
+ "INFO",
+ "--concurrency",
+ str(concurrency),
+ "--hostname",
+ hostname,
+ ]
+
+
+def start_processes(
+ *,
+ worker_count: int,
+ worker_concurrency: int,
+ api_server_workers: int,
+ port: int = API_SERVER_PORT,
+ triggerer: bool = False,
+) -> tuple[dict[str, subprocess.Popen], float]:
+ """Start the processes of a Celery executor setup, keyed by role, plus the
scheduler's start time."""
+ processes: dict[str, subprocess.Popen] = {}
+ try:
+ # First: every task's first act is to call it.
+ processes["api_server"] = start_process(
+ build_api_server_command(port=port, workers=api_server_workers)
+ )
+ wait_for_api_server(processes["api_server"], port=port)
+ for index in range(1, worker_count + 1):
+ command = build_celery_worker_command(hostname=f"worker{index}",
concurrency=worker_concurrency)
+ processes[f"worker_{index}"] = start_process(command)
+ # Only for Dags that defer.
+ if triggerer:
+ processes["triggerer"] = start_process(["airflow", "triggerer"])
+ # There isn't any actual execution before the scheduler start,
+ # so timing starts here and includes the settle sleep below.
+ scheduler_started_at = time.monotonic()
+ processes["scheduler"] = start_process(["airflow", "scheduler"])
+
+ # Enough for a misconfigured process to have exited.
+ time.sleep(5)
+ for role, process in processes.items():
+ if process.poll() is not None:
+ raise RuntimeError(f"{role} exited early with code
{process.returncode}")
+ except Exception:
+ terminate_processes(processes)
+ raise
+ return processes, scheduler_started_at
+
+
+def terminate_processes(processes: dict[str, subprocess.Popen]) -> None:
+ """Stop every process group started by :func:`start_process`, SIGKILL as
the fallback."""
+ for role, process in processes.items():
+ terminate_process(process, process_group=True)
+ if process.poll() is None:
+ raise RuntimeError(f"{role} is still running after termination")
+
+
+def create_queued_dag_runs(
+ dags: dict[str, SerializedDAG], *, run_id_prefix: str, dag_run_count: int,
run_conf: dict[str, Any]
+) -> list[tuple[str, str]]:
+ """Unpause every Dag in ``dags`` and create ``dag_run_count`` queued
manual runs of it through the ORM."""
+ base = timezone.utcnow()
+ runs: list[tuple[str, str]] = []
+ with create_session() as session:
+ for dag_id, dag in sorted(dags.items()):
+ session.execute(update(DagModel).where(DagModel.dag_id ==
dag_id).values(is_paused=False))
+ for run_index in range(1, dag_run_count + 1):
+ run_id = f"{run_id_prefix}__{run_index}"
+ dag.create_dagrun(
+ run_id=run_id,
+ # (dag_id, logical_date) is unique.
+ logical_date=base + datetime.timedelta(seconds=run_index),
+ data_interval=None,
+ # Same for all, so every run is eligible at once.
+ run_after=base,
+ conf=run_conf,
+ run_type=DagRunType.MANUAL,
+ triggered_by=DagRunTriggeredByType.CLI,
+ state=DagRunState.QUEUED,
+ session=session,
+ )
+ runs.append((dag_id, run_id))
+ log.info("Created %d queued Dag runs across %d Dags with conf %s",
len(runs), len(dags), run_conf)
+ return runs
+
+
+def format_state_counts(counts: Sequence[Any]) -> str:
+ if not counts:
+ return "-"
+ parts = [f"{state or 'none'}={count}" for state, count in counts]
+ return " ".join(sorted(parts))
+
+
+class ProgressReporter:
+ """
+ Show a periodic state summary of ``runs`` while the test is active.
+
+ Apart from providing an update of the test state, it also helps identify
+ a frozen run that isn't making any progress.
+ """
+
+ def __init__(self, runs: list[tuple[str, str]], interval: int = 15):
+ self._dag_ids = sorted({dag_id for dag_id, _ in runs})
+ self._run_ids = sorted({run_id for _, run_id in runs})
+ self._interval = interval
+ self._stop = threading.Event()
+ self._thread = threading.Thread(target=self._poll, daemon=True)
+ self._start_time = 0.0
+ self._last_finished = 0
+
+ def __enter__(self) -> ProgressReporter:
+ self._start_time = time.monotonic()
+ self._thread.start()
+ return self
+
+ def __exit__(self, *exc_info) -> None:
+ self._stop.set()
+ self._thread.join(timeout=self._interval + 5)
+ self._report()
+
+ def _poll(self) -> None:
+ while not self._stop.wait(self._interval):
+ self._report()
+
+ def _report(self) -> None:
+ # A failed query must not end the reporting; the next interval tries
again.
+ try:
+ self._query_and_print()
+ except Exception as error:
+ print_to_terminal(f"[progress] report failed: {error!r}")
+
+ def _query_and_print(self) -> None:
+ with create_session() as session:
+ ti_counts = session.execute(
+ select(TaskInstance.state, func.count())
+ .where(TaskInstance.dag_id.in_(self._dag_ids),
TaskInstance.run_id.in_(self._run_ids))
+ .group_by(TaskInstance.state)
+ ).all()
+ dr_counts = session.execute(
+ select(DagRun.state, func.count())
+ .where(DagRun.dag_id.in_(self._dag_ids),
DagRun.run_id.in_(self._run_ids))
+ .group_by(DagRun.state)
+ ).all()
+
+ finished = sum(count for state, count in ti_counts if state in
FINISHED_TI_STATES)
+ rate = (finished - self._last_finished) / self._interval
+ self._last_finished = finished
+
+ print_to_terminal(
+ f"[progress {time.monotonic() - self._start_time:5.0f}s] "
+ f"dag_runs: {format_state_counts(dr_counts)} | "
+ f"tis: {format_state_counts(ti_counts)} | "
+ f"finished {finished} ({rate:.1f}/s)"
+ )
diff --git
a/providers/apache/kafka/tests/integration/apache/kafka/plugins/test_event_producer.py
b/providers/apache/kafka/tests/integration/apache/kafka/plugins/test_event_producer.py
index 81cbc4ca931..057727706d1 100644
---
a/providers/apache/kafka/tests/integration/apache/kafka/plugins/test_event_producer.py
+++
b/providers/apache/kafka/tests/integration/apache/kafka/plugins/test_event_producer.py
@@ -35,7 +35,7 @@ from tests_common.test_utils.integration_setup import (
start_scheduler,
terminate_process,
unpause_trigger_dag_and_get_run_id,
- wait_for_dag_run,
+ wait_for_dag_runs,
)
log = logging.getLogger(__name__)
@@ -136,7 +136,7 @@ class TestEventProducer:
dag_id = "demo_dag"
run_id = unpause_trigger_dag_and_get_run_id(dag_id=dag_id)
- state = wait_for_dag_run(dag_id=dag_id, run_id=run_id,
max_wait_time=90)
+ state = wait_for_dag_runs([(dag_id, run_id)],
max_wait_time=90)[(dag_id, run_id)]
assert state == State.SUCCESS, f"Dag run did not complete
successfully. Final state: {state}."
expected_events = [
diff --git
a/scripts/ci/docker-compose/grafana/volume/dashboards/scheduler_perf.json
b/scripts/ci/docker-compose/grafana/volume/dashboards/scheduler_perf.json
new file mode 100644
index 00000000000..a32176df712
--- /dev/null
+++ b/scripts/ci/docker-compose/grafana/volume/dashboards/scheduler_perf.json
@@ -0,0 +1,480 @@
+{
+ "uid": "airflow-scheduler-perf",
+ "title": "Scheduler performance",
+ "id": null,
+ "tags": [
+ "perf"
+ ],
+ "timezone": "browser",
+ "editable": true,
+ "refresh": "10s",
+ "time": {
+ "from": "now-30m",
+ "to": "now"
+ },
+ "schemaVersion": 30,
+ "panels": [
+ {
+ "id": 1,
+ "type": "timeseries",
+ "title": "Utilization",
+ "description": "Scheduler: percentage of time spent actively scheduling
instead of sleeping between loops. Workers: Celery's own count of held slots
over the budget the harness configured.",
+ "datasource": "Prometheus",
+ "gridPos": {
+ "x": 0,
+ "y": 0,
+ "w": 12,
+ "h": 8
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "clamp_max(100 *
histogram_sum(rate(airflow_scheduler_scheduler_loop_duration_milliseconds[2m]))
/ 1000, 100)",
+ "legendFormat": "scheduler % of active time"
+ },
+ {
+ "refId": "B",
+ "expr": "clamp_max(100 * perf_worker_slots_occupied /
perf_worker_slot_budget, 100)",
+ "legendFormat": "worker % of slots occupied"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "custom": {
+ "drawStyle": "line",
+ "lineWidth": 2,
+ "fillOpacity": 15,
+ "spanNulls": true
+ },
+ "unit": "percent",
+ "min": 0,
+ "max": 100
+ },
+ "overrides": []
+ },
+ "options": {
+ "legend": {
+ "displayMode": "list",
+ "placement": "bottom"
+ },
+ "tooltip": {
+ "mode": "multi"
+ }
+ }
+ },
+ {
+ "id": 2,
+ "type": "timeseries",
+ "title": "CPU usage per process",
+ "description": "Per process tree the harness started; 100 is one busy
core. Worker trees are summed.",
+ "datasource": "Prometheus",
+ "gridPos": {
+ "x": 12,
+ "y": 0,
+ "w": 12,
+ "h": 8
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "perf_process_cpu_percent{role!~\"worker_.*\"}",
+ "legendFormat": "{{role}}"
+ },
+ {
+ "refId": "B",
+ "expr": "sum(perf_process_cpu_percent{role=~\"worker_.*\"})",
+ "legendFormat": "workers"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "custom": {
+ "drawStyle": "line",
+ "lineWidth": 2,
+ "fillOpacity": 10,
+ "spanNulls": true
+ },
+ "unit": "percent",
+ "min": 0
+ },
+ "overrides": []
+ },
+ "options": {
+ "legend": {
+ "displayMode": "list",
+ "placement": "bottom"
+ },
+ "tooltip": {
+ "mode": "multi"
+ }
+ }
+ },
+ {
+ "id": 3,
+ "type": "timeseries",
+ "title": "Worker slots",
+ "description": "Slots held according to Celery, which includes the fork
and supervisor overhead that the database's running state never sees.",
+ "datasource": "Prometheus",
+ "gridPos": {
+ "x": 0,
+ "y": 8,
+ "w": 12,
+ "h": 8
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "perf_worker_slots_occupied",
+ "legendFormat": "occupied"
+ },
+ {
+ "refId": "B",
+ "expr": "perf_worker_slot_budget",
+ "legendFormat": "total"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "custom": {
+ "drawStyle": "line",
+ "lineWidth": 2,
+ "fillOpacity": 10,
+ "spanNulls": true
+ },
+ "unit": "short",
+ "min": 0
+ },
+ "overrides": [
+ {
+ "matcher": {
+ "id": "byName",
+ "options": "total"
+ },
+ "properties": [
+ {
+ "id": "custom.lineStyle",
+ "value": {
+ "fill": "dash",
+ "dash": [
+ 10,
+ 10
+ ]
+ }
+ },
+ {
+ "id": "custom.fillOpacity",
+ "value": 0
+ }
+ ]
+ }
+ ]
+ },
+ "options": {
+ "legend": {
+ "displayMode": "list",
+ "placement": "bottom"
+ },
+ "tooltip": {
+ "mode": "multi"
+ }
+ }
+ },
+ {
+ "id": 4,
+ "type": "timeseries",
+ "title": "Memory usage per process",
+ "description": "Summed over each process tree, so pages shared with
forked children count more than once.",
+ "datasource": "Prometheus",
+ "gridPos": {
+ "x": 12,
+ "y": 8,
+ "w": 12,
+ "h": 8
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "perf_process_rss_bytes{role!~\"worker_.*\"}",
+ "legendFormat": "{{role}}"
+ },
+ {
+ "refId": "B",
+ "expr": "sum(perf_process_rss_bytes{role=~\"worker_.*\"})",
+ "legendFormat": "workers"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "custom": {
+ "drawStyle": "line",
+ "lineWidth": 2,
+ "fillOpacity": 10,
+ "spanNulls": true
+ },
+ "unit": "bytes",
+ "min": 0
+ },
+ "overrides": []
+ },
+ "options": {
+ "legend": {
+ "displayMode": "list",
+ "placement": "bottom"
+ },
+ "tooltip": {
+ "mode": "multi"
+ }
+ }
+ },
+ {
+ "id": 5,
+ "type": "timeseries",
+ "title": "Hand-off rate (TIs/sec)",
+ "description": "Task instances per second crossing each state boundary.
The first curve is the scheduler handing work to the executor, the second the
workers starting it. Prometheus scrapes every 30 seconds, so a stage that fills
and empties within one scrape leaves no rate behind; the cumulative panel below
counts those too.",
+ "datasource": "Prometheus",
+ "gridPos": {
+ "x": 0,
+ "y": 16,
+ "w": 12,
+ "h": 8
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr":
"sum(histogram_count(rate(airflow_task_scheduled_duration_milliseconds[2m])))",
+ "legendFormat": "scheduled to queued (scheduler)"
+ },
+ {
+ "refId": "B",
+ "expr":
"sum(histogram_count(rate(airflow_task_queued_duration_milliseconds[2m])))",
+ "legendFormat": "queued to running (worker)"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "custom": {
+ "drawStyle": "line",
+ "lineWidth": 2,
+ "fillOpacity": 10,
+ "spanNulls": true
+ },
+ "unit": "short",
+ "min": 0
+ },
+ "overrides": []
+ },
+ "options": {
+ "legend": {
+ "displayMode": "list",
+ "placement": "bottom"
+ },
+ "tooltip": {
+ "mode": "multi"
+ }
+ }
+ },
+ {
+ "id": 6,
+ "type": "timeseries",
+ "title": "Task timeline, mean seconds per phase",
+ "description": "Where a task instance spends its life. A scheduler
change should move the first curve. The first two are means over the last five
minutes. Each task process reports its own running time once and exits, so that
curve is the mean over the task processes the collector still exposes, roughly
the last five minutes as well.",
+ "datasource": "Prometheus",
+ "gridPos": {
+ "x": 12,
+ "y": 16,
+ "w": 12,
+ "h": 8
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr":
"sum(histogram_sum(rate(airflow_task_scheduled_duration_milliseconds[5m]))) /
sum(histogram_count(rate(airflow_task_scheduled_duration_milliseconds[5m]))) /
1000",
+ "legendFormat": "scheduled: waiting on the scheduler"
+ },
+ {
+ "refId": "B",
+ "expr":
"sum(histogram_sum(rate(airflow_task_queued_duration_milliseconds[5m]))) /
sum(histogram_count(rate(airflow_task_queued_duration_milliseconds[5m]))) /
1000",
+ "legendFormat": "queued: waiting for a worker slot"
+ },
+ {
+ "refId": "C",
+ "expr": "sum(histogram_sum(airflow_task_duration_milliseconds)) /
sum(histogram_count(airflow_task_duration_milliseconds)) / 1000",
+ "legendFormat": "running"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "custom": {
+ "drawStyle": "line",
+ "lineWidth": 2,
+ "fillOpacity": 10,
+ "spanNulls": true
+ },
+ "unit": "s",
+ "min": 0
+ },
+ "overrides": []
+ },
+ "options": {
+ "legend": {
+ "displayMode": "list",
+ "placement": "bottom"
+ },
+ "tooltip": {
+ "mode": "multi"
+ }
+ }
+ },
+ {
+ "id": 7,
+ "type": "timeseries",
+ "title": "Scheduler loop duration",
+ "description": "",
+ "datasource": "Prometheus",
+ "gridPos": {
+ "x": 0,
+ "y": 24,
+ "w": 12,
+ "h": 8
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr":
"histogram_sum(rate(airflow_scheduler_scheduler_loop_duration_milliseconds[2m]))
/
histogram_count(rate(airflow_scheduler_scheduler_loop_duration_milliseconds[2m]))",
+ "legendFormat": "mean"
+ },
+ {
+ "refId": "B",
+ "expr": "histogram_quantile(0.95,
rate(airflow_scheduler_scheduler_loop_duration_milliseconds[2m]))",
+ "legendFormat": "p95"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "custom": {
+ "drawStyle": "line",
+ "lineWidth": 2,
+ "fillOpacity": 10,
+ "spanNulls": true
+ },
+ "unit": "ms",
+ "min": 0
+ },
+ "overrides": []
+ },
+ "options": {
+ "legend": {
+ "displayMode": "list",
+ "placement": "bottom"
+ },
+ "tooltip": {
+ "mode": "multi"
+ }
+ }
+ },
+ {
+ "id": 8,
+ "type": "timeseries",
+ "title": "Task Instance Backlog",
+ "description": "",
+ "datasource": "Prometheus",
+ "gridPos": {
+ "x": 12,
+ "y": 24,
+ "w": 12,
+ "h": 8
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "airflow_pool_scheduled_slots{pool_name=\"default_pool\"}",
+ "legendFormat": "in state SCHEDULED"
+ },
+ {
+ "refId": "B",
+ "expr": "airflow_pool_queued_slots{pool_name=\"default_pool\"}",
+ "legendFormat": "in state QUEUED"
+ },
+ {
+ "refId": "C",
+ "expr": "airflow_pool_running_slots{pool_name=\"default_pool\"}",
+ "legendFormat": "in state RUNNING"
+ },
+ {
+ "refId": "D",
+ "expr": "airflow_executor_queued_tasks",
+ "legendFormat": "executor queued: not yet sent to broker"
+ },
+ {
+ "refId": "E",
+ "expr": "airflow_executor_running_tasks",
+ "legendFormat": "executor running: sent to broker, not finished"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "custom": {
+ "drawStyle": "line",
+ "lineWidth": 2,
+ "fillOpacity": 10,
+ "spanNulls": true
+ },
+ "unit": "short",
+ "min": 0
+ },
+ "overrides": []
+ },
+ "options": {
+ "legend": {
+ "displayMode": "list",
+ "placement": "bottom"
+ },
+ "tooltip": {
+ "mode": "multi"
+ }
+ }
+ },
+ {
+ "id": 9,
+ "type": "timeseries",
+ "title": "Tasks handed off, cumulative, per scheduler process",
+ "description": "Each test case of the test starts its own scheduler, so
each test case is its own curve; the slope is the hand-off rate.",
+ "datasource": "Prometheus",
+ "gridPos": {
+ "x": 0,
+ "y": 32,
+ "w": 24,
+ "h": 8
+ },
+ "targets": [
+ {
+ "refId": "A",
+ "expr": "sum by (exported_instance)
(histogram_count(airflow_task_scheduled_duration_milliseconds))",
+ "legendFormat": "{{exported_instance}}"
+ }
+ ],
+ "fieldConfig": {
+ "defaults": {
+ "custom": {
+ "drawStyle": "line",
+ "lineWidth": 2,
+ "fillOpacity": 0,
+ "spanNulls": true
+ },
+ "unit": "short",
+ "min": 0
+ },
+ "overrides": []
+ },
+ "options": {
+ "legend": {
+ "displayMode": "list",
+ "placement": "bottom"
+ },
+ "tooltip": {
+ "mode": "multi"
+ }
+ }
+ }
+ ]
+}
diff --git a/scripts/ci/prek/check_tests_in_right_folders.py
b/scripts/ci/prek/check_tests_in_right_folders.py
index 2eb82cf7b72..ddb6b794c11 100755
--- a/scripts/ci/prek/check_tests_in_right_folders.py
+++ b/scripts/ci/prek/check_tests_in_right_folders.py
@@ -65,6 +65,7 @@ POSSIBLE_TEST_FOLDERS = [
"observability",
"operators",
"otel",
+ "performance",
"plugins",
"providers",
"partition_mappers",