amoghrajesh commented on code in PR #74212:
URL: https://github.com/apache/airflow/pull/74212#discussion_r4753080731


##########
airflow-core/tests/unit/jobs/test_scheduler_job.py:
##########
@@ -1268,6 +1269,164 @@ def 
test_process_executor_events_stale_success_when_queued_after_defer(
             tags={"dag_id": dag_id, "task_id": ti1.task_id},
         )
 
+    @pytest.mark.parametrize("ti_state", [State.SCHEDULED, State.QUEUED])
+    @mock.patch("airflow._shared.observability.metrics.stats._get_backend")
+    def test_process_executor_events_stale_success_between_reschedule_pokes(
+        self, mock_get_backend, ti_state, dag_maker
+    ):
+        """
+        A reschedule-mode sensor was queued for its next poke before the 
previous poke's success arrived.
+
+        Regression for https://github.com/apache/airflow/issues/71172 — must 
not treat as state mismatch.
+        """
+        mock_stats = mock.MagicMock(spec=StatsLogger)
+        mock_get_backend.return_value = mock_stats
+        dag_id = 
"test_process_executor_events_stale_success_between_reschedule_pokes"
+
+        session = settings.Session()
+        with dag_maker(dag_id=dag_id, fileloc="/test_path1/"):
+            task1 = EmptyOperator(task_id="dummy_task")
+        ti1 = dag_maker.create_dagrun().get_task_instance(task1.task_id)
+
+        executor = MockExecutor(do_update=False)
+        scheduler_job = Job()
+        session.add(scheduler_job)
+        session.flush()
+        self.job_runner = SchedulerJobRunner(scheduler_job, 
executors=[executor])
+
+        # A reschedule exit leaves next_method unset and keeps the same 
try_number.
+        ti1.state = ti_state
+        ti1.next_method = None
+        ti1.queued_by_job_id = scheduler_job.id
+        ti1.try_number = 1
+        session.merge(ti1)
+        poke_end = DEFAULT_DATE + timedelta(seconds=5)
+        session.add(
+            TaskReschedule(
+                ti_id=ti1.id,
+                start_date=DEFAULT_DATE,
+                end_date=poke_end,
+                reschedule_date=poke_end + timedelta(seconds=60),
+            )
+        )
+        session.commit()
+
+        executor.event_buffer[TaskInstanceUuid(ti1.id)] = State.SUCCESS, None
+        executor.has_task = mock.MagicMock(return_value=False)
+        mock_stats.incr.reset_mock()
+
+        self.job_runner._process_executor_events(executor=executor, 
session=session)
+        ti1.refresh_from_db(session=session)
+        assert ti1.state == ti_state
+        self.job_runner.executor.callback_sink.send.assert_not_called()
+        
mock_stats.incr.assert_called_once_with("scheduler.executor_events.processed", 
count=1)
+
+    @pytest.mark.parametrize("ti_state", [State.SCHEDULED, State.QUEUED])
+    @pytest.mark.parametrize("event_state", [State.QUEUED, State.RUNNING])
+    def 
test_process_executor_events_skips_reschedule_lookup_without_success_event(

Review Comment:
   This passes on the base branch, since the base has no `task_reschedule` 
query at all. It only guards the PR's own `if not success_ti_ids` shortcut, and 
it matches raw SQL text. Delete it, or say in the PR body why the guard is kept.



##########
airflow-core/tests/unit/jobs/test_scheduler_job.py:
##########
@@ -1268,6 +1269,164 @@ def 
test_process_executor_events_stale_success_when_queued_after_defer(
             tags={"dag_id": dag_id, "task_id": ti1.task_id},
         )
 
+    @pytest.mark.parametrize("ti_state", [State.SCHEDULED, State.QUEUED])
+    @mock.patch("airflow._shared.observability.metrics.stats._get_backend")
+    def test_process_executor_events_stale_success_between_reschedule_pokes(

Review Comment:
   Here and 1381 repeat about 25 lines of identical setup (Dag, executor, job, 
TaskReschedule row). They differ only in the event state and the expected 
outcome. Merge them into one `@pytest.mark.parametrize` test with ids 
success_is_stale and failed_still_fails.



##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -1426,6 +1427,38 @@ def _emit_executor_events_batch_metrics(num_events: int) 
-> None:
         stats.gauge("scheduler.executor_events.batch_size", num_events)
         stats.incr("scheduler.executor_events.processed", num_events)
 
+    @staticmethod
+    def _find_rescheduled_ti_ids(
+        tis: Sequence[TI],
+        *,
+        success_ti_ids: Collection[UUID],
+        session: Session,
+    ) -> set[UUID]:
+        """
+        Return ids of scheduled or queued task instances that already have a 
reschedule row.
+
+        Only a SUCCESS executor event can be a stale reschedule poke, so 
``success_ti_ids``
+        is that set. An empty set skips the query: QUEUED, RUNNING, and 
failure events never
+        read the result.
+        """
+        if not success_ti_ids:
+            return set()
+        candidate_ids = [

Review Comment:
   `_find_rescheduled_ti_ids` repeats the `SCHEDULED`/`QUEUED` and `next_method 
is None` filters that the main loop already applies at lines 1667-1672. If one 
copy changes, the other silently drifts. Do the lookup lazily inside that 
branch with an `exists()` query, or build the candidates from one shared 
predicate.



##########
airflow-core/tests/unit/jobs/test_scheduler_job.py:
##########
@@ -1268,6 +1269,164 @@ def 
test_process_executor_events_stale_success_when_queued_after_defer(
             tags={"dag_id": dag_id, "task_id": ti1.task_id},
         )
 
+    @pytest.mark.parametrize("ti_state", [State.SCHEDULED, State.QUEUED])
+    @mock.patch("airflow._shared.observability.metrics.stats._get_backend")
+    def test_process_executor_events_stale_success_between_reschedule_pokes(
+        self, mock_get_backend, ti_state, dag_maker
+    ):
+        """
+        A reschedule-mode sensor was queued for its next poke before the 
previous poke's success arrived.
+
+        Regression for https://github.com/apache/airflow/issues/71172 — must 
not treat as state mismatch.
+        """
+        mock_stats = mock.MagicMock(spec=StatsLogger)
+        mock_get_backend.return_value = mock_stats
+        dag_id = 
"test_process_executor_events_stale_success_between_reschedule_pokes"
+
+        session = settings.Session()
+        with dag_maker(dag_id=dag_id, fileloc="/test_path1/"):
+            task1 = EmptyOperator(task_id="dummy_task")
+        ti1 = dag_maker.create_dagrun().get_task_instance(task1.task_id)
+
+        executor = MockExecutor(do_update=False)
+        scheduler_job = Job()
+        session.add(scheduler_job)
+        session.flush()
+        self.job_runner = SchedulerJobRunner(scheduler_job, 
executors=[executor])
+
+        # A reschedule exit leaves next_method unset and keeps the same 
try_number.
+        ti1.state = ti_state
+        ti1.next_method = None
+        ti1.queued_by_job_id = scheduler_job.id
+        ti1.try_number = 1
+        session.merge(ti1)
+        poke_end = DEFAULT_DATE + timedelta(seconds=5)
+        session.add(
+            TaskReschedule(
+                ti_id=ti1.id,
+                start_date=DEFAULT_DATE,
+                end_date=poke_end,
+                reschedule_date=poke_end + timedelta(seconds=60),
+            )
+        )
+        session.commit()
+
+        executor.event_buffer[TaskInstanceUuid(ti1.id)] = State.SUCCESS, None
+        executor.has_task = mock.MagicMock(return_value=False)
+        mock_stats.incr.reset_mock()
+
+        self.job_runner._process_executor_events(executor=executor, 
session=session)
+        ti1.refresh_from_db(session=session)
+        assert ti1.state == ti_state
+        self.job_runner.executor.callback_sink.send.assert_not_called()
+        
mock_stats.incr.assert_called_once_with("scheduler.executor_events.processed", 
count=1)
+
+    @pytest.mark.parametrize("ti_state", [State.SCHEDULED, State.QUEUED])
+    @pytest.mark.parametrize("event_state", [State.QUEUED, State.RUNNING])
+    def 
test_process_executor_events_skips_reschedule_lookup_without_success_event(
+        self, ti_state, event_state, dag_maker
+    ):
+        """QUEUED and RUNNING events never read reschedule history, so they 
must not query it."""
+        dag_id = "test_process_executor_events_skips_reschedule_lookup"
+
+        session = settings.Session()
+        with dag_maker(dag_id=dag_id, fileloc="/test_path1/"):
+            task1 = EmptyOperator(task_id="dummy_task")
+        ti1 = dag_maker.create_dagrun().get_task_instance(task1.task_id)
+
+        executor = MockExecutor(do_update=False)
+        scheduler_job = Job()
+        session.add(scheduler_job)
+        session.flush()
+        self.job_runner = SchedulerJobRunner(scheduler_job, 
executors=[executor])
+
+        # Same shape as a reschedule poke waiting for its next run: the old 
lookup would query.
+        ti1.state = ti_state
+        ti1.next_method = None
+        ti1.queued_by_job_id = scheduler_job.id
+        session.merge(ti1)
+        poke_end = DEFAULT_DATE + timedelta(seconds=5)
+        session.add(
+            TaskReschedule(
+                ti_id=ti1.id,
+                start_date=DEFAULT_DATE,
+                end_date=poke_end,
+                reschedule_date=poke_end + timedelta(seconds=60),
+            )
+        )
+        session.commit()
+
+        executor.event_buffer[TaskInstanceUuid(ti1.id)] = event_state, 
"worker-1"
+
+        statements: list[str] = []
+
+        def capture_statement(orm_execute_state):
+            statements.append(str(orm_execute_state.statement))
+
+        event.listen(session, "do_orm_execute", capture_statement)
+        try:
+            self.job_runner._process_executor_events(executor=executor, 
session=session)
+        finally:
+            event.remove(session, "do_orm_execute", capture_statement)
+
+        session.flush()
+        ti1.refresh_from_db(session=session)
+        assert ti1.state == ti_state
+        assert ti1.external_executor_id == "worker-1"
+        assert statements, "the task instance load should still query"
+        assert not any("task_reschedule" in statement.lower() for statement in 
statements)
+
+    @pytest.mark.parametrize("ti_state", [State.SCHEDULED, State.QUEUED])
+    @mock.patch("airflow._shared.observability.metrics.stats._get_backend")
+    def test_process_executor_events_failed_with_reschedule_row_still_fails(

Review Comment:
   Same as above.



##########
airflow-core/tests/unit/jobs/test_scheduler_job.py:
##########
@@ -1268,6 +1269,164 @@ def 
test_process_executor_events_stale_success_when_queued_after_defer(
             tags={"dag_id": dag_id, "task_id": ti1.task_id},
         )
 
+    @pytest.mark.parametrize("ti_state", [State.SCHEDULED, State.QUEUED])
+    @mock.patch("airflow._shared.observability.metrics.stats._get_backend")
+    def test_process_executor_events_stale_success_between_reschedule_pokes(
+        self, mock_get_backend, ti_state, dag_maker
+    ):
+        """
+        A reschedule-mode sensor was queued for its next poke before the 
previous poke's success arrived.
+
+        Regression for https://github.com/apache/airflow/issues/71172 — must 
not treat as state mismatch.

Review Comment:
   Remove the issue linking



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