You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "seanghaeli (via GitHub)" <gi...@apache.org> on 2025/08/30 00:26:20 UTC

[PR] User average runtime as deadline reference [airflow]

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

   Calculate average of previous dag runtimes to use as a deadline reference. 
   
   Currently initializing it so that if there are no previous dag runs, it will use an average time of 0, but maybe it would be better to throw an error in this case?


-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/tests/unit/models/test_deadline.py:
##########
@@ -375,11 +383,145 @@ def test_deadline_database_integration(self, reference, expected_column, session
             if expected_column is not None:
                 result = reference.evaluate_with(session=session, interval=interval, **conditions)
                 mock_fetch.assert_called_once_with(expected_column, session=session, **conditions)
+            elif reference == DeadlineReference.AVERAGE_RUNTIME():
+                with mock.patch("airflow._shared.timezones.timezone.utcnow") as mock_utcnow:
+                    mock_utcnow.return_value = DEFAULT_DATE
+                    # No DAG runs exist, so it should use 24-hour default
+                    result = reference.evaluate_with(session=session, interval=interval, dag_id=DAG_ID)
+                    mock_fetch.assert_not_called()
+                    # Should return None when no DAG runs exist
+                    assert result is None
             else:
                 result = reference.evaluate_with(session=session, interval=interval)
                 mock_fetch.assert_not_called()
+                assert result == DEFAULT_DATE + interval
+
+    @pytest.mark.usefixtures("freeze_time")
+    def test_average_runtime_with_sufficient_history(self, session, dag_maker):
+        """Test AverageRuntimeDeadline when enough historical data exists."""
+        with dag_maker(DAG_ID):
+            EmptyOperator(task_id="test_task")
+
+        # Create 10 completed DAG runs with known durations
+        base_time = DEFAULT_DATE
+        durations = [3600, 7200, 1800, 5400, 2700, 4500, 3300, 6000, 2400, 4200]
+
+        for i, duration in enumerate(durations):
+            logical_date = base_time + timedelta(days=i)
+            start_time = logical_date + timedelta(minutes=5)
+            end_time = start_time + timedelta(seconds=duration)
+
+            dagrun = dag_maker.create_dagrun(
+                logical_date=logical_date, run_id=f"test_run_{i}", state=DagRunState.SUCCESS
+            )
+            # Manually set start and end times
+            dagrun.start_date = start_time
+            dagrun.end_date = end_time
+
+        session.commit()
+
+        # Test with default limit (10)
+        reference = DeadlineReference.AVERAGE_RUNTIME()
+        interval = timedelta(hours=1)
+
+        with mock.patch("airflow._shared.timezones.timezone.utcnow") as mock_utcnow:
+            mock_utcnow.return_value = DEFAULT_DATE
+            result = reference.evaluate_with(session=session, interval=interval, dag_id=DAG_ID)
+
+            # Calculate expected average: sum(durations) / len(durations)
+            expected_avg_seconds = sum(durations) / len(durations)
+            expected = DEFAULT_DATE + timedelta(seconds=expected_avg_seconds) + interval
+
+            # Compare only up to minutes to avoid sub-second timing issues in CI
+            assert result.replace(second=0, microsecond=0) == expected.replace(second=0, microsecond=0)

Review Comment:
   If you are doing this, do you still need the freeze_time fixture?  Seems like you should only need to do one or the other.



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +366,64 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        limit: int
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit
+            query = query.limit(self.limit)
+
+            # Get all durations and calculate average
+            durations = session.execute(query).scalars().all()
+
+            if len(durations) < self.limit:
+                logger.warning(
+                    "Only %d completed DAG runs found for dag_id: %s (need %d), using 24 hour default",

Review Comment:
   Nitpick:  I wonder if we should preface the message with something, there is no indication there that this is related to calculating the deadline.



-- 
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] User average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -355,6 +355,31 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            query = select(func.avg(func.extract("epoch", DagRun.end_date - DagRun.start_date))).filter(
+                DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None)
+            )
+
+            avg_seconds = session.execute(query).scalar()

Review Comment:
   We discussed a few variants of this including rolling averages, average by dag version, average since a given datetime, average since a given dagrun_id, etc.  I think we decided to do this as the basic one then add a parameterized version that accepts a dict of conditions that get assembled into `WHERE` clauses.  Would you be cool with that approach?



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +366,64 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        limit: int
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit
+            query = query.limit(self.limit)
+
+            # Get all durations and calculate average
+            durations = session.execute(query).scalars().all()
+
+            if len(durations) < self.limit:
+                logger.warning(
+                    "Only %d completed DAG runs found for dag_id: %s (need %d), using 24 hour default",
+                    len(durations),
+                    dag_id,
+                    self.limit,
+                )
+                avg_seconds = 48 * 3600  # 48 hours as default
+            else:
+                avg_seconds = sum(durations) / len(durations)
+                logger.info(
+                    "Average runtime for dag_id %s (from %d runs): %.2f seconds",
+                    dag_id,
+                    len(durations),
+                    avg_seconds,
+                )
+                with open("/temporary.txt", "a") as f:
+                    f.write(f"Calculated average: {avg_seconds} seconds\n")

Review Comment:
   Is this meant to be here or was that for debugging?



-- 
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] User average runtime as deadline reference [airflow]

Posted by "o-nikolas (via GitHub)" <gi...@apache.org>.
o-nikolas commented on code in PR #55088:
URL: https://github.com/apache/airflow/pull/55088#discussion_r2320340939


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -355,6 +355,31 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            query = select(func.avg(func.extract("epoch", DagRun.end_date - DagRun.start_date))).filter(
+                DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None)
+            )
+
+            avg_seconds = session.execute(query).scalar()

Review Comment:
   Maybe just take an `int` for now that specifies how many runs back to look, and then in the future you can pair that with the different kinds of _what_ it looks for (per dag_version etc)



-- 
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] User average runtime as deadline reference [airflow]

Posted by "o-nikolas (via GitHub)" <gi...@apache.org>.
o-nikolas commented on code in PR #55088:
URL: https://github.com/apache/airflow/pull/55088#discussion_r2320298677


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -355,6 +355,31 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            query = select(func.avg(func.extract("epoch", DagRun.end_date - DagRun.start_date))).filter(
+                DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None)
+            )
+
+            avg_seconds = session.execute(query).scalar()

Review Comment:
   I think you'll want to put a count restriction on that so that you have a rolling window. Otherwise the average will be increasingly difficult to change over time and won't react well if the dag structure or underlying code/infrastructure changes.



-- 
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] User average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -355,6 +355,31 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            query = select(func.avg(func.extract("epoch", DagRun.end_date - DagRun.start_date))).filter(
+                DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None)
+            )
+
+            avg_seconds = session.execute(query).scalar()

Review Comment:
   Optional int with a default, so the minimal UX is simplified?



-- 
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] User average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -355,6 +355,31 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            query = select(func.avg(func.extract("epoch", DagRun.end_date - DagRun.start_date))).filter(
+                DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None)
+            )
+
+            avg_seconds = session.execute(query).scalar()

Review Comment:
   Okay, that makes sense



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +366,64 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        limit: int
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit
+            query = query.limit(self.limit)
+
+            # Get all durations and calculate average
+            durations = session.execute(query).scalars().all()
+
+            if len(durations) < self.limit:
+                logger.warning(
+                    "Only %d completed DAG runs found for dag_id: %s (need %d), using 24 hour default",
+                    len(durations),
+                    dag_id,
+                    self.limit,
+                )
+                avg_seconds = 48 * 3600  # 48 hours as default

