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


##########
airflow-core/tests/unit/utils/test_event_scheduler.py:
##########
@@ -71,3 +71,33 @@ def 
test_call_regular_interval_non_fatal_swallows_action_exception(self):
         # The next cycle was still scheduled despite the exception.
         assert len(timers.queue) == 2
         assert timers.queue[0].time < timers.queue[1].time
+
+    def test_call_regular_interval_expedites_next_run_on_numeric_return(self):
+        """An action returning a non-negative delay reschedules the next run 
at that delay."""
+        action = mock.MagicMock(return_value=0)
+
+        timers = EventScheduler()
+        timers.call_regular_interval(30, action)
+        regular_time = timers.queue[0].time
+
+        # Fake a run; the action asks for an expedited rerun by returning 0.
+        timers.queue[0].action()

Review Comment:
   Calling `timers.queue[0].action()` directly skips what `run(blocking=False)` 
does with a 0 delay, which is where both problems above show up. With a fake 
`timefunc`, an action with `side_effect=[0, 0, None]` and one 
`run(blocking=False)` call, asserting `call_count == 1` fails on this branch. A 
case with an int-returning action that didn't opt in would cover the orphan 
check too.



##########
airflow-core/src/airflow/config_templates/config.yml:
##########
@@ -2899,8 +2899,11 @@ scheduler:
     max_tis_per_query:
       description: |
         This determines the number of task instances to be evaluated for 
scheduling
-        during each scheduler loop.
-        Set this to 0 to use the value of ``[core] parallelism``
+        during each scheduler loop. It also bounds how many 
heartbeat-timed-out task
+        instances the scheduler purges per pass, so a mass heartbeat-loss 
event is
+        cleared in bounded batches (oldest heartbeat first) over successive 
loops
+        instead of in one scheduler-loop-stalling pass.
+        Set this to 0 to use the value of ``[core] parallelism`` (for both 
uses).

Review Comment:
   Small one: `DagRun.schedule_tis` still treats 0 as no chunking 
(`max_tis_per_query or len(schedulable_ti_ids)` in dagrun.py), so "(for both 
uses)" isn't quite right. Dropping the parenthetical is enough. The PR 
description also still says 0 keeps the old unbounded behaviour.



##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -3949,19 +3960,26 @@ def 
_find_and_purge_task_instances_without_heartbeats(self) -> None:
         A TaskCallbackRequest is also created for the killed task instance to 
be
         handled by the DAG processor, and the executor is informed to no longer
         count the task instance as running when it calculates parallelism.
