vincbeck commented on code in PR #76410:
URL: https://github.com/apache/airflow/pull/76410#discussion_r4681194826


##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -456,6 +500,186 @@ def __init__(
     def heartbeat_callback(self, *, session: Session = NEW_SESSION) -> None:
         stats.incr("scheduler_heartbeat", 1, 1)
 
+    def _check_executor_health(self) -> None:
+        """
+        Kick off a health check for each reporting executor, in the background.
+
+        Called on its own timer (``[scheduler] 
executor_health_check_interval``), independent of the
+        scheduling loop and of each executor's own 
:meth:`~airflow.executors.base_executor.BaseExecutor.heartbeat`.
+        A new check for a given executor is skipped while its previous check 
is still running, so a
+        slow or hung dependency can only ever delay that executor's own health 
being updated, never
+        pile up work or block this (or any other) scheduler tick.
+
+        ``get_health()`` is passed a timeout, but an implementation that 
ignores it can still leave its
+        check thread running forever. Once a running check is a few intervals 
old, it's reported as
+        stalled: the scheduler records UNHEALTHY itself, since a check that 
hasn't answered isn't
+        still-healthy, and logs and emits a metric so the stall is visible. If 
the stuck call does
+        eventually return, its result overwrites this one.
+        """
+        for executor in self.executors:
+            key = _executor_health_key(executor)
+            if key not in self._executor_health_keys:
+                continue
+            thread, started = self._executor_health_check_threads.get(key, 
(None, 0.0))
+            if thread is not None and thread.is_alive():
+                stall_after = (
+                    self._executor_health_check_interval * 
self._executor_health_check_stall_after_intervals
+                )
+                if time.monotonic() - started > stall_after and key not in 
self._stalled_health_checks:
+                    self._stalled_health_checks.add(key)
+                    self.log.warning("Health check for executor %s has stopped 
responding", key)
+                    stats.incr(
+                        "scheduler.executor_health_check.stalled",
+                        tags=prune_dict(
+                            {"executor": type(executor).__name__, "team_name": 
executor.team_name}
+                        ),
+                    )
+                    try:
+                        self._record_executor_health_result(
+                            key, executor.team_name, 
HealthCheckResult.UNHEALTHY
+                        )
+                    except Exception:
+                        self.log.exception("Failed to record health check 
result for executor %s", key)
+                else:
+                    self.log.debug(
+                        "Skipping health check for executor %s, the previous 
check hasn't finished", key
+                    )
+                continue
+            self._stalled_health_checks.discard(key)
+            thread = threading.Thread(
+                target=self._run_executor_health_check,
+                args=(executor, key),
+                name=f"executor-health-check-{key}",
+                daemon=True,
+            )
+            thread.start()
+            self._executor_health_check_threads[key] = (thread, 
time.monotonic())
+
+    def _join_executor_health_check_threads(self) -> None:
+        """
+        Wait for any in-flight executor health check before this scheduler's 
ExecutorJob rows are closed.
+
+        Without this, a check thread still running when ``_end_executor_jobs`` 
closes those rows would
+        go on to call ``_get_or_create_executor_job`` afterwards, find no open 
row, and insert a fresh
+        RUNNING one -- bringing a row back to life right after the scheduler 
declared it stopped. Bounded
+        by the same timeout passed to ``get_health()``, so an implementation 
that ignores it can delay
+        shutdown but not hang it; that one case still risks the race, same as 
before this existed.

Review Comment:
   nit: the docstrings are still long and some still describe the review 
history ("same as before this existed" here, "there is no class-name fallback 
for that case" in `_executor_health_key`). Can you keep only what the code does 
not already say?



##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -456,6 +500,186 @@ def __init__(
     def heartbeat_callback(self, *, session: Session = NEW_SESSION) -> None:
         stats.incr("scheduler_heartbeat", 1, 1)
 
+    def _check_executor_health(self) -> None:
+        """
+        Kick off a health check for each reporting executor, in the background.
+
+        Called on its own timer (``[scheduler] 
executor_health_check_interval``), independent of the
+        scheduling loop and of each executor's own 
:meth:`~airflow.executors.base_executor.BaseExecutor.heartbeat`.
+        A new check for a given executor is skipped while its previous check 
is still running, so a
+        slow or hung dependency can only ever delay that executor's own health 
being updated, never
+        pile up work or block this (or any other) scheduler tick.
+
+        ``get_health()`` is passed a timeout, but an implementation that 
ignores it can still leave its
+        check thread running forever. Once a running check is a few intervals 
old, it's reported as
+        stalled: the scheduler records UNHEALTHY itself, since a check that 
hasn't answered isn't
+        still-healthy, and logs and emits a metric so the stall is visible. If 
the stuck call does
+        eventually return, its result overwrites this one.
+        """
+        for executor in self.executors:
+            key = _executor_health_key(executor)
+            if key not in self._executor_health_keys:
+                continue
+            thread, started = self._executor_health_check_threads.get(key, 
(None, 0.0))
+            if thread is not None and thread.is_alive():
+                stall_after = (
+                    self._executor_health_check_interval * 
self._executor_health_check_stall_after_intervals
+                )
+                if time.monotonic() - started > stall_after and key not in 
self._stalled_health_checks:
+                    self._stalled_health_checks.add(key)
+                    self.log.warning("Health check for executor %s has stopped 
responding", key)
+                    stats.incr(
+                        "scheduler.executor_health_check.stalled",
+                        tags=prune_dict(
+                            {"executor": type(executor).__name__, "team_name": 
executor.team_name}
+                        ),
+                    )
+                    try:
+                        self._record_executor_health_result(
+                            key, executor.team_name, 
HealthCheckResult.UNHEALTHY
+                        )
+                    except Exception:
+                        self.log.exception("Failed to record health check 
result for executor %s", key)
+                else:
+                    self.log.debug(
+                        "Skipping health check for executor %s, the previous 
check hasn't finished", key
+                    )
+                continue
+            self._stalled_health_checks.discard(key)
+            thread = threading.Thread(
+                target=self._run_executor_health_check,
+                args=(executor, key),
+                name=f"executor-health-check-{key}",
+                daemon=True,
+            )
+            thread.start()
+            self._executor_health_check_threads[key] = (thread, 
time.monotonic())
+
+    def _join_executor_health_check_threads(self) -> None:
+        """
+        Wait for any in-flight executor health check before this scheduler's 
ExecutorJob rows are closed.
+
+        Without this, a check thread still running when ``_end_executor_jobs`` 
closes those rows would
+        go on to call ``_get_or_create_executor_job`` afterwards, find no open 
row, and insert a fresh
+        RUNNING one -- bringing a row back to life right after the scheduler 
declared it stopped. Bounded
+        by the same timeout passed to ``get_health()``, so an implementation 
that ignores it can delay
+        shutdown but not hang it; that one case still risks the race, same as 
before this existed.
+        """
+        for thread, _ in self._executor_health_check_threads.values():
+            thread.join(timeout=self._executor_health_check_timeout)
+
+    def _run_executor_health_check(self, executor: BaseExecutor, key: str) -> 
None:
+        """Run one executor's get_health() off the scheduler thread and record 
an explicit result."""
+        try:
+            healthy = 
executor.get_health(timeout=self._executor_health_check_timeout)
+        except NotImplementedError:
+            result = HealthCheckResult.UNKNOWN
+        except Exception:
+            self.log.exception("Health check for executor %s raised an 
exception", key)
+            result = HealthCheckResult.UNHEALTHY
+        else:
+            if healthy is None:
+                result = HealthCheckResult.UNKNOWN
+            elif healthy:
+                result = HealthCheckResult.HEALTHY
+            else:
+                self.log.warning("Executor %s reported itself unhealthy", key)
+                result = HealthCheckResult.UNHEALTHY
+        try:
+            self._record_executor_health_result(key, executor.team_name, 
result)
+        except Exception:
+            self.log.exception("Failed to record health check result for 
executor %s", key)
+
+    @provide_session
+    def _touch_executor_heartbeats(self, *, session: Session = NEW_SESSION) -> 
None:
+        """
+        Keep every reporting executor's Job row heartbeat moving on the 
scheduler's own cadence.
+
+        ``get_health()`` itself only runs every 
``executor_health_check_interval`` (default 30s), far
+        slower than a Job row can go quiet for before 
``health_check_threshold`` calls it dead.
+        Updating the heartbeat only when a check finishes would make a 
perfectly healthy executor
+        flicker to UNHEALTHY between checks, every cycle. Keeping the 
heartbeat on the scheduler's own
+        short cadence instead, the same way it already does for its own Job 
row, means the row's
+        liveness reflects "the scheduler is still running and still intends to 
check this executor",
+        while ``health_check_result`` -- not this heartbeat -- carries 
whatever the last actual check
+        found.
+        """
+        if not self._executor_health_keys:
+            return
+        now = timezone.utcnow()
+        for key, team_name in self._executor_health_keys.items():
+            job = self._get_or_create_executor_job(key, team_name, 
session=session)
+            job.latest_heartbeat = now
+
+    def _get_or_create_executor_job(
+        self, executor_key: str, team_name: str | None, *, session: Session
+    ) -> Job:
+        """
+        Return this scheduler's own Job row for ``executor_key``, creating it 
if needed.
+
+        Keyed by ``owner_job_id`` (this scheduler's own Job id), not just 
``hostname``: two schedulers
+        running the same executor against shared infrastructure (e.g. the same 
Celery broker) each get
+        their own row, so one scheduler's healthy report can never paper over 
another's failing one.
+        A restarted scheduler gets a fresh row for the same reason its own Job 
row is fresh -- a new
+        id -- instead of quietly taking over a row left behind by its previous 
instance.
+
+        Inserted directly rather than through ``Job(...)``: that constructor 
fires the ``on_starting``
+        listener hook, meant for "a component is starting", but the scheduler 
is already running and
+        nothing here ever fires the matching ``before_stopping``. A plain 
insert sidesteps that, the
+        same way the Execution API's job-registration endpoint does for Jobs 
it creates on another
+        component's behalf.
+        """
+        job = session.scalar(
+            select(Job).where(
+                Job.job_type == EXECUTOR_JOB_TYPE,
+                Job.executor_class == executor_key,
+                Job.owner_job_id == self.job.id,
+                Job.end_date.is_(None),
+            )
+        )
+        if job is None:
+            now = timezone.utcnow()
+            inserted = session.execute(
+                insert(Job).values(
+                    job_type=EXECUTOR_JOB_TYPE,
+                    executor_class=executor_key,
+                    owner_job_id=self.job.id,
+                    health_check_result=HealthCheckResult.UNKNOWN,
+                    state=JobState.RUNNING,
+                    start_date=now,
+                    latest_heartbeat=now,
+                    hostname=get_hostname(),
+                    unixname=getuser(),
+                )
+            )
+            job_id = cast("CursorResult", inserted).inserted_primary_key[0]  # 
type: ignore[index]
+            if team_name:
+                session.add(JobTeam(job_id=job_id, team_name=team_name))
+            session.flush()
+            job = session.get(Job, job_id)
+        job.state = JobState.RUNNING
+        return job
+
+    @provide_session
+    def _record_executor_health_result(
+        self,
+        executor_key: str,
+        team_name: str | None,
+        result: HealthCheckResult,
+        *,
+        session: Session = NEW_SESSION,
+    ) -> None:
+        """
+        Record the outcome of an executor's health check as an explicit result.
+
+        Reuses the existing Jobs table rather than introducing a new status 
model, but the result
+        itself -- not heartbeat silence -- is what ``/monitor/health`` reads 
as HEALTHY/UNHEALTHY: a
+        row that is alive but has never completed a check, or whose last check 
raised or is still

Review Comment:
   nit: this is outdated, a check that raised or stalled is now recorded as 
UNHEALTHY, not UNKNOWN.



##########
airflow-core/tests/unit/jobs/test_scheduler_job_executor_health.py:
##########
@@ -0,0 +1,311 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+import threading
+import time
+from unittest import mock
+
+import pytest
+from sqlalchemy import select
+
+from airflow.executors.base_executor import BaseExecutor
+from airflow.executors.executor_utils import ExecutorName
+from airflow.jobs.job import EXECUTOR_JOB_TYPE, HealthCheckResult, Job, 
JobState
+from airflow.jobs.scheduler_job_runner import SchedulerJobRunner, 
_executor_health_key
+
+from tests_common.test_utils.config import conf_vars
+from tests_common.test_utils.db import clear_db_jobs
+
+pytestmark = pytest.mark.db_test
+
+
+class _StubExecutor(BaseExecutor):
+    mock_module_path = "stub.executor.path"
+    mock_alias = "stub_executor"
+
+    def __init__(self, result=True, team_name=None, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        self.name = ExecutorName(module_path=self.mock_module_path, 
alias=self.mock_alias)
+        self.team_name = team_name
+        self.result = result
+        self.calls: list[float] = []
+
+    def get_health(self, timeout: float) -> bool | None:
+        self.calls.append(timeout)
+        if isinstance(self.result, Exception):
+            raise self.result
+        return self.result
+
+
[email protected](autouse=True)
+def clean_jobs():
+    clear_db_jobs()
+    yield
+    clear_db_jobs()
+
+
+def _make_runner(executor, session):
+    scheduler_job = Job()
+    session.add(scheduler_job)
+    session.commit()
+    runner = SchedulerJobRunner(job=scheduler_job, executors=[executor])
+    return runner
+
+
+def _get_executor_job(session, owner_job_id, executor_key):
+    return session.scalar(
+        select(Job).where(
+            Job.job_type == EXECUTOR_JOB_TYPE,
+            Job.owner_job_id == owner_job_id,
+            Job.executor_class == executor_key,
+        )
+    )
+
+
+def 
test_touch_executor_heartbeats_creates_a_row_for_a_reporting_executor(session):
+    executor = _StubExecutor()
+    runner = _make_runner(executor, session)
+    key = _executor_health_key(executor)
+
+    runner._touch_executor_heartbeats(session=session)
+
+    job = _get_executor_job(session, runner.job.id, key)
+    assert job is not None
+    assert job.health_check_result == HealthCheckResult.UNKNOWN
+    assert job.latest_heartbeat is not None
+    assert job.hostname != key
+
+
+def 
test_touch_executor_heartbeats_skips_executors_that_do_not_override_get_health(session):
+    executor = BaseExecutor()
+    executor.name = 
ExecutorName(module_path="airflow.executors.local_executor.LocalExecutor", 
alias="Local")
+    runner = _make_runner(executor, session)
+
+    runner._touch_executor_heartbeats(session=session)
+
+    assert session.scalar(select(Job).where(Job.job_type == 
EXECUTOR_JOB_TYPE)) is None
+
+
+def 
test_touch_executor_heartbeats_moves_the_heartbeat_without_changing_the_result(session):
+    executor = _StubExecutor()
+    runner = _make_runner(executor, session)
+    key = _executor_health_key(executor)
+
+    runner._touch_executor_heartbeats(session=session)
+    first = _get_executor_job(session, runner.job.id, key)
+    first.health_check_result = HealthCheckResult.HEALTHY
+    first_heartbeat = first.latest_heartbeat
+    session.commit()
+
+    runner._touch_executor_heartbeats(session=session)
+    second = _get_executor_job(session, runner.job.id, key)
+
+    assert second.id == first.id
+    assert second.health_check_result == HealthCheckResult.HEALTHY
+    assert second.latest_heartbeat >= first_heartbeat
+
+
[email protected](
+    ("result", "expected"),
+    [
+        pytest.param(True, HealthCheckResult.HEALTHY, id="healthy"),
+        pytest.param(False, HealthCheckResult.UNHEALTHY, id="unhealthy"),
+        pytest.param(None, HealthCheckResult.UNKNOWN, id="unknown_on_none"),
+        pytest.param(RuntimeError("boom"), HealthCheckResult.UNHEALTHY, 
id="unhealthy_and_does_not_raise"),
+        pytest.param(NotImplementedError(), HealthCheckResult.UNKNOWN, 
id="unknown_on_not_implemented"),
+    ],
+)
+def test_run_executor_health_check_records_result(session, result, expected):
+    executor = _StubExecutor(result=result)
+    runner = _make_runner(executor, session)
+    key = _executor_health_key(executor)
+
+    runner._run_executor_health_check(executor, key)
+
+    job = _get_executor_job(session, runner.job.id, key)
+    assert job.health_check_result == expected
+
+
+def 
test_run_executor_health_check_does_not_log_reported_itself_unhealthy_when_it_raised(session):
+    executor = _StubExecutor(result=RuntimeError("boom"))
+    runner = _make_runner(executor, session)
+    key = _executor_health_key(executor)
+
+    with mock.patch.object(runner.log, "warning") as mock_warning:

Review Comment:
   nit: can you use `caplog` instead of patching `runner.log`?



##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -456,6 +500,186 @@ def __init__(
     def heartbeat_callback(self, *, session: Session = NEW_SESSION) -> None:
         stats.incr("scheduler_heartbeat", 1, 1)
 
+    def _check_executor_health(self) -> None:
+        """
+        Kick off a health check for each reporting executor, in the background.
+
+        Called on its own timer (``[scheduler] 
executor_health_check_interval``), independent of the
+        scheduling loop and of each executor's own 
:meth:`~airflow.executors.base_executor.BaseExecutor.heartbeat`.
+        A new check for a given executor is skipped while its previous check 
is still running, so a
+        slow or hung dependency can only ever delay that executor's own health 
being updated, never
+        pile up work or block this (or any other) scheduler tick.
+
+        ``get_health()`` is passed a timeout, but an implementation that 
ignores it can still leave its
+        check thread running forever. Once a running check is a few intervals 
old, it's reported as
+        stalled: the scheduler records UNHEALTHY itself, since a check that 
hasn't answered isn't
+        still-healthy, and logs and emits a metric so the stall is visible. If 
the stuck call does
+        eventually return, its result overwrites this one.
+        """
+        for executor in self.executors:
+            key = _executor_health_key(executor)
+            if key not in self._executor_health_keys:
+                continue
+            thread, started = self._executor_health_check_threads.get(key, 
(None, 0.0))
+            if thread is not None and thread.is_alive():
+                stall_after = (
+                    self._executor_health_check_interval * 
self._executor_health_check_stall_after_intervals
+                )
+                if time.monotonic() - started > stall_after and key not in 
self._stalled_health_checks:
+                    self._stalled_health_checks.add(key)
+                    self.log.warning("Health check for executor %s has stopped 
responding", key)
+                    stats.incr(
+                        "scheduler.executor_health_check.stalled",
+                        tags=prune_dict(
+                            {"executor": type(executor).__name__, "team_name": 
executor.team_name}
+                        ),
+                    )
+                    try:
+                        self._record_executor_health_result(
+                            key, executor.team_name, 
HealthCheckResult.UNHEALTHY
+                        )
+                    except Exception:
+                        self.log.exception("Failed to record health check 
result for executor %s", key)
+                else:
+                    self.log.debug(
+                        "Skipping health check for executor %s, the previous 
check hasn't finished", key
+                    )
+                continue
+            self._stalled_health_checks.discard(key)
+            thread = threading.Thread(
+                target=self._run_executor_health_check,
+                args=(executor, key),
+                name=f"executor-health-check-{key}",
+                daemon=True,
+            )
+            thread.start()
+            self._executor_health_check_threads[key] = (thread, 
time.monotonic())
+
+    def _join_executor_health_check_threads(self) -> None:
+        """
+        Wait for any in-flight executor health check before this scheduler's 
ExecutorJob rows are closed.
+
+        Without this, a check thread still running when ``_end_executor_jobs`` 
closes those rows would
+        go on to call ``_get_or_create_executor_job`` afterwards, find no open 
row, and insert a fresh
+        RUNNING one -- bringing a row back to life right after the scheduler 
declared it stopped. Bounded
+        by the same timeout passed to ``get_health()``, so an implementation 
that ignores it can delay
+        shutdown but not hang it; that one case still risks the race, same as 
before this existed.
+        """
+        for thread, _ in self._executor_health_check_threads.values():
+            thread.join(timeout=self._executor_health_check_timeout)
+
+    def _run_executor_health_check(self, executor: BaseExecutor, key: str) -> 
None:
+        """Run one executor's get_health() off the scheduler thread and record 
an explicit result."""
+        try:
+            healthy = 
executor.get_health(timeout=self._executor_health_check_timeout)
+        except NotImplementedError:
+            result = HealthCheckResult.UNKNOWN
+        except Exception:
+            self.log.exception("Health check for executor %s raised an 
exception", key)
+            result = HealthCheckResult.UNHEALTHY
+        else:
+            if healthy is None:
+                result = HealthCheckResult.UNKNOWN
+            elif healthy:
+                result = HealthCheckResult.HEALTHY
+            else:
+                self.log.warning("Executor %s reported itself unhealthy", key)
+                result = HealthCheckResult.UNHEALTHY
+        try:
+            self._record_executor_health_result(key, executor.team_name, 
result)
+        except Exception:
+            self.log.exception("Failed to record health check result for 
executor %s", key)
+
+    @provide_session
+    def _touch_executor_heartbeats(self, *, session: Session = NEW_SESSION) -> 
None:
+        """
+        Keep every reporting executor's Job row heartbeat moving on the 
scheduler's own cadence.
+
+        ``get_health()`` itself only runs every 
``executor_health_check_interval`` (default 30s), far
+        slower than a Job row can go quiet for before 
``health_check_threshold`` calls it dead.
+        Updating the heartbeat only when a check finishes would make a 
perfectly healthy executor
+        flicker to UNHEALTHY between checks, every cycle. Keeping the 
heartbeat on the scheduler's own
+        short cadence instead, the same way it already does for its own Job 
row, means the row's
+        liveness reflects "the scheduler is still running and still intends to 
check this executor",
+        while ``health_check_result`` -- not this heartbeat -- carries 
whatever the last actual check
+        found.
+        """
+        if not self._executor_health_keys:
+            return
+        now = timezone.utcnow()
+        for key, team_name in self._executor_health_keys.items():
+            job = self._get_or_create_executor_job(key, team_name, 
session=session)
+            job.latest_heartbeat = now
+
+    def _get_or_create_executor_job(
+        self, executor_key: str, team_name: str | None, *, session: Session
+    ) -> Job:
+        """
+        Return this scheduler's own Job row for ``executor_key``, creating it 
if needed.
+
+        Keyed by ``owner_job_id`` (this scheduler's own Job id), not just 
``hostname``: two schedulers
+        running the same executor against shared infrastructure (e.g. the same 
Celery broker) each get
+        their own row, so one scheduler's healthy report can never paper over 
another's failing one.
+        A restarted scheduler gets a fresh row for the same reason its own Job 
row is fresh -- a new
+        id -- instead of quietly taking over a row left behind by its previous 
instance.
+
+        Inserted directly rather than through ``Job(...)``: that constructor 
fires the ``on_starting``
+        listener hook, meant for "a component is starting", but the scheduler 
is already running and
+        nothing here ever fires the matching ``before_stopping``. A plain 
insert sidesteps that, the
+        same way the Execution API's job-registration endpoint does for Jobs 
it creates on another
+        component's behalf.
+        """
+        job = session.scalar(
+            select(Job).where(
+                Job.job_type == EXECUTOR_JOB_TYPE,
+                Job.executor_class == executor_key,
+                Job.owner_job_id == self.job.id,
+                Job.end_date.is_(None),
+            )
+        )
+        if job is None:
+            now = timezone.utcnow()
+            inserted = session.execute(
+                insert(Job).values(
+                    job_type=EXECUTOR_JOB_TYPE,
+                    executor_class=executor_key,
+                    owner_job_id=self.job.id,
+                    health_check_result=HealthCheckResult.UNKNOWN,
+                    state=JobState.RUNNING,
+                    start_date=now,
+                    latest_heartbeat=now,
+                    hostname=get_hostname(),
+                    unixname=getuser(),
+                )
+            )
+            job_id = cast("CursorResult", inserted).inserted_primary_key[0]  # 
type: ignore[index]
+            if team_name:
+                session.add(JobTeam(job_id=job_id, team_name=team_name))
+            session.flush()
+            job = session.get(Job, job_id)
+        job.state = JobState.RUNNING
+        return job
+
+    @provide_session
+    def _record_executor_health_result(
+        self,
+        executor_key: str,
+        team_name: str | None,
+        result: HealthCheckResult,
+        *,
+        session: Session = NEW_SESSION,
+    ) -> None:
+        """
+        Record the outcome of an executor's health check as an explicit result.
+
+        Reuses the existing Jobs table rather than introducing a new status 
model, but the result
+        itself -- not heartbeat silence -- is what ``/monitor/health`` reads 
as HEALTHY/UNHEALTHY: a
+        row that is alive but has never completed a check, or whose last check 
raised or is still
+        hanging, stays UNKNOWN instead of looking identical to a genuine 
failure.
+        """
+        job = self._get_or_create_executor_job(executor_key, team_name, 
session=session)

Review Comment:
   The second part of my previous comment is not fixed yet. This still goes 
through `_get_or_create_executor_job`, so the check thread and 
`_touch_executor_heartbeats` can both insert a row when there is no open one 
(e.g. after another scheduler's `adopt_or_reset_orphaned_tasks` failed it). Can 
this only update the open row, and do nothing when there is none?



##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -2174,6 +2433,20 @@ def _run_scheduler_loop(self) -> None:
             non_fatal=True,
         )
 
+        if self._executor_health_keys:
+            if self.job.heartrate > 0:
+                timers.call_regular_interval(
+                    delay=self.job.heartrate,
+                    action=self._touch_executor_heartbeats,
+                    non_fatal=True,
+                )

Review Comment:
   With `scheduler_heartbeat_sec = 0` this timer is never registered, and 
`_record_executor_health_result` does not update `latest_heartbeat`. So the 
`ExecutorJob` row goes stale after `scheduler_health_check_threshold`, 
`/monitor/health` reports the executor DOWN, and 
`adopt_or_reset_orphaned_tasks` fails the row, so the next check inserts a new 
one. The `max(self.job.heartrate, 1.0)` floor you had before handled that, can 
you bring it back?
   
   ```suggestion
               timers.call_regular_interval(
                   delay=max(self.job.heartrate, 1.0),
                   action=self._touch_executor_heartbeats,
                   non_fatal=True,
               )
   ```



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