Review Comment:
   Maybe I'm missing something, in L398 you say "using 24 hour default" but here you are setting it to 48 hours?



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +366,62 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        DEFAULT_LIMIT = 10
+        limit: int
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit
+            query = query.limit(self.limit)
+
+            # Get all durations and calculate average
+            durations = session.execute(query).scalars().all()
+
+            if len(durations) < self.limit:
+                logger.warning(
+                    "In the AverageRuntimeDeadline: Only %d completed DAG runs found for dag_id: %s (need %d), using 48 hour default",
+                    len(durations),
+                    dag_id,
+                    self.limit,
+                )
+                avg_seconds = 48 * 3600  # 48 hours as default

Review Comment:
   Had a chat with Sean offline, he's going to add a min-number-of-records, so the logic will be:
   
   - Query the db for up to `max_records` number of historical durations
   - If the resulting list is less than `min_records` then return None (no deadline set); else use the average of that you have.
   
   The min will default to the max unless the user overrides it.  So in practice:
   
   | min_records | max_records | Result                                                                                                                                  |
   |-------------|-------------|-----------------------------------------------------------------------------------------------------------------------------------------|
   | 10          | 10          | No failures until run 11 which uses he average of the 10 previous                                                                       |
   | 1           | 10          | First run can not fail, second run fails if it runs longer than the first, third run averages the  previous two, etc up to 10                                                                    |
   | 5           | 10          | First 5 can not fail, run 6 uses the average of the 5 previous values, run 7 - 10 build up that average, run 11 uses the 10-run average |



-- 
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] User average runtime as deadline reference [airflow]

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

   > Currently initializing it so that if there are no previous dag runs, it will use an average time of 0, but maybe it would be better to throw an error in this case?
   
   Yeah, that seems like a sharp corner users are going to bump into. I wonder if it should just do nothing (log a warning saying so) until you reach the window of time you're using for your rolling average? 
   
   


-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +366,64 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        limit: int
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit
+            query = query.limit(self.limit)
+
+            # Get all durations and calculate average
+            durations = session.execute(query).scalars().all()
+
+            if len(durations) < self.limit:
+                logger.warning(
+                    "Only %d completed DAG runs found for dag_id: %s (need %d), using 24 hour default",
+                    len(durations),
+                    dag_id,
+                    self.limit,
+                )
+                avg_seconds = 48 * 3600  # 48 hours as default
+            else:
+                avg_seconds = sum(durations) / len(durations)
+                logger.info(
+                    "Average runtime for dag_id %s (from %d runs): %.2f seconds",
+                    dag_id,
+                    len(durations),
+                    avg_seconds,
+                )
+                with open("/temporary.txt", "a") as f:
+                    f.write(f"Calculated average: {avg_seconds} seconds\n")
+
+            return timezone.utcnow() + timedelta(seconds=avg_seconds)
+
+        def serialize_reference(self) -> dict:
+            return {
+                ReferenceModels.REFERENCE_TYPE_FIELD: self.reference_name,
+                "limit": self.limit,
+            }
+
+        @classmethod
+        def deserialize_reference(cls, reference_data: dict):
+            return cls(limit=reference_data.get("limit", 10))

Review Comment:
   IF we're going to put the default value in there, then I think it should be a constant somewhere so it stays in sync with the actual method's default, especially since they are in different files and would be easy to miss if we change one later.



-- 
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] Use average runtime as deadline reference [airflow]

Posted by "o-nikolas (via GitHub)" <gi...@apache.org>.
o-nikolas commented on code in PR #55088:
URL: https://github.com/apache/airflow/pull/55088#discussion_r2350255295


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -283,7 +283,7 @@ class BaseDeadlineReference(LoggingMixin, ABC):
         def reference_name(cls: Any) -> str:
             return cls.__name__
 
-        def evaluate_with(self, *, session: Session, interval: timedelta, **kwargs: Any) -> datetime:
+        def evaluate_with(self, *, session: Session, interval: timedelta, **kwargs: Any) -> datetime | None:

Review Comment:
   The caller(s) of `evaluate_with` need(s) updating now right?



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +367,76 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        DEFAULT_LIMIT = 10
+        limit: int
+        min_runs: int | None = None
+        required_kwargs = {"dag_id"}
+
+        def __post_init__(self):
+            if self.min_runs is None:
+                self.min_runs = self.limit
+            if self.min_runs < 1:
+                raise ValueError("min_runs must be at least 1")
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime | None:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit
+            query = query.limit(self.limit)
+
+            # Get all durations and calculate average
+            durations = session.execute(query).scalars().all()
+
+            if len(durations) < cast("int", self.min_runs):
+                logger.info(
+                    "Only %d completed DAG runs found for dag_id: %s (need %d), skipping deadline creation",
+                    len(durations),
+                    dag_id,
+                    self.min_runs,
+                )
+                return None
+            avg_seconds = sum(durations) / len(durations)
+            logger.info(
+                "Average runtime for dag_id %s (from %d runs): %.2f seconds",
+                dag_id,
+                len(durations),
+                avg_seconds,
+            )
+            return timezone.utcnow() + timedelta(seconds=avg_seconds)

Review Comment:
   `DeadlineReference.AVERAGE_RUNTIME()` doesn't do anything with `interval` right now.  Did you intend to add the provided interval to the average as a buffer?  The docs and tests seem to indicate that was the intent, but I don't see where it's happening.  Which also makes me wonder how those unit tests are passing.



##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +367,76 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        DEFAULT_LIMIT = 10
+        limit: int

Review Comment:
   Feel free to just resolve, but I'd suggest `max_runs` instead of `limit` to match your new parameter name.



