vincbeck commented on code in PR #76410:
URL: https://github.com/apache/airflow/pull/76410#discussion_r4668032960
##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -456,6 +501,181 @@ 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
+ future pending forever. Once a pending future 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
+ future, started = self._executor_health_check_futures.get(key,
(None, 0.0))
+ if future is not None and not future.done():
+ 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)
+ future = Future()
+ threading.Thread(
+ target=self._run_executor_health_check_and_resolve,
+ args=(executor, key, future),
+ name=f"executor-health-check-{key}",
+ daemon=True,
+ ).start()
+ self._executor_health_check_futures[key] = (future,
time.monotonic())
+
+ def _run_executor_health_check_and_resolve(
+ self, executor: BaseExecutor, key: str, future: Future
+ ) -> None:
+ """Run one executor's health check and resolve its tracking future,
even if it raises."""
+ try:
+ self._run_executor_health_check(executor, key)
+ finally:
+ future.set_result(None)
+
+ 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:
+ healthy = None
+ except Exception:
+ self.log.exception("Health check for executor %s raised an
exception", key)
+ healthy = False
+ 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:
A health check that finishes after shutdown brings the row back.
`_end_executor_jobs` closes this scheduler's `ExecutorJob` rows in `finally`,
but a check thread still running then lands here, `_get_or_create_executor_job`
finds no open row, and inserts a new RUNNING row owned by the scheduler that
just exited. It stays RUNNING until another scheduler's
`adopt_or_reset_orphaned_tasks` fails it. The same select-then-insert also runs
from the main thread in `_touch_executor_heartbeats`, so once another scheduler
fails the old row, both threads can insert one and the heartbeat and the result
end up on different rows. Fix: create rows only from the main thread, and make
this method update the open row and do nothing when there is none.
##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -456,6 +501,181 @@ 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
+ future pending forever. Once a pending future 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
+ future, started = self._executor_health_check_futures.get(key,
(None, 0.0))
+ if future is not None and not future.done():
+ 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)
+ future = Future()
Review Comment:
nit: the `Future` is only used as a done flag. Why not keep the `Thread` and
check `is_alive()`? That would also remove
`_run_executor_health_check_and_resolve`.
##########
airflow-core/src/airflow/jobs/scheduler_job_runner.py:
##########
@@ -456,6 +501,181 @@ 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
+ future pending forever. Once a pending future 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
+ future, started = self._executor_health_check_futures.get(key,
(None, 0.0))
+ if future is not None and not future.done():
+ 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)
+ future = Future()
+ threading.Thread(
+ target=self._run_executor_health_check_and_resolve,
+ args=(executor, key, future),
+ name=f"executor-health-check-{key}",
+ daemon=True,
+ ).start()
+ self._executor_health_check_futures[key] = (future,
time.monotonic())
+
+ def _run_executor_health_check_and_resolve(
+ self, executor: BaseExecutor, key: str, future: Future
+ ) -> None:
+ """Run one executor's health check and resolve its tracking future,
even if it raises."""
+ try:
+ self._run_executor_health_check(executor, key)
+ finally:
+ future.set_result(None)
+
+ 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:
+ healthy = None
+ except Exception:
+ self.log.exception("Health check for executor %s raised an
exception", key)
+ healthy = False
+ if healthy is None:
+ result = HealthCheckResult.UNKNOWN
+ elif healthy:
+ result = HealthCheckResult.HEALTHY
+ else:
+ self.log.warning("Executor %s reported itself unhealthy", key)
Review Comment:
nit: when `get_health()` raises, this also logs "reported itself unhealthy"
right after the traceback, which reads like it returned `False`. Can you log it
only when it actually returned `False`?
##########
airflow-core/tests/unit/api/common/test_airflow_health.py:
##########
@@ -663,3 +673,330 @@ def
test_get_airflow_health_mixed_triggerers_include_team_names(self, testing_te
},
]
assert health_status["triggerer"]["latest_triggerer_heartbeat"] ==
alive_heartbeat.isoformat()
+
+
+# -- Executor health: no configured executor overrides get_health() by
default, so these tests patch
+# -- _configured_executor_keys directly rather than relying on a real executor
class, exactly as the
+# -- bundle/team partition tests above patch _configured_bundle_teams.
+
+
+def _executor(
+ *,
+ alive: bool,
+ healthy: bool | None = True,
+ team_name: str | None = None,
+ executor: str | None = None,
+ owner_job_id: int = 1,
+) -> MagicMock:
+ job = _mock_job(
+ hostname=f"host-{owner_job_id}",
+ heartbeat=datetime(2024, 2, 1),
+ alive=alive,
+ team_names=[team_name] if team_name else [],
+ )
+ job.executor_class = executor or f"executor-{team_name}-{'alive' if alive
else 'stale'}"
+ job.owner_job_id = owner_job_id
+ if healthy is None:
+ job.health_check_result = HealthCheckResult.UNKNOWN
+ else:
+ job.health_check_result = HealthCheckResult.HEALTHY if healthy else
HealthCheckResult.UNHEALTHY
+ return job
+
+
+def _patch_executor_keys(keys: set[str]):
+ return
patch("airflow.api.common.airflow_health._configured_executor_keys",
return_value=keys)
+
+
+def _patch_live_scheduler_ids(ids: set[int]):
+ """Patch which owning-scheduler ids count as alive, standing in for a real
SchedulerJob query."""
+ return patch("airflow.api.common.airflow_health._live_scheduler_job_ids",
return_value=ids)
+
+
+class _HealthCheckingExecutor(BaseExecutor):
+ """A stand-in for a concrete executor (e.g. Celery) that has implemented
get_health()."""
+
+ def get_health(self, timeout: float) -> bool | None:
+ return True
+
+
+class TestConfiguredExecutorKeys:
+ """``_configured_executor_keys`` only counts an executor that actually
implements get_health()."""
+
+ @pytest.fixture(autouse=True)
+ def clear_executor_caches(self):
+ _configured_executor_keys.cache_clear()
+ _configured_executor_names.cache_clear()
+ yield
+ _configured_executor_keys.cache_clear()
+ _configured_executor_names.cache_clear()
+
+
@patch("airflow.api.common.airflow_health.ExecutorLoader.get_executor_names")
+ def test_empty_when_no_executor_overrides_get_health(self,
mock_get_executor_names):
+ mock_get_executor_names.return_value = [
+
ExecutorName(module_path="airflow.executors.local_executor.LocalExecutor",
alias="Local")
+ ]
+ assert _configured_executor_keys() == set()
+
+
@patch("airflow.api.common.airflow_health.ExecutorLoader.import_executor_cls")
+
@patch("airflow.api.common.airflow_health.ExecutorLoader.get_executor_names")
+ def test_includes_an_executor_that_overrides_get_health(
Review Comment:
nit: this test and
`test_module_path_configured_executor_has_no_alias_but_still_matches` only
differ by the alias, can you merge them into one `@pytest.mark.parametrize`
test? Same for the alias and module path tests in
`TestExecutorInstanceHealthDisplayName`.
--
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]