+
+        Returns ``0`` when a full batch was purged, asking the caller to run 
the next pass on the
+        following loop instead of waiting the full detection interval; 
otherwise returns ``None`` so
+        the regular interval applies.
         """
         with create_session() as session:
-            if task_instances_without_heartbeats := 
self._find_task_instances_without_heartbeats(
-                session=session
-            ):
-                stats.incr(
-                    "scheduler.zombies.detected",
-                    len(task_instances_without_heartbeats),
-                    tags={"reason": "heartbeat_timeout"},
-                )
-                self._purge_task_instances_without_heartbeats(
-                    task_instances_without_heartbeats, session=session
-                )
+            task_instances_without_heartbeats = 
self._find_task_instances_without_heartbeats(session=session)
+            if not task_instances_without_heartbeats:
+                return None
+            stats.incr(
+                "scheduler.zombies.detected",
+                len(task_instances_without_heartbeats),
+                tags={"reason": "heartbeat_timeout"},
+            )
+            
self._purge_task_instances_without_heartbeats(task_instances_without_heartbeats,
 session=session)
+        # A full batch means more stale rows are likely waiting; drain them on 
the next loop rather
+        # than after the full interval, so a mass event recovers quickly while 
each pass stays bounded.
+        if len(task_instances_without_heartbeats) >= 
self._heartbeat_purge_batch_limit:
+            return 0.0

Review Comment:
   The same `sched.run` behaviour applies here. Returning a zero delay re-runs 
the purge before `timers.run()` returns, so a mass event still drains every 
batch inside one scheduler loop, with no scheduling or executor heartbeat in 
between (5 full batches then a partial one ran 6 times in a single `run()`). 
The docstring, the comment above the `.limit()` and the config.yml text all 
promise the next loop. A backlog flag that `_run_scheduler_loop` checks once 
per iteration would give one bounded pass per loop.



##########
airflow-core/tests/unit/jobs/test_scheduler_job.py:
##########
@@ -4448,6 +4521,39 @@ def 
test_purge_without_heartbeat_skips_when_missing_dag_version(self, dag_maker,
         assert any("Backfilled dag_version_id" in rec.message for rec in 
caplog.records)
         mock_executor.send_callback.assert_called_once()
 
+    def 
test_purge_without_heartbeat_fails_ti_when_dag_version_unresolvable(self, 
dag_maker, session):
+        """
+        A TI whose dag_version_id cannot be resolved (no DagVersion at all, 
e.g. an adopted Airflow 2
+        task never reparsed) must still be failed -- without the callback -- 
not skipped. Skipping
+        would leave it RUNNING with its stale heartbeat, so with oldest-first 
batching it would sort to
+        the front of every batch and starve the purge.
+        """
+        with dag_maker("test_purge_unresolvable_dag_version", session=session):
+            EmptyOperator(task_id="task")
+
+        dag_run = dag_maker.create_dagrun(run_id="test_run", 
state=DagRunState.RUNNING)
+
+        mock_executor = MagicMock()
+        scheduler_job = Job()
+        self.job_runner = SchedulerJobRunner(scheduler_job, 
executors=[mock_executor])
+
+        ti = dag_run.get_task_instance(task_id="task", session=session)
+        ti.state = TaskInstanceState.RUNNING
+        ti.queued_by_job_id = scheduler_job.id
+        ti.last_heartbeat_at = timezone.utcnow() - timedelta(hours=1)
+        ti.dag_version_id = None
+        session.merge(ti)
+        session.commit()
+
+        # No DagVersion can be found, so the callback version cannot be 
resolved.
+        with 
mock.patch("airflow.jobs.scheduler_job_runner.DagVersion.get_latest_version", 
return_value=None):
+            self.job_runner._purge_task_instances_without_heartbeats([ti], 
session=session)
+
+        session.refresh(ti)
+        # Released (failed), not left RUNNING; and no callback was sent since 
it had no dag version.
+        assert ti.state in (TaskInstanceState.FAILED, 
TaskInstanceState.UP_FOR_RETRY)

Review Comment:
   `EmptyOperator` has no retries here, so this can assert `ti.state == 
TaskInstanceState.FAILED`.



##########
airflow-core/src/airflow/utils/event_scheduler.py:
##########
@@ -57,10 +58,17 @@ def repeat(*args, **kwargs):
                         exc_info=True,
                     )
             else:
-                action(*args, **kwargs)
+                result = action(*args, **kwargs)
+            # An action may request an earlier next run -- e.g. it cleared a 
full bounded batch and
+            # more work is likely waiting -- by returning a non-negative delay 
in seconds; otherwise
+            # the regular interval is used. A bool is ignored so a 
truthy/falsey return can't re-time
+            # the timer by accident.
+            next_delay = delay
+            if isinstance(result, (int, float)) and not isinstance(result, 
bool):
+                next_delay = max(0.0, float(result))

Review Comment:
   `adopt_or_reset_orphaned_tasks` is also registered through 
`call_regular_interval` and returns `len(to_reset)`, so when nothing is 
orphaned it now returns 0 and gets re-entered at delay 0. 
`sched.run(blocking=False)` pops any event whose time is <= now, so it keeps 
re-running that action inside the same `timers.run()` call and the scheduler 
stops looping and heartbeating about 300s after start. I reproduced it with the 
real `EventScheduler`: over 1000 calls in one `run()` before I stopped it. 
Could re-timing be opt-in for the one registration that wants it (a flag on 
`call_regular_interval`, or a dedicated return type) rather than any numeric 
return?



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

To unsubscribe, e-mail: [email protected]

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

Reply via email to