##########
airflow-core/tests/unit/models/test_deadline.py:
##########
@@ -375,11 +377,140 @@ def test_deadline_database_integration(self, reference, expected_column, session
             if expected_column is not None:
                 result = reference.evaluate_with(session=session, interval=interval, **conditions)
                 mock_fetch.assert_called_once_with(expected_column, session=session, **conditions)
+            elif reference == DeadlineReference.AVERAGE_RUNTIME():
+                with mock.patch("airflow._shared.timezones.timezone.utcnow") as mock_utcnow:
+                    mock_utcnow.return_value = DEFAULT_DATE
+                    # No DAG runs exist, so it should use 24-hour default
+                    result = reference.evaluate_with(session=session, interval=interval, dag_id=DAG_ID)
+                    mock_fetch.assert_not_called()
+                    # Should return None when no DAG runs exist
+                    assert result is None

Review Comment:
   This needs to be updated now right, at least the comment about the 24-hour default?



##########
airflow-core/docs/howto/deadline-alerts.rst:
##########
@@ -97,6 +97,55 @@ Airflow provides several built-in reference points that you can use with Deadlin
 ``DeadlineReference.FIXED_DATETIME``
     Specifies a fixed point in time. Useful when Dags must complete by a specific time.
 
+``DeadlineReference.AVERAGE_RUNTIME``
+    Calculates deadlines based on the average runtime of previous DAG runs. This reference
+    analyzes historical execution data to predict when the current run should complete.
+    The deadline is set to the current time plus the calculated average runtime plus the interval.
+    If insufficient historical data exists, no deadline is created.
+
+    Parameters:
+        * ``limit`` (int, optional): Maximum number of recent DAG runs to analyze. Defaults to 10.
+        * ``min_runs`` (int, optional): Minimum number of completed runs required to calculate average. Defaults to same value as ``limit``.
+
+    Example usage:
+
+    .. code-block:: python
+
+        # Use default settings (analyze up to 10 runs, require 10 runs)
+        DeadlineReference.AVERAGE_RUNTIME()
+
+        # Analyze up to 20 runs but calculate with minimum 5 runs
+        DeadlineReference.AVERAGE_RUNTIME(limit=20, min_runs=5)
+
+        # Strict: require exactly 15 runs to calculate
+        DeadlineReference.AVERAGE_RUNTIME(limit=15, min_runs=15)
+
+Here's an example using average runtime:
+
+.. code-block:: python
+
+    with DAG(
+        dag_id="average_runtime_deadline",
+        deadline=DeadlineAlert(
+            reference=DeadlineReference.AVERAGE_RUNTIME(limit=15, min_runs=5),
+            interval=timedelta(minutes=30),  # Alert if 30 minutes past expected completion
+            callback=AsyncCallback(
+                SlackWebhookNotifier,
+                kwargs={"text": "🚨 DAG {{ dag_run.dag_id }} is running longer than expected!"},
+            ),
+        ),
+    ):
+        EmptyOperator(task_id="data_processing")
+
+The timeline for this example would look like this:
+
+::
+
+    |------|----------|---------|------------|--------|
+         Queued     Start    Expected    Deadline
+         09:00      09:05     09:35       10:05
+                              (avg+30min)
+

Review Comment:
   Could just be me, but this timeline is confusing me.  Maybe consider something like this??
   
   
   ```
   If the calculated historical average was 30 minutes, the timeline for this example would look like this:
   
   ::
   
       |------|----------|--------------|--------------|--------|
            Queued     Start            |           Deadline
            09:00      09:05          09:35          10:05
                         |              |              |
                         |--- Average --|-- Interval --|
                              (30 min)      (30 min)
   
   ```



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/docs/howto/deadline-alerts.rst:
##########
@@ -72,14 +72,6 @@ Below is an example Dag implementation. If the Dag has not finished 15 minutes a
     ):
         EmptyOperator(task_id="example_task")
 
-The timeline for this example would look like this:
-
-::
-
-    |------|-----------|---------|-----------|--------|
-        Scheduled    Queued    Started    Deadline
-         00:00       00:03      00:05      00:18
-

Review Comment:
   Why was this timeline removed?  It's still a valid timeline for the above example, right?



-- 
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] User average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -355,6 +355,31 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            query = select(func.avg(func.extract("epoch", DagRun.end_date - DagRun.start_date))).filter(
+                DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None)
+            )
+
+            avg_seconds = session.execute(query).scalar()

Review Comment:
   That makes sense, I can see where you are coming from.   How would you feel about an optional int with a default, so the minimal UX is simplified?



-- 
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] User average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -355,6 +355,31 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            query = select(func.avg(func.extract("epoch", DagRun.end_date - DagRun.start_date))).filter(
+                DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None)
+            )
+
+            avg_seconds = session.execute(query).scalar()

Review Comment:
   And when there are less dag runs than the rolling average number, the deadline would just throw a warning and do nothing?



-- 
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] User average runtime as deadline reference [airflow]

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

   Looks like you need to adjust some test(s) to account for the "list of deadlines" PR perhaps?


-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +366,62 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        DEFAULT_LIMIT = 10
+        limit: int
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit
+            query = query.limit(self.limit)
+
+            # Get all durations and calculate average
+            durations = session.execute(query).scalars().all()
+
+            if len(durations) < self.limit:
+                logger.warning(
+                    "In the AverageRuntimeDeadline: Only %d completed DAG runs found for dag_id: %s (need %d), using 48 hour default",
+                    len(durations),
+                    dag_id,
+                    self.limit,
+                )
+                avg_seconds = 48 * 3600  # 48 hours as default

Review Comment:
   Had a chat with Sean offline, he's going to add a min-number-of-records, so the logic will be:
   
   - Query the db for up to `max_records` number of historical durations
   - If the resulting list is less than `min_records` then return None (no deadline set); else use the average of what you have.
   
   The min will default to the max unless the user overrides it.  So in practice:
   
   | min_records | max_records | Result                                                                                                                                  |
   |-------------|-------------|-----------------------------------------------------------------------------------------------------------------------------------------|
   | not set     | 10          | No failures until run 11 which uses the average of the 10 previous                                                                       |
   | 10          | 10          | No failures until run 11 which uses the average of the 10 previous                                                                       |
   | 1           | 10          | First run can not fail, second run fails if it runs longer than the first, third run averages the previous two, etc up to 10                                                               |
   | 5           | 10          | First 5 can not fail, run 6 uses the average of the 5 previous values, run 7 - 10 build up that average, run 11 uses the 10-run average |



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/docs/howto/deadline-alerts.rst:
##########
@@ -97,6 +100,55 @@ Airflow provides several built-in reference points that you can use with Deadlin
 ``DeadlineReference.FIXED_DATETIME``
     Specifies a fixed point in time. Useful when Dags must complete by a specific time.
 
+``DeadlineReference.AVERAGE_RUNTIME``
+    Calculates deadlines based on the average runtime of previous DAG runs. This reference
+    analyzes historical execution data to predict when the current run should complete.
+    The deadline is set to the current time plus the calculated average runtime plus the interval.
+    If insufficient historical data exists, no deadline is created.
+
+    Parameters:
+        * ``limit`` (int, optional): Maximum number of recent DAG runs to analyze. Defaults to 10.
+        * ``min_runs`` (int, optional): Minimum number of completed runs required to calculate average. Defaults to same value as ``limit``.
+
+    Example usage:
+
+    .. code-block:: python
+
+        # Use default settings (analyze up to 10 runs, require 10 runs)
+        DeadlineReference.AVERAGE_RUNTIME()
+
+        # Analyze up to 20 runs but calculate with minimum 5 runs
+        DeadlineReference.AVERAGE_RUNTIME(limit=20, min_runs=5)
+
+        # Strict: require exactly 15 runs to calculate
+        DeadlineReference.AVERAGE_RUNTIME(limit=15, min_runs=15)
+
+Here's an example using average runtime:
+
+.. code-block:: python
+
+    with DAG(
+        dag_id="average_runtime_deadline",
+        deadline=DeadlineAlert(
+            reference=DeadlineReference.AVERAGE_RUNTIME(limit=15, min_runs=5),
+            interval=timedelta(minutes=30),  # Alert if 30 minutes past expected completion
+            callback=AsyncCallback(
+                SlackWebhookNotifier,
+                kwargs={"text": "🚨 DAG {{ dag_run.dag_id }} is running longer than expected!"},
+            ),
+        ),
+    ):
+        EmptyOperator(task_id="data_processing")
+
+The timeline for this example would look like this:
+
+::
+
+    |------|----------|---------|------------|--------|
+         Queued     Start    Expected    Deadline
+         09:00      09:05     09:35       10:05
+                              (avg+30min)

Review Comment:
   Ah, yup, something got weird there. I think the above example can be moved down to replace this one.



-- 
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] Use average DAG run execution times as deadline reference [airflow]

