This is an automated email from the ASF dual-hosted git repository.
ferruzzi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new 1974010722d Add scaffolding for per-executor health reporting (#76410)
1974010722d is described below
commit 1974010722dd64c2fdf6b0f29d9ac17c551bf781
Author: Joel Emmanuel <[email protected]>
AuthorDate: Wed Nov 25 23:23:55 2026 +0000
Add scaffolding for per-executor health reporting (#76410)
Executors did not appear on /monitor/health, so an executor whose backend
was unreachable looked fine as long as the scheduler was alive. This adds the
plumbing a concrete executor needs to report its own health, without changing
behaviour for any existing executor.
---
.../logging-monitoring/check-health.rst | 29 +-
airflow-core/docs/migrations-ref.rst | 4 +-
.../src/airflow/api/common/airflow_health.py | 175 +++++++++-
.../airflow/api_fastapi/common/parameters/misc.py | 7 +-
.../api_fastapi/core_api/datamodels/monitor.py | 20 ++
.../core_api/openapi/v2-rest-api-generated.yaml | 91 +++++
.../src/airflow/cli/commands/jobs_command.py | 6 +-
.../src/airflow/config_templates/config.yml | 13 +
.../src/airflow/executors/base_executor.py | 31 ++
airflow-core/src/airflow/jobs/job.py | 38 ++
.../src/airflow/jobs/scheduler_job_runner.py | 278 ++++++++++++++-
...158_3_5_0_add_executor_health_columns_to_job.py | 55 +++
.../airflow/ui/openapi-gen/requests/schemas.gen.ts | 136 ++++++++
.../airflow/ui/openapi-gen/requests/types.gen.ts | 33 ++
airflow-core/src/airflow/utils/db.py | 2 +-
.../tests/unit/api/common/test_airflow_health.py | 382 +++++++++++++++++++--
.../api_fastapi/core_api/routes/public/test_job.py | 21 +-
.../tests/unit/cli/commands/test_jobs_command.py | 28 +-
.../tests/unit/executors/test_base_executor.py | 5 +
airflow-core/tests/unit/jobs/test_scheduler_job.py | 37 +-
.../jobs/test_scheduler_job_executor_health.py | 330 ++++++++++++++++++
.../src/airflowctl/api/datamodels/generated.py | 40 +++
.../src/airflowctl/ctl/commands/jobs_command.py | 4 +
.../airflow_ctl/ctl/commands/test_jobs_command.py | 20 +-
.../observability/metrics/metrics_template.yaml | 8 +
25 files changed, 1738 insertions(+), 55 deletions(-)
diff --git
a/airflow-core/docs/administration-and-deployment/logging-monitoring/check-health.rst
b/airflow-core/docs/administration-and-deployment/logging-monitoring/check-health.rst
index c259a68d3b3..614480c855d 100644
---
a/airflow-core/docs/administration-and-deployment/logging-monitoring/check-health.rst
+++
b/airflow-core/docs/administration-and-deployment/logging-monitoring/check-health.rst
@@ -79,6 +79,20 @@ including per-instance details when multiple schedulers,
triggerers, or Dag proc
"bundle_names": ["dags-team-a"]
}
]
+ },
+ "executor": {
+ "status": "healthy",
+ "latest_executor_heartbeat": "2018-12-26T17:16:12+00:00",
+ "detailed_status": "healthy",
+ "instances": [
+ {
+ "hostname": "scheduler-1.example.com",
+ "latest_executor_heartbeat": "2018-12-26T17:16:12+00:00",
+ "executor": "CeleryExecutor",
+ "team_names": ["team-a"],
+ "health_check_result": "healthy"
+ }
+ ]
}
}
@@ -86,7 +100,11 @@ including per-instance details when multiple schedulers,
triggerers, or Dag proc
* ``status`` is ``"healthy"`` when a valid connection can be initiated with
the database, otherwise ``"unhealthy"``.
-* Component-level fields for ``scheduler``, ``triggerer``, and
``dag_processor``
+* The ``executor`` block is only present when at least one configured executor
implements its own
+ health check. Most executors don't, so on most deployments this block is
omitted entirely rather
+ than shown as unhealthy.
+
+* Component-level fields for ``scheduler``, ``triggerer``, ``dag_processor``,
and ``executor``
* ``status`` (legacy aggregate): ``"healthy"`` if **any** running instance
is alive, otherwise ``"unhealthy"``
(including when no running jobs exist for that component).
@@ -108,6 +126,10 @@ including per-instance details when multiple schedulers,
triggerers, or Dag proc
to report: ``"healthy"`` if at least one is alive, ``"down"`` if none
is. ``"degraded"`` is never
returned for the scheduler. Use ``instances`` to see how many replicas
are up, and your orchestrator
or the ``scheduler_heartbeat`` metric to alert on reduced scheduling
throughput.
+ * **Executor** — each configured executor that implements a health check
is its own part.
+ ``"healthy"`` when every such executor has a live, passing check,
``"degraded"`` when only some
+ do, ``"down"`` when none do. A check still waiting on its first result
does not count against
+ coverage.
Because the expected set of work comes from configuration rather than from
the job table,
``detailed_status`` is unaffected by how instances come and go. Restarting
an instance — including after
@@ -130,8 +152,11 @@ including per-instance details when multiple schedulers,
triggerers, or Dag proc
* ``hostname``: host where the component is running
* the corresponding ``latest_*_heartbeat`` for that instance
- * ``team_names`` (triggerer only): teams the triggerer is scoped to, empty
when unscoped
+ * ``team_names`` (triggerer and executor): teams the triggerer is scoped
to, or the executor's team,
+ empty when unscoped
* ``bundle_names`` (Dag processor only): Dag bundles that processor is
configured to parse, or ``null`` when unset
+ * ``executor`` (executor only): the name configured in ``[core] executor``
for this entry
+ * ``health_check_result`` (executor only): the last result of that
executor's own health check
* For HA deployments, prefer ``detailed_status`` and ``instances`` when you
need to see every scheduler,
triggerer, or Dag processor. The top-level ``status`` remains useful for
simple probes that only care
diff --git a/airflow-core/docs/migrations-ref.rst
b/airflow-core/docs/migrations-ref.rst
index a8a8f6c67e2..4b360fdda96 100644
--- a/airflow-core/docs/migrations-ref.rst
+++ b/airflow-core/docs/migrations-ref.rst
@@ -39,7 +39,9 @@ Here's the list of all the Database Migrations that are
executed via when you ru
+-------------------------+------------------+-------------------+--------------------------------------------------------------+
| Revision ID | Revises ID | Airflow Version | Description
|
+=========================+==================+===================+==============================================================+
-| ``c64b10719069`` (head) | ``d8c6f3a129b0`` | ``3.5.0`` | Rename
trigger owner_ref to used_by_ref. |
+| ``feb8b1e719ee`` (head) | ``c64b10719069`` | ``3.5.0`` | Add
health_check_result and owner_job_id to Job. |
++-------------------------+------------------+-------------------+--------------------------------------------------------------+
+| ``c64b10719069`` | ``d8c6f3a129b0`` | ``3.5.0`` | Rename
trigger owner_ref to used_by_ref. |
+-------------------------+------------------+-------------------+--------------------------------------------------------------+
| ``d8c6f3a129b0`` | ``687eb253de24`` | ``3.5.0`` | Add durable
Dag processor work claims. |
+-------------------------+------------------+-------------------+--------------------------------------------------------------+
diff --git a/airflow-core/src/airflow/api/common/airflow_health.py
b/airflow-core/src/airflow/api/common/airflow_health.py
index 7b05a03f959..82aff5fe4c3 100644
--- a/airflow-core/src/airflow/api/common/airflow_health.py
+++ b/airflow-core/src/airflow/api/common/airflow_health.py
@@ -19,6 +19,7 @@ from __future__ import annotations
import logging
from datetime import datetime
from enum import Enum
+from functools import lru_cache
from typing import TYPE_CHECKING, Any
from sqlalchemy import select
@@ -26,8 +27,9 @@ from sqlalchemy import select
from airflow._shared.timezones import timezone
from airflow.configuration import conf
from airflow.dag_processing.bundles.manager import
get_configured_bundle_team_names
+from airflow.executors.executor_loader import ExecutorLoader
from airflow.jobs.dag_processor_job_runner import DagProcessorJobRunner
-from airflow.jobs.job import Job
+from airflow.jobs.job import EXECUTOR_JOB_TYPE, HealthCheckResult, Job
from airflow.jobs.scheduler_job_runner import SchedulerJobRunner
from airflow.jobs.triggerer_job_runner import TriggererJobRunner
from airflow.utils.session import NEW_SESSION, provide_session
@@ -35,6 +37,8 @@ from airflow.utils.session import NEW_SESSION, provide_session
if TYPE_CHECKING:
from sqlalchemy.orm import Session
+ from airflow.executors.executor_utils import ExecutorName
+
log = logging.getLogger(__name__)
@@ -54,13 +58,12 @@ class DetailedHealthStatus(str, Enum):
@provide_session
-def get_jobs_health(job_runner_class, *, session: Session = NEW_SESSION) ->
list[Job]:
+def get_jobs_health(job_type: str, *, session: Session = NEW_SESSION) ->
list[Job]:
"""
- Return live unfinished jobs and the latest unfinished job, ordered by
heartbeat.
+ Return live unfinished jobs and the latest unfinished job of the given job
type, ordered by heartbeat.
Keep the latest job even when dead so health responses retain its
heartbeat.
"""
- job_type = job_runner_class.job_type
unfinished = Job.end_date.is_(None)
# Two separate queries rather than one ``id IN (... UNION ALL ...)``:
MySQL cannot semijoin that
# form and runs it as a dependent subquery per ``job`` row, which scales
with job history.
@@ -120,6 +123,48 @@ def _dag_processor_instance_health(job: Job) -> dict[str,
Any]:
}
+@lru_cache
+def _configured_executor_names() -> dict[str, ExecutorName]:
+ """
+ Map every configured executor's health key to its ``ExecutorName``, for
display purposes.
+
+ Cached for the same reason :func:`_configured_executor_keys` is: the
configured executors can't
+ change while the process runs.
+ """
+ try:
+ return {repr(name): name for name in
ExecutorLoader.get_executor_names(validate_teams=False)}
+ except Exception:
+ # A health probe must not fail on malformed executor config; the row's
own key is still shown.
+ log.warning("Could not read the executor configuration", exc_info=True)
+ return {}
+
+
+def _executor_instance_health(job: Job) -> dict[str, Any]:
+ # job.executor_class is the internal identity key (e.g.
":CeleryExecutor:"), not the name the user
+ # configured. Reporting the alias or module path they wrote in [core]
executor instead is a better
+ # user experience; the key itself is only shown as a fallback, e.g. for a
since-reconfigured executor.
+ name = _configured_executor_names().get(job.executor_class) if
job.executor_class else None
+ return {
+ **_job_instance_health(job, "latest_executor_heartbeat"),
+ "executor": (name.alias or name.module_path) if name else
job.executor_class,
+ "team_names": job.team_names,
+ "health_check_result": job.health_check_result,
+ }
+
+
+def _live_executor_jobs(jobs: list[Job], live_scheduler_ids: set[int]) ->
list[Job]:
+ """
+ Narrow executor rows down to live instances whose owning scheduler is also
still alive.
+
+ A row can stay technically alive for a little while after its scheduler
process has already
+ died (its heartbeat hasn't crossed the staleness threshold yet), so
liveness on the row alone
+ isn't enough; cross-checking the owner avoids briefly reporting a dead
scheduler's executor as
+ healthy. ``live_scheduler_ids`` comes from the caller's own scheduler job
query (e.g.
+ :func:`get_airflow_health`) rather than this re-querying them.
+ """
+ return [job for job in jobs if job.is_alive() and job.owner_job_id in
live_scheduler_ids]
+
+
# ``detailed_status`` answers "is every part of this component's work being
done", which needs a
# denominator. Counting job rows cannot supply one: ``end_date`` is only
written by a cooperative
# shutdown, so a replica lost to SIGKILL, an OOM kill, or a node eviction
leaves an unfinished row
@@ -170,6 +215,83 @@ def _dag_processor_detailed_status(jobs: list[Job]) ->
DetailedHealthStatus:
return _coverage_status(expected, covered)
+@lru_cache
+def _configured_executor_keys() -> set[str]:
+ """
+ Return the key each configured executor that implements a health check
would be recorded under.
+
+ Most executors don't override
:meth:`~airflow.executors.base_executor.BaseExecutor.get_health`,
+ so this deliberately excludes them rather than counting every configured
executor: an executor
+ that was never going to report anything isn't a gap in coverage, and a
deployment where nothing
+ implements a health check should see no ``executor`` block at all in
``/monitor/health``, not an
+ ``unhealthy`` one.
+
+ Also empty when ``executor_health_check_interval`` is 0: the scheduler
records no ``ExecutorJob``
+ rows in that case either, so nothing would ever cover an expected key and
``/monitor/health`` would
+ report the executor DOWN forever instead of omitting the block.
+
+ Cached: this calls
:meth:`~airflow.executors.executor_loader.ExecutorLoader.import_executor_cls`,
+ which imports every configured executor class, and the configured
executors can't change while the
+ process runs. Without caching, an API server would redo those imports --
and reproduce any import
+ failure's warning and traceback -- on every single call to
``/monitor/health``. Team validation is
+ skipped (``validate_teams=False``), the same as ``connections.py`` does,
so a database hiccup on
+ the first call can't get cached as "no executors".
+ """
+ try:
+ if conf.getfloat("scheduler", "executor_health_check_interval",
fallback=30.0) <= 0:
+ return set()
+ names = ExecutorLoader.get_executor_names(validate_teams=False)
+ except Exception:
+ # A health probe must not fail on malformed executor config; callers
fall back to liveness only.
+ log.warning("Could not read the executor configuration", exc_info=True)
+ return set()
+
+ keys = set()
+ for name in names:
+ try:
+ executor_cls, _ = ExecutorLoader.import_executor_cls(name)
+ except Exception:
+ log.warning("Could not import configured executor %s",
name.module_path, exc_info=True)
+ continue
+ if executor_cls.overrides_get_health():
+ keys.add(repr(name))
+ return keys
+
+
+def _executor_detailed_status(jobs: list[Job], live_scheduler_ids: set[int])
-> DetailedHealthStatus:
+ """
+ Status from configured-executor coverage: each configured executor is its
own partition.
+
+ A shared executor backend (e.g. one Celery broker) can be reachable from
one scheduler and not
+ another, so coverage is decided per live, currently-owned row rather than
by any single row for
+ that executor key: one scheduler finding it down is real signal, not noise
an unrelated healthy
+ row should paper over.
+
+ ``live_scheduler_ids`` is forwarded to :func:`_live_executor_jobs`; see
its docstring.
+ """
+ expected = _configured_executor_keys()
+ live_jobs = _live_executor_jobs(jobs, live_scheduler_ids)
+ if not expected:
+ return _liveness_status(live_jobs)
+
+ covered: set[str] = set()
+ unhealthy: set[str] = set()
+ seen: set[str] = set()
+ for job in live_jobs:
+ if not job.executor_class or job.executor_class not in expected:
+ continue
+ seen.add(job.executor_class)
+ if job.health_check_result == HealthCheckResult.HEALTHY:
+ covered.add(job.executor_class)
+ elif job.health_check_result == HealthCheckResult.UNHEALTHY:
+ unhealthy.add(job.executor_class)
+ expected = expected - (seen - covered - unhealthy)
+ if not expected:
+ return _liveness_status(live_jobs)
+ covered -= unhealthy
+ return _coverage_status(expected, covered)
+
+
def _triggerer_detailed_status(jobs: list[Job]) -> DetailedHealthStatus:
"""Status from team coverage, since a triggerer only picks up triggers for
its own team."""
if not conf.getboolean("core", "multi_team"):
@@ -192,27 +314,32 @@ def _triggerer_detailed_status(jobs: list[Job]) ->
DetailedHealthStatus:
def get_airflow_health() -> dict[str, Any]:
- """Get the health for Airflow metadatabase, scheduler, triggerer, and dag
processor."""
+ """Get the health for Airflow metadatabase, scheduler, triggerer, dag
processor, and executors."""
metadatabase_status = HealthStatus.HEALTHY
latest_scheduler_heartbeat = None
latest_triggerer_heartbeat = None
latest_dag_processor_heartbeat = None
+ latest_executor_heartbeat = None
scheduler_instances: list[dict[str, Any]] | None = None
triggerer_instances: list[dict[str, Any]] | None = None
dag_processor_instances: list[dict[str, Any]] | None = None
+ executor_instances: list[dict[str, Any]] | None = None
scheduler_status = HealthStatus.UNHEALTHY
triggerer_status = HealthStatus.UNHEALTHY
dag_processor_status = HealthStatus.UNHEALTHY
+ executor_status = HealthStatus.UNHEALTHY
scheduler_detailed_status = DetailedHealthStatus.DOWN
triggerer_detailed_status = DetailedHealthStatus.DOWN
dag_processor_detailed_status = DetailedHealthStatus.DOWN
+ executor_detailed_status = DetailedHealthStatus.DOWN
+ scheduler_jobs: list[Job] = []
try:
- scheduler_jobs = get_jobs_health(SchedulerJobRunner)
+ scheduler_jobs = get_jobs_health(SchedulerJobRunner.job_type)
scheduler_status = _legacy_status(scheduler_jobs)
scheduler_detailed_status = _liveness_status(scheduler_jobs)
if scheduler_jobs and scheduler_jobs[0].latest_heartbeat:
@@ -225,7 +352,7 @@ def get_airflow_health() -> dict[str, Any]:
metadatabase_status = HealthStatus.UNHEALTHY
try:
- triggerer_jobs = get_jobs_health(TriggererJobRunner)
+ triggerer_jobs = get_jobs_health(TriggererJobRunner.job_type)
triggerer_status = _legacy_status(triggerer_jobs)
triggerer_detailed_status = _triggerer_detailed_status(triggerer_jobs)
if triggerer_jobs and triggerer_jobs[0].latest_heartbeat:
@@ -238,7 +365,7 @@ def get_airflow_health() -> dict[str, Any]:
triggerer_detailed_status = DetailedHealthStatus.DOWN
try:
- dag_processor_jobs = get_jobs_health(DagProcessorJobRunner)
+ dag_processor_jobs = get_jobs_health(DagProcessorJobRunner.job_type)
dag_processor_status = _legacy_status(dag_processor_jobs)
dag_processor_detailed_status =
_dag_processor_detailed_status(dag_processor_jobs)
if dag_processor_jobs and dag_processor_jobs[0].latest_heartbeat:
@@ -250,6 +377,30 @@ def get_airflow_health() -> dict[str, Any]:
dag_processor_status = HealthStatus.UNHEALTHY
dag_processor_detailed_status = DetailedHealthStatus.DOWN
+ # Omitted entirely, not just reported unhealthy, when no configured
executor implements a health
+ # check: a reporting mechanism nothing has opted into isn't a gap in
coverage, and showing it as
+ # "unhealthy" on every deployment that hasn't adopted it yet would be a
false alarm, not a signal.
+ report_executor_health = bool(_configured_executor_keys())
+ if report_executor_health:
+ try:
+ executor_jobs = get_jobs_health(EXECUTOR_JOB_TYPE)
+ # Reuse scheduler_jobs fetched above instead of re-querying the
same rows.
+ live_scheduler_ids = {job.id for job in scheduler_jobs if
job.is_alive()}
+ executor_detailed_status =
_executor_detailed_status(executor_jobs, live_scheduler_ids)
+ executor_status = (
+ HealthStatus.UNHEALTHY
+ if executor_detailed_status == DetailedHealthStatus.DOWN
+ else HealthStatus.HEALTHY
+ )
+ if executor_jobs and executor_jobs[0].latest_heartbeat:
+ latest_executor_heartbeat =
executor_jobs[0].latest_heartbeat.isoformat()
+ if live_executor_jobs := _live_executor_jobs(executor_jobs,
live_scheduler_ids):
+ executor_instances = [_executor_instance_health(job) for job
in live_executor_jobs]
+ except Exception:
+ metadatabase_status = HealthStatus.UNHEALTHY
+ executor_status = HealthStatus.UNHEALTHY
+ executor_detailed_status = DetailedHealthStatus.DOWN
+
airflow_health_status = {
"metadatabase": {"status": metadatabase_status},
"scheduler": {
@@ -272,4 +423,12 @@ def get_airflow_health() -> dict[str, Any]:
},
}
+ if report_executor_health:
+ airflow_health_status["executor"] = {
+ "status": executor_status,
+ "latest_executor_heartbeat": latest_executor_heartbeat,
+ "detailed_status": executor_detailed_status,
+ "instances": executor_instances,
+ }
+
return airflow_health_status
diff --git a/airflow-core/src/airflow/api_fastapi/common/parameters/misc.py
b/airflow-core/src/airflow/api_fastapi/common/parameters/misc.py
index b6130a77f47..9c31ed0b947 100644
--- a/airflow-core/src/airflow/api_fastapi/common/parameters/misc.py
+++ b/airflow-core/src/airflow/api_fastapi/common/parameters/misc.py
@@ -90,12 +90,15 @@ class _IsAliveFilter(BaseParam[bool]):
from sqlalchemy import case
- from airflow.jobs.job import Job
+ from airflow.jobs.job import EXECUTOR_JOB_TYPE, Job
# The case wraps the result so it is always True/False (never NULL),
keeping the negated
# is_alive=False query exact.
alive = case(
- (Job.is_alive_clause(("SchedulerJob", "TriggererJob",
"DagProcessorJob")), True),
+ (
+ Job.is_alive_clause(("SchedulerJob", "TriggererJob",
"DagProcessorJob", EXECUTOR_JOB_TYPE)),
+ True,
+ ),
else_=False,
)
return select.where(alive if self.value else ~alive)
diff --git
a/airflow-core/src/airflow/api_fastapi/core_api/datamodels/monitor.py
b/airflow-core/src/airflow/api_fastapi/core_api/datamodels/monitor.py
index 4af62ae387b..2e513d561fb 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/datamodels/monitor.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/datamodels/monitor.py
@@ -18,6 +18,7 @@ from __future__ import annotations
from airflow.api.common.airflow_health import DetailedHealthStatus,
HealthStatus
from airflow.api_fastapi.core_api.base import BaseModel
+from airflow.jobs.job import HealthCheckResult
class BaseInfoResponse(BaseModel):
@@ -51,6 +52,16 @@ class DagProcessorInstanceInfoResponse(BaseModel):
bundle_names: list[str] | None
+class ExecutorInstanceInfoResponse(BaseModel):
+ """Executor instance info serializer for responses."""
+
+ hostname: str | None
+ executor: str | None
+ latest_executor_heartbeat: str | None
+ team_names: list[str]
+ health_check_result: HealthCheckResult | None
+
+
class SchedulerInfoResponse(BaseInfoResponse):
"""Scheduler info serializer for responses."""
@@ -75,6 +86,14 @@ class DagProcessorInfoResponse(BaseInfoResponse):
instances: list[DagProcessorInstanceInfoResponse] | None = None
+class ExecutorInfoResponse(BaseInfoResponse):
+ """Executor info serializer for responses."""
+
+ latest_executor_heartbeat: str | None
+ detailed_status: DetailedHealthStatus | None
+ instances: list[ExecutorInstanceInfoResponse] | None = None
+
+
class HealthInfoResponse(BaseModel):
"""Health serializer for responses."""
@@ -82,3 +101,4 @@ class HealthInfoResponse(BaseModel):
scheduler: SchedulerInfoResponse
triggerer: TriggererInfoResponse
dag_processor: DagProcessorInfoResponse | None = None
+ executor: ExecutorInfoResponse | None = None
diff --git
a/airflow-core/src/airflow/api_fastapi/core_api/openapi/v2-rest-api-generated.yaml
b/airflow-core/src/airflow/api_fastapi/core_api/openapi/v2-rest-api-generated.yaml
index ccc53a72ea8..80ca332dd46 100644
---
a/airflow-core/src/airflow/api_fastapi/core_api/openapi/v2-rest-api-generated.yaml
+++
b/airflow-core/src/airflow/api_fastapi/core_api/openapi/v2-rest-api-generated.yaml
@@ -16926,6 +16926,70 @@ components:
- extra
title: EventLogResponse
description: Event Log Response.
+ ExecutorInfoResponse:
+ properties:
+ status:
+ anyOf:
+ - $ref: '#/components/schemas/HealthStatus'
+ - type: 'null'
+ latest_executor_heartbeat:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Latest Executor Heartbeat
+ detailed_status:
+ anyOf:
+ - $ref: '#/components/schemas/DetailedHealthStatus'
+ - type: 'null'
+ instances:
+ anyOf:
+ - items:
+ $ref: '#/components/schemas/ExecutorInstanceInfoResponse'
+ type: array
+ - type: 'null'
+ title: Instances
+ type: object
+ required:
+ - status
+ - latest_executor_heartbeat
+ - detailed_status
+ title: ExecutorInfoResponse
+ description: Executor info serializer for responses.
+ ExecutorInstanceInfoResponse:
+ properties:
+ hostname:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Hostname
+ executor:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Executor
+ latest_executor_heartbeat:
+ anyOf:
+ - type: string
+ - type: 'null'
+ title: Latest Executor Heartbeat
+ team_names:
+ items:
+ type: string
+ type: array
+ title: Team Names
+ health_check_result:
+ anyOf:
+ - $ref: '#/components/schemas/HealthCheckResult'
+ - type: 'null'
+ type: object
+ required:
+ - hostname
+ - executor
+ - latest_executor_heartbeat
+ - team_names
+ - health_check_result
+ title: ExecutorInstanceInfoResponse
+ description: Executor instance info serializer for responses.
ExternalLogUrlResponse:
properties:
url:
@@ -17278,6 +17342,29 @@ components:
title: Detail
type: object
title: HTTPValidationError
+ HealthCheckResult:
+ type: string
+ enum:
+ - healthy
+ - unhealthy
+ - unknown
+ title: HealthCheckResult
+ description: 'Explicit outcome of a component''s own last health check.
+
+
+ Separate from whether the Job row itself is alive: a row can be alive
(recent
+ heartbeat) while
+
+ this stays UNKNOWN because the check hasn''t completed yet, raised, or
was
+ never implemented.
+
+ Collapsing all of that into "no heartbeat means unhealthy" makes a
real failure
+ indistinguishable
+
+ from "never checked" or "check is hanging", which is why this is a
value of
+ its own rather than
+
+ being inferred from heartbeat recency.'
HealthInfoResponse:
properties:
metadatabase:
@@ -17290,6 +17377,10 @@ components:
anyOf:
- $ref: '#/components/schemas/DagProcessorInfoResponse'
- type: 'null'
+ executor:
+ anyOf:
+ - $ref: '#/components/schemas/ExecutorInfoResponse'
+ - type: 'null'
type: object
required:
- metadatabase
diff --git a/airflow-core/src/airflow/cli/commands/jobs_command.py
b/airflow-core/src/airflow/cli/commands/jobs_command.py
index e03a0feb7c2..55694bee04c 100644
--- a/airflow-core/src/airflow/cli/commands/jobs_command.py
+++ b/airflow-core/src/airflow/cli/commands/jobs_command.py
@@ -21,7 +21,7 @@ from typing import TYPE_CHECKING
from sqlalchemy import select
from airflow.cli.utils import deprecated_for_airflowctl
-from airflow.jobs.job import Job, JobState
+from airflow.jobs.job import EXECUTOR_JOB_TYPE, Job, JobState
from airflow.utils.net import get_hostname
from airflow.utils.providers_configuration_loader import
providers_configuration_loaded
from airflow.utils.session import NEW_SESSION, provide_session
@@ -46,6 +46,10 @@ def check(args, *, session: Session = NEW_SESSION) -> None:
query = select(Job).where(Job.state ==
JobState.RUNNING).order_by(Job.latest_heartbeat.desc())
if args.job_type:
query = query.where(Job.job_type == args.job_type)
+ else:
+ # ExecutorJob rows share a host with the scheduler that owns them, not
a host of their own,
+ # so an unscoped check should not count them alongside the job types
--job-type can select.
+ query = query.where(Job.job_type != EXECUTOR_JOB_TYPE)
if args.hostname:
query = query.where(Job.hostname == args.hostname)
if args.local:
diff --git a/airflow-core/src/airflow/config_templates/config.yml
b/airflow-core/src/airflow/config_templates/config.yml
index 142eb60909f..70b0b9c75ab 100644
--- a/airflow-core/src/airflow/config_templates/config.yml
+++ b/airflow-core/src/airflow/config_templates/config.yml
@@ -3020,6 +3020,19 @@ scheduler:
type: float
example: ~
default: "120.0"
+ executor_health_check_interval:
+ description: |
+ How often, in seconds, the scheduler checks each configured executor's
health via
+ ``get_health()``, reported on ``/monitor/health``. Each check runs on
its own background
+ thread so a slow or unresponsive executor backend cannot delay task
scheduling; this setting
+ also bounds how long a single check is allowed to take, since each
call is given half this
+ interval as its timeout. Only meaningful for an executor that
overrides ``get_health()``; the
+ default implementation returns ``None`` and nothing is reported for
it. Set to 0 to disable
+ the check entirely.
+ version_added: 3.5.0
+ type: float
+ example: ~
+ default: "30.0"
allowed_run_id_pattern:
description: |
The run_id pattern used to verify the validity of user input to the
run_id parameter when
diff --git a/airflow-core/src/airflow/executors/base_executor.py
b/airflow-core/src/airflow/executors/base_executor.py
index f47410be70f..874161062f3 100644
--- a/airflow-core/src/airflow/executors/base_executor.py
+++ b/airflow-core/src/airflow/executors/base_executor.py
@@ -506,6 +506,37 @@ class BaseExecutor(LoggingMixin):
Executors should override this to perform gather statuses.
"""
+ def get_health(self, timeout: float) -> bool | None:
+ """
+ Report whether this executor's backend is reachable, for the
scheduler's health check.
+
+ Override this for an executor backed by something that can be
independently down, such as a
+ message broker or a cluster control plane, that the executor itself
can't detect from its
+ in-memory task-tracking state alone. Return ``True`` if the dependency
check succeeded,
+ ``False`` if it explicitly failed, or ``None`` (the default) if this
executor has nothing
+ useful to report.
+
+ ``timeout`` is in seconds and is always comfortably below the
scheduler's own check interval,
+ so an implementation that honours it, passing it through to its own
client's connect/read
+ timeout (``Celery.inspect(timeout=...)``, botocore's
``Config(connect_timeout=..., read_timeout=...)``,
+ etc.), always finishes before the next check is due. One that ignores
it risks its slot
+ looking hung indefinitely, which the scheduler reports as a stalled
check rather than silently
+ skipping forever, but still can't be reclaimed until the call actually
returns.
+
+ This is called from a worker thread with no open database session, on
its own schedule
+ independent of :meth:`heartbeat`, so it must not assume either. The
scheduler records an
+ explicit result either way: ``True``/``False`` become
HEALTHY/UNHEALTHY, a call that returns
+ ``None`` or raises :class:`NotImplementedError` is recorded as
UNKNOWN, and any other exception
+ is recorded as UNHEALTHY, rather than silently carrying over whatever
the previous result was.
+ A hung call delays that update, not task scheduling.
+ """
+ return None
+
+ @classmethod
+ def overrides_get_health(cls) -> bool:
+ """Whether this executor class implements :meth:`get_health` itself,
rather than inheriting the no-op default."""
+ return cls.get_health is not BaseExecutor.get_health
+
def heartbeat(self) -> None:
"""Heartbeat sent to trigger new jobs."""
open_slots = self.parallelism - len(self.running)
diff --git a/airflow-core/src/airflow/jobs/job.py
b/airflow-core/src/airflow/jobs/job.py
index 5241bb7aef5..fbbf319fc65 100644
--- a/airflow-core/src/airflow/jobs/job.py
+++ b/airflow-core/src/airflow/jobs/job.py
@@ -54,6 +54,29 @@ class JobState(StrEnum):
FAILED = "failed"
+# Executors don't run as their own process the way
SchedulerJob/TriggererJob/DagProcessorJob do, so
+# there is no ExecutorJobRunner to own this constant. The scheduler writes
rows with this job_type
+# directly when it records an executor's health, reusing the Job table and
JobState exactly as the
+# other components do instead of introducing a parallel status model.
+EXECUTOR_JOB_TYPE = "ExecutorJob"
+
+
+class HealthCheckResult(StrEnum):
+ """
+ Explicit outcome of a component's own last health check.
+
+ Separate from whether the Job row itself is alive: a row can be alive
(recent heartbeat) while
+ this stays UNKNOWN because the check hasn't completed yet, raised, or was
never implemented.
+ Collapsing all of that into "no heartbeat means unhealthy" makes a real
failure indistinguishable
+ from "never checked" or "check is hanging", which is why this is a value
of its own rather than
+ being inferred from heartbeat recency.
+ """
+
+ HEALTHY = "healthy"
+ UNHEALTHY = "unhealthy"
+ UNKNOWN = "unknown"
+
+
if TYPE_CHECKING:
from sqlalchemy.orm.session import Session
from sqlalchemy.sql.elements import ColumnElement
@@ -75,6 +98,12 @@ def health_check_threshold(job_type: str, heartrate: int) ->
int | float:
health_check_threshold_value = conf.getfloat("triggerer",
"triggerer_health_check_threshold")
elif job_type == "DagProcessorJob":
health_check_threshold_value = conf.getint("dag_processor",
"health_check_threshold")
+ elif job_type == EXECUTOR_JOB_TYPE:
+ # The scheduler keeps an ExecutorJob row's heartbeat moving on its own
cadence (see
+ # SchedulerJobRunner._touch_executor_heartbeats), independent of how
often the executor's
+ # own check actually runs, so the row goes stale at the same rate the
scheduler's own Job
+ # row does -- and for the same reason: the scheduler itself has
stopped.
+ health_check_threshold_value = conf.getint("scheduler",
"scheduler_health_check_threshold")
else:
health_check_threshold_value = heartrate * grace_multiplier
return health_check_threshold_value
@@ -106,6 +135,15 @@ class Job(Base, LoggingMixin):
"""Component session that registered this Job over the Execution API;
``None`` for Jobs written directly or replaced by a newer registration."""
registration_id: Mapped[UUID | None] = mapped_column(Uuid(),
nullable=True, unique=True)
"""Process registration that created this Job; it creates no other Job,
even after this one ends."""
+ health_check_result: Mapped[str | None] = mapped_column(String(20),
nullable=True)
+ """Outcome of this job's own last health check (see
:class:`HealthCheckResult`), independent of
+ whether this row itself is alive. Only meaningful for a job type whose
component runs its own
+ dependency check, e.g. :data:`EXECUTOR_JOB_TYPE`."""
+ owner_job_id: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ """Id of the Job (typically a SchedulerJob) that created and maintains
this row, so a restarted
+ owner gets a fresh row instead of silently taking over one left behind by
its previous instance.
+ Only meaningful for a job type that is recorded on another component's
behalf, e.g.
+ :data:`EXECUTOR_JOB_TYPE`."""
__table_args__ = (
Index("job_type_heart", job_type, latest_heartbeat),
diff --git a/airflow-core/src/airflow/jobs/scheduler_job_runner.py
b/airflow-core/src/airflow/jobs/scheduler_job_runner.py
index 94af3bd3488..9f3ea9db915 100644
--- a/airflow-core/src/airflow/jobs/scheduler_job_runner.py
+++ b/airflow-core/src/airflow/jobs/scheduler_job_runner.py
@@ -24,6 +24,7 @@ import operator
import os
import signal
import sys
+import threading
import time
from collections import Counter, defaultdict, deque
from collections.abc import Callable, Collection, Iterable, Iterator, Sequence
@@ -42,6 +43,7 @@ from sqlalchemy import (
delete,
exists,
func,
+ insert,
inspect,
or_,
select,
@@ -76,7 +78,7 @@ from airflow.executors import workloads
from airflow.executors.executor_loader import ExecutorLoader
from airflow.executors.workloads.types import TaskInstanceUuid
from airflow.jobs.base_job_runner import BaseJobRunner
-from airflow.jobs.job import Job, JobState, perform_heartbeat
+from airflow.jobs.job import EXECUTOR_JOB_TYPE, HealthCheckResult, Job,
JobState, perform_heartbeat
from airflow.models import Deadline, Log
from airflow.models.asset import (
AssetActive,
@@ -117,7 +119,7 @@ from airflow.models.pool import
normalize_pool_name_for_stats
from airflow.models.serialized_dag import SerializedDagModel
from airflow.models.task_coordinates import LOOP_GATE_OPERATOR,
TaskCoordinateResolver
from airflow.models.taskinstance import TaskInstance
-from airflow.models.team import Team
+from airflow.models.team import JobTeam, Team
from airflow.models.trigger import TRIGGER_FAIL_REPR, Trigger,
TriggerFailureReason, handle_event_submit
from airflow.observability.metrics import stats_utils
from airflow.partition_mappers.base import is_rollup
@@ -130,6 +132,8 @@ from airflow.utils.event_scheduler import EventScheduler
from airflow.utils.helpers import chunks, prune_dict
from airflow.utils.log.logging_mixin import LoggingMixin
from airflow.utils.log.task_log_address import prepare_task_log_contexts
+from airflow.utils.net import get_hostname
+from airflow.utils.platform import getuser
from airflow.utils.retries import MAX_DB_RETRIES, retry_db_transaction,
run_with_db_retries
from airflow.utils.session import NEW_SESSION, create_session, provide_session
from airflow.utils.sqlalchemy import (
@@ -365,6 +369,18 @@ def _build_pending_partitioned_apdr_filters() ->
tuple[ColumnElement[bool], ...]
)
+def _executor_health_key(executor: BaseExecutor) -> str | None:
+ """
+ Return the key an executor's health is tracked and recorded under, or None
if it has no name.
+
+ ``ExecutorName.__repr__()`` is the identity ``ExecutorName`` already uses
for equality and
+ hashing, so using it here too keeps this side and
``_configured_executor_keys()`` in
+ ``airflow_health.py`` from drifting apart. ``load_executor()`` always sets
``executor.name``;
+ an executor constructed without one gets no row.
+ """
+ return repr(executor.name) if executor.name is not None else None
+
+
class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
"""
SchedulerJobRunner runs for a specific time interval and schedules jobs
that are ready to run.
@@ -435,6 +451,32 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
self.executors: list[BaseExecutor] = executors if executors else
ExecutorLoader.init_executors()
self.executor: BaseExecutor = self.executors[0]
+ # Daemon thread per check, not a pool: only one check is ever in
flight per executor, and a
+ # hung check can't block process exit the way a pool worker would.
+ self._executor_health_check_threads: dict[str, tuple[threading.Thread,
float]] = {}
+ # A probe that ignores its timeout would otherwise occupy its slot
forever.
+ self._executor_health_check_stall_after_intervals = 3
+ self._stalled_health_checks: set[str] = set()
+
+ self._executor_health_check_interval = conf.getfloat(
+ "scheduler", "executor_health_check_interval", fallback=30.0
+ )
+ self._executor_health_check_timeout =
self._executor_health_check_interval / 2
+
+ # Only executors that override get_health() get a Job row; one with no
name has nothing
+ # stable to key its row under. Empty outright when the interval is 0:
nothing would ever
+ # get checked, so a row that only ever heartbeats and never reports a
result would be
+ # misleading, not useful.
+ self._executor_health_keys: dict[str, str | None] = (
+ {
+ key: executor.team_name
+ for executor in self.executors
+ if executor.overrides_get_health() and (key :=
_executor_health_key(executor)) is not None
+ }
+ if self._executor_health_check_interval > 0
+ else {}
+ )
+
if self._enable_tracemalloc:
import tracemalloc
@@ -456,6 +498,182 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
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:
+ if 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,
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 _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, 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 _open_executor_job(self, executor_key: str, *, session: Session) ->
Job | None:
+ """Return this scheduler's own open Job row for ``executor_key``, or
None if it has none."""
+ return 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),
+ )
+ )
+
+ 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.
+
+ Only called from the main thread (``_touch_executor_heartbeats``). The
health check thread
+ must never create a row here: right after another scheduler's
``adopt_or_reset_orphaned_tasks``
+ closes the old one, both threads could otherwise find no open row and
each insert their own,
+ splitting the heartbeat and the health check result across two
different rows.
+
+ 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 = self._open_executor_job(executor_key, session=session)
+ 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)
+ if TYPE_CHECKING:
+ assert job is not None
+ job.state = JobState.RUNNING
+ return job
+
+ @provide_session
+ def _record_executor_health_result(
+ self,
+ executor_key: str,
+ result: HealthCheckResult,
+ *,
+ session: Session = NEW_SESSION,
+ ) -> None:
+ """
+ Record the outcome of an executor's health check on this scheduler's
open row.
+
+ Never creates a row -- only ``_get_or_create_executor_job``, on the
main thread, does that.
+ With no open row the result is dropped; the next heartbeat tick
creates a fresh row for the
+ next check to update.
+ """
+ job = self._open_executor_job(executor_key, session=session)
+ if job is not None:
+ job.health_check_result = result
+
def _get_current_dag(self, dag_id: str, session: Session) -> SerializedDAG
| None:
try:
serdag = SerializedDagModel.get(dag_id=dag_id, session=session)
@@ -1962,6 +2180,9 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
self.log.info("Starting the scheduler")
reset_signals = self.register_signals()
+ # Matches the state execute_job() in job.py would give this
scheduler's own Job row: SUCCESS
+ # for a normal return or SystemExit (^C, SIGTERM), FAILED if the loop
raised.
+ executor_jobs_state = JobState.SUCCESS
try:
callback_sink: DatabaseCallbackSink
@@ -1987,6 +2208,7 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
if settings.Session is not None:
settings.Session.remove()
except Exception as exc:
+ executor_jobs_state = JobState.FAILED
stats.incr("scheduler.loop_exceptions", tags={"exception_class":
type(exc).__name__})
self.log.exception("Exception when executing
SchedulerJob._run_scheduler_loop")
raise
@@ -1997,12 +2219,38 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
except Exception:
self.log.exception("Exception when executing Executor.end
on %s", executor)
+ try:
+ self._end_executor_jobs(executor_jobs_state)
+ except Exception:
+ self.log.exception("Failed to close this scheduler's
ExecutorJob rows")
+
# Under normal execution, this doesn't matter, but by resetting
signals it lets us run more things
# in the same process under testing without leaking global state
reset_signals.close()
self.log.info("Exited execute loop")
return None
+ @provide_session
+ def _end_executor_jobs(self, state: JobState, *, session: Session =
NEW_SESSION) -> None:
+ """
+ Close this scheduler's own ExecutorJob rows on a clean exit, including
SIGTERM.
+
+ Nothing else ever gives these rows an ``end_date``, so without this
they stay RUNNING forever
+ after their scheduler exits, and every restart adds one more row per
reporting executor. A
+ crash (SIGKILL, OOM, a lost node) skips this -- ``finally`` never runs
-- so that case is
+ instead handled alongside ``adopt_or_reset_orphaned_tasks``, which
already does the same for
+ stale SchedulerJob rows.
+ """
+ session.execute(
+ update(Job)
+ .where(
+ Job.job_type == EXECUTOR_JOB_TYPE,
+ Job.owner_job_id == self.job.id,
+ Job.end_date.is_(None),
+ )
+ .values(state=state, end_date=timezone.utcnow())
+ )
+
@provide_session
def _update_dag_run_state_for_paused_dags(self, *, session: Session =
NEW_SESSION) -> None:
try:
@@ -2174,6 +2422,19 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
non_fatal=True,
)
+ if self._executor_health_keys:
+ timers.call_regular_interval(
+ delay=max(self.job.heartrate, 1.0),
+ action=self._touch_executor_heartbeats,
+ non_fatal=True,
+ )
+
+ timers.call_regular_interval(
+ delay=self._executor_health_check_interval,
+ action=self._check_executor_health,
+ non_fatal=True,
+ )
+
idle_count = 0
for loop_count in itertools.count(start=1):
@@ -3912,6 +4173,19 @@ class SchedulerJobRunner(BaseJobRunner, LoggingMixin):
self.log.info("Marked %d SchedulerJob instances as
failed", num_failed)
stats.incr(self.__class__.__name__.lower() + "_end",
num_failed)
+ # Separate from the SchedulerJob update above so that log
line and metric keep
+ # counting only schedulers. Catches ExecutorJob rows left
running when their
+ # owning scheduler is killed before _end_executor_jobs can
close them.
+ session.execute(
+ update(Job)
+ .where(
+ Job.job_type == EXECUTOR_JOB_TYPE,
+ Job.state == JobState.RUNNING,
+ Job.latest_heartbeat < (timezone.utcnow() -
timedelta(seconds=timeout)),
+ )
+ .values(state=JobState.FAILED,
end_date=timezone.utcnow())
+ )
+
query = (
select(TI)
.options(lazyload(TI.dag_run)) # avoids double join
to dag_run
diff --git
a/airflow-core/src/airflow/migrations/versions/0158_3_5_0_add_executor_health_columns_to_job.py
b/airflow-core/src/airflow/migrations/versions/0158_3_5_0_add_executor_health_columns_to_job.py
new file mode 100644
index 00000000000..8c11c622d55
--- /dev/null
+++
b/airflow-core/src/airflow/migrations/versions/0158_3_5_0_add_executor_health_columns_to_job.py
@@ -0,0 +1,55 @@
+#
+# 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.
+
+"""
+Add health_check_result and owner_job_id to Job.
+
+Revision ID: feb8b1e719ee
+Revises: c64b10719069
+Create Date: 2026-11-05 09:00:00.000000
+
+"""
+
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+from airflow.migrations.utils import disable_sqlite_fkeys
+
+revision = "feb8b1e719ee"
+down_revision = "c64b10719069"
+branch_labels = None
+depends_on = None
+airflow_version = "3.5.0"
+
+
+def upgrade():
+ """Add the nullable health_check_result and owner_job_id columns to Job."""
+ with disable_sqlite_fkeys(op):
+ with op.batch_alter_table("job", schema=None) as batch_op:
+ batch_op.add_column(sa.Column("health_check_result",
sa.String(length=20), nullable=True))
+ batch_op.add_column(sa.Column("owner_job_id", sa.Integer(),
nullable=True))
+
+
+def downgrade():
+ """Remove health_check_result and owner_job_id from Job."""
+ with disable_sqlite_fkeys(op):
+ with op.batch_alter_table("job", schema=None) as batch_op:
+ batch_op.drop_column("owner_job_id")
+ batch_op.drop_column("health_check_result")
diff --git a/airflow-core/src/airflow/ui/openapi-gen/requests/schemas.gen.ts
b/airflow-core/src/airflow/ui/openapi-gen/requests/schemas.gen.ts
index 27089657617..5ef8e7d6d2b 100644
--- a/airflow-core/src/airflow/ui/openapi-gen/requests/schemas.gen.ts
+++ b/airflow-core/src/airflow/ui/openapi-gen/requests/schemas.gen.ts
@@ -6016,6 +6016,119 @@ export const $EventLogResponse = {
description: 'Event Log Response.'
} as const;
+export const $ExecutorInfoResponse = {
+ properties: {
+ status: {
+ anyOf: [
+ {
+ '$ref': '#/components/schemas/HealthStatus'
+ },
+ {
+ type: 'null'
+ }
+ ]
+ },
+ latest_executor_heartbeat: {
+ anyOf: [
+ {
+ type: 'string'
+ },
+ {
+ type: 'null'
+ }
+ ],
+ title: 'Latest Executor Heartbeat'
+ },
+ detailed_status: {
+ anyOf: [
+ {
+ '$ref': '#/components/schemas/DetailedHealthStatus'
+ },
+ {
+ type: 'null'
+ }
+ ]
+ },
+ instances: {
+ anyOf: [
+ {
+ items: {
+ '$ref':
'#/components/schemas/ExecutorInstanceInfoResponse'
+ },
+ type: 'array'
+ },
+ {
+ type: 'null'
+ }
+ ],
+ title: 'Instances'
+ }
+ },
+ type: 'object',
+ required: ['status', 'latest_executor_heartbeat', 'detailed_status'],
+ title: 'ExecutorInfoResponse',
+ description: 'Executor info serializer for responses.'
+} as const;
+
+export const $ExecutorInstanceInfoResponse = {
+ properties: {
+ hostname: {
+ anyOf: [
+ {
+ type: 'string'
+ },
+ {
+ type: 'null'
+ }
+ ],
+ title: 'Hostname'
+ },
+ executor: {
+ anyOf: [
+ {
+ type: 'string'
+ },
+ {
+ type: 'null'
+ }
+ ],
+ title: 'Executor'
+ },
+ latest_executor_heartbeat: {
+ anyOf: [
+ {
+ type: 'string'
+ },
+ {
+ type: 'null'
+ }
+ ],
+ title: 'Latest Executor Heartbeat'
+ },
+ team_names: {
+ items: {
+ type: 'string'
+ },
+ type: 'array',
+ title: 'Team Names'
+ },
+ health_check_result: {
+ anyOf: [
+ {
+ '$ref': '#/components/schemas/HealthCheckResult'
+ },
+ {
+ type: 'null'
+ }
+ ]
+ }
+ },
+ type: 'object',
+ required: ['hostname', 'executor', 'latest_executor_heartbeat',
'team_names', 'health_check_result'],
+ title: 'ExecutorInstanceInfoResponse',
+ description: 'Executor instance info serializer for responses.'
+} as const;
+
export const $ExternalLogUrlResponse = {
properties: {
url: {
@@ -6534,6 +6647,19 @@ export const $HTTPValidationError = {
title: 'HTTPValidationError'
} as const;
+export const $HealthCheckResult = {
+ type: 'string',
+ enum: ['healthy', 'unhealthy', 'unknown'],
+ title: 'HealthCheckResult',
+ description: `Explicit outcome of a component's own last health check.
+
+Separate from whether the Job row itself is alive: a row can be alive (recent
heartbeat) while
+this stays UNKNOWN because the check hasn't completed yet, raised, or was
never implemented.
+Collapsing all of that into "no heartbeat means unhealthy" makes a real
failure indistinguishable
+from "never checked" or "check is hanging", which is why this is a value of
its own rather than
+being inferred from heartbeat recency.`
+} as const;
+
export const $HealthInfoResponse = {
properties: {
metadatabase: {
@@ -6554,6 +6680,16 @@ export const $HealthInfoResponse = {
type: 'null'
}
]
+ },
+ executor: {
+ anyOf: [
+ {
+ '$ref': '#/components/schemas/ExecutorInfoResponse'
+ },
+ {
+ type: 'null'
+ }
+ ]
}
},
type: 'object',
diff --git a/airflow-core/src/airflow/ui/openapi-gen/requests/types.gen.ts
b/airflow-core/src/airflow/ui/openapi-gen/requests/types.gen.ts
index 8fa9eb8caa1..b9e6bcfa16a 100644
--- a/airflow-core/src/airflow/ui/openapi-gen/requests/types.gen.ts
+++ b/airflow-core/src/airflow/ui/openapi-gen/requests/types.gen.ts
@@ -1665,6 +1665,27 @@ export type EventLogResponse = {
team_name?: string | null;
};
+/**
+ * Executor info serializer for responses.
+ */
+export type ExecutorInfoResponse = {
+ status: HealthStatus | null;
+ latest_executor_heartbeat: string | null;
+ detailed_status: DetailedHealthStatus | null;
+ instances?: Array<ExecutorInstanceInfoResponse> | null;
+};
+
+/**
+ * Executor instance info serializer for responses.
+ */
+export type ExecutorInstanceInfoResponse = {
+ hostname: string | null;
+ executor: string | null;
+ latest_executor_heartbeat: string | null;
+ team_names: Array<(string)>;
+ health_check_result: HealthCheckResult | null;
+};
+
/**
* Response for the external log URL endpoint.
*/
@@ -1809,6 +1830,17 @@ export type HTTPValidationError = {
detail?: Array<ValidationError>;
};
+/**
+ * Explicit outcome of a component's own last health check.
+ *
+ * Separate from whether the Job row itself is alive: a row can be alive
(recent heartbeat) while
+ * this stays UNKNOWN because the check hasn't completed yet, raised, or was
never implemented.
+ * Collapsing all of that into "no heartbeat means unhealthy" makes a real
failure indistinguishable
+ * from "never checked" or "check is hanging", which is why this is a value of
its own rather than
+ * being inferred from heartbeat recency.
+ */
+export type HealthCheckResult = 'healthy' | 'unhealthy' | 'unknown';
+
/**
* Health serializer for responses.
*/
@@ -1817,6 +1849,7 @@ export type HealthInfoResponse = {
scheduler: SchedulerInfoResponse;
triggerer: TriggererInfoResponse;
dag_processor?: DagProcessorInfoResponse | null;
+ executor?: ExecutorInfoResponse | null;
};
/**
diff --git a/airflow-core/src/airflow/utils/db.py
b/airflow-core/src/airflow/utils/db.py
index 05ea0302261..9471796fc24 100644
--- a/airflow-core/src/airflow/utils/db.py
+++ b/airflow-core/src/airflow/utils/db.py
@@ -113,7 +113,7 @@ _REVISION_HEADS_MAP: dict[str, str] = {
"3.2.0": "1d6611b6ab7c",
"3.3.0": "d2f4e1b3c5a7",
"3.4.0": "b4f1a7d2c903",
- "3.5.0": "c64b10719069",
+ "3.5.0": "feb8b1e719ee",
}
# Prefix used to identify tables holding data moved during migration.
diff --git a/airflow-core/tests/unit/api/common/test_airflow_health.py
b/airflow-core/tests/unit/api/common/test_airflow_health.py
index 649ad465c5c..dc9b5f3181f 100644
--- a/airflow-core/tests/unit/api/common/test_airflow_health.py
+++ b/airflow-core/tests/unit/api/common/test_airflow_health.py
@@ -27,13 +27,19 @@ from airflow.api.common.airflow_health import (
DetailedHealthStatus,
HealthStatus,
_configured_bundle_teams,
+ _configured_executor_keys,
+ _configured_executor_names,
_dag_processor_detailed_status,
+ _executor_detailed_status,
+ _executor_instance_health,
_triggerer_detailed_status,
get_airflow_health,
get_jobs_health,
)
+from airflow.executors.base_executor import BaseExecutor
+from airflow.executors.executor_utils import ExecutorName
from airflow.jobs.dag_processor_job_runner import DagProcessorJobRunner
-from airflow.jobs.job import Job, JobState, health_check_threshold
+from airflow.jobs.job import EXECUTOR_JOB_TYPE, HealthCheckResult, Job,
JobState, health_check_threshold
from airflow.jobs.scheduler_job_runner import SchedulerJobRunner
from airflow.jobs.triggerer_job_runner import TriggererJobRunner
from airflow.utils.session import provide_session
@@ -306,7 +312,7 @@ def _triggerer(*, alive: bool, team_name: str | None) ->
MagicMock:
class TestDagProcessorDetailedStatus:
"""``detailed_status`` measures which configured bundles a live processor
is parsing."""
- BUNDLES = {"bundle-a": None, "bundle-b": None}
+ BUNDLES: dict[str, str | None] = {"bundle-a": None, "bundle-b": None}
@pytest.mark.parametrize(
("jobs", "expected"),
@@ -352,19 +358,19 @@ class TestDagProcessorDetailedStatus:
pytest.param([], DetailedHealthStatus.DOWN,
id="no_processor_at_all"),
],
)
- def test_bundle_coverage(self, jobs, expected):
- with _patch_bundles(self.BUNDLES):
- assert _dag_processor_detailed_status(jobs) == expected
+ @_patch_bundles(BUNDLES)
+ def test_bundle_coverage(self, mock_bundles, jobs, expected):
+ assert _dag_processor_detailed_status(jobs) == expected
- def test_restarted_processor_leaves_the_component_healthy(self):
+ @_patch_bundles(BUNDLES)
+ def test_restarted_processor_leaves_the_component_healthy(self,
mock_bundles):
"""A hard-killed replica keeps an unfinished job row; its replacement
must still read healthy."""
jobs = [
_processor(alive=True, bundle_names=["bundle-a", "bundle-b"]),
_processor(alive=False, bundle_names=["bundle-a", "bundle-b"]),
]
- with _patch_bundles(self.BUNDLES):
- assert _dag_processor_detailed_status(jobs) ==
DetailedHealthStatus.HEALTHY
+ assert _dag_processor_detailed_status(jobs) ==
DetailedHealthStatus.HEALTHY
@pytest.mark.parametrize(
("jobs", "expected"),
@@ -381,9 +387,9 @@ class TestDagProcessorDetailedStatus:
),
],
)
- def test_falls_back_to_liveness_without_configured_bundles(self, jobs,
expected):
- with _patch_bundles({}):
- assert _dag_processor_detailed_status(jobs) == expected
+ @_patch_bundles({})
+ def test_falls_back_to_liveness_without_configured_bundles(self,
mock_bundles, jobs, expected):
+ assert _dag_processor_detailed_status(jobs) == expected
class TestTriggererDetailedStatus:
@@ -432,18 +438,20 @@ class TestTriggererDetailedStatus:
pytest.param([], DetailedHealthStatus.DOWN,
id="no_triggerer_at_all"),
],
)
- def test_team_coverage(self, jobs, expected):
- with conf_vars({("core", "multi_team"): "True"}),
_patch_bundles(self.BUNDLES):
- assert _triggerer_detailed_status(jobs) == expected
-
- def test_restarted_triggerer_leaves_the_component_healthy(self):
+ @conf_vars({("core", "multi_team"): "True"})
+ @_patch_bundles(BUNDLES)
+ def test_team_coverage(self, mock_bundles, jobs, expected):
+ assert _triggerer_detailed_status(jobs) == expected
+
+ @conf_vars({("core", "multi_team"): "True"})
+ @_patch_bundles({"bundle-a": "team-a"})
+ def test_restarted_triggerer_leaves_the_component_healthy(self,
mock_bundles):
jobs = [
_triggerer(alive=True, team_name="team-a"),
_triggerer(alive=False, team_name="team-a"),
]
- with conf_vars({("core", "multi_team"): "True"}),
_patch_bundles({"bundle-a": "team-a"}):
- assert _triggerer_detailed_status(jobs) ==
DetailedHealthStatus.HEALTHY
+ assert _triggerer_detailed_status(jobs) == DetailedHealthStatus.HEALTHY
@pytest.mark.parametrize(
("jobs", "expected"),
@@ -460,16 +468,18 @@ class TestTriggererDetailedStatus:
),
],
)
- def test_ignores_teams_without_multi_team(self, jobs, expected):
- with conf_vars({("core", "multi_team"): "False"}),
_patch_bundles(self.BUNDLES):
- assert _triggerer_detailed_status(jobs) == expected
-
- def test_falls_back_to_liveness_without_configured_bundles(self):
- with conf_vars({("core", "multi_team"): "True"}), _patch_bundles({}):
- assert (
- _triggerer_detailed_status([_triggerer(alive=True,
team_name="team-a")])
- == DetailedHealthStatus.HEALTHY
- )
+ @conf_vars({("core", "multi_team"): "False"})
+ @_patch_bundles(BUNDLES)
+ def test_ignores_teams_without_multi_team(self, mock_bundles, jobs,
expected):
+ assert _triggerer_detailed_status(jobs) == expected
+
+ @conf_vars({("core", "multi_team"): "True"})
+ @_patch_bundles({})
+ def test_falls_back_to_liveness_without_configured_bundles(self,
mock_bundles):
+ assert (
+ _triggerer_detailed_status([_triggerer(alive=True,
team_name="team-a")])
+ == DetailedHealthStatus.HEALTHY
+ )
@conf_vars({("dag_processor", "dag_bundle_config_list"): "not json"})
@@ -529,7 +539,7 @@ class TestAirflowHealthFromDb:
_create_job(session, other_runner, hostname="other-component",
heartbeat=now)
session.commit()
- jobs = get_jobs_health(runner_class, session=session)
+ jobs = get_jobs_health(runner_class.job_type, session=session)
expected = ["live-newer", "live-older"]
if latest_failed:
@@ -542,7 +552,7 @@ class TestAirflowHealthFromDb:
_create_job(session, SchedulerJobRunner, hostname="no-heartbeat-2",
heartbeat=None)
session.commit()
- jobs = get_jobs_health(SchedulerJobRunner, session=session)
+ jobs = get_jobs_health(SchedulerJobRunner.job_type, session=session)
assert len(jobs) == 1
assert jobs[0].latest_heartbeat is None
@@ -621,7 +631,7 @@ class TestAirflowHealthFromDb:
_create_job(session, SchedulerJobRunner, hostname="stale-3",
heartbeat=third)
session.commit()
- jobs = get_jobs_health(SchedulerJobRunner, session=session)
+ jobs = get_jobs_health(SchedulerJobRunner.job_type, session=session)
assert [job.hostname for job in jobs] == ["stale-1"]
health_status = get_airflow_health()
@@ -663,3 +673,313 @@ class TestAirflowHealthFromDb:
},
]
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)
+
+
+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()
+
+ @pytest.mark.parametrize("alias", [None, "Celery"])
+
@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(
+ self, mock_get_executor_names, mock_import_executor_cls, alias
+ ):
+ """The key must agree with the scheduler side whether or not the
executor has an alias."""
+ names = [
+ ExecutorName(
+
module_path=f"{_HealthCheckingExecutor.__module__}.{_HealthCheckingExecutor.__qualname__}",
+ alias=alias,
+ )
+ ]
+ mock_get_executor_names.return_value = names
+ mock_import_executor_cls.return_value = (_HealthCheckingExecutor, None)
+
+ assert _configured_executor_keys() == {repr(names[0])}
+
+
@patch("airflow.api.common.airflow_health.ExecutorLoader.get_executor_names",
side_effect=Exception)
+ def test_survives_unreadable_executor_config(self,
mock_get_executor_names):
+ assert _configured_executor_keys() == set()
+
+ @conf_vars({("scheduler", "executor_health_check_interval"): "30s"})
+ def test_survives_unparseable_interval_config(self):
+ assert _configured_executor_keys() == set()
+
+ @conf_vars({("scheduler", "executor_health_check_interval"): "0"})
+
@patch("airflow.api.common.airflow_health.ExecutorLoader.import_executor_cls")
+
@patch("airflow.api.common.airflow_health.ExecutorLoader.get_executor_names")
+ def test_empty_when_interval_is_zero(self, mock_get_executor_names,
mock_import_executor_cls):
+ """The scheduler records no row for any executor when the check is
disabled."""
+ names = [
+ ExecutorName(
+
module_path=f"{_HealthCheckingExecutor.__module__}.{_HealthCheckingExecutor.__qualname__}",
+ alias="Celery",
+ )
+ ]
+ mock_get_executor_names.return_value = names
+ mock_import_executor_cls.return_value = (_HealthCheckingExecutor, None)
+
+ assert _configured_executor_keys() == set()
+
+
+class TestExecutorInstanceHealthDisplayName:
+ """The API reports the name the user configured, not the internal
executor_class key."""
+
+ @pytest.fixture(autouse=True)
+ def clear_executor_caches(self):
+ _configured_executor_names.cache_clear()
+ yield
+ _configured_executor_names.cache_clear()
+
+ @pytest.mark.parametrize(
+ ("alias", "expected"),
+ [
+ ("Celery", "Celery"),
+ (None,
f"{_HealthCheckingExecutor.__module__}.{_HealthCheckingExecutor.__qualname__}"),
+ ],
+ )
+
@patch("airflow.api.common.airflow_health.ExecutorLoader.get_executor_names")
+ def test_reports_alias_or_module_path_depending_on_what_is_configured(
+ self, mock_get_executor_names, alias, expected
+ ):
+ name = ExecutorName(
+
module_path=f"{_HealthCheckingExecutor.__module__}.{_HealthCheckingExecutor.__qualname__}",
+ alias=alias,
+ )
+ job = _executor(alive=True, executor=repr(name))
+ mock_get_executor_names.return_value = [name]
+
+ instance = _executor_instance_health(job)
+
+ assert instance["executor"] == expected
+
+
@patch("airflow.api.common.airflow_health.ExecutorLoader.get_executor_names",
return_value=[])
+ def test_falls_back_to_the_raw_key_when_nothing_configured_matches(self,
mock_get_executor_names):
+ job = _executor(alive=True, executor=":SomeExecutor:")
+
+ instance = _executor_instance_health(job)
+
+ assert instance["executor"] == ":SomeExecutor:"
+
+
+class TestExecutorDetailedStatus:
+ """Each executor that implements a health check is its own coverage
partition."""
+
+ @pytest.mark.parametrize(
+ ("keys", "jobs", "expected"),
+ [
+ pytest.param(
+ {"Celery"},
+ [_executor(alive=True, executor="Celery")],
+ DetailedHealthStatus.HEALTHY,
+ id="the_only_configured_executor_is_alive",
+ ),
+ pytest.param(
+ {"Celery", "Kubernetes"},
+ [_executor(alive=True, executor="Celery"),
_executor(alive=True, executor="Kubernetes")],
+ DetailedHealthStatus.HEALTHY,
+ id="both_configured_executors_are_alive",
+ ),
+ pytest.param(
+ {"Celery", "Kubernetes"},
+ [_executor(alive=True, executor="Celery")],
+ DetailedHealthStatus.DEGRADED,
+ id="one_of_two_configured_executors_reports",
+ ),
+ pytest.param(
+ {"Celery"},
+ [_executor(alive=False, executor="Celery")],
+ DetailedHealthStatus.DOWN,
+ id="the_only_configured_executor_is_stale",
+ ),
+ pytest.param({"Celery"}, [], DetailedHealthStatus.DOWN,
id="no_executor_has_ever_reported"),
+ pytest.param(
+ {"Celery"},
+ [_executor(alive=True, healthy=None, executor="Celery")],
+ DetailedHealthStatus.HEALTHY,
+ id="first_check_still_pending_is_not_a_coverage_gap",
+ ),
+ ],
+ )
+ def test_coverage(self, keys, jobs, expected):
+ with _patch_executor_keys(keys):
+ assert _executor_detailed_status(jobs, {1}) == expected
+
+ def
test_liveness_fallback_ignores_a_dead_schedulers_row_when_nothing_is_configured(self):
+ """No configured executor falls back to liveness, which must still
respect the owner check."""
+ with _patch_executor_keys(set()):
+ jobs = [_executor(alive=True, executor="Celery", owner_job_id=2)]
+ assert _executor_detailed_status(jobs, {1}) ==
DetailedHealthStatus.DOWN
+
+ @_patch_executor_keys({"Celery"})
+ def test_restart_while_another_scheduler_already_reports_healthy(self,
mock_keys):
+ jobs = [
+ _executor(alive=True, healthy=None, executor="Celery",
owner_job_id=1),
+ _executor(alive=True, healthy=True, executor="Celery",
owner_job_id=2),
+ ]
+ assert _executor_detailed_status(jobs, {1, 2}) ==
DetailedHealthStatus.HEALTHY
+
+ @_patch_executor_keys({"Celery"})
+ def test_unknown_does_not_mask_a_real_unhealthy_report(self, mock_keys):
+ jobs = [
+ _executor(alive=True, healthy=None, executor="Celery",
owner_job_id=1),
+ _executor(alive=True, healthy=False, executor="Celery",
owner_job_id=2),
+ ]
+ assert _executor_detailed_status(jobs, {1, 2}) ==
DetailedHealthStatus.DOWN
+
+ @_patch_executor_keys({"Celery"})
+ def test_restarted_executor_leaves_the_component_healthy(self, mock_keys):
+ """A hard-killed replica leaves its row behind; a fresh one taking
over must still read healthy."""
+ jobs = [
+ _executor(alive=True, executor="Celery"),
+ _executor(alive=False, executor="Celery"),
+ ]
+ assert _executor_detailed_status(jobs, {1}) ==
DetailedHealthStatus.HEALTHY
+
+ @_patch_executor_keys({"Celery"})
+ def test_one_scheduler_reporting_unhealthy_is_not_masked_by_another(self,
mock_keys):
+ """Two schedulers checking the same broker: one healthy row must not
hide another's failure."""
+ jobs = [
+ _executor(alive=True, healthy=True, executor="Celery",
owner_job_id=1),
+ _executor(alive=True, healthy=False, executor="Celery",
owner_job_id=2),
+ ]
+ assert _executor_detailed_status(jobs, {1, 2}) ==
DetailedHealthStatus.DOWN
+
+ @_patch_executor_keys({"Celery"})
+ def test_row_left_behind_by_crashed_scheduler_is_ignored(self, mock_keys):
+ """A row can still look alive right after its scheduler died; it must
not count as coverage."""
+ jobs = [_executor(alive=True, healthy=True, executor="Celery",
owner_job_id=2)]
+ assert _executor_detailed_status(jobs, {1}) ==
DetailedHealthStatus.DOWN
+
+
+class TestAirflowHealthExecutor:
+ @pytest.fixture(autouse=True)
+ def cleanup_jobs(self):
+ clear_db_jobs()
+ _configured_executor_names.cache_clear()
+ yield
+ clear_db_jobs()
+ _configured_executor_names.cache_clear()
+
+ def test_executor_key_omitted_when_nothing_implements_get_health(self):
+ """The default, unmodified state: no executor overrides get_health, so
there's no false alarm."""
+ health_status = get_airflow_health()
+
+ assert "executor" not in health_status
+
+ @_patch_executor_keys({"Celery"})
+ @provide_session
+ def
test_executor_key_present_and_healthy_when_implemented_and_reporting(self,
mock_keys, *, session):
+ heartbeat = timezone.utcnow()
+ scheduler_job = Job(job_type=SchedulerJobRunner.job_type,
state=JobState.RUNNING)
+ scheduler_job.latest_heartbeat = heartbeat
+ session.add(scheduler_job)
+ session.commit()
+
+ job = Job(job_type=EXECUTOR_JOB_TYPE, state=JobState.RUNNING,
executor_class="Celery")
+ job.latest_heartbeat = heartbeat
+ job.owner_job_id = scheduler_job.id
+ job.health_check_result = HealthCheckResult.HEALTHY
+ session.add(job)
+ session.commit()
+
+ health_status = get_airflow_health()
+
+ assert health_status["executor"]["status"] == HealthStatus.HEALTHY
+ assert health_status["executor"]["detailed_status"] ==
DetailedHealthStatus.HEALTHY
+ assert health_status["executor"]["latest_executor_heartbeat"] ==
heartbeat.isoformat()
+ assert health_status["executor"]["instances"] == [
+ {
+ "hostname": job.hostname,
+ "executor": "Celery",
+ "latest_executor_heartbeat": heartbeat.isoformat(),
+ "team_names": [],
+ "health_check_result": HealthCheckResult.HEALTHY,
+ }
+ ]
+
+ @_patch_executor_keys({"Celery"})
+ @provide_session
+ def
test_executor_key_unhealthy_when_last_check_failed_despite_live_heartbeat(
+ self, mock_keys, *, session
+ ):
+ """A row can be alive (heartbeat moving) while the last real check
still failed."""
+ heartbeat = timezone.utcnow()
+ scheduler_job = Job(job_type=SchedulerJobRunner.job_type,
state=JobState.RUNNING)
+ scheduler_job.latest_heartbeat = heartbeat
+ session.add(scheduler_job)
+ session.commit()
+
+ job = Job(job_type=EXECUTOR_JOB_TYPE, state=JobState.RUNNING,
executor_class="Celery")
+ job.latest_heartbeat = heartbeat
+ job.owner_job_id = scheduler_job.id
+ job.health_check_result = HealthCheckResult.UNHEALTHY
+ session.add(job)
+ session.commit()
+
+ health_status = get_airflow_health()
+
+ assert health_status["executor"]["status"] == HealthStatus.UNHEALTHY
+ assert health_status["executor"]["detailed_status"] ==
DetailedHealthStatus.DOWN
+
+ @_patch_executor_keys({"Celery"})
+ def
test_executor_key_present_and_down_when_implemented_but_never_reported(self,
mock_keys):
+ """Implemented but never seen a healthy check: a real outage,
correctly reported, not omitted."""
+ health_status = get_airflow_health()
+
+ assert health_status["executor"]["status"] == HealthStatus.UNHEALTHY
+ assert health_status["executor"]["detailed_status"] ==
DetailedHealthStatus.DOWN
+ assert health_status["executor"]["instances"] is None
diff --git
a/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_job.py
b/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_job.py
index 133c5db75a7..d25705f8d71 100644
--- a/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_job.py
+++ b/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_job.py
@@ -24,7 +24,7 @@ import time_machine
from sqlalchemy import delete
from sqlalchemy.orm import Session
-from airflow.jobs.job import Job, JobState
+from airflow.jobs.job import EXECUTOR_JOB_TYPE, Job, JobState
from airflow.jobs.scheduler_job_runner import SchedulerJobRunner
from airflow.models.team import JobTeam, Team
from airflow.utils.session import NEW_SESSION, provide_session
@@ -273,6 +273,25 @@ class TestGetJobs(TestJobEndpoint):
assert paged["total_entries"] == 2
assert len(paged["jobs"]) == 1
+ @time_machine.travel(datetime(2024, 1, 1, tzinfo=UTC), tick=False)
+ def test_get_jobs_is_alive_filter_recognizes_executor_job_type(self,
test_client, session: Session):
+ clear_db_jobs()
+ now = datetime(2024, 1, 1, tzinfo=UTC)
+ fresh = Job(state=JobState.RUNNING, job_type=EXECUTOR_JOB_TYPE,
latest_heartbeat=now)
+ stale = Job(
+ state=JobState.RUNNING,
+ job_type=EXECUTOR_JOB_TYPE,
+ latest_heartbeat=now - timedelta(days=1),
+ )
+ session.add_all([fresh, stale])
+ session.commit()
+
+ alive = test_client.get("/jobs", params={"is_alive": True}).json()
+ assert {job["id"] for job in alive["jobs"]} == {fresh.id}
+
+ not_alive = test_client.get("/jobs", params={"is_alive": False}).json()
+ assert {job["id"] for job in not_alive["jobs"]} == {stale.id}
+
def test_should_raises_401_unauthenticated(self,
unauthenticated_test_client):
response = unauthenticated_test_client.get("/jobs")
assert response.status_code == 401
diff --git a/airflow-core/tests/unit/cli/commands/test_jobs_command.py
b/airflow-core/tests/unit/cli/commands/test_jobs_command.py
index 6fa1007ef17..a77babbdc3d 100644
--- a/airflow-core/tests/unit/cli/commands/test_jobs_command.py
+++ b/airflow-core/tests/unit/cli/commands/test_jobs_command.py
@@ -18,9 +18,10 @@ from __future__ import annotations
import pytest
+from airflow._shared.timezones import timezone
from airflow.cli import cli_parser
from airflow.cli.commands import jobs_command
-from airflow.jobs.job import Job, JobState
+from airflow.jobs.job import EXECUTOR_JOB_TYPE, Job, JobState
from airflow.jobs.scheduler_job_runner import SchedulerJobRunner
from airflow.utils.session import create_session
from airflow.utils.state import State
@@ -73,6 +74,31 @@ class TestCliConfigList:
)
assert "Found one alive job." in temp_stdout.getvalue()
+ def test_without_job_type_ignores_executor_job_rows_on_the_same_host(self,
stdout_capture):
+ with create_session() as session:
+ self.scheduler_job = Job()
+ self.job_runner = SchedulerJobRunner(job=self.scheduler_job)
+ self.scheduler_job.state = State.RUNNING
+ self.scheduler_job.hostname = "HOSTNAME"
+ session.add(self.scheduler_job)
+ session.commit()
+
self.scheduler_job.heartbeat(heartbeat_callback=self.job_runner.heartbeat_callback)
+
+ executor_job = Job(
+ job_type=EXECUTOR_JOB_TYPE,
+ state=State.RUNNING,
+ hostname="HOSTNAME",
+ latest_heartbeat=timezone.utcnow(),
+ )
+ session.add(executor_job)
+ session.commit()
+
+ with stdout_capture as temp_stdout:
+ jobs_command.check(
+ self.parser.parse_args(["jobs", "check", "--hostname",
"HOSTNAME", "--limit", "0"])
+ )
+ assert "Found one alive job." in temp_stdout.getvalue()
+
def test_should_report_success_for_ha_schedulers(self, stdout_capture):
scheduler_jobs = []
job_runners = []
diff --git a/airflow-core/tests/unit/executors/test_base_executor.py
b/airflow-core/tests/unit/executors/test_base_executor.py
index d2c769d2943..a10534813b4 100644
--- a/airflow-core/tests/unit/executors/test_base_executor.py
+++ b/airflow-core/tests/unit/executors/test_base_executor.py
@@ -76,6 +76,11 @@ def test_invalid_slotspool():
BaseExecutor(0)
+def test_get_health_default_value():
+ """An executor that doesn't override get_health() reports nothing, not
failure."""
+ assert BaseExecutor().get_health(timeout=5.0) is None
+
+
def test_get_task_log():
executor = BaseExecutor()
ti = TaskInstance(task=SerializedBaseOperator(task_id="dummy"),
dag_version_id=mock.MagicMock(spec=UUID))
diff --git a/airflow-core/tests/unit/jobs/test_scheduler_job.py
b/airflow-core/tests/unit/jobs/test_scheduler_job.py
index cb4bc8d1bea..34f1857d9f6 100644
--- a/airflow-core/tests/unit/jobs/test_scheduler_job.py
+++ b/airflow-core/tests/unit/jobs/test_scheduler_job.py
@@ -69,7 +69,7 @@ from airflow.executors.executor_utils import ExecutorName
from airflow.executors.local_executor import LocalExecutor
from airflow.executors.workloads import WorkloadType
from airflow.executors.workloads.types import TaskInstanceUuid
-from airflow.jobs.job import Job, run_job
+from airflow.jobs.job import EXECUTOR_JOB_TYPE, Job, run_job
from airflow.jobs.scheduler_job_runner import (
MAX_TI_REFILL_QUERIES_PER_LOOP,
TASK_STUCK_IN_QUEUED_RESCHEDULE_EVENT,
@@ -483,18 +483,24 @@ class TestSchedulerJob:
mock_jwt_generator = MagicMock(spec=JWTGenerator)
mock_jwt_generator.generate.return_value = "mock-token"
- default_executor = mock.MagicMock(name="DefaultExecutor",
slots_available=8, slots_occupied=0)
+ default_executor = mock.MagicMock(
+ spec=BaseExecutor, name="DefaultExecutor", slots_available=8,
slots_occupied=0
+ )
default_executor.name = ExecutorName(alias="default_exec",
module_path="default.exec.module.path")
default_executor.jwt_generator = mock_jwt_generator
default_executor.team_name = None # Global executor
default_executor.sentry_integration = ""
default_executor._drain_events_with_task_ids.return_value = {}, {}
- second_executor = mock.MagicMock(name="SeconadaryExecutor",
slots_available=8, slots_occupied=0)
+ default_executor.overrides_get_health.return_value = False
+ second_executor = mock.MagicMock(
+ spec=BaseExecutor, name="SeconadaryExecutor", slots_available=8,
slots_occupied=0
+ )
second_executor.name = ExecutorName(alias="secondary_exec",
module_path="secondary.exec.module.path")
second_executor.jwt_generator = mock_jwt_generator
second_executor.team_name = None # Global executor
second_executor.sentry_integration = ""
second_executor._drain_events_with_task_ids.return_value = {}, {}
+ second_executor.overrides_get_health.return_value = False
# TODO: Task-SDK Make it look like a bound method. Needed until we
remove the old queue_workload
# interface from executors
@@ -7175,6 +7181,30 @@ class TestSchedulerJob:
assert old_task_job.state == State.RUNNING
assert "Marked 1 SchedulerJob instances as failed" in caplog.messages
+ def test_adopt_or_reset_orphaned_tasks_fails_stale_executor_jobs(self):
+ """A stale ExecutorJob row gets marked failed with an end_date, a
fresh one is left alone."""
+ session = settings.Session()
+
+ scheduler_job = Job()
+ self.job_runner = SchedulerJobRunner(job=scheduler_job)
+
+ stale_executor_job = Job(job_type=EXECUTOR_JOB_TYPE,
state=State.RUNNING)
+ stale_executor_job.latest_heartbeat = timezone.utcnow() -
timedelta(minutes=15)
+ session.add(stale_executor_job)
+
+ fresh_executor_job = Job(job_type=EXECUTOR_JOB_TYPE,
state=State.RUNNING)
+ fresh_executor_job.latest_heartbeat = timezone.utcnow()
+ session.add(fresh_executor_job)
+ session.flush()
+
+ self.job_runner.adopt_or_reset_orphaned_tasks(session=session)
+ session.expire_all()
+
+ assert stale_executor_job.state == State.FAILED
+ assert stale_executor_job.end_date is not None
+ assert fresh_executor_job.state == State.RUNNING
+ assert fresh_executor_job.end_date is None
+
def test_should_update_dag_next_dagrun(self, session, dag_maker):
"""We should always update next_dagrun after scheduler creates a new
dag run."""
with dag_maker(schedule="0 0 * * *"):
@@ -12033,6 +12063,7 @@ class TestSchedulerJob:
# Mock the executor to simulate a task failure
mock_executor = MagicMock(spec=BaseExecutor)
mock_executor.has_task = mock.MagicMock(return_value=False)
+ mock_executor.overrides_get_health.return_value = False
scheduler_job = Job()
self.job_runner = SchedulerJobRunner(scheduler_job,
executors=[mock_executor])
diff --git a/airflow-core/tests/unit/jobs/test_scheduler_job_executor_health.py
b/airflow-core/tests/unit/jobs/test_scheduler_job_executor_health.py
new file mode 100644
index 00000000000..39acc83833a
--- /dev/null
+++ b/airflow-core/tests/unit/jobs/test_scheduler_job_executor_health.py
@@ -0,0 +1,330 @@
+#
+# 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 logging
+import threading
+import time
+
+import pytest
+from sqlalchemy import select
+
+from airflow._shared.timezones import timezone
+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._touch_executor_heartbeats(session=session)
+ session.commit()
+
+ 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_create_a_row_when_none_is_open(session):
+ """The health check thread only ever updates a row; only
_touch_executor_heartbeats creates one."""
+ executor = _StubExecutor()
+ runner = _make_runner(executor, session)
+ key = _executor_health_key(executor)
+
+ runner._run_executor_health_check(executor, key)
+
+ assert _get_executor_job(session, runner.job.id, key) is None
+
+
+def
test_run_executor_health_check_does_not_log_reported_itself_unhealthy_when_it_raised(session,
caplog):
+ executor = _StubExecutor(result=RuntimeError("boom"))
+ runner = _make_runner(executor, session)
+ key = _executor_health_key(executor)
+
+ with caplog.at_level(logging.WARNING,
logger="airflow.jobs.scheduler_job_runner"):
+ runner._run_executor_health_check(executor, key)
+
+ assert f"Health check for executor {key} raised an exception" in caplog
+ assert f"Executor {key} reported itself unhealthy" not in caplog
+
+
+@conf_vars({("scheduler", "executor_health_check_interval"): "10.0"})
+def
test_run_executor_health_check_passes_half_the_configured_interval_as_timeout(session):
+ executor = _StubExecutor(result=True)
+ runner = _make_runner(executor, session)
+ key = _executor_health_key(executor)
+
+ runner._run_executor_health_check(executor, key)
+
+ assert executor.calls == [5.0]
+
+
+def
test_get_or_create_executor_job_reuses_the_row_for_the_same_scheduler(session):
+ executor = _StubExecutor(team_name="team-a")
+ runner = _make_runner(executor, session)
+ key = _executor_health_key(executor)
+
+ first = runner._get_or_create_executor_job(key, None, session=session)
+ session.commit()
+ first_id = first.id
+ second = runner._get_or_create_executor_job(key, None, session=session)
+ session.commit()
+
+ assert second.id == first_id
+
+
+def test_get_or_create_executor_job_sets_team_names(session, testing_team):
+ executor = _StubExecutor(team_name=testing_team.name)
+ runner = _make_runner(executor, session)
+ key = _executor_health_key(executor)
+
+ job = runner._get_or_create_executor_job(key, executor.team_name,
session=session)
+ session.commit()
+
+ assert job.team_names == [testing_team.name]
+
+
+def test_get_or_create_executor_job_gives_each_scheduler_its_own_row(session):
+ executor_a = _StubExecutor()
+ executor_b = _StubExecutor()
+ runner_a = _make_runner(executor_a, session)
+ runner_b = _make_runner(executor_b, session)
+ key = _executor_health_key(executor_a)
+
+ job_a = runner_a._get_or_create_executor_job(key, None, session=session)
+ job_b = runner_b._get_or_create_executor_job(key, None, session=session)
+ session.commit()
+
+ assert job_a.id != job_b.id
+ assert job_a.owner_job_id == runner_a.job.id
+ assert job_b.owner_job_id == runner_b.job.id
+
+
+def test_executor_health_key_is_none_for_an_executor_with_no_name():
+ executor = BaseExecutor()
+ assert executor.name is None
+ assert _executor_health_key(executor) is None
+
+
+def test_unnamed_executor_that_overrides_get_health_gets_no_row(session):
+ executor = _StubExecutor()
+ executor.name = None
+ runner = _make_runner(executor, session)
+
+ assert runner._executor_health_keys == {}
+
+ runner._touch_executor_heartbeats(session=session)
+
+ assert session.scalar(select(Job).where(Job.job_type ==
EXECUTOR_JOB_TYPE)) is None
+
+
+def test_check_executor_health_records_unhealthy_when_a_check_stalls(session):
+ executor = _StubExecutor()
+ runner = _make_runner(executor, session)
+ key = _executor_health_key(executor)
+ runner._touch_executor_heartbeats(session=session)
+ session.commit()
+
+ block_forever = threading.Event()
+ stuck = threading.Thread(target=block_forever.wait, daemon=True)
+ stuck.start()
+ runner._executor_health_check_interval = 0.01
+ runner._executor_health_check_threads[key] = (stuck, time.monotonic() - 10)
+
+ runner._check_executor_health()
+
+ job = _get_executor_job(session, runner.job.id, key)
+ assert job is not None
+ assert job.health_check_result == HealthCheckResult.UNHEALTHY
+ assert key in runner._stalled_health_checks
+
+ block_forever.set()
+ stuck.join()
+
+
+def
test_check_executor_health_marks_unhealthy_on_every_tick_while_stalled(session):
+ """A stalled check must keep marking UNHEALTHY even after the row it wrote
to gets replaced."""
+ executor = _StubExecutor()
+ runner = _make_runner(executor, session)
+ key = _executor_health_key(executor)
+ runner._touch_executor_heartbeats(session=session)
+ session.commit()
+
+ block_forever = threading.Event()
+ stuck = threading.Thread(target=block_forever.wait, daemon=True)
+ stuck.start()
+ runner._executor_health_check_interval = 0.01
+ runner._executor_health_check_threads[key] = (stuck, time.monotonic() - 10)
+
+ runner._check_executor_health()
+ first_job = runner._open_executor_job(key, session=session)
+ assert first_job.health_check_result == HealthCheckResult.UNHEALTHY
+
+ first_job.end_date = timezone.utcnow()
+ session.commit()
+ runner._touch_executor_heartbeats(session=session)
+ session.commit()
+ second_job = runner._open_executor_job(key, session=session)
+ assert second_job.id != first_job.id
+
+ runner._check_executor_health()
+ second_job = runner._open_executor_job(key, session=session)
+ assert second_job.health_check_result == HealthCheckResult.UNHEALTHY
+
+ block_forever.set()
+ stuck.join()
+
+
+def
test_end_executor_jobs_closes_this_scheduler_rows_with_the_given_state(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.end_date is None
+
+ runner._end_executor_jobs(JobState.SUCCESS, session=session)
+ session.commit()
+ session.refresh(job)
+
+ assert job.state == JobState.SUCCESS
+ assert job.end_date is not None
+
+
+def test_end_executor_jobs_does_not_touch_another_schedulers_rows(session):
+ executor_a = _StubExecutor()
+ executor_b = _StubExecutor()
+ runner_a = _make_runner(executor_a, session)
+ runner_b = _make_runner(executor_b, session)
+ key = _executor_health_key(executor_a)
+
+ runner_a._touch_executor_heartbeats(session=session)
+ runner_b._touch_executor_heartbeats(session=session)
+
+ runner_a._end_executor_jobs(JobState.SUCCESS, session=session)
+ session.commit()
+
+ job_b = _get_executor_job(session, runner_b.job.id, key)
+ assert job_b.state == JobState.RUNNING
+ assert job_b.end_date is None
diff --git a/airflow-ctl/src/airflowctl/api/datamodels/generated.py
b/airflow-ctl/src/airflowctl/api/datamodels/generated.py
index 232878dfaa2..d74a877d211 100644
--- a/airflow-ctl/src/airflowctl/api/datamodels/generated.py
+++ b/airflow-ctl/src/airflowctl/api/datamodels/generated.py
@@ -1051,6 +1051,22 @@ class HTTPExceptionResponse(BaseModel):
detail: Annotated[str | dict[str, Any], Field(title="Detail")]
+class HealthCheckResult(str, Enum):
+ """
+ Explicit outcome of a component's own last health check.
+
+ Separate from whether the Job row itself is alive: a row can be alive
(recent heartbeat) while
+ this stays UNKNOWN because the check hasn't completed yet, raised, or was
never implemented.
+ Collapsing all of that into "no heartbeat means unhealthy" makes a real
failure indistinguishable
+ from "never checked" or "check is hanging", which is why this is a value
of its own rather than
+ being inferred from heartbeat recency.
+ """
+
+ HEALTHY = "healthy"
+ UNHEALTHY = "unhealthy"
+ UNKNOWN = "unknown"
+
+
class HealthStatus(str, Enum):
"""
Aggregate health of a component: whether it has at least one live instance.
@@ -2777,6 +2793,18 @@ class EventLogCollectionResponse(BaseModel):
] = None
+class ExecutorInstanceInfoResponse(BaseModel):
+ """
+ Executor instance info serializer for responses.
+ """
+
+ hostname: Annotated[str | None, Field(title="Hostname")]
+ executor: Annotated[str | None, Field(title="Executor")]
+ latest_executor_heartbeat: Annotated[str | None, Field(title="Latest
Executor Heartbeat")]
+ team_names: Annotated[list[str], Field(title="Team Names")]
+ health_check_result: HealthCheckResult | None
+
+
class ExternalViewResponse(BaseModel):
"""
Serializer for External View Plugin responses.
@@ -3462,6 +3490,17 @@ class DagStatsCollectionResponse(BaseModel):
total_entries: Annotated[int, Field(title="Total Entries")]
+class ExecutorInfoResponse(BaseModel):
+ """
+ Executor info serializer for responses.
+ """
+
+ status: HealthStatus | None
+ latest_executor_heartbeat: Annotated[str | None, Field(title="Latest
Executor Heartbeat")]
+ detailed_status: DetailedHealthStatus | None
+ instances: Annotated[list[ExecutorInstanceInfoResponse] | None,
Field(title="Instances")] = None
+
+
class HITLDetail(BaseModel):
"""
Schema for Human-in-the-loop detail.
@@ -3522,6 +3561,7 @@ class HealthInfoResponse(BaseModel):
scheduler: SchedulerInfoResponse
triggerer: TriggererInfoResponse
dag_processor: DagProcessorInfoResponse | None = None
+ executor: ExecutorInfoResponse | None = None
class PluginCollectionResponse(BaseModel):
diff --git a/airflow-ctl/src/airflowctl/ctl/commands/jobs_command.py
b/airflow-ctl/src/airflowctl/ctl/commands/jobs_command.py
index 0eb9a47a62a..056530aee32 100644
--- a/airflow-ctl/src/airflowctl/ctl/commands/jobs_command.py
+++ b/airflow-ctl/src/airflowctl/ctl/commands/jobs_command.py
@@ -36,6 +36,10 @@ def check(args, api_client=NEW_API_CLIENT) -> None:
hostname = socket.getfqdn() if args.local else args.hostname
alive_jobs = api_client.jobs.list(job_type=args.job_type,
hostname=hostname, is_alive=True).jobs
+ if not args.job_type:
+ # ExecutorJob rows share a host with the scheduler that owns them, not
a host of their own,
+ # so an unscoped check should not count them alongside the job types
--job-type can select.
+ alive_jobs = [job for job in alive_jobs if job.job_type !=
"ExecutorJob"]
if args.limit > 0:
alive_jobs = alive_jobs[: args.limit]
diff --git a/airflow-ctl/tests/airflow_ctl/ctl/commands/test_jobs_command.py
b/airflow-ctl/tests/airflow_ctl/ctl/commands/test_jobs_command.py
index 697faa682c4..200264d27a7 100644
--- a/airflow-ctl/tests/airflow_ctl/ctl/commands/test_jobs_command.py
+++ b/airflow-ctl/tests/airflow_ctl/ctl/commands/test_jobs_command.py
@@ -25,9 +25,9 @@ from airflowctl.ctl import cli_parser
from airflowctl.ctl.commands import jobs_command
-def _make_jobs(count: int) -> SimpleNamespace:
+def _make_jobs(count: int, job_type: str = "SchedulerJob") -> SimpleNamespace:
"""Build a stand-in for the ``JobCollectionResponse`` of ``count``
already-alive jobs."""
- return SimpleNamespace(jobs=[SimpleNamespace(id=i) for i in range(count)])
+ return SimpleNamespace(jobs=[SimpleNamespace(id=i, job_type=job_type) for
i in range(count)])
class TestCliJobsCheck:
@@ -50,6 +50,22 @@ class TestCliJobsCheck:
assert expected_output in capsys.readouterr().out
+ def test_without_job_type_ignores_executor_job_rows(self, capsys):
+ api_client = mock.MagicMock()
+ api_client.jobs.list.return_value = SimpleNamespace(
+ jobs=[
+ SimpleNamespace(id=1, job_type="SchedulerJob"),
+ SimpleNamespace(id=2, job_type="ExecutorJob"),
+ ]
+ )
+
+ jobs_command.check(
+ self.parser.parse_args(["jobs", "check", "--hostname", "HOSTNAME",
"--limit", "0"]),
+ api_client=api_client,
+ )
+
+ assert "Found one alive job." in capsys.readouterr().out
+
@pytest.mark.parametrize(
("argv", "local_hostname", "expected_kwargs"),
[
diff --git
a/shared/observability/src/airflow_shared/observability/metrics/metrics_template.yaml
b/shared/observability/src/airflow_shared/observability/metrics/metrics_template.yaml
index 1eeb7606a39..bab312f39e4 100644
---
a/shared/observability/src/airflow_shared/observability/metrics/metrics_template.yaml
+++
b/shared/observability/src/airflow_shared/observability/metrics/metrics_template.yaml
@@ -283,6 +283,14 @@ metrics:
legacy_name: "-"
name_variables: []
+ - name: "scheduler.executor_health_check.stalled"
+ description: "Number of times an executor's health check was reported as
stalled: its
+ get_health() call hadn't returned after several check intervals. Metric
with executor
+ and team_name tagging."
+ type: "counter"
+ legacy_name: "-"
+ name_variables: []
+
- name: "scheduler.critical_section_busy"
description: "Count of times a scheduler process tried to get a lock on
the critical
section (needed to send tasks to the executor) and found it locked by
another process."