You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "john-rodriguez-mgni (via GitHub)" <gi...@apache.org> on 2026/02/05 05:40:39 UTC

[PR] perf(api): optimize /ui/dags endpoint serialization [airflow]

john-rodriguez-mgni opened a new pull request, #61483:
URL: https://github.com/apache/airflow/pull/61483

   ## Summary
   
   This PR addresses a significant performance issue in the `/ui/dags` endpoint where page load times scaled poorly with the number of DAGs (12-16 seconds for just 25 DAGs in our testing).
   
   Two optimizations are implemented:
   
   ### 1. Cache URLSafeSerializer for file_token generation
   
   Previously, a new `URLSafeSerializer` was instantiated and `conf.get_mandatory_value()` was called for **every DAG** in the response. Now uses `@lru_cache` to create the serializer once and reuse it.
   
   ### 2. Eliminate redundant Pydantic validation in response construction
   
   The original pattern used:
   ```python
   DAGWithLatestDagRunsResponse.model_validate({
       **DAGResponse.model_validate(dag).model_dump(),
       ...
   })
   ```
   
   This caused triple serialization overhead per DAG (validate → dump → validate). The fix validates once with `DAGResponse.model_validate()`, then uses `model_construct()` to build `DAGWithLatestDagRunsResponse` without redundant validation.
   
   ## Results
   
   Together, these changes reduced page load time from **12-16 seconds to ~130ms** in our dev environment.
   
   ## Test Plan
   
   - [ ] Existing unit tests pass
   - [ ] Manual testing of /ui/dags endpoint with varying numbers of DAGs
   - [ ] Verify file_token generation still works correctly
   
   Made with [Cursor](https://cursor.com)


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "uranusjr (via GitHub)" <gi...@apache.org>.
uranusjr commented on code in PR #61483:
URL: https://github.com/apache/airflow/pull/61483#discussion_r2785869682


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py:
##########
@@ -190,7 +189,7 @@ def get_dags(
             DagRun.run_after,
             DagRun.start_date,
             DagRun.state,
-            DagRun.duration.expression,  # type: ignore[attr-defined]
+            DagRun.duration,

Review Comment:
   Hm, #58352 (cc @KoviAnusha)



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "john-rodriguez-mgni (via GitHub)" <gi...@apache.org>.
john-rodriguez-mgni commented on PR #61483:
URL: https://github.com/apache/airflow/pull/61483#issuecomment-3954071746

   @pierrejeambrun it seems that all 10 CI failures failures trace back to the same root cause; the `allowed_run_types` field was added to DAGResponse on the`main` branch after this branch was created. Since the optimization switches from DAGResponse.model_validate(dag) (which dynamically picks up all model fields from the ORM object) to an explicit dict construction, the new field is missing from the dict, causing a `ValidationError: allowed_run_types - Field required on DAGWithLatestDagRunsResponse`. The 7 API/Serialization suite failures hit this directly, and the 3 UI e2e failures (Chromium/Firefox/WebKit) are a downstream consequence — the /ui/dags endpoint returns 500, so the dags-list e2e tests can't render anything.
   
   The immediate fix is simple — add `"allowed_run_types": dag.allowed_run_types` to the dict. However, this highlights a fragility in the explicit-field approach: any new field added to DAGResponse requires a corresponding update here, which is easy to miss. To make this more robust, we could build the dict dynamically from DAGResponse.model_fields which iterates over the model's field definitions to pull attributes from the ORM object, so new fields are picked up automatically. The dict construction is still just cheap `getattr` calls, and there's still only one model_validate call. Overhead of iterating model_fields is negligible compared to Pydantic validation.
   
   Thoughts?


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(api): optimize /ui/dags endpoint serialization [airflow]

Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #61483:
URL: https://github.com/apache/airflow/pull/61483#discussion_r2783745753


##########
airflow-core/src/airflow/api_fastapi/core_api/datamodels/dags.py:
##########
@@ -41,6 +42,19 @@
 if TYPE_CHECKING:
     from airflow.serialization.definitions.param import SerializedParamsDict
 
+
+@lru_cache(maxsize=1)
+def _get_file_token_serializer() -> URLSafeSerializer:

Review Comment:
   +1 for this, probably a module constant is better. (Yes I think it's guaranteed to be loaded, some other fn read conf to define default args, those are done a module level too)



##########
airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py:
##########
@@ -234,18 +234,48 @@ def get_dags(
             pending_actions_by_dag_id[dag_id].append(hitl_detail)
 
     # aggregate rows by dag_id
-    dag_runs_by_dag_id: dict[str, DAGWithLatestDagRunsResponse] = {
-        dag.dag_id: DAGWithLatestDagRunsResponse.model_validate(
-            {
-                **DAGResponse.model_validate(dag).model_dump(),
-                "asset_expression": dag.asset_expression,
-                "latest_dag_runs": [],
-                "pending_actions": pending_actions_by_dag_id[dag.dag_id],
-                "is_favorite": dag.dag_id in favorite_dag_ids,
-            }
+    # PERFORMANCE FIX: Validate once per DAG, then extend with extra fields
+    dag_runs_by_dag_id: dict[str, DAGWithLatestDagRunsResponse] = {}
+    for dag in dags:
+        # Validate ORM to DAGResponse once (this computes file_token)
+        dag_response = DAGResponse.model_validate(dag)
+        # Construct DAGWithLatestDagRunsResponse directly from validated response
+        # Use model_construct with explicit field copying to avoid model_dump() overhead
+        # which would convert DagTagResponse objects to dicts
+        dag_runs_by_dag_id[dag.dag_id] = DAGWithLatestDagRunsResponse.model_construct(
+            # Fields from DAGResponse (keep objects as-is, don't serialize to dict)
+            dag_id=dag_response.dag_id,
+            dag_display_name=dag_response.dag_display_name,
+            is_paused=dag_response.is_paused,
+            is_stale=dag_response.is_stale,
+            last_parsed_time=dag_response.last_parsed_time,
+            last_parse_duration=dag_response.last_parse_duration,
+            last_expired=dag_response.last_expired,
+            bundle_name=dag_response.bundle_name,
+            bundle_version=dag_response.bundle_version,
+            relative_fileloc=dag_response.relative_fileloc,
+            fileloc=dag_response.fileloc,
+            description=dag_response.description,
+            timetable_summary=dag_response.timetable_summary,
+            timetable_description=dag_response.timetable_description,
+            tags=dag_response.tags,  # Keep as DagTagResponse objects
+            max_active_tasks=dag_response.max_active_tasks,
+            max_active_runs=dag_response.max_active_runs,
+            max_consecutive_failed_dag_runs=dag_response.max_consecutive_failed_dag_runs,
+            has_task_concurrency_limits=dag_response.has_task_concurrency_limits,
+            has_import_errors=dag_response.has_import_errors,
+            next_dagrun_logical_date=dag_response.next_dagrun_logical_date,
+            next_dagrun_data_interval_start=dag_response.next_dagrun_data_interval_start,
+            next_dagrun_data_interval_end=dag_response.next_dagrun_data_interval_end,
+            next_dagrun_run_after=dag_response.next_dagrun_run_after,
+            owners=dag_response.owners,
+            file_token=dag_response.file_token,  # Computed field - already computed
+            # Extra fields for DAGWithLatestDagRunsResponse
+            asset_expression=dag.asset_expression,
+            latest_dag_runs=[],
+            pending_actions=pending_actions_by_dag_id[dag.dag_id],
+            is_favorite=dag.dag_id in favorite_dag_ids,

Review Comment:
   Shouldn't this be valided too? A `DAGResponse` can be valid, but this extra fields can fail validation, and we're not checking.
   
   I would remove the `DAGResponse.model_validate` call and keep the `DAGWithLatestDagRunsResponse.model_validate` so we are sure that the final full object is validated `DAGWithLatestDagRunsResponse` 



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "jason810496 (via GitHub)" <gi...@apache.org>.
jason810496 commented on code in PR #61483:
URL: https://github.com/apache/airflow/pull/61483#discussion_r2796590839


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py:
##########
@@ -270,8 +297,7 @@ def get_latest_run_info(dag_id: str, session: SessionDep) -> DAGRunLightResponse
             status.HTTP_400_BAD_REQUEST,
             "`~` was supplied as dag_id, but querying multiple dags is not supported.",
         )
-
-    latest_run_info_select = (
+    return session.execute(

Review Comment:
   Could we add a comment explaining that we return the ORM object instead of a Pydantic data model for performance reasons, to prevent future PRs from changing the return type back to a Pydantic data model?



##########
airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py:
##########


Review Comment:
   ```bash
     airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py:300: error: Incompatible return value type (got "Row[Any] | None", expected "DAGRunLightResponse | None")  [return-value]
             return session.execute(
   ```
   
   Mypy is not happy with the type annotation. It seems the only way is to workaround with `response_model`:
   
   ```suggestion
   def get_latest_run_info(dag_id: str, session: SessionDep, response_model=DAGRunLightResponse):
   ```



##########
airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py:
##########
@@ -190,7 +189,7 @@ def get_dags(
             DagRun.run_after,
             DagRun.start_date,
             DagRun.state,
-            DagRun.duration.expression,  # type: ignore[attr-defined]
+            DagRun.duration,

Review Comment:
   It seems we have to keep `DagRun.duration.expression,  # type: ignore[attr-defined]` for mypy.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "john-rodriguez-mgni (via GitHub)" <gi...@apache.org>.
john-rodriguez-mgni commented on PR #61483:
URL: https://github.com/apache/airflow/pull/61483#issuecomment-3923513813

   @pierrejeambrun just checking on this to see if there was anything else required on my end, I have made the changes necessary to address the CI failures... I think we just need someone to approve the workflows.


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(api): optimize /ui/dags endpoint serialization [airflow]

Posted by "boring-cyborg[bot] (via GitHub)" <gi...@apache.org>.
boring-cyborg[bot] commented on PR #61483:
URL: https://github.com/apache/airflow/pull/61483#issuecomment-3851204516

   Congratulations on your first Pull Request and welcome to the Apache Airflow community! If you have any issues or are unsure about any anything please check our Contributors' Guide (https://github.com/apache/airflow/blob/main/contributing-docs/README.rst)
   Here are some useful points:
   - Pay attention to the quality of your code (ruff, mypy and type annotations). Our [prek-hooks]( https://github.com/apache/airflow/blob/main/contributing-docs/08_static_code_checks.rst#prerequisites-for-prek-hooks) will help you with that.
   - In case of a new feature add useful documentation (in docstrings or in `docs/` directory). Adding a new operator? Check this short [guide](https://github.com/apache/airflow/blob/main/airflow-core/docs/howto/custom-operator.rst) Consider adding an example DAG that shows how users should use it.
   - Consider using [Breeze environment](https://github.com/apache/airflow/blob/main/dev/breeze/doc/README.rst) for testing locally, it's a heavy docker but it ships with a working Airflow and a lot of integrations.
   - Be patient and persistent. It might take some time to get a review or get the final approval from Committers.
   - Please follow [ASF Code of Conduct](https://www.apache.org/foundation/policies/conduct) for all communication including (but not limited to) comments on Pull Requests, Mailing list and Slack.
   - Be sure to read the [Airflow Coding style]( https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#coding-style-and-best-practices).
   - Always keep your Pull Requests rebased, otherwise your build might fail due to changes not related to your commits.
   Apache Airflow is a community-driven project and together we are making it better šŸš€.
   In case of doubts contact the developers at:
   Mailing List: dev@airflow.apache.org
   Slack: https://s.apache.org/airflow-slack
   


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "uranusjr (via GitHub)" <gi...@apache.org>.
uranusjr commented on code in PR #61483:
URL: https://github.com/apache/airflow/pull/61483#discussion_r2785865959


##########
airflow-core/src/airflow/api_fastapi/core_api/datamodels/dags.py:
##########
@@ -41,6 +41,14 @@
 if TYPE_CHECKING:
     from airflow.serialization.definitions.param import SerializedParamsDict
 
+
+# Module-level serializer instance for file tokens.
+# This avoids creating a new serializer and calling conf.get_mandatory_value()
+# for every DAG when generating file tokens, which significantly improves
+# performance of the /ui/dags endpoint.
+_FILE_TOKEN_SERIALIZER: URLSafeSerializer = URLSafeSerializer(conf.get_mandatory_value("api", "secret_key"))

Review Comment:
   I’d prefer to avoid using `conf` eagerly on import time. Maybe a `@cache`-ed function instead?



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(api): optimize /ui/dags endpoint serialization [airflow]

Posted by "john-rodriguez-mgni (via GitHub)" <gi...@apache.org>.
john-rodriguez-mgni commented on code in PR #61483:
URL: https://github.com/apache/airflow/pull/61483#discussion_r2770081933


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py:
##########
@@ -234,18 +234,22 @@ def get_dags(
             pending_actions_by_dag_id[dag_id].append(hitl_detail)
 
     # aggregate rows by dag_id
-    dag_runs_by_dag_id: dict[str, DAGWithLatestDagRunsResponse] = {
-        dag.dag_id: DAGWithLatestDagRunsResponse.model_validate(
-            {
-                **DAGResponse.model_validate(dag).model_dump(),
-                "asset_expression": dag.asset_expression,
-                "latest_dag_runs": [],
-                "pending_actions": pending_actions_by_dag_id[dag.dag_id],
-                "is_favorite": dag.dag_id in favorite_dag_ids,
-            }
+    # Performance optimization: Validate ORM to DAGResponse once per DAG, then use model_construct
+    # to build DAGWithLatestDagRunsResponse without redundant validation.
+    # The original pattern (model_validate -> model_dump -> model_validate) caused triple
+    # serialization overhead that scaled poorly with the number of DAGs.
+    dag_runs_by_dag_id: dict[str, DAGWithLatestDagRunsResponse] = {}
+    for dag in dags:
+        dag_response = DAGResponse.model_validate(dag)
+        dag_data = dag_response.model_dump()
+        dag_data["asset_expression"] = dag.asset_expression
+        dag_data["latest_dag_runs"] = []
+        dag_data["pending_actions"] = pending_actions_by_dag_id[dag.dag_id]
+        dag_data["is_favorite"] = dag.dag_id in favorite_dag_ids
+        dag_runs_by_dag_id[dag.dag_id] = DAGWithLatestDagRunsResponse.model_construct(

Review Comment:
   I am sorry I accidentally included the wrong dags.py in the PR because I had my patch which I applied to our custom Airflow image for testing in a different directory.  I have updated the PR with the same dags.py that is in my Airflow installation and I can confirm that I have DAGs with tags and don't see the issue.
   ```
   airflow@ip-10-128-236-181:/opt/airflow$ python3 -c "
   from sqlalchemy import text
   from airflow.settings import Session
   with Session() as session:
       result = session.execute(text('SELECT COUNT(DISTINCT dag_id) FROM dag_tag'))
       print(f'DAGs with tags: {result.scalar()}')
   "
   DAGs with tags: 26
   ```
   



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "jason810496 (via GitHub)" <gi...@apache.org>.
jason810496 commented on code in PR #61483:
URL: https://github.com/apache/airflow/pull/61483#discussion_r2800086241


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py:
##########
@@ -270,8 +297,7 @@ def get_latest_run_info(dag_id: str, session: SessionDep) -> DAGRunLightResponse
             status.HTTP_400_BAD_REQUEST,
             "`~` was supplied as dag_id, but querying multiple dags is not supported.",
         )
-
-    latest_run_info_select = (
+    return session.execute(

Review Comment:
   I see, so the main problem is continuously instantiating ā€Ž`URLSafeSerializer` rather than Pydantic serialization issue.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "john-rodriguez-mgni (via GitHub)" <gi...@apache.org>.
john-rodriguez-mgni commented on PR #61483:
URL: https://github.com/apache/airflow/pull/61483#issuecomment-3985821129

   @pierrejeambrun fix the issue with the static check (i.e. ruff wanting the imports sorted alphabetically). The browser failures do not appear to be related to my changes. The  `K8S System:KubernetesExecutor` test is a full Kubernetes integration test and the change I am introducing has no interaction with the Kubernetes executor. Please approve the workflows at your earliest convenience.


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "boring-cyborg[bot] (via GitHub)" <gi...@apache.org>.
boring-cyborg[bot] commented on PR #61483:
URL: https://github.com/apache/airflow/pull/61483#issuecomment-4012496691

   Awesome work, congrats on your first merged pull request! You are invited to check our [Issue Tracker](https://github.com/apache/airflow/issues) for additional contributions.
   


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "john-rodriguez-mgni (via GitHub)" <gi...@apache.org>.
john-rodriguez-mgni commented on code in PR #61483:
URL: https://github.com/apache/airflow/pull/61483#discussion_r2785810835


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py:
##########
@@ -234,18 +234,48 @@ def get_dags(
             pending_actions_by_dag_id[dag_id].append(hitl_detail)
 
     # aggregate rows by dag_id
-    dag_runs_by_dag_id: dict[str, DAGWithLatestDagRunsResponse] = {
-        dag.dag_id: DAGWithLatestDagRunsResponse.model_validate(
-            {
-                **DAGResponse.model_validate(dag).model_dump(),
-                "asset_expression": dag.asset_expression,
-                "latest_dag_runs": [],
-                "pending_actions": pending_actions_by_dag_id[dag.dag_id],
-                "is_favorite": dag.dag_id in favorite_dag_ids,
-            }
+    # PERFORMANCE FIX: Validate once per DAG, then extend with extra fields
+    dag_runs_by_dag_id: dict[str, DAGWithLatestDagRunsResponse] = {}
+    for dag in dags:
+        # Validate ORM to DAGResponse once (this computes file_token)
+        dag_response = DAGResponse.model_validate(dag)
+        # Construct DAGWithLatestDagRunsResponse directly from validated response
+        # Use model_construct with explicit field copying to avoid model_dump() overhead
+        # which would convert DagTagResponse objects to dicts
+        dag_runs_by_dag_id[dag.dag_id] = DAGWithLatestDagRunsResponse.model_construct(
+            # Fields from DAGResponse (keep objects as-is, don't serialize to dict)
+            dag_id=dag_response.dag_id,
+            dag_display_name=dag_response.dag_display_name,
+            is_paused=dag_response.is_paused,
+            is_stale=dag_response.is_stale,
+            last_parsed_time=dag_response.last_parsed_time,
+            last_parse_duration=dag_response.last_parse_duration,
+            last_expired=dag_response.last_expired,
+            bundle_name=dag_response.bundle_name,
+            bundle_version=dag_response.bundle_version,
+            relative_fileloc=dag_response.relative_fileloc,
+            fileloc=dag_response.fileloc,
+            description=dag_response.description,
+            timetable_summary=dag_response.timetable_summary,
+            timetable_description=dag_response.timetable_description,
+            tags=dag_response.tags,  # Keep as DagTagResponse objects
+            max_active_tasks=dag_response.max_active_tasks,
+            max_active_runs=dag_response.max_active_runs,
+            max_consecutive_failed_dag_runs=dag_response.max_consecutive_failed_dag_runs,
+            has_task_concurrency_limits=dag_response.has_task_concurrency_limits,
+            has_import_errors=dag_response.has_import_errors,
+            next_dagrun_logical_date=dag_response.next_dagrun_logical_date,
+            next_dagrun_data_interval_start=dag_response.next_dagrun_data_interval_start,
+            next_dagrun_data_interval_end=dag_response.next_dagrun_data_interval_end,
+            next_dagrun_run_after=dag_response.next_dagrun_run_after,
+            owners=dag_response.owners,
+            file_token=dag_response.file_token,  # Computed field - already computed
+            # Extra fields for DAGWithLatestDagRunsResponse
+            asset_expression=dag.asset_expression,
+            latest_dag_runs=[],
+            pending_actions=pending_actions_by_dag_id[dag.dag_id],
+            is_favorite=dag.dag_id in favorite_dag_ids,

Review Comment:
   Thanks for the feedback! @pierrejeambrun...  I've updated the PR with both suggestions:
   
   1. Module-level serializer: Replaced @lru_cache with a module-level `_FILE_TOKEN_SERIALIZER` constant.
   
   2. Single validation pass: Refactored to use a single` DAGWithLatestDagRunsResponse.model_validate()` call on a dict built from ORM attributes + extra fields. This ensures all fields go through Pydantic validation in one pass while avoiding the double-validation overhead.
   
   Tested locally with ~25 DAGs - the /ui/dags endpoint responds in ~130ms 



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(api): optimize /ui/dags endpoint serialization [airflow]

Posted by "tirkarthi (via GitHub)" <gi...@apache.org>.
tirkarthi commented on code in PR #61483:
URL: https://github.com/apache/airflow/pull/61483#discussion_r2767333305


##########
airflow-core/src/airflow/api_fastapi/core_api/datamodels/dags.py:
##########
@@ -41,6 +42,19 @@
 if TYPE_CHECKING:
     from airflow.serialization.definitions.param import SerializedParamsDict
 
+
+@lru_cache(maxsize=1)
+def _get_file_token_serializer() -> URLSafeSerializer:

Review Comment:
   Since the secret_key doesn't change could this be just set as a module level private attribute instead of a cached function?



##########
airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py:
##########
@@ -234,18 +234,22 @@ def get_dags(
             pending_actions_by_dag_id[dag_id].append(hitl_detail)
 
     # aggregate rows by dag_id
-    dag_runs_by_dag_id: dict[str, DAGWithLatestDagRunsResponse] = {
-        dag.dag_id: DAGWithLatestDagRunsResponse.model_validate(
-            {
-                **DAGResponse.model_validate(dag).model_dump(),
-                "asset_expression": dag.asset_expression,
-                "latest_dag_runs": [],
-                "pending_actions": pending_actions_by_dag_id[dag.dag_id],
-                "is_favorite": dag.dag_id in favorite_dag_ids,
-            }
+    # Performance optimization: Validate ORM to DAGResponse once per DAG, then use model_construct
+    # to build DAGWithLatestDagRunsResponse without redundant validation.
+    # The original pattern (model_validate -> model_dump -> model_validate) caused triple
+    # serialization overhead that scaled poorly with the number of DAGs.
+    dag_runs_by_dag_id: dict[str, DAGWithLatestDagRunsResponse] = {}
+    for dag in dags:
+        dag_response = DAGResponse.model_validate(dag)
+        dag_data = dag_response.model_dump()
+        dag_data["asset_expression"] = dag.asset_expression
+        dag_data["latest_dag_runs"] = []
+        dag_data["pending_actions"] = pending_actions_by_dag_id[dag.dag_id]
+        dag_data["is_favorite"] = dag.dag_id in favorite_dag_ids
+        dag_runs_by_dag_id[dag.dag_id] = DAGWithLatestDagRunsResponse.model_construct(

Review Comment:
   I see below traceback while testing dags with tags. Can you please test this PR with dags that have tags? I tried the below patch but it would change the signature to include dict.
   
   ```diff
   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 cf0d69357a..5516cea9c8 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
   @@ -102,7 +102,7 @@ class DAGResponse(BaseModel):
        @field_serializer("tags")
        def serialize_tags(self, tags: list[DagTagResponse]) -> list[DagTagResponse]:
            """Sort tags alphabetically by name."""
   -        return sorted(tags, key=lambda tag: tag.name)
   +        return sorted(tags, key=lambda tag: tag["name"] if isinstance(tag, dict) else tag.name)
    
        @field_validator("owners", mode="before")
        @classmethod
   
   ```
   
   ```
   ERROR:    Exception in ASGI application
   Traceback (most recent call last):
     File "/home/karthikeyan/stuff/python/airflow/airflow-core/src/airflow/api_fastapi/core_api/datamodels/dags.py", line 105, in serialize_tags
       return sorted(tags, key=lambda tag: tag.name)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     File "/home/karthikeyan/stuff/python/airflow/airflow-core/src/airflow/api_fastapi/core_api/datamodels/dags.py", line 105, in <lambda>
       return sorted(tags, key=lambda tag: tag.name)
                                           ^^^^^^^^
   AttributeError: 'dict' object has no attribute 'name'
   
   The above exception was the direct cause of the following exception:
   
   Traceback (most recent call last):
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/uvicorn/protocols/http/httptools_impl.py", line 409, in run_asgi
       result = await app(  # type: ignore[func-returns-value]
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/fastapi/applications.py", line 1138, in __call__
       await super().__call__(scope, receive, send)
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/starlette/applications.py", line 112, in __call__
       await self.middleware_stack(scope, receive, send)
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/starlette/middleware/errors.py", line 187, in __call__
       raise exc
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/starlette/middleware/errors.py", line 165, in __call__
       await self.app(scope, receive, _send)
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/starlette/middleware/cors.py", line 85, in __call__
       await self.app(scope, receive, send)
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/starlette/middleware/gzip.py", line 22, in __call__
       await self.app(scope, receive, send)
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/starlette/middleware/base.py", line 177, in __call__
       with recv_stream, send_stream, collapse_excgroups():
     File "/usr/lib/python3.11/contextlib.py", line 158, in __exit__
       self.gen.throw(typ, value, traceback)
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/starlette/_utils.py", line 82, in collapse_excgroups
       raise exc
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/starlette/middleware/base.py", line 179, in __call__
       response = await self.dispatch_func(request, call_next)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     File "/home/karthikeyan/stuff/python/airflow/airflow-core/src/airflow/api_fastapi/auth/middlewares/refresh_token.py", line 61, in dispatch
       response = await call_next(request)
                  ^^^^^^^^^^^^^^^^^^^^^^^^
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/starlette/middleware/base.py", line 154, in call_next
       raise app_exc
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/starlette/middleware/base.py", line 141, in coro
       await self.app(scope, receive_or_disconnect, send_no_error)
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/starlette/middleware/exceptions.py", line 62, in __call__
       await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
       raise exc
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app
       await app(scope, receive, sender)
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/fastapi/middleware/asyncexitstack.py", line 18, in __call__
       await self.app(scope, receive, send)
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/starlette/routing.py", line 715, in __call__
       await self.middleware_stack(scope, receive, send)
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/starlette/routing.py", line 735, in app
       await route.handle(scope, receive, send)
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/starlette/routing.py", line 288, in handle
       await self.app(scope, receive, send)
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/fastapi/routing.py", line 115, in app
       await wrap_app_handling_exceptions(app, request)(scope, receive, send)
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/starlette/_exception_handler.py", line 53, in wrapped_app
       raise exc
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/starlette/_exception_handler.py", line 42, in wrapped_app
       await app(scope, receive, sender)
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/fastapi/routing.py", line 101, in app
       response = await f(request)
                  ^^^^^^^^^^^^^^^^
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/fastapi/routing.py", line 377, in app
       content = await serialize_response(
                 ^^^^^^^^^^^^^^^^^^^^^^^^^
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/fastapi/routing.py", line 221, in serialize_response
       return field.serialize(
              ^^^^^^^^^^^^^^^^
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/fastapi/_compat/v2.py", line 197, in serialize
       return self._type_adapter.dump_python(
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     File "/home/karthikeyan/stuff/python/airflow/.venv/lib/python3.11/site-packages/pydantic/type_adapter.py", line 572, in dump_python
       return self.serializer.to_python(
              ^^^^^^^^^^^^^^^^^^^^^^^^^^
   pydantic_core._pydantic_core.PydanticSerializationError: Error calling function `serialize_tags`: AttributeError: 'dict' object has no attribute 'name'
   ```



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "john-rodriguez-mgni (via GitHub)" <gi...@apache.org>.
john-rodriguez-mgni commented on code in PR #61483:
URL: https://github.com/apache/airflow/pull/61483#discussion_r2790068878


##########
airflow-core/src/airflow/api_fastapi/core_api/datamodels/dags.py:
##########
@@ -41,6 +41,14 @@
 if TYPE_CHECKING:
     from airflow.serialization.definitions.param import SerializedParamsDict
 
+
+# Module-level serializer instance for file tokens.
+# This avoids creating a new serializer and calling conf.get_mandatory_value()
+# for every DAG when generating file tokens, which significantly improves
+# performance of the /ui/dags endpoint.
+_FILE_TOKEN_SERIALIZER: URLSafeSerializer = URLSafeSerializer(conf.get_mandatory_value("api", "secret_key"))

Review Comment:
   yeah previously I was using `@lru_cache` for lazy initialization but per @pierrejeambrun and @tirkarthi I made the change as it stands now. https://github.com/apache/airflow/pull/61483#discussion_r2783745753. I could switch this back to do lazy initalization using `@cache` instead if that is the preferred method.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "john-rodriguez-mgni (via GitHub)" <gi...@apache.org>.
john-rodriguez-mgni commented on PR #61483:
URL: https://github.com/apache/airflow/pull/61483#issuecomment-3909924219

   > > Let me know what else is required to move this along. Again, really appreciate your feedback and thank you for your help throughout this process!
   > 
   > Can you just fix the CI please (mypy static check error). There are two discussion above that explains what the problem is.
   > 
   > Basically we need to keep the ` # type: ignore[attr-defined]` and revert the change to the `get_latest_run_info` which is creating mypy errors and isn't really needed for that PR. (that endpoint isn't the performance bottleneck)
   
   Made updates as requested!


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(api): optimize /ui/dags endpoint serialization [airflow]

Posted by "john-rodriguez-mgni (via GitHub)" <gi...@apache.org>.
john-rodriguez-mgni commented on code in PR #61483:
URL: https://github.com/apache/airflow/pull/61483#discussion_r2775518011


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py:
##########
@@ -234,18 +234,22 @@ def get_dags(
             pending_actions_by_dag_id[dag_id].append(hitl_detail)
 
     # aggregate rows by dag_id
-    dag_runs_by_dag_id: dict[str, DAGWithLatestDagRunsResponse] = {
-        dag.dag_id: DAGWithLatestDagRunsResponse.model_validate(
-            {
-                **DAGResponse.model_validate(dag).model_dump(),
-                "asset_expression": dag.asset_expression,
-                "latest_dag_runs": [],
-                "pending_actions": pending_actions_by_dag_id[dag.dag_id],
-                "is_favorite": dag.dag_id in favorite_dag_ids,
-            }
+    # Performance optimization: Validate ORM to DAGResponse once per DAG, then use model_construct
+    # to build DAGWithLatestDagRunsResponse without redundant validation.
+    # The original pattern (model_validate -> model_dump -> model_validate) caused triple
+    # serialization overhead that scaled poorly with the number of DAGs.
+    dag_runs_by_dag_id: dict[str, DAGWithLatestDagRunsResponse] = {}
+    for dag in dags:
+        dag_response = DAGResponse.model_validate(dag)
+        dag_data = dag_response.model_dump()
+        dag_data["asset_expression"] = dag.asset_expression
+        dag_data["latest_dag_runs"] = []
+        dag_data["pending_actions"] = pending_actions_by_dag_id[dag.dag_id]
+        dag_data["is_favorite"] = dag.dag_id in favorite_dag_ids
+        dag_runs_by_dag_id[dag.dag_id] = DAGWithLatestDagRunsResponse.model_construct(

Review Comment:
   @tirkarthi let me know how this looks for you now.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "john-rodriguez-mgni (via GitHub)" <gi...@apache.org>.
john-rodriguez-mgni commented on code in PR #61483:
URL: https://github.com/apache/airflow/pull/61483#discussion_r2795598543


##########
airflow-core/src/airflow/api_fastapi/core_api/datamodels/dags.py:
##########
@@ -41,6 +41,14 @@
 if TYPE_CHECKING:
     from airflow.serialization.definitions.param import SerializedParamsDict
 
+
+# Module-level serializer instance for file tokens.
+# This avoids creating a new serializer and calling conf.get_mandatory_value()
+# for every DAG when generating file tokens, which significantly improves
+# performance of the /ui/dags endpoint.
+_FILE_TOKEN_SERIALIZER: URLSafeSerializer = URLSafeSerializer(conf.get_mandatory_value("api", "secret_key"))

Review Comment:
   @pierrejeambrun, @uranusjr I have gone back to performing the cached function as requested.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #61483:
URL: https://github.com/apache/airflow/pull/61483#discussion_r2793830691


##########
airflow-core/src/airflow/api_fastapi/core_api/datamodels/dags.py:
##########
@@ -41,6 +41,14 @@
 if TYPE_CHECKING:
     from airflow.serialization.definitions.param import SerializedParamsDict
 
+
+# Module-level serializer instance for file tokens.
+# This avoids creating a new serializer and calling conf.get_mandatory_value()
+# for every DAG when generating file tokens, which significantly improves
+# performance of the /ui/dags endpoint.
+_FILE_TOKEN_SERIALIZER: URLSafeSerializer = URLSafeSerializer(conf.get_mandatory_value("api", "secret_key"))

Review Comment:
   There was a cached function originally in this PR.
   
   I figured it's not needed because there are a lot of places where default parameters for functions are computed from config, and that's done at module level too. 
   
   Lets go back to your original idea @john-rodriguez-mgni  with the cached function so it's safer.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #61483:
URL: https://github.com/apache/airflow/pull/61483#discussion_r2800032878


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py:
##########
@@ -270,8 +297,7 @@ def get_latest_run_info(dag_id: str, session: SessionDep) -> DAGRunLightResponse
             status.HTTP_400_BAD_REQUEST,
             "`~` was supplied as dag_id, but querying multiple dags is not supported.",
         )
-
-    latest_run_info_select = (
+    return session.execute(

Review Comment:
   We can revert the change about this endpoint. Returning a validating a `DAGRunLightResponse` shouldn't ever be a problem. 
   
   The main reason for this PR really is the above change. 



##########
airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py:
##########


Review Comment:
   Yeah I'd revert that and won't bother with an endpoint that probably isn't a bottleneck.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "john-rodriguez-mgni (via GitHub)" <gi...@apache.org>.
john-rodriguez-mgni commented on PR #61483:
URL: https://github.com/apache/airflow/pull/61483#issuecomment-3893047423

   Just an update on this... since opening this PR, I have included this patch in our dev and QA environments and validated there are no issues and that it resolves the load time for the ui/dags endpoint seen with the base airflow 3.1.7 release sans patches. Earlier today I released it to our production environment and are not seeing any issues either and can confirm that load time for the ui/dags endpoint is fixed.
   
   Let me know what else is required to move this along. Again, really appreciate your feedback and thank you for your help throughout this process!


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on PR #61483:
URL: https://github.com/apache/airflow/pull/61483#issuecomment-4012727254

   Manual backport https://github.com/apache/airflow/pull/63001


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #61483:
URL: https://github.com/apache/airflow/pull/61483#issuecomment-4012502117

   ### Backport failed to create: v3-1-test. View the failure log <a href='https://github.com/apache/airflow/actions/runs/22770582082'> Run details </a>
   
   Note: As of [Merging PRs targeted for Airflow 3.X](https://github.com/apache/airflow/blob/main/dev/README_AIRFLOW3_DEV.md#merging-prs-targeted-for-airflow-3x)
   the committer who merges the PR is responsible for backporting the PRs that are bug fixes (generally speaking) to the maintenance branches.
   
   In matter of doubt please ask in [#release-management](https://apache-airflow.slack.com/archives/C03G9H97MM2) Slack channel.
   
   <table>
       <tr>
           <th>Status</th>
           <th>Branch</th>
           <th>Result</th>
       </tr>
       <tr>
           <td>āŒ</td>
           <td>v3-1-test</td>
           <td><a href="https://github.com/apache/airflow/commit/a915216434cf583b0b54eee129cc9a93b96492b2"><img src='https://img.shields.io/badge/Commit-a915216-red' alt='Commit Link'></a></td>
       </tr>
   </table>
   
   You can attempt to backport this manually by running:
   
   ```bash
   cherry_picker a915216 v3-1-test
   ```
   
   This should apply the commit to the v3-1-test branch and leave the commit in conflict state marking
   the files that need manual conflict resolution.
   
   After you have resolved the conflicts, you can continue the backport process by running:
   
   ```bash
   cherry_picker --continue
   ```
   
   If you don't have cherry-picker installed, see the [installation guide](https://github.com/apache/airflow/blob/main/dev/README_AIRFLOW3_DEV.md#how-to-backport-pr-with-cherry-picker-cli).
   


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun merged PR #61483:
URL: https://github.com/apache/airflow/pull/61483


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] perf(api): optimize /ui/dags endpoint serialization [airflow]

Posted by "john-rodriguez-mgni (via GitHub)" <gi...@apache.org>.
john-rodriguez-mgni commented on code in PR #61483:
URL: https://github.com/apache/airflow/pull/61483#discussion_r2770302359


##########
airflow-core/src/airflow/api_fastapi/core_api/datamodels/dags.py:
##########
@@ -41,6 +42,19 @@
 if TYPE_CHECKING:
     from airflow.serialization.definitions.param import SerializedParamsDict
 
+
+@lru_cache(maxsize=1)
+def _get_file_token_serializer() -> URLSafeSerializer:

Review Comment:
   Good question - I used @lru_cache to ensure lazy initialization in case this module is imported before the Airflow configuration is fully loaded. Is that not a concern in this context? If the config is guaranteed to be loaded by the time this module is imported, I'm happy to simplify to a module-level attribute.



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "john-rodriguez-mgni (via GitHub)" <gi...@apache.org>.
john-rodriguez-mgni commented on PR #61483:
URL: https://github.com/apache/airflow/pull/61483#issuecomment-3992407198

   @pierrejeambrun , @vatsrahul1001 looks like we are good to merge?


-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "john-rodriguez-mgni (via GitHub)" <gi...@apache.org>.
john-rodriguez-mgni commented on code in PR #61483:
URL: https://github.com/apache/airflow/pull/61483#discussion_r2785810835


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py:
##########
@@ -234,18 +234,48 @@ def get_dags(
             pending_actions_by_dag_id[dag_id].append(hitl_detail)
 
     # aggregate rows by dag_id
-    dag_runs_by_dag_id: dict[str, DAGWithLatestDagRunsResponse] = {
-        dag.dag_id: DAGWithLatestDagRunsResponse.model_validate(
-            {
-                **DAGResponse.model_validate(dag).model_dump(),
-                "asset_expression": dag.asset_expression,
-                "latest_dag_runs": [],
-                "pending_actions": pending_actions_by_dag_id[dag.dag_id],
-                "is_favorite": dag.dag_id in favorite_dag_ids,
-            }
+    # PERFORMANCE FIX: Validate once per DAG, then extend with extra fields
+    dag_runs_by_dag_id: dict[str, DAGWithLatestDagRunsResponse] = {}
+    for dag in dags:
+        # Validate ORM to DAGResponse once (this computes file_token)
+        dag_response = DAGResponse.model_validate(dag)
+        # Construct DAGWithLatestDagRunsResponse directly from validated response
+        # Use model_construct with explicit field copying to avoid model_dump() overhead
+        # which would convert DagTagResponse objects to dicts
+        dag_runs_by_dag_id[dag.dag_id] = DAGWithLatestDagRunsResponse.model_construct(
+            # Fields from DAGResponse (keep objects as-is, don't serialize to dict)
+            dag_id=dag_response.dag_id,
+            dag_display_name=dag_response.dag_display_name,
+            is_paused=dag_response.is_paused,
+            is_stale=dag_response.is_stale,
+            last_parsed_time=dag_response.last_parsed_time,
+            last_parse_duration=dag_response.last_parse_duration,
+            last_expired=dag_response.last_expired,
+            bundle_name=dag_response.bundle_name,
+            bundle_version=dag_response.bundle_version,
+            relative_fileloc=dag_response.relative_fileloc,
+            fileloc=dag_response.fileloc,
+            description=dag_response.description,
+            timetable_summary=dag_response.timetable_summary,
+            timetable_description=dag_response.timetable_description,
+            tags=dag_response.tags,  # Keep as DagTagResponse objects
+            max_active_tasks=dag_response.max_active_tasks,
+            max_active_runs=dag_response.max_active_runs,
+            max_consecutive_failed_dag_runs=dag_response.max_consecutive_failed_dag_runs,
+            has_task_concurrency_limits=dag_response.has_task_concurrency_limits,
+            has_import_errors=dag_response.has_import_errors,
+            next_dagrun_logical_date=dag_response.next_dagrun_logical_date,
+            next_dagrun_data_interval_start=dag_response.next_dagrun_data_interval_start,
+            next_dagrun_data_interval_end=dag_response.next_dagrun_data_interval_end,
+            next_dagrun_run_after=dag_response.next_dagrun_run_after,
+            owners=dag_response.owners,
+            file_token=dag_response.file_token,  # Computed field - already computed
+            # Extra fields for DAGWithLatestDagRunsResponse
+            asset_expression=dag.asset_expression,
+            latest_dag_runs=[],
+            pending_actions=pending_actions_by_dag_id[dag.dag_id],
+            is_favorite=dag.dag_id in favorite_dag_ids,

Review Comment:
   Thanks for the feedback! @pierrejeambrun...  I've updated the PR with both suggestions:
   
   1. Module-level serializer: Replaced @lru_cache with a module-level `_FILE_TOKEN_SERIALIZER` constant.
   
   2. Single validation pass: Refactored to use a single` DAGWithLatestDagRunsResponse.model_validate()` call on a dict built from ORM attributes + extra fields. This ensures all fields go through Pydantic validation in one pass while avoiding the double-validation overhead.
   
   Tested locally with ~25 DAGs - the /ui/dags endpoint responds in ~130ms 



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "john-rodriguez-mgni (via GitHub)" <gi...@apache.org>.
john-rodriguez-mgni commented on code in PR #61483:
URL: https://github.com/apache/airflow/pull/61483#discussion_r2785813067


##########
airflow-core/src/airflow/api_fastapi/core_api/routes/ui/dags.py:
##########
@@ -234,18 +234,48 @@ def get_dags(
             pending_actions_by_dag_id[dag_id].append(hitl_detail)
 
     # aggregate rows by dag_id
-    dag_runs_by_dag_id: dict[str, DAGWithLatestDagRunsResponse] = {
-        dag.dag_id: DAGWithLatestDagRunsResponse.model_validate(
-            {
-                **DAGResponse.model_validate(dag).model_dump(),
-                "asset_expression": dag.asset_expression,
-                "latest_dag_runs": [],
-                "pending_actions": pending_actions_by_dag_id[dag.dag_id],
-                "is_favorite": dag.dag_id in favorite_dag_ids,
-            }
+    # PERFORMANCE FIX: Validate once per DAG, then extend with extra fields
+    dag_runs_by_dag_id: dict[str, DAGWithLatestDagRunsResponse] = {}
+    for dag in dags:
+        # Validate ORM to DAGResponse once (this computes file_token)
+        dag_response = DAGResponse.model_validate(dag)
+        # Construct DAGWithLatestDagRunsResponse directly from validated response
+        # Use model_construct with explicit field copying to avoid model_dump() overhead
+        # which would convert DagTagResponse objects to dicts
+        dag_runs_by_dag_id[dag.dag_id] = DAGWithLatestDagRunsResponse.model_construct(
+            # Fields from DAGResponse (keep objects as-is, don't serialize to dict)
+            dag_id=dag_response.dag_id,
+            dag_display_name=dag_response.dag_display_name,
+            is_paused=dag_response.is_paused,
+            is_stale=dag_response.is_stale,
+            last_parsed_time=dag_response.last_parsed_time,
+            last_parse_duration=dag_response.last_parse_duration,
+            last_expired=dag_response.last_expired,
+            bundle_name=dag_response.bundle_name,
+            bundle_version=dag_response.bundle_version,
+            relative_fileloc=dag_response.relative_fileloc,
+            fileloc=dag_response.fileloc,
+            description=dag_response.description,
+            timetable_summary=dag_response.timetable_summary,
+            timetable_description=dag_response.timetable_description,
+            tags=dag_response.tags,  # Keep as DagTagResponse objects
+            max_active_tasks=dag_response.max_active_tasks,
+            max_active_runs=dag_response.max_active_runs,
+            max_consecutive_failed_dag_runs=dag_response.max_consecutive_failed_dag_runs,
+            has_task_concurrency_limits=dag_response.has_task_concurrency_limits,
+            has_import_errors=dag_response.has_import_errors,
+            next_dagrun_logical_date=dag_response.next_dagrun_logical_date,
+            next_dagrun_data_interval_start=dag_response.next_dagrun_data_interval_start,
+            next_dagrun_data_interval_end=dag_response.next_dagrun_data_interval_end,
+            next_dagrun_run_after=dag_response.next_dagrun_run_after,
+            owners=dag_response.owners,
+            file_token=dag_response.file_token,  # Computed field - already computed
+            # Extra fields for DAGWithLatestDagRunsResponse
+            asset_expression=dag.asset_expression,
+            latest_dag_runs=[],
+            pending_actions=pending_actions_by_dag_id[dag.dag_id],
+            is_favorite=dag.dag_id in favorite_dag_ids,

Review Comment:
   Thanks for the feedback! @pierrejeambrun...  I've updated the PR with both suggestions:
   
   1. Module-level serializer: Replaced @lru_cache with a module-level `_FILE_TOKEN_SERIALIZER` constant.
   
   2. Single validation pass: Refactored to use a single` DAGWithLatestDagRunsResponse.model_validate()` call on a dict built from ORM attributes + extra fields. This ensures all fields go through Pydantic validation in one pass while avoiding the double-validation overhead.
   
   Tested locally with ~25 DAGs - the /ui/dags endpoint responds in ~130ms



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Optimize /ui/dags endpoint serialization [airflow]

Posted by "pierrejeambrun (via GitHub)" <gi...@apache.org>.
pierrejeambrun commented on code in PR #61483:
URL: https://github.com/apache/airflow/pull/61483#discussion_r2793830691


##########
airflow-core/src/airflow/api_fastapi/core_api/datamodels/dags.py:
##########
@@ -41,6 +41,14 @@
 if TYPE_CHECKING:
     from airflow.serialization.definitions.param import SerializedParamsDict
 
+
+# Module-level serializer instance for file tokens.
+# This avoids creating a new serializer and calling conf.get_mandatory_value()
+# for every DAG when generating file tokens, which significantly improves
+# performance of the /ui/dags endpoint.
+_FILE_TOKEN_SERIALIZER: URLSafeSerializer = URLSafeSerializer(conf.get_mandatory_value("api", "secret_key"))

Review Comment:
   If you prefer we can yes. There was a cached function originally in this PR and we can go back to that.
   
   I figured it's not needed because there are a lot of places where default parameters for functions are computed from config, and that's done at module level too. 
   
   But it doesn't cost much to put it under a fn



-- 
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: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org