Posted by "o-nikolas (via GitHub)" <gi...@apache.org>.
o-nikolas commented on code in PR #55088:
URL: https://github.com/apache/airflow/pull/55088#discussion_r2330883810


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -355,6 +355,52 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+            limit = kwargs.get("limit", 10)  # Default to 10 runs if not specified
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit (defaults to 10)
+            query = query.limit(limit)
+            logger.info(

Review Comment:
   Is this going to log on each dag parse? We might want to switch this to debug



##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -355,6 +355,52 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+            limit = kwargs.get("limit", 10)  # Default to 10 runs if not specified
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit (defaults to 10)
+            query = query.limit(limit)
+            logger.info(
+                "Limiting average runtime calculation to latest %d runs for dag_id: %s", limit, dag_id
+            )
+
+            # Get all durations and calculate average
+            durations = session.execute(query).scalars().all()
+
+            if not durations:
+                logger.warning(
+                    "In the AverageRuntimeDeadline, no completed DAG runs found for dag_id: %s, defaulting to 0 seconds",
+                    dag_id,
+                )
+                avg_seconds = 0

Review Comment:
   Doesn't this mean the deadline will fire immediately? I think we should return whatever a "Truthy" value we need to in this case (so that the deadline is guaranteed not to fire) to ensure it doesn't auto fail until we've reached the limit and can calculate a good average?



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
providers/edge3/src/airflow/providers/edge3/plugins/www/__init__.py:
##########
@@ -0,0 +1,16 @@
+# Licensed to the Apache Software Foundation (ASF) under one

Review Comment:
   It looks like this file was created accidentally?



##########
airflow-core/tests/unit/models/test_deadline.py:
##########
@@ -371,11 +373,25 @@ def test_deadline_database_integration(self, reference, expected_column, session
             if expected_column is not None:
                 result = reference.evaluate_with(session=session, interval=interval, **conditions)
                 mock_fetch.assert_called_once_with(expected_column, session=session, **conditions)
+            elif reference == DeadlineReference.AVERAGE_RUNTIME:
+                with mock.patch("airflow._shared.timezones.timezone.utcnow") as mock_utcnow:
+                    mock_utcnow.return_value = DEFAULT_DATE
+                    with mock.patch.object(session, "execute") as mock_execute:

Review Comment:
   It looks like this a DB test so I'm not sure if we should be mocking session.execute



-- 
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] User average runtime as deadline reference [airflow]

Posted by "o-nikolas (via GitHub)" <gi...@apache.org>.
o-nikolas commented on code in PR #55088:
URL: https://github.com/apache/airflow/pull/55088#discussion_r2320339872


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -355,6 +355,31 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            query = select(func.avg(func.extract("epoch", DagRun.end_date - DagRun.start_date))).filter(
+                DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None)
+            )
+
+            avg_seconds = session.execute(query).scalar()

Review Comment:
   I like the iterative approach! But I think the default one we go with for now should be some kind of rolling average (probably, again in the name of simplicity like you were shooting for, just use the last N dag runs, and don't factor in dag versions etc yet). After you get a lot of dag runs this deadline type will become almost unusable since the weight of all of history will make the average difficult to move.



-- 
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] User average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -355,6 +355,31 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            query = select(func.avg(func.extract("epoch", DagRun.end_date - DagRun.start_date))).filter(
+                DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None)
+            )
+
+            avg_seconds = session.execute(query).scalar()

Review Comment:
   Got it. Implementation is now in this PR.



-- 
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] User average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -355,6 +355,31 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            query = select(func.avg(func.extract("epoch", DagRun.end_date - DagRun.start_date))).filter(
+                DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None)
+            )
+
+            avg_seconds = session.execute(query).scalar()

Review Comment:
   And under that rolling average number, the deadline would just throw a warning and do nothing?



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/docs/howto/deadline-alerts.rst:
##########
@@ -72,13 +72,16 @@ Below is an example Dag implementation. If the Dag has not finished 15 minutes a
     ):
         EmptyOperator(task_id="example_task")
 
-The timeline for this example would look like this:
+If the calculated historical average was 30 minutes, the timeline for this example would look like this:

Review Comment:
   The example right above uses DeadlineReference.DAGRUN_QUEUED_AT so it seems like this was added here instead of further down accidentally?



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/tests/unit/models/test_deadline.py:
##########
@@ -371,11 +373,25 @@ def test_deadline_database_integration(self, reference, expected_column, session
             if expected_column is not None:
                 result = reference.evaluate_with(session=session, interval=interval, **conditions)
                 mock_fetch.assert_called_once_with(expected_column, session=session, **conditions)
+            elif reference == DeadlineReference.AVERAGE_RUNTIME:
+                with mock.patch("airflow._shared.timezones.timezone.utcnow") as mock_utcnow:
+                    mock_utcnow.return_value = DEFAULT_DATE
+                    with mock.patch.object(session, "execute") as mock_execute:

Review Comment:
   It looks like this is a DB test so I'm not sure if we should be mocking session.execute



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +366,62 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        DEFAULT_LIMIT = 10
+        limit: int
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit
+            query = query.limit(self.limit)
+
+            # Get all durations and calculate average
+            durations = session.execute(query).scalars().all()
+
+            if len(durations) < self.limit:
+                logger.warning(
+                    "In the AverageRuntimeDeadline: Only %d completed DAG runs found for dag_id: %s (need %d), using 48 hour default",
+                    len(durations),
+                    dag_id,
+                    self.limit,
+                )
+                avg_seconds = 48 * 3600  # 48 hours as default

Review Comment:
   @ferruzzi do you know if this is doable?



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +366,62 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        DEFAULT_LIMIT = 10
+        limit: int
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit
+            query = query.limit(self.limit)
+
+            # Get all durations and calculate average
+            durations = session.execute(query).scalars().all()
+
+            if len(durations) < self.limit:
+                logger.warning(
+                    "In the AverageRuntimeDeadline: Only %d completed DAG runs found for dag_id: %s (need %d), using 48 hour default",
+                    len(durations),
+                    dag_id,
+                    self.limit,
+                )
+                avg_seconds = 48 * 3600  # 48 hours as default

Review Comment:
   This is in _evaluate_with which returns the calculated deadline timestamp which then gets written to the `deadline` database, right?  Then, later, the scheduler checks this table to see if any of these calculated values are in the past and handles any that are.  An easy answer then could be to return a specific datetime which the scheduler never considers a miss, maybe `datetime.datetime(datetime.MINYEAR, 1, 1, 0, 0, 0, 0)` but this feels like a hack... I think the better way would be to add a mechanism to skip the "write the calculated deadline to the DB" step if there is no historical data.  That could maybe be as simple as making _evaluate_with return `datetime | None` and then check `if None` before adding it to the deadline table?



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +366,62 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        DEFAULT_LIMIT = 10
+        limit: int
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit
+            query = query.limit(self.limit)
+
+            # Get all durations and calculate average
+            durations = session.execute(query).scalars().all()
+
+            if len(durations) < self.limit:
+                logger.warning(
+                    "In the AverageRuntimeDeadline: Only %d completed DAG runs found for dag_id: %s (need %d), using 48 hour default",
+                    len(durations),
+                    dag_id,
+                    self.limit,
+                )
+                avg_seconds = 48 * 3600  # 48 hours as default

Review Comment:
   Had a chat with Sean offline, he's going to rename "limit" to be a max-number-of-records and add an optional min-number-of-records which defaults to the same value, so the logic will be:
   
   - Query the db for up to `max_records` number of historical durations
   - If the resulting list is less than `min_records` then return None (no deadline set); else use the average of what you have.
   
   The min will default to the max unless the user overrides it.  So in practice:
   
   | min_records | max_records | Result                                                                                                                                  |
   |-------------|-------------|-----------------------------------------------------------------------------------------------------------------------------------------|
   | not set     | 10          | No failures until run 11 which uses the average of the 10 previous                                                                       |
   | 10          | 10          | No failures until run 11 which uses the average of the 10 previous                                                                       |
   | 1           | 10          | First run can not fail, second run fails if it runs longer than the first, third run averages the previous two, etc up to 10                                                               |
   | 5           | 10          | First 5 can not fail, run 6 uses the average of the 5 previous values, run 7 - 10 build up that average, run 11 uses the 10-run average |



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +367,76 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        DEFAULT_LIMIT = 10
+        limit: int
+        min_runs: int | None = None
+        required_kwargs = {"dag_id"}
+
+        def __post_init__(self):
+            if self.min_runs is None:
+                self.min_runs = self.limit
+            if self.min_runs < 1:
+                raise ValueError("min_runs must be at least 1")
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime | None:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit
+            query = query.limit(self.limit)
+
+            # Get all durations and calculate average
+            durations = session.execute(query).scalars().all()
+
+            if len(durations) < cast("int", self.min_runs):
+                logger.info(
+                    "Only %d completed DAG runs found for dag_id: %s (need %d), skipping deadline creation",
+                    len(durations),
+                    dag_id,
+                    self.min_runs,
+                )
+                return None
+            avg_seconds = sum(durations) / len(durations)
+            logger.info(
+                "Average runtime for dag_id %s (from %d runs): %.2f seconds",
+                dag_id,
+                len(durations),
+                avg_seconds,
+            )
+            return timezone.utcnow() + timedelta(seconds=avg_seconds)

Review Comment:
   Interval is added in the base class's `evaluate_with` after the child class's `_evaluate_with` returns.  My mistake.



-- 
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] Use average runtime as deadline reference [airflow]

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

   Need to update a unit test, will do that in the next few hours and then this will be mergeable


