kaxil commented on code in PR #74791:
URL: https://github.com/apache/airflow/pull/74791#discussion_r4468533339


##########
airflow-core/src/airflow/dag_processing/maintenance.py:
##########
@@ -0,0 +1,156 @@
+# 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.
+
+"""Bounded metadata maintenance owned by the scheduler, including absent 
bundles."""
+
+from __future__ import annotations
+
+from datetime import timedelta
+from typing import TYPE_CHECKING
+
+import structlog
+from sqlalchemy import delete, exists, select, tuple_
+
+from airflow._shared.timezones import timezone
+from airflow.dag_processing.timeouts import get_job_heartbeat_timeout
+from airflow.exceptions import AirflowConfigException
+from airflow.jobs.job import Job, JobState
+from airflow.models.dag import DagModel
+from airflow.models.dag_processor_publication_receipt import 
DagProcessorPublicationReceipt
+from airflow.models.dagbundle import DagBundleModel
+from airflow.models.dagwarning import DagWarning
+from airflow.utils.session import create_session
+from airflow.utils.sqlalchemy import with_row_locks
+
+if TYPE_CHECKING:
+    from sqlalchemy.orm import Session
+
+log = structlog.get_logger(__name__)
+
+
+def cleanup_processor_metadata(batch_size: int = 500) -> None:
+    """Drain inactive Dags and retired checkpoints, committing each bounded 
batch."""
+    if batch_size < 1:
+        raise ValueError("batch_size must be positive")
+    while True:
+        with create_session() as session:
+            inactive = 
select(DagBundleModel.name).where(DagBundleModel.active.is_(False))
+            query = (
+                select(DagModel)
+                .where(
+                    DagModel.is_stale.is_(False),
+                    DagModel.bundle_name.in_(inactive),
+                )
+                .order_by(DagModel.dag_id)
+                .limit(batch_size)
+            )
+            dags = session.scalars(with_row_locks(query, session=session, 
skip_locked=True)).all()
+            for dag in dags:
+                log.info(
+                    "Deactivating Dag because its bundle is no longer active",
+                    dag_id=dag.dag_id,
+                    bundle_name=dag.bundle_name,
+                )
+                dag.is_stale = True
+        if len(dags) < batch_size:
+            break
+    # Each key needs two bind parameters; older SQLite versions allow only 999.
+    warning_batch_size = min(batch_size, 499)
+    while True:
+        with create_session() as session:
+            warning_query = (
+                select(DagWarning.dag_id, DagWarning.warning_type)
+                .join(DagModel)
+                .where(
+                    DagModel.is_stale.is_(True),
+                )
+                .order_by(DagWarning.dag_id, DagWarning.warning_type)
+                .limit(warning_batch_size)
+            )
+            keys = session.execute(
+                with_row_locks(warning_query, of=DagWarning, session=session, 
skip_locked=True)
+            ).all()
+            if keys:
+                session.execute(
+                    delete(DagWarning).where(tuple_(DagWarning.dag_id, 
DagWarning.warning_type).in_(keys))
+                )
+        if len(keys) < warning_batch_size:
+            break
+    with create_session() as session:
+        _expire_stale_api_jobs(batch_size, session=session)
+    # Visit already-ended Jobs too: retirement may have committed before 
cleanup was interrupted.
+    checkpoint_batch_size = min(batch_size, 499)

Review Comment:
   This is the same select-keys-then-delete-by-`tuple_` loop as the 
`DagWarning` one above, and the 499 only makes sense next to the SQLite comment 
on line 71. Could the two share one helper, or at least one `key_batch_size` 
under that comment?



##########
airflow-core/src/airflow/config_templates/config.yml:
##########
@@ -2775,7 +2775,9 @@ scheduler:
       description: |
         How often (in seconds) to check for stale DAGs (DAGs which are no 
longer present in
         the expected files) which should be deactivated, as well as assets 
that are no longer
-        referenced and should be marked as orphaned.
+        referenced and should be marked as orphaned. The same cleanup marks 
the Dags of inactive
+        bundles stale, removes stale Dag warnings, and ends Dag processor Jobs 
that
+        exceeded ``[dag_processor] job_heartbeat_timeout``.

Review Comment:
   This reads as if every Dag processor Job gets ended after 
`job_heartbeat_timeout`, but `_expire_stale_api_jobs` only selects Jobs with a 
`session_id`, so DB-mode processors are never expired here. Could it say "ends 
Dag processor Jobs using the Execution API that exceeded ...", matching the 
`job_heartbeat_timeout` description?



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

To unsubscribe, e-mail: [email protected]

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

Reply via email to