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

vatsrahul1001 pushed a commit to branch v3-4-test
in repository https://gitbox.apache.org/repos/asf/airflow.git


The following commit(s) were added to refs/heads/v3-4-test by this push:
     new e277621172b [v3-4-test] Keep Dag and deadline list serialization off 
the API server event loop (#76525) (#77765)
e277621172b is described below

commit e277621172b1ff5c8330e5c97772117ef0285ff3
Author: Rahul Vats <[email protected]>
AuthorDate: Mon Nov 30 16:13:27 2026 +0530

    [v3-4-test] Keep Dag and deadline list serialization off the API server 
event loop (#76525) (#77765)
    
    * Keep Dag and deadline list serialization off the API server event loop
    
    
    
    * Eager-load Dag tags in PATCH /dags to avoid n+1 queries
    
    
    
    * Build the Dag and deadline lists without model_validate
    
    The list fields already make pydantic validate the items when the route 
builds the response, so validating each row in the route was redundant.
    
    ---------
    
    
    
    (cherry picked from commit 24464f6d728f362dbb46920e33b152db79e94d79)
    
    Co-authored-by: ccoliu <[email protected]>
    Co-authored-by: Claude <[email protected]>
---
 .../airflow/api_fastapi/core_api/datamodels/dags.py    |  4 ++--
 .../api_fastapi/core_api/datamodels/ui/deadline.py     |  2 +-
 .../airflow/api_fastapi/core_api/routes/public/dags.py |  7 ++++---
 .../api_fastapi/core_api/routes/ui/deadlines.py        |  2 +-
 .../api_fastapi/core_api/routes/public/test_dags.py    | 18 ++++++++++++++++++
 .../api_fastapi/core_api/routes/ui/test_deadlines.py   | 12 ++++++++++++
 6 files changed, 38 insertions(+), 7 deletions(-)

diff --git a/airflow-core/src/airflow/api_fastapi/core_api/datamodels/dags.py 
b/airflow-core/src/airflow/api_fastapi/core_api/datamodels/dags.py
index 17c8c52158f..0b614348066 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/datamodels/dags.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/datamodels/dags.py
@@ -18,7 +18,7 @@
 from __future__ import annotations
 
 import inspect
-from collections.abc import Iterable, Mapping
+from collections.abc import Mapping
 from datetime import datetime, timedelta
 from functools import cache
 from typing import TYPE_CHECKING, Any
@@ -190,7 +190,7 @@ class BulkDAGBody(DAGPatchBody):
 class DAGCollectionResponse(BaseModel):
     """Dag Collection serializer for responses."""
 
-    dags: Iterable[DAGResponse]
+    dags: list[DAGResponse]
     total_entries: int
 
 
diff --git 
a/airflow-core/src/airflow/api_fastapi/core_api/datamodels/ui/deadline.py 
b/airflow-core/src/airflow/api_fastapi/core_api/datamodels/ui/deadline.py
index 0ea484817ac..8d27b74052e 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/datamodels/ui/deadline.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/datamodels/ui/deadline.py
@@ -51,7 +51,7 @@ class DeadlineResponse(BaseModel):
 class DeadlineCollectionResponse(BaseModel):
     """Deadline Collection serializer for responses."""
 
-    deadlines: Iterable[DeadlineResponse]
+    deadlines: list[DeadlineResponse]
     total_entries: int
 
 
diff --git 
a/airflow-core/src/airflow/api_fastapi/core_api/routes/public/dags.py 
b/airflow-core/src/airflow/api_fastapi/core_api/routes/public/dags.py
index 11dbc1792fc..94abf2ec5ec 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/routes/public/dags.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/routes/public/dags.py
@@ -23,6 +23,7 @@ from fastapi import Depends, HTTPException, Query, Response, 
status
 from fastapi.exceptions import RequestValidationError
 from pydantic import ValidationError
 from sqlalchemy import delete, func, insert, select, update
+from sqlalchemy.orm import selectinload
 
 from airflow.api.common import delete_dag as delete_dag_module
 from airflow.api_fastapi.common.asset_expression import redact_asset_expression
@@ -200,7 +201,7 @@ def get_dags(
     dags = session.scalars(dags_select)
 
     return DAGCollectionResponse(
-        dags=dags,
+        dags=list(dags),
         total_entries=total_entries,
     )
 
@@ -411,7 +412,7 @@ def patch_dags(
             raise RequestValidationError(errors=e.errors())
 
     dags_select, total_entries = paginated_select(
-        statement=select(DagModel),
+        statement=select(DagModel).options(selectinload(DagModel.tags)),
         filters=[
             exclude_stale,
             paused,
@@ -453,7 +454,7 @@ def patch_dags(
     )
 
     return DAGCollectionResponse(
-        dags=dags,
+        dags=list(dags),
         total_entries=total_entries,
     )
 
diff --git 
a/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/deadlines.py 
b/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/deadlines.py
index c6298e2062e..3cd16762070 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/deadlines.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/routes/ui/deadlines.py
@@ -160,7 +160,7 @@ def get_deadlines(
                 f"DagRun with dag_id: `{dag_id}` and run_id: `{dag_run_id}` 
was not found",
             )
 
-    return DeadlineCollectionResponse(deadlines=deadlines, 
total_entries=total_entries)
+    return DeadlineCollectionResponse(deadlines=list(deadlines), 
total_entries=total_entries)
 
 
 @deadlines_router.get(
diff --git 
a/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dags.py 
b/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dags.py
index 186c75e42cc..b69a99d362d 100644
--- a/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dags.py
+++ b/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dags.py
@@ -916,6 +916,14 @@ class TestGetDags(TestDagEndpoint):
             f"({first_query_count} → {second_query_count}), suggesting n+1 
queries for tags"
         )
 
+    def test_get_dags_should_not_query_on_event_loop(self, test_client, 
event_loop_queries):
+        """Nothing is queried while the response is serialized on the event 
loop."""
+        response = test_client.get("/dags")
+        assert response.status_code == 200
+        tags = {dag["dag_id"]: [tag["name"] for tag in dag["tags"]] for dag in 
response.json()["dags"]}
+        assert "tag_2" in tags[DAG1_ID]
+        assert event_loop_queries == []
+
     @pytest.mark.parametrize(
         ("deadline", "expected_alert_count"),
         [
@@ -1181,6 +1189,16 @@ class TestPatchDags(TestDagEndpoint):
             assert paused_dag_ids == set(expected_paused_ids)
             check_last_log(session, dag_id=None, event="patch_dags", 
logical_date=None)
 
+    def test_patch_dags_should_not_query_tags_on_event_loop(self, test_client, 
event_loop_queries):
+        """Nothing is queried while the response is serialized on the event 
loop."""
+        response = test_client.patch("/dags", json={"is_paused": True}, 
params={"dag_id_pattern": "~"})
+        assert response.status_code == 200
+        tags = {dag["dag_id"]: [tag["name"] for tag in dag["tags"]] for dag in 
response.json()["dags"]}
+        assert "tag_2" in tags[DAG1_ID]
+        # Only the audit log is written on the event loop, through the async 
engine, which doesn't block it.
+        assert len(event_loop_queries) == 1
+        assert event_loop_queries[0].startswith("INSERT INTO log ")
+
     @pytest.mark.parametrize(
         ("tags_to_add", "query_params", "body", "expected_ids", 
"expected_paused_ids"),
         [
diff --git 
a/airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_deadlines.py 
b/airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_deadlines.py
index 3943b9cc9b4..9893e146ac0 100644
--- a/airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_deadlines.py
+++ b/airflow-core/tests/unit/api_fastapi/core_api/routes/ui/test_deadlines.py
@@ -502,6 +502,18 @@ class TestGetDeadlines:
             teams_by_dag = {dl["dag_id"]: dl["team_name"] for dl in 
response.json()["deadlines"]}
             assert teams_by_dag == {DAG_ID: expected_team_name, DAG_ID_2: None}
 
+    @conf_vars({("core", "multi_team"): "True"})
+    def test_should_not_query_on_event_loop(self, test_client, session, 
event_loop_queries):
+        """Nothing is queried while the response is serialized on the event 
loop."""
+        with attach_dag_to_team(
+            session, DAG_ID, bundle_name="team-bundle-deadline-loop", 
team_name="team-deadline-loop"
+        ):
+            response = test_client.get("/dags/~/dagRuns/~/deadlines")
+            assert response.status_code == 200
+            teams_by_dag = {dl["dag_id"]: dl["team_name"] for dl in 
response.json()["deadlines"]}
+            assert teams_by_dag == {DAG_ID: "team-deadline-loop", DAG_ID_2: 
None}
+        assert event_loop_queries == []
+
     @conf_vars({("core", "multi_team"): "True"})
     def test_filter_by_team(self, test_client, session):
         with attach_dag_to_team(

Reply via email to