-- 
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] Use average runtime as deadline reference [airflow]

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


-- 
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] User average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -355,6 +355,31 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            query = select(func.avg(func.extract("epoch", DagRun.end_date - DagRun.start_date))).filter(
+                DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None)
+            )
+
+            avg_seconds = session.execute(query).scalar()

Review Comment:
   That makes sense, I can see where you are coming from.   How would you feel about an optional int with a default (I don't know, maybe 30 runs?), so the minimal UX is simplified?



-- 
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] User average runtime as deadline reference [airflow]

Posted by "o-nikolas (via GitHub)" <gi...@apache.org>.
o-nikolas commented on code in PR #55088:
URL: https://github.com/apache/airflow/pull/55088#discussion_r2320520849


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -355,6 +355,31 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            query = select(func.avg(func.extract("epoch", DagRun.end_date - DagRun.start_date))).filter(
+                DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None)
+            )
+
+            avg_seconds = session.execute(query).scalar()

Review Comment:
   We can't error on zero otherwise we'll never get past zero right? I think the best we can do is log a warning saying that we can't yet compute and average.
   
   Then it's up to documentation to instruct people ("hey, you really should only add this deadline to an established dag") but surely people will not follow that (and can't in all cases of deploying dags via ci/cd).
   



-- 
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] User average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -355,6 +355,31 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            query = select(func.avg(func.extract("epoch", DagRun.end_date - DagRun.start_date))).filter(
+                DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None)
+            )
+
+            avg_seconds = session.execute(query).scalar()

Review Comment:
   I guess error on 0, otherwise treat the value as a cap?
   
   I'm still not sure what makes the most sense for the first run here, TBH other than "if there is no precedent then it can't possibly fail"



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/docs/howto/deadline-alerts.rst:
##########
@@ -97,6 +100,55 @@ Airflow provides several built-in reference points that you can use with Deadlin
 ``DeadlineReference.FIXED_DATETIME``
     Specifies a fixed point in time. Useful when Dags must complete by a specific time.
 
+``DeadlineReference.AVERAGE_RUNTIME``
+    Calculates deadlines based on the average runtime of previous DAG runs. This reference
+    analyzes historical execution data to predict when the current run should complete.
+    The deadline is set to the current time plus the calculated average runtime plus the interval.
+    If insufficient historical data exists, no deadline is created.
+
+    Parameters:
+        * ``limit`` (int, optional): Maximum number of recent DAG runs to analyze. Defaults to 10.
+        * ``min_runs`` (int, optional): Minimum number of completed runs required to calculate average. Defaults to same value as ``limit``.
+
+    Example usage:
+
+    .. code-block:: python
+
+        # Use default settings (analyze up to 10 runs, require 10 runs)
+        DeadlineReference.AVERAGE_RUNTIME()
+
+        # Analyze up to 20 runs but calculate with minimum 5 runs
+        DeadlineReference.AVERAGE_RUNTIME(limit=20, min_runs=5)
+
+        # Strict: require exactly 15 runs to calculate
+        DeadlineReference.AVERAGE_RUNTIME(limit=15, min_runs=15)
+
+Here's an example using average runtime:
+
+.. code-block:: python
+
+    with DAG(
+        dag_id="average_runtime_deadline",
+        deadline=DeadlineAlert(
+            reference=DeadlineReference.AVERAGE_RUNTIME(limit=15, min_runs=5),
+            interval=timedelta(minutes=30),  # Alert if 30 minutes past expected completion
+            callback=AsyncCallback(
+                SlackWebhookNotifier,
+                kwargs={"text": "🚨 DAG {{ dag_run.dag_id }} is running longer than expected!"},
+            ),
+        ),
+    ):
+        EmptyOperator(task_id="data_processing")
+
+The timeline for this example would look like this:
+
+::
+
+    |------|----------|---------|------------|--------|
+         Queued     Start    Expected    Deadline
+         09:00      09:05     09:35       10:05
+                              (avg+30min)

Review Comment:
   I think you are looking at an older version, that's been changed already



-- 
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] Use average runtime as deadline reference [airflow]

Posted by "o-nikolas (via GitHub)" <gi...@apache.org>.
o-nikolas commented on code in PR #55088:
URL: https://github.com/apache/airflow/pull/55088#discussion_r2350216427


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +366,62 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        DEFAULT_LIMIT = 10
+        limit: int
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit
+            query = query.limit(self.limit)
+
+            # Get all durations and calculate average
+            durations = session.execute(query).scalars().all()
+
+            if len(durations) < self.limit:
+                logger.warning(
+                    "In the AverageRuntimeDeadline: Only %d completed DAG runs found for dag_id: %s (need %d), using 48 hour default",
+                    len(durations),
+                    dag_id,
+                    self.limit,
+                )
+                avg_seconds = 48 * 3600  # 48 hours as default

Review Comment:
   I still think we should not make up a default deadline that will likely not work for any users. Is it not possible to just disable the Deadline if we don't have enough data points? Return None or something like that and the rest of the deadline logic would know to discard this deadline?
   
   I'm not going to die on this hill if you and @ferruzzi prefer it this way though. 



##########
airflow-core/tests/unit/models/test_deadline.py:
##########
@@ -371,11 +373,25 @@ def test_deadline_database_integration(self, reference, expected_column, session
             if expected_column is not None:
                 result = reference.evaluate_with(session=session, interval=interval, **conditions)
                 mock_fetch.assert_called_once_with(expected_column, session=session, **conditions)
+            elif reference == DeadlineReference.AVERAGE_RUNTIME:
+                with mock.patch("airflow._shared.timezones.timezone.utcnow") as mock_utcnow:
+                    mock_utcnow.return_value = DEFAULT_DATE
+                    with mock.patch.object(session, "execute") as mock_execute:

Review Comment:
   What was the resolution on this? I see it was resolved but I don't see any replies here and the code seems to still be mocking session.execute?



##########
airflow-core/tests/unit/models/test_deadline.py:
##########
@@ -375,11 +377,25 @@ def test_deadline_database_integration(self, reference, expected_column, session
             if expected_column is not None:
                 result = reference.evaluate_with(session=session, interval=interval, **conditions)
                 mock_fetch.assert_called_once_with(expected_column, session=session, **conditions)
+            elif reference == DeadlineReference.AVERAGE_RUNTIME():
+                with mock.patch("airflow._shared.timezones.timezone.utcnow") as mock_utcnow:
+                    mock_utcnow.return_value = DEFAULT_DATE
+                    with mock.patch.object(session, "execute") as mock_execute:
+                        # Mock the result object that execute() returns
+                        mock_result = mock.Mock()
+                        mock_scalars = mock.Mock()
+                        mock_scalars.all.return_value = [3600]
+                        mock_result.scalars.return_value = mock_scalars
+                        mock_execute.return_value = mock_result
+                        result = reference.evaluate_with(session=session, interval=interval, dag_id=DAG_ID)
+                        mock_fetch.assert_not_called()
+                        # Should be DEFAULT_DATE + default average deadline of 48 hours + the 1 hour mocked execution time

Review Comment:
   This is testing the path of the default, but where is the test for the path where we have enough history to compute an average?



-- 
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] Use average runtime as deadline reference [airflow]

Posted by "o-nikolas (via GitHub)" <gi...@apache.org>.
o-nikolas commented on code in PR #55088:
URL: https://github.com/apache/airflow/pull/55088#discussion_r2350251547


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +366,62 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        DEFAULT_LIMIT = 10
+        limit: int
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit
+            query = query.limit(self.limit)
+
+            # Get all durations and calculate average
+            durations = session.execute(query).scalars().all()
+
+            if len(durations) < self.limit:
+                logger.warning(
+                    "In the AverageRuntimeDeadline: Only %d completed DAG runs found for dag_id: %s (need %d), using 48 hour default",
+                    len(durations),
+                    dag_id,
+                    self.limit,
+                )
+                avg_seconds = 48 * 3600  # 48 hours as default

Review Comment:
   Agreed with that order of thinking
   



-- 
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] Use average runtime as deadline reference [airflow]

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

   Whoops, pushed a bad rebase. Please ignore if you got pinged, sorry!


-- 
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] User average runtime as deadline reference [airflow]

Posted by "o-nikolas (via GitHub)" <gi...@apache.org>.
o-nikolas commented on code in PR #55088:
URL: https://github.com/apache/airflow/pull/55088#discussion_r2320479327


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -355,6 +355,31 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            query = select(func.avg(func.extract("epoch", DagRun.end_date - DagRun.start_date))).filter(
+                DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None)
+            )
+
+            avg_seconds = session.execute(query).scalar()

Review Comment:
   Yup that sounds great, a default for sure. Some low number in the tens of runs range (30, 20 or even 10)
   



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/docs/howto/deadline-alerts.rst:
##########
@@ -97,6 +100,55 @@ Airflow provides several built-in reference points that you can use with Deadlin
 ``DeadlineReference.FIXED_DATETIME``
     Specifies a fixed point in time. Useful when Dags must complete by a specific time.
 
+``DeadlineReference.AVERAGE_RUNTIME``
+    Calculates deadlines based on the average runtime of previous DAG runs. This reference
+    analyzes historical execution data to predict when the current run should complete.
+    The deadline is set to the current time plus the calculated average runtime plus the interval.
+    If insufficient historical data exists, no deadline is created.
+
+    Parameters:
+        * ``limit`` (int, optional): Maximum number of recent DAG runs to analyze. Defaults to 10.
+        * ``min_runs`` (int, optional): Minimum number of completed runs required to calculate average. Defaults to same value as ``limit``.
+
+    Example usage:
+
+    .. code-block:: python
+
+        # Use default settings (analyze up to 10 runs, require 10 runs)
+        DeadlineReference.AVERAGE_RUNTIME()
+
+        # Analyze up to 20 runs but calculate with minimum 5 runs
+        DeadlineReference.AVERAGE_RUNTIME(limit=20, min_runs=5)
+
+        # Strict: require exactly 15 runs to calculate
+        DeadlineReference.AVERAGE_RUNTIME(limit=15, min_runs=15)
+
+Here's an example using average runtime:
+
+.. code-block:: python
+
+    with DAG(
+        dag_id="average_runtime_deadline",
+        deadline=DeadlineAlert(
+            reference=DeadlineReference.AVERAGE_RUNTIME(limit=15, min_runs=5),
+            interval=timedelta(minutes=30),  # Alert if 30 minutes past expected completion
+            callback=AsyncCallback(
+                SlackWebhookNotifier,
+                kwargs={"text": "🚨 DAG {{ dag_run.dag_id }} is running longer than expected!"},
+            ),
+        ),
+    ):
+        EmptyOperator(task_id="data_processing")
+
+The timeline for this example would look like this:
+
+::
+
+    |------|----------|---------|------------|--------|
+         Queued     Start    Expected    Deadline
+         09:00      09:05     09:35       10:05
+                              (avg+30min)

Review Comment:
   ```suggestion
                             (avg + 30 min)
   ```



##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +367,76 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        DEFAULT_LIMIT = 10
+        limit: int

Review Comment:
   +1



##########
airflow-core/docs/howto/deadline-alerts.rst:
##########
@@ -97,6 +100,55 @@ Airflow provides several built-in reference points that you can use with Deadlin
 ``DeadlineReference.FIXED_DATETIME``
     Specifies a fixed point in time. Useful when Dags must complete by a specific time.
 
+``DeadlineReference.AVERAGE_RUNTIME``
+    Calculates deadlines based on the average runtime of previous DAG runs. This reference
+    analyzes historical execution data to predict when the current run should complete.
+    The deadline is set to the current time plus the calculated average runtime plus the interval.
+    If insufficient historical data exists, no deadline is created.
+
+    Parameters:
+        * ``limit`` (int, optional): Maximum number of recent DAG runs to analyze. Defaults to 10.
+        * ``min_runs`` (int, optional): Minimum number of completed runs required to calculate average. Defaults to same value as ``limit``.
+
+    Example usage:
+
+    .. code-block:: python
+
+        # Use default settings (analyze up to 10 runs, require 10 runs)
+        DeadlineReference.AVERAGE_RUNTIME()
+
+        # Analyze up to 20 runs but calculate with minimum 5 runs
+        DeadlineReference.AVERAGE_RUNTIME(limit=20, min_runs=5)
+
+        # Strict: require exactly 15 runs to calculate
+        DeadlineReference.AVERAGE_RUNTIME(limit=15, min_runs=15)
+
+Here's an example using average runtime:
+
+.. code-block:: python
+
+    with DAG(
+        dag_id="average_runtime_deadline",
+        deadline=DeadlineAlert(
+            reference=DeadlineReference.AVERAGE_RUNTIME(limit=15, min_runs=5),
+            interval=timedelta(minutes=30),  # Alert if 30 minutes past expected completion

Review Comment:
   ```suggestion
               interval=timedelta(minutes=30),  # Alert if 30 minutes past average runtime
   ```



##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +367,95 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        DEFAULT_LIMIT = 10
+        limit: int
+        min_runs: int | None = None

Review Comment:
   If we verify the user input and apply defaults in the Task SDK definition, then I think we should just be able to assume that min_runs is provided and is valid
   ```suggestion
           min_runs: int
   ```
   (and also remove `__post_init__` if we go ahead with this)



##########
task-sdk/src/airflow/sdk/definitions/deadline.py:
##########
@@ -299,6 +300,14 @@ class TYPES:
     DAGRUN_LOGICAL_DATE: DeadlineReferenceType = ReferenceModels.DagRunLogicalDateDeadline()
     DAGRUN_QUEUED_AT: DeadlineReferenceType = ReferenceModels.DagRunQueuedAtDeadline()
 
+    @classmethod
+    def AVERAGE_RUNTIME(cls, limit: int = 0, min_runs: int | None = None) -> DeadlineReferenceType:

Review Comment:
   ```suggestion
       def AVERAGE_RUNTIME(cls, limit: int = cls.ReferenceModels.AverageRuntimeDeadline.DEFAULT_LIMIT, min_runs: int = cls.ReferenceModels.AverageRuntimeDeadline.DEFAULT_LIMIT) -> DeadlineReferenceType:
           return cls.ReferenceModels.AverageRuntimeDeadline(limit, min_runs)
   ```



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/docs/howto/deadline-alerts.rst:
##########
@@ -97,6 +100,55 @@ Airflow provides several built-in reference points that you can use with Deadlin
 ``DeadlineReference.FIXED_DATETIME``
     Specifies a fixed point in time. Useful when Dags must complete by a specific time.
 
+``DeadlineReference.AVERAGE_RUNTIME``
+    Calculates deadlines based on the average runtime of previous DAG runs. This reference
+    analyzes historical execution data to predict when the current run should complete.
+    The deadline is set to the current time plus the calculated average runtime plus the interval.
+    If insufficient historical data exists, no deadline is created.
+
+    Parameters:
+        * ``limit`` (int, optional): Maximum number of recent DAG runs to analyze. Defaults to 10.
+        * ``min_runs`` (int, optional): Minimum number of completed runs required to calculate average. Defaults to same value as ``limit``.
+
+    Example usage:
+
+    .. code-block:: python
+
+        # Use default settings (analyze up to 10 runs, require 10 runs)
+        DeadlineReference.AVERAGE_RUNTIME()
+
+        # Analyze up to 20 runs but calculate with minimum 5 runs
+        DeadlineReference.AVERAGE_RUNTIME(limit=20, min_runs=5)
+
+        # Strict: require exactly 15 runs to calculate
+        DeadlineReference.AVERAGE_RUNTIME(limit=15, min_runs=15)
+
+Here's an example using average runtime:
+
+.. code-block:: python
+
+    with DAG(
+        dag_id="average_runtime_deadline",
+        deadline=DeadlineAlert(
+            reference=DeadlineReference.AVERAGE_RUNTIME(limit=15, min_runs=5),
+            interval=timedelta(minutes=30),  # Alert if 30 minutes past expected completion

Review Comment:
   Ah, yup, something got weird there.  I think the above example can be moved down to replace this one.



##########
airflow-core/docs/howto/deadline-alerts.rst:
##########
@@ -97,6 +100,55 @@ Airflow provides several built-in reference points that you can use with Deadlin
 ``DeadlineReference.FIXED_DATETIME``
     Specifies a fixed point in time. Useful when Dags must complete by a specific time.
 
+``DeadlineReference.AVERAGE_RUNTIME``
+    Calculates deadlines based on the average runtime of previous DAG runs. This reference
+    analyzes historical execution data to predict when the current run should complete.
+    The deadline is set to the current time plus the calculated average runtime plus the interval.
+    If insufficient historical data exists, no deadline is created.
+
+    Parameters:
+        * ``limit`` (int, optional): Maximum number of recent DAG runs to analyze. Defaults to 10.
+        * ``min_runs`` (int, optional): Minimum number of completed runs required to calculate average. Defaults to same value as ``limit``.
+
+    Example usage:
+
+    .. code-block:: python
+
+        # Use default settings (analyze up to 10 runs, require 10 runs)
+        DeadlineReference.AVERAGE_RUNTIME()
+
+        # Analyze up to 20 runs but calculate with minimum 5 runs
+        DeadlineReference.AVERAGE_RUNTIME(limit=20, min_runs=5)
+
+        # Strict: require exactly 15 runs to calculate
+        DeadlineReference.AVERAGE_RUNTIME(limit=15, min_runs=15)
+
+Here's an example using average runtime:
+
+.. code-block:: python
+
+    with DAG(
+        dag_id="average_runtime_deadline",
+        deadline=DeadlineAlert(
+            reference=DeadlineReference.AVERAGE_RUNTIME(limit=15, min_runs=5),
+            interval=timedelta(minutes=30),  # Alert if 30 minutes past expected completion

Review Comment:
   Ah, yup, something got weird there.  I think the above example can be moved down to replace this one.



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/docs/howto/deadline-alerts.rst:
##########
@@ -97,6 +100,55 @@ Airflow provides several built-in reference points that you can use with Deadlin
 ``DeadlineReference.FIXED_DATETIME``
     Specifies a fixed point in time. Useful when Dags must complete by a specific time.
 
+``DeadlineReference.AVERAGE_RUNTIME``
+    Calculates deadlines based on the average runtime of previous DAG runs. This reference
+    analyzes historical execution data to predict when the current run should complete.
+    The deadline is set to the current time plus the calculated average runtime plus the interval.
+    If insufficient historical data exists, no deadline is created.
+
+    Parameters:
+        * ``limit`` (int, optional): Maximum number of recent DAG runs to analyze. Defaults to 10.
+        * ``min_runs`` (int, optional): Minimum number of completed runs required to calculate average. Defaults to same value as ``limit``.
+
+    Example usage:
+
+    .. code-block:: python
+
+        # Use default settings (analyze up to 10 runs, require 10 runs)
+        DeadlineReference.AVERAGE_RUNTIME()
+
+        # Analyze up to 20 runs but calculate with minimum 5 runs
+        DeadlineReference.AVERAGE_RUNTIME(limit=20, min_runs=5)
+
+        # Strict: require exactly 15 runs to calculate
+        DeadlineReference.AVERAGE_RUNTIME(limit=15, min_runs=15)
+
+Here's an example using average runtime:
+
+.. code-block:: python
+
+    with DAG(
+        dag_id="average_runtime_deadline",
+        deadline=DeadlineAlert(
+            reference=DeadlineReference.AVERAGE_RUNTIME(limit=15, min_runs=5),
+            interval=timedelta(minutes=30),  # Alert if 30 minutes past expected completion
+            callback=AsyncCallback(
+                SlackWebhookNotifier,
+                kwargs={"text": "🚨 DAG {{ dag_run.dag_id }} is running longer than expected!"},
+            ),
+        ),
+    ):
+        EmptyOperator(task_id="data_processing")
+
+The timeline for this example would look like this:
+
+::
+
+    |------|----------|---------|------------|--------|
+         Queued     Start    Expected    Deadline
+         09:00      09:05     09:35       10:05
+                              (avg+30min)

Review Comment:
   I double-checked and it seems like I am indeed on the latest version but I just realized that the change you were talking about is in another location?
   https://github.com/apache/airflow/pull/55088/files#r2356852450



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +366,62 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        DEFAULT_LIMIT = 10
+        limit: int
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit
+            query = query.limit(self.limit)
+
+            # Get all durations and calculate average
+            durations = session.execute(query).scalars().all()
+
+            if len(durations) < self.limit:
+                logger.warning(
+                    "In the AverageRuntimeDeadline: Only %d completed DAG runs found for dag_id: %s (need %d), using 48 hour default",
+                    len(durations),
+                    dag_id,
+                    self.limit,
+                )
+                avg_seconds = 48 * 3600  # 48 hours as default

Review Comment:
   Thinking this through, 
   
   By adding some kind of "don't store this deadline" escape hatch, then the deadline can never expire, so the first run wouldn't ever fail deadline, but the second would use the first run's duration as the "average" and then build up from there over time.
   
   We would just have t make it clear that "no historical data means no failure"



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +366,62 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        DEFAULT_LIMIT = 10
+        limit: int
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit
+            query = query.limit(self.limit)
+
+            # Get all durations and calculate average
+            durations = session.execute(query).scalars().all()
+
+            if len(durations) < self.limit:
+                logger.warning(
+                    "In the AverageRuntimeDeadline: Only %d completed DAG runs found for dag_id: %s (need %d), using 48 hour default",
+                    len(durations),
+                    dag_id,
+                    self.limit,
+                )
+                avg_seconds = 48 * 3600  # 48 hours as default

Review Comment:
   Had a chat with Sean offline, he's going to add a min-number-of-records, so the logic will be:
   
   - Query the db for up to `max_records` number of historical durations
   - If the resulting list is less than `min_records` then return None (no deadline set); else use the average of that you have.
   
   The min will default to the max unless the user overrides it.  So in practice:
   
   | min_records | max_records | Result                                                                                                                                  |
   |-------------|-------------|-----------------------------------------------------------------------------------------------------------------------------------------|
   | not set     | 10          | No failures until run 11 which uses the average of the 10 previous                                                                       |
   | 10          | 10          | No failures until run 11 which uses the average of the 10 previous                                                                       |
   | 1           | 10          | First run can not fail, second run fails if it runs longer than the first, third run averages the previous two, etc up to 10                                                               |
   | 5           | 10          | First 5 can not fail, run 6 uses the average of the 5 previous values, run 7 - 10 build up that average, run 11 uses the 10-run average |



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +366,62 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        DEFAULT_LIMIT = 10
+        limit: int
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit
+            query = query.limit(self.limit)
+
+            # Get all durations and calculate average
+            durations = session.execute(query).scalars().all()
+
+            if len(durations) < self.limit:
+                logger.warning(
+                    "In the AverageRuntimeDeadline: Only %d completed DAG runs found for dag_id: %s (need %d), using 48 hour default",
+                    len(durations),
+                    dag_id,
+                    self.limit,
+                )
+                avg_seconds = 48 * 3600  # 48 hours as default

Review Comment:
   Had a chat with Sean offline, he's going to add a min-number-of-records, so the logic will be:
   
   - Query the db for up to `max_records` number of historical durations
   - If the resulting list is less than `min_records` then return None (no deadline set); else use the average of that you have.
   
   The min will default to the max unless the user overrides it.  So in practice:
   
   | min_records | max_records | Result                                                                                                                                  |
   |-------------|-------------|-----------------------------------------------------------------------------------------------------------------------------------------|
   | not set     | 10          | No failures until run 11 which uses he average of the 10 previous                                                                       |
   | 10          | 10          | No failures until run 11 which uses he average of the 10 previous                                                                       |
   | 1           | 10          | First run can not fail, second run starts a running average up to 10                                                                    |
   | 5           | 10          | First 5 can not fail, run 6 uses the average of the 5 previous values, run 7 - 10 build up that average, run 11 uses the 10-run average |



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/src/airflow/models/deadline.py:
##########
@@ -366,6 +366,62 @@ def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
 
             return _fetch_from_db(DagRun.queued_at, session=session, **kwargs)
 
+    @dataclass
+    class AverageRuntimeDeadline(BaseDeadlineReference):
+        """A deadline that calculates the average runtime from past DAG runs."""
+
+        DEFAULT_LIMIT = 10
+        limit: int
+        required_kwargs = {"dag_id"}
+
+        @provide_session
+        def _evaluate_with(self, *, session: Session, **kwargs: Any) -> datetime:
+            from airflow.models import DagRun
+
+            dag_id = kwargs["dag_id"]
+
+            # Query for completed DAG runs with both start and end dates
+            # Order by logical_date descending to get most recent runs first
+            query = (
+                select(func.extract("epoch", DagRun.end_date - DagRun.start_date))
+                .filter(DagRun.dag_id == dag_id, DagRun.start_date.isnot(None), DagRun.end_date.isnot(None))
+                .order_by(DagRun.logical_date.desc())
+            )
+
+            # Apply limit
+            query = query.limit(self.limit)
+
+            # Get all durations and calculate average
+            durations = session.execute(query).scalars().all()
+
+            if len(durations) < self.limit:
+                logger.warning(
+                    "In the AverageRuntimeDeadline: Only %d completed DAG runs found for dag_id: %s (need %d), using 48 hour default",
+                    len(durations),
+                    dag_id,
+                    self.limit,
+                )
+                avg_seconds = 48 * 3600  # 48 hours as default

Review Comment:
   Had a chat with Sean offline, he's going to add a min-number-of-records, so the logic will be:
   
   - Query the db for up to `max_records` number of historical durations
   - If the resulting list is less than `min_records` then return None (no deadline set); else use the average of that you have.
   
   The min will default to the max unless the user overrides it.  So in practice:
   
   | min_records | max_records | Result                                                                                                                                  |
   |-------------|-------------|-----------------------------------------------------------------------------------------------------------------------------------------|
   | not set     | 10          | No failures until run 11 which uses the average of the 10 previous                                                                       |
   | 10          | 10          | No failures until run 11 which uses the average of the 10 previous                                                                       |
   | 1           | 10          | First run can not fail, second run starts a running average up to 10                                                                    |
   | 5           | 10          | First 5 can not fail, run 6 uses the average of the 5 previous values, run 7 - 10 build up that average, run 11 uses the 10-run average |



-- 
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] Use average runtime as deadline reference [airflow]

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


##########
airflow-core/docs/howto/deadline-alerts.rst:
##########
@@ -72,14 +72,6 @@ Below is an example Dag implementation. If the Dag has not finished 15 minutes a
     ):
         EmptyOperator(task_id="example_task")
 
-The timeline for this example would look like this:
-
-::
-
-    |------|-----------|---------|-----------|--------|
-        Scheduled    Queued    Started    Deadline
-         00:00       00:03      00:05      00:18
-

Review Comment:
   Looks like you already got it.  Resolving.



-- 
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