Skip to content

AIP-97: Add optional task failure metadata in core - #73816

Draft
1fanwang wants to merge 12 commits into
apache:mainfrom
1fanwang:aip97-composite-poc
Draft

1fanwang wants to merge 12 commits into
apache:mainfrom
1fanwang:aip97-composite-poc

Conversation

@1fanwang

@1fanwang 1fanwang commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Why

A missing heartbeat tells the scheduler that a worker stopped reporting, not why. Even a SIGKILL notice identifies the signal but not who sent it. Failure listeners need a way to report a known cause without treating either observation as proof of preemption.

What

This draft implements the core part of AIP-97, Task Failure Classification. The proposal is still under discussion:

https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=399279312

The Task SDK reports application exceptions and execution timeouts to worker-side listeners. A custom executor can pass a failure category and a short reason to the scheduler. If it supplies only a reason, the listener receives that reason with no category, and the task and operator failure counters use unclassified. When a user marks a task failed through the public API, the listener receives manual.

This PR does not include a Kubernetes provider classifier or change how Airflow counts attempts. AIP-122 separately proposes when a confirmed infrastructure failure should get an extra retry:

https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=451974654

Risk

Existing listeners can keep their signatures, and existing executors can keep sending their usual info. Only the category becomes a metric tag. The SDK keeps its failure metadata on the worker; it adds no Execution API or database fields.

Testing Done

The two-file scheduler replay is the shortest check. On a fresh database at the PR head, the listener received SIGKILL without a category and the task never started. In the full run on the same head, both failure counters recorded unclassified for that notice and infra for an explicit category from the test executor. An ordinary retry succeeded on attempt 2 with max_tries still 1. The macOS and Breeze comparisons below use their own pinned base commits.

Failure before a worker starts

At 287983c the SDK reported application and timeout failures, and the retry succeeded on attempt 2 with its original retry budget:

LISTENER {"event": "typed", "failure_kind": "application", "reason": null, "task_id": "application_failure", "id": "01a21125-9844-7f66-b122-4c1253d20956", "try_number": 1, "state": "failed"}
LISTENER {"event": "typed", "failure_kind": "timeout", "reason": null, "task_id": "timeout_failure", "id": "01a21125-9848-75be-b4e3-f48adb9c3eb0", "try_number": 1, "state": "failed"}
RETRY [[1, "failed", 1], [2, "success", 1]]

A separate replay on that head rejected a queued task before dispatch. The executor used the legacy task key and supplied SIGKILL as its reason. The scheduler listener received the reason without inferring a category. No process received that signal.

With this checkout's Airflow environment on PATH, save the two files below in an empty directory and run:

env -i PATH="$PATH" /bin/sh check.sh
LISTENER task=never_started kind=None reason=SIGKILL
DATABASE ('never_started', 'failed', None)
Reproducer source: queue_notice.py
from __future__ import annotations

from collections.abc import Sequence
from datetime import datetime, timezone
from typing import TYPE_CHECKING

from airflow.executors.local_executor import LocalExecutor
from airflow.executors.workloads import ExecuteTask, ExecutorWorkload
from airflow.listeners import hookimpl
from airflow.listeners.listener import get_listener_manager
from airflow.sdk import DAG, task

if TYPE_CHECKING:
    from airflow._shared.state import TaskFailureKind
    from airflow.models.taskinstance import TaskInstance


class QueueNotice(LocalExecutor):
    def _process_workloads(self, workload_list: Sequence[ExecutorWorkload]) -> None:
        get_listener_manager().add_listener(self)
        for workload in workload_list:
            assert isinstance(workload, ExecuteTask) and workload.ti.dag_id == "queue_notice"
            self.executor_queues[workload.type].pop(self.get_workload_key(workload))
            self.fail(key=workload.key, reason="SIGKILL")

    @hookimpl
    def on_task_instance_failed(
        self, task_instance: TaskInstance, failure_kind: TaskFailureKind | None, reason: str | None
    ) -> None:
        print(f"LISTENER task={task_instance.task_id} kind={failure_kind} reason={reason}", flush=True)


with DAG(dag_id="queue_notice", schedule=None, start_date=datetime(2026, 1, 1, tzinfo=timezone.utc)):
    @task
    def never_started() -> None:
        raise AssertionError("executor should have rejected the workload")

    never_started()
Reproducer source: check.sh
#!/bin/sh
set -eu
umask 077
ROOT="$PWD/queue-notice-run"
mkdir "$ROOT"
mkdir -p "$ROOT/dags" "$ROOT/home" "$ROOT/tmp"
cp queue_notice.py "$ROOT/dags/"
export HOME="$ROOT/home" TMPDIR="$ROOT/tmp" AIRFLOW_HOME="$ROOT"
export AIRFLOW_CONFIG="$ROOT/airflow.cfg" PYTHONPATH="$PWD" PYTHONNOUSERSITE=1 PYTHONDONTWRITEBYTECODE=1
export AIRFLOW__DATABASE__SQL_ALCHEMY_CONN="sqlite:///$ROOT/airflow.db"
export AIRFLOW__CORE__LOAD_EXAMPLES=False AIRFLOW__CORE__EXECUTOR=queue_notice.QueueNotice
export AIRFLOW__CORE__EXECUTION_API_SERVER_URL=http://127.0.0.1:0/execution/
export AIRFLOW__CORE__DAGS_ARE_PAUSED_AT_CREATION=False AIRFLOW__CORE__PARALLELISM=1
export AIRFLOW__SCHEDULER__ENABLE_HEALTH_CHECK=False AIRFLOW__METRICS__STATSD_ON=False
airflow db migrate > "$ROOT/migration.log" 2>&1
airflow dags reserialize > "$ROOT/serialize.log" 2>&1
airflow dags trigger queue_notice --run-id controlled-notice > "$ROOT/trigger.log" 2>&1
airflow scheduler --skip-serve-logs --num-runs 10 > "$ROOT/scheduler.log" 2>&1
grep '^LISTENER task=never_started kind=None reason=SIGKILL$' "$ROOT/scheduler.log"
python - <<'PY'
import os
import sqlite3
from pathlib import Path

uri = Path(os.environ["AIRFLOW_HOME"], "airflow.db").as_uri() + "?mode=ro"
with sqlite3.connect(database=uri, uri=True) as db:
    rows = db.execute("SELECT task_id,state,start_date FROM task_instance WHERE dag_id='queue_notice'").fetchall()
assert rows == [("never_started", "failed", None)], rows
print("DATABASE", rows[0])
PY

Demo on current main

Ran natively on macOS 26.7.3 (arm64) with Python 3.12.16, uv 0.13.8 and Airflow 3.5.0, against current main at 8f88f8d. The reproducer below starts the real API server, Dag processor and scheduler on a SQLite metadata database. It runs failing tasks through the Task SDK and records what a listener plugin, the failure callbacks and a DogStatsD receiver see.

Failure Listener receives Metric tag
Application exception application failure_kind:application
Execution timeout timeout failure_kind:timeout
Executor notice with a known cause (UUID key) infra, reason ControlledBackendNotice failure_kind:infra
Executor loss with only a reason (legacy key) no kind, reason SIGKILL failure_kind:unclassified
Executor loss with no reason (UUID key) no kind, no reason failure_kind:unclassified
Ordinary retry application on attempt 1, then attempt 2 succeeded failure_kind:application, max_tries unchanged at 1

Callbacks and legacy listeners kept their failed-attempt identities. ControlledBackendNotice comes from the reproducer's executor, so this run shows the custom-executor transport and the consumers rather than a production infrastructure classifier. SDK causes do not travel to the scheduler through the Execution API.

Setup in a checkout of this branch, with the four reproducer files below copied to dev/:

git fetch https://github.com/apache/airflow.git main
git merge --no-commit --no-ff FETCH_HEAD
pkgs=(--package apache-airflow --package apache-airflow-devel-common)
for d in shared/*/; do n=$(basename "$d"); pkgs+=(--package "apache-airflow-shared-${n//_/-}"); done
uv sync --frozen --no-default-groups "${pkgs[@]}" --python 3.12
uv pip install datadog==0.56.0

The core install does not include the DogStatsD client, so datadog is added at the version pinned in uv.lock.

Run:

PATH="$PWD/.venv/bin:$PATH" python dev/aip97_core_repro.py --label after > run-after.log 2>&1
grep -E '^UDP_METRIC|^CONSUMER .*metadata_failure|^RESULT' run-after.log

Raw output (exit 0, 43.7 seconds):

UDP_METRIC airflow.ti_failures:1|c|#dag_id:aip97_core_repro,task_id:application_failure,run_type:manual,failure_kind:application
UDP_METRIC airflow.operator_failures:1|c|#dag_id:aip97_core_repro,task_id:application_failure,run_type:manual,failure_kind:application,operator_name:_PythonDecoratedOperator
CONSUMER {"event": "metadata_failure", "failure_kind": "application", "reason": null, "id": "01a1e7aa-f245-7a3a-a380-814c77b10396", "task_id": "application_failure", "try_number": 1, "state": "failed"}
UDP_METRIC airflow.ti_failures:1|c|#dag_id:aip97_core_repro,task_id:timeout_failure,run_type:manual,failure_kind:timeout
UDP_METRIC airflow.operator_failures:1|c|#dag_id:aip97_core_repro,task_id:timeout_failure,run_type:manual,failure_kind:timeout,operator_name:_PythonDecoratedOperator
CONSUMER {"event": "metadata_failure", "failure_kind": "timeout", "reason": null, "id": "01a1e7aa-f246-7f84-b9bc-4414096e43c6", "task_id": "timeout_failure", "try_number": 1, "state": "failed"}
UDP_METRIC airflow.ti_failures:1|c|#dag_id:aip97_core_repro,task_id:ordinary_retry,run_type:manual,failure_kind:application
UDP_METRIC airflow.operator_failures:1|c|#dag_id:aip97_core_repro,task_id:ordinary_retry,run_type:manual,failure_kind:application,operator_name:_PythonDecoratedOperator
CONSUMER {"event": "metadata_failure", "failure_kind": "application", "reason": null, "id": "01a1e7aa-f247-7908-9f5e-ded2c0511882", "task_id": "ordinary_retry", "try_number": 1, "state": "up_for_retry"}
UDP_METRIC airflow.ti_failures:1|c|#dag_id:aip97_core_repro,run_type:manual,task_id:executor_uuid,failure_kind:infra
UDP_METRIC airflow.operator_failures:1|c|#dag_id:aip97_core_repro,run_type:manual,task_id:executor_uuid,failure_kind:infra,operator_name:_PythonDecoratedOperator
CONSUMER {"event": "metadata_failure", "failure_kind": "infra", "reason": "ControlledBackendNotice", "id": "01a1e7aa-f248-7ac8-b171-8c0c42423239", "task_id": "executor_uuid", "try_number": 1, "state": "failed"}
UDP_METRIC airflow.ti_failures:1|c|#dag_id:aip97_core_repro,run_type:manual,task_id:executor_legacy,failure_kind:unclassified
UDP_METRIC airflow.operator_failures:1|c|#dag_id:aip97_core_repro,run_type:manual,task_id:executor_legacy,failure_kind:unclassified,operator_name:_PythonDecoratedOperator
CONSUMER {"event": "metadata_failure", "failure_kind": null, "reason": "SIGKILL", "id": "01a1e7aa-f249-78e3-9e91-8eff1f8a2b56", "task_id": "executor_legacy", "try_number": 1, "state": "failed"}
UDP_METRIC airflow.ti_failures:1|c|#dag_id:aip97_core_repro,run_type:manual,task_id:executor_unknown,failure_kind:unclassified
UDP_METRIC airflow.operator_failures:1|c|#dag_id:aip97_core_repro,run_type:manual,task_id:executor_unknown,failure_kind:unclassified,operator_name:_PythonDecoratedOperator
CONSUMER {"event": "metadata_failure", "failure_kind": null, "reason": null, "id": "01a1e7aa-f24a-74e7-bf2e-c98ff98f2802", "task_id": "executor_unknown", "try_number": 1, "state": "failed"}
RESULT after: real DB, SDK, scheduler, callbacks, legacy listeners and UDP metrics verified; typed metadata verified

The retry kept its ordinary attempt accounting:

grep '^FINAL_ATTEMPTS' run-after.log | sed 's/^FINAL_ATTEMPTS //' | jq -c '.[] | select(.task_id == "ordinary_retry") | {task_id, try_number, state, max_tries}'
{"task_id":"ordinary_retry","try_number":1,"state":"failed","max_tries":1}
{"task_id":"ordinary_retry","try_number":2,"state":"success","max_tries":1}

Current main without this change

The same command on current main:

PATH="$PWD/.venv/bin:$PATH" python dev/aip97_core_repro.py --label before > run-before.log 2>&1
grep -E '^UDP_METRIC|^CONSUMER .*metadata_failure|^RESULT' run-before.log

Raw output (exit 0, 31.5 seconds):

UDP_METRIC airflow.ti_failures:1|c|#dag_id:aip97_core_repro,task_id:application_failure,run_type:manual
UDP_METRIC airflow.operator_failures:1|c|#dag_id:aip97_core_repro,task_id:application_failure,run_type:manual,operator_name:_PythonDecoratedOperator
UDP_METRIC airflow.ti_failures:1|c|#dag_id:aip97_core_repro,task_id:timeout_failure,run_type:manual
UDP_METRIC airflow.operator_failures:1|c|#dag_id:aip97_core_repro,task_id:timeout_failure,run_type:manual,operator_name:_PythonDecoratedOperator
UDP_METRIC airflow.ti_failures:1|c|#dag_id:aip97_core_repro,task_id:ordinary_retry,run_type:manual
UDP_METRIC airflow.operator_failures:1|c|#dag_id:aip97_core_repro,task_id:ordinary_retry,run_type:manual,operator_name:_PythonDecoratedOperator
UDP_METRIC airflow.ti_failures:1|c|#dag_id:aip97_core_repro,run_type:manual,task_id:executor_uuid
UDP_METRIC airflow.operator_failures:1|c|#dag_id:aip97_core_repro,run_type:manual,task_id:executor_uuid,operator_name:_PythonDecoratedOperator
UDP_METRIC airflow.ti_failures:1|c|#dag_id:aip97_core_repro,run_type:manual,task_id:executor_legacy
UDP_METRIC airflow.operator_failures:1|c|#dag_id:aip97_core_repro,run_type:manual,task_id:executor_legacy,operator_name:_PythonDecoratedOperator
UDP_METRIC airflow.ti_failures:1|c|#dag_id:aip97_core_repro,run_type:manual,task_id:executor_unknown
UDP_METRIC airflow.operator_failures:1|c|#dag_id:aip97_core_repro,run_type:manual,task_id:executor_unknown,operator_name:_PythonDecoratedOperator
RESULT before: real DB, SDK, scheduler, callbacks, legacy listeners and UDP metrics verified; typed metadata absent on untouched upstream

Linux Breeze run

The same reproducer also passed in Linux amd64 Breeze with Python 3.12.16 and Airflow 3.5.0. The control was 0bc9e82:

set -e; uv run dev/aip97_core_repro.py --label before
set -e; uv run dev/aip97_core_repro.py --label after

DogStatsD packets on the control:

airflow.ti_failures:1|c|#dag_id:aip97_core_repro,task_id:application_failure,run_type:manual|c:in-25159
airflow.ti_failures:1|c|#dag_id:aip97_core_repro,run_type:manual,task_id:executor_uuid|c:in-25159

DogStatsD packets and listener records with this change:

airflow.ti_failures:1|c|#dag_id:aip97_core_repro,task_id:application_failure,run_type:manual,failure_kind:application|c:in-25244
airflow.ti_failures:1|c|#dag_id:aip97_core_repro,task_id:timeout_failure,run_type:manual,failure_kind:timeout|c:in-25244
airflow.ti_failures:1|c|#dag_id:aip97_core_repro,run_type:manual,task_id:executor_uuid,failure_kind:infra|c:in-25244
airflow.ti_failures:1|c|#dag_id:aip97_core_repro,run_type:manual,task_id:executor_legacy,failure_kind:unclassified|c:in-25244
airflow.ti_failures:1|c|#dag_id:aip97_core_repro,run_type:manual,task_id:executor_unknown,failure_kind:unclassified|c:in-25244
airflow.operator_failures:1|c|#dag_id:aip97_core_repro,run_type:manual,task_id:executor_uuid,failure_kind:infra,operator_name:_PythonDecoratedOperator|c:in-25244
CONSUMER {"event": "metadata_failure", "failure_kind": "infra", "reason": "ControlledBackendNotice", "id": "01a1d1f1-b90d-74ec-a807-19655a9e27ac", "task_id": "executor_uuid", "try_number": 1, "state": "failed"}
CONSUMER {"event": "metadata_failure", "failure_kind": null, "reason": "SIGKILL", "id": "01a1d1f1-b90e-7634-b126-b94d25e931a0", "task_id": "executor_legacy", "try_number": 1, "state": "failed"}
CONSUMER {"event": "metadata_failure", "failure_kind": null, "reason": null, "id": "01a1d1f1-b90f-71c4-8c4d-cb1dd836b6f4", "task_id": "executor_unknown", "try_number": 1, "state": "failed"}
Reproducer source: aip97_core_repro.py
#!/usr/bin/env python3
# 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.
#
# /// script
# requires-python = ">=3.12"
# ///
from __future__ import annotations

import argparse
import contextlib
import json
import os
import secrets
import shutil
import signal
import socket
import sqlite3
import subprocess
import threading
import time
from pathlib import Path
from typing import Any
from uuid import UUID


def read_events(path: Path) -> list[dict[str, Any]]:
    return [json.loads(line) for line in path.read_text().splitlines()] if path.exists() else []


def read_attempts(database: Path) -> list[dict[str, Any]]:
    with sqlite3.connect(database=database, timeout=5) as connection:
        connection.row_factory = sqlite3.Row
        rows = connection.execute(
            "SELECT id, task_id, state, try_number, max_tries, start_date, last_heartbeat_at, "
            "queued_by_job_id FROM task_instance WHERE dag_id = ? ORDER BY task_id",
            ("aip97_core_repro",),
        ).fetchall()
    return [dict(row) for row in rows]


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--label", required=True, choices=["before", "after"])
    arguments = parser.parse_args()
    source = Path(__file__).resolve().parent
    output = source / "files" / f"aip97-core-{arguments.label}"
    output.mkdir(parents=True, exist_ok=False)
    home = Path("/tmp") / f"aip97-core-{arguments.label}"
    home.mkdir(exist_ok=False)
    for folder in ("dags", "plugins"):
        (home / folder).mkdir()
    shutil.copyfile(src=source / "aip97_repro_dag.py", dst=home / "dags" / "repro.py")
    shutil.copyfile(src=source / "aip97_repro_listener.py", dst=home / "plugins" / "aip97_repro_listener.py")
    events_path = output / "events.jsonl"
    database = home / "airflow.db"
    environment: dict[str, str] = {
        **os.environ,
        "AIRFLOW_HOME": str(home),
        "AIRFLOW__DATABASE__SQL_ALCHEMY_CONN": f"sqlite:///{database}",
        "AIRFLOW__CORE__DAGS_FOLDER": str(home / "dags"),
        "AIRFLOW__CORE__PLUGINS_FOLDER": str(home / "plugins"),
        "AIRFLOW__CORE__LOAD_EXAMPLES": "False",
        "AIRFLOW__CORE__EXECUTOR": "aip97_repro_executor.ReproExecutor",
        "AIRFLOW__CORE__PARALLELISM": "2",
        "AIRFLOW__CORE__EXECUTION_API_SERVER_URL": "http://127.0.0.1:8080/execution/",
        "AIRFLOW__CORE__DAGS_ARE_PAUSED_AT_CREATION": "False",
        "AIRFLOW__DAG_PROCESSOR__REFRESH_INTERVAL": "1",
        "AIRFLOW__DAG_PROCESSOR__MIN_FILE_PROCESS_INTERVAL": "1",
        "AIRFLOW__SCHEDULER__SCHEDULER_HEARTBEAT_SEC": "1",
        "AIRFLOW__SCHEDULER__TASK_INSTANCE_HEARTBEAT_SEC": "1",
        "AIRFLOW__SCHEDULER__TASK_INSTANCE_HEARTBEAT_TIMEOUT": "60",
        "AIRFLOW__SCHEDULER__MIN_SERIALIZED_DAG_FETCH_INTERVAL": "0",
        "AIRFLOW__API_AUTH__JWT_SECRET": secrets.token_urlsafe(64),
        "AIRFLOW__METRICS__STATSD_ON": "True",
        "AIRFLOW__METRICS__STATSD_DATADOG_ENABLED": "True",
        "AIRFLOW__METRICS__STATSD_HOST": "127.0.0.1",
        "AIP97_EVENT_LOG": str(events_path),
        "PYTHONPATH": f"{source}:{os.environ.get('PYTHONPATH', '')}",
    }
    processes: list[subprocess.Popen[bytes]] = []
    stop = threading.Event()
    metrics_path = output / "metrics.log"
    with socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) as receiver:
        receiver.bind(("127.0.0.1", 0))
        receiver.settimeout(0.2)
        environment["AIRFLOW__METRICS__STATSD_PORT"] = str(receiver.getsockname()[1])

        def capture_metrics() -> None:
            with metrics_path.open(mode="a") as metrics_output:
                while not stop.is_set():
                    try:
                        packet, _ = receiver.recvfrom(65535)
                    except TimeoutError:
                        continue
                    metrics_output.write(packet.decode() + "\n")
                    metrics_output.flush()

        metrics_thread = threading.Thread(target=capture_metrics, daemon=True)
        metrics_thread.start()
        with contextlib.ExitStack() as stack:

            def run_cli(command: list[str]) -> None:
                print("COMMAND", " ".join(["airflow", *command]), flush=True)
                subprocess.run(args=["airflow", *command], env=environment, check=True, timeout=120)

            def launch(name: str, command: list[str]) -> None:
                log = stack.enter_context((output / f"{name}.log").open(mode="wb"))
                process = subprocess.Popen(
                    args=["airflow", *command],
                    env=environment,
                    stdout=log,
                    stderr=subprocess.STDOUT,
                    start_new_session=True,
                )
                processes.append(process)
                print("STARTED", name, process.pid, flush=True)

            try:
                run_cli(command=["db", "migrate"])
                launch(
                    name="api",
                    command=["api-server", "--apps", "execution", "--host", "127.0.0.1", "--port", "8080"],
                )
                launch(name="processor", command=["dag-processor"])
                launch(name="scheduler", command=["scheduler"])
                deadline = time.monotonic() + 120
                while True:
                    with sqlite3.connect(database=database) as connection:
                        found = connection.execute(
                            "SELECT dag_id FROM dag WHERE dag_id = ?", ("aip97_core_repro",)
                        ).fetchone()
                    if found:
                        break
                    if time.monotonic() >= deadline:
                        raise TimeoutError("Real Dag processor did not serialize the fixture")
                    time.sleep(0.5)
                run_cli(command=["dags", "unpause", "aip97_core_repro"])
                run_cli(
                    command=[
                        "dags",
                        "trigger",
                        "aip97_core_repro",
                        "--run-id",
                        f"aip97-core-{arguments.label}",
                    ]
                )
                deadline = time.monotonic() + 240
                snapshots: list[dict[str, Any]] = []
                while True:
                    attempts = read_attempts(database=database)
                    for attempt in attempts:
                        task_id = attempt["task_id"]
                        release = home / f"release_{task_id}"
                        if (
                            task_id.startswith("executor_")
                            and attempt["state"] == "running"
                            and attempt["last_heartbeat_at"] is not None
                            and attempt["last_heartbeat_at"] > attempt["start_date"]
                            and not release.exists()
                            and (home / f"ready_{task_id}").exists()
                        ):
                            print("BEFORE_PROCESS_LOSS", json.dumps(attempt), flush=True)
                            snapshots.append(attempt)
                            release.touch()
                    events = read_events(path=events_path)
                    callbacks = [event for event in events if event["event"] == "callback"]
                    if (
                        len(attempts) == 7
                        and all(attempt["state"] in ("failed", "success") for attempt in attempts)
                        and len(callbacks) == 6
                    ):
                        break
                    if time.monotonic() >= deadline:
                        raise TimeoutError(
                            f"Real execution did not complete: {attempts}; callbacks={callbacks}"
                        )
                    time.sleep(0.5)
                (output / "before-process-loss.json").write_text(json.dumps(snapshots, indent=2))
                (output / "final-attempts.json").write_text(json.dumps(attempts, indent=2))
                verify_results(
                    label=arguments.label,
                    attempts=attempts,
                    snapshots=snapshots,
                    events=events,
                    metrics=metrics_path.read_text().splitlines(),
                )
            finally:
                for process in reversed(processes):
                    with contextlib.suppress(ProcessLookupError):
                        os.killpg(process.pid, signal.SIGTERM)
                for process in processes:
                    try:
                        process.wait(timeout=15)
                    except subprocess.TimeoutExpired:
                        with contextlib.suppress(ProcessLookupError):
                            os.killpg(process.pid, signal.SIGKILL)
                        process.wait(timeout=5)
                stop.set()
                metrics_thread.join(timeout=2)
                for name in ("api", "processor", "scheduler"):
                    path = output / f"{name}.log"
                    if path.exists():
                        print(f"\nRAW_{name.upper()}_TAIL\n" + "\n".join(path.read_text().splitlines()[-25:]))


def verify_results(
    label: str,
    attempts: list[dict[str, Any]],
    snapshots: list[dict[str, Any]],
    events: list[dict[str, Any]],
    metrics: list[str],
) -> None:
    expected: dict[str, tuple[str | None, str | None]] = {
        "application_failure": ("application", None),
        "timeout_failure": ("timeout", None),
        "ordinary_retry": ("application", None),
        "executor_uuid": ("infra", "ControlledBackendNotice"),
        "executor_legacy": (None, "SIGKILL"),
        "executor_unknown": (None, None),
    }
    if len(snapshots) != 3:
        raise AssertionError(f"Missing real running/heartbeat snapshots: {snapshots}")
    retry_attempts = sorted(
        [
            (attempt["try_number"], attempt["state"], attempt["max_tries"])
            for attempt in attempts
            if attempt["task_id"] == "ordinary_retry"
        ]
    )
    if retry_attempts != [(1, "failed", 1), (2, "success", 1)]:
        raise AssertionError(f"Ordinary retry changed: {retry_attempts}")
    for task_id, (failure_kind, reason) in expected.items():
        legacy = [
            event for event in events if event["event"] == "legacy_failure" and event["task_id"] == task_id
        ]
        callbacks = [
            event for event in events if event["event"] == "callback" and event["task_id"] == task_id
        ]
        metadata = [
            event for event in events if event["event"] == "metadata_failure" and event["task_id"] == task_id
        ]
        if len(legacy) != 1 or len(callbacks) != 1:
            raise AssertionError(f"Missing real consumer: {task_id}, {legacy}, {callbacks}")
        if (legacy[0]["id"], legacy[0]["try_number"]) != (
            callbacks[0]["id"],
            callbacks[0]["try_number"],
        ):
            raise AssertionError(f"Failed-attempt notification identity changed: {legacy}, {callbacks}")
        if label == "after":
            if len(metadata) != 1 or (metadata[0]["failure_kind"], metadata[0]["reason"]) != (
                failure_kind,
                reason,
            ):
                raise AssertionError(f"Metadata lost: {task_id}, {metadata}")
            if metadata[0]["id"] != legacy[0]["id"]:
                raise AssertionError(f"Listener identity changed: {metadata}, {legacy}")
        elif metadata:
            raise AssertionError(f"Baseline unexpectedly has the optional contract: {metadata}")
        for metric in ("ti_failures", "operator_failures"):
            received = [
                line
                for line in metrics
                if line.startswith(f"airflow.{metric}:") and f"task_id:{task_id}" in line
            ]
            if not received:
                raise AssertionError(f"No real UDP metric: {metric}, {task_id}")
            expected_tag = f"failure_kind:{failure_kind or 'unclassified'}"
            if label == "after" and not all(expected_tag in line for line in received):
                raise AssertionError(f"Missing bounded metric tag: {received}")
            if label == "before" and any("failure_kind:" in line for line in received):
                raise AssertionError(f"Baseline unexpectedly has category metrics: {received}")
            print("UDP_METRIC", "\n".join(received), flush=True)
        for event in (*legacy, *metadata, *callbacks):
            print("CONSUMER", json.dumps(event), flush=True)
    for snapshot in snapshots:
        failure = next(
            event
            for event in events
            if event["event"] == "legacy_failure" and event["task_id"] == snapshot["task_id"]
        )
        if UUID(failure["id"]) != UUID(snapshot["id"]):
            raise AssertionError(f"Scheduler reported a different attempt: {snapshot}, {failure}")
    print("FINAL_ATTEMPTS", json.dumps(attempts), flush=True)
    print(
        f"RESULT {label}: real DB, SDK, scheduler, callbacks, legacy listeners and UDP metrics verified; "
        + ("typed metadata verified" if label == "after" else "typed metadata absent on untouched upstream"),
        flush=True,
    )


if __name__ == "__main__":
    main()
Reproducer source: aip97_repro_dag.py
# 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 os
import signal
import time
from datetime import timedelta
from pathlib import Path

import pendulum
from aip97_repro_listener import record_callback, record_event

from airflow.sdk import DAG, get_current_context, task


@task
def application_failure() -> None:
    raise RuntimeError("Controlled application exception")


@task
def timeout_failure() -> None:
    time.sleep(20)


@task
def ordinary_retry() -> None:
    if get_current_context()["ti"].try_number == 1:
        raise RuntimeError("Controlled first-attempt exception")


@task
def lose_worker() -> None:
    ti = get_current_context()["ti"]
    home = Path(os.environ["AIRFLOW_HOME"])
    (home / f"ready_{ti.task_id}").touch()
    deadline = time.monotonic() + 90
    while not (home / f"release_{ti.task_id}").exists():
        if time.monotonic() >= deadline:
            raise TimeoutError("Driver did not observe a real worker heartbeat")
        time.sleep(0.1)
    record_event(event="controlled_process_loss", task_instance=ti)
    os.kill(os.getppid(), signal.SIGKILL)
    os.kill(os.getpid(), signal.SIGKILL)


with DAG(
    dag_id="aip97_core_repro",
    start_date=pendulum.datetime(2026, 1, 1, tz="UTC"),
    schedule=None,
    catchup=False,
    is_paused_upon_creation=False,
    default_args={
        "retries": 0,
        "on_failure_callback": record_callback,
        "on_retry_callback": record_callback,
    },
) as dag:
    application_failure()
    timeout_failure.override(execution_timeout=timedelta(seconds=3))()
    ordinary_retry.override(retries=1, retry_delay=timedelta(seconds=1))()
    for task_id in ("executor_uuid", "executor_legacy", "executor_unknown"):
        lose_worker.override(task_id=task_id)()
Reproducer source: aip97_repro_executor.py
# 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 inspect
import os
from pathlib import Path
from typing import TYPE_CHECKING

from aip97_repro_listener import record_event

from airflow.executors import base_executor
from airflow.executors.local_executor import LocalExecutor
from airflow.executors.workloads.types import TaskInstanceUuid
from airflow.utils.state import TaskInstanceState

if TYPE_CHECKING:
    from airflow.executors.base_executor import TaskFailureKind
    from airflow.executors.workloads.types import WorkloadKey


class ReproExecutor(LocalExecutor):
    def sync(self) -> None:
        super().sync()
        for key, (state, info) in list(self.event_buffer.items()):
            if not isinstance(key, TaskInstanceUuid) or state != TaskInstanceState.FAILED:
                continue
            coordinates = self._task_coordinates.get(key)
            if coordinates is None or not coordinates.task_id.startswith("executor_"):
                continue
            if not Path(os.environ["AIRFLOW_HOME"], f"ready_{coordinates.task_id}").exists():
                raise RuntimeError("Controlled task did not reach its real worker body")
            failure_kind_type: type[TaskFailureKind] | None = getattr(base_executor, "TaskFailureKind", None)
            failure_kind: TaskFailureKind | None = None
            reason: str | None = None
            if coordinates.task_id == "executor_uuid":
                reason = "ControlledBackendNotice"
                if failure_kind_type is not None:
                    failure_kind = failure_kind_type.INFRA
            elif coordinates.task_id == "executor_legacy":
                reason = "SIGKILL"
            event_key: WorkloadKey = key
            if coordinates.task_id == "executor_legacy":
                self.event_buffer.pop(key)
                event_key = coordinates
            contract_available = "failure_kind" in inspect.signature(self.fail).parameters
            record_event(
                event="executor_report",
                task_id=coordinates.task_id,
                id=str(key),
                try_number=coordinates.try_number,
                contract_available=contract_available,
                key_form="legacy" if event_key == coordinates else "uuid",
                controlled_notice=reason == "ControlledBackendNotice",
            )
            if contract_available:
                self.fail(key=event_key, info=info, failure_kind=failure_kind, reason=reason)
            else:
                self.fail(key=event_key, info=info)
Reproducer source: aip97_repro_listener.py
# 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 inspect
import json
import os
from pathlib import Path
from typing import TYPE_CHECKING, Protocol
from uuid import UUID

from airflow.sdk._shared.listeners import hookimpl
from airflow.sdk._shared.listeners.spec import taskinstance as hookspec
from airflow.sdk.plugins_manager import AirflowPlugin

if TYPE_CHECKING:
    from airflow.sdk._shared.state import TaskFailureKind, TaskInstanceState
    from airflow.sdk.types import Context


class Attempt(Protocol):
    id: UUID
    task_id: str
    try_number: int
    state: str | None


def record_event(event: str, task_instance: Attempt | None = None, **fields: object) -> None:
    payload: dict[str, object] = {"event": event, **fields}
    if task_instance is not None:
        payload.update(
            id=str(task_instance.id),
            task_id=task_instance.task_id,
            try_number=task_instance.try_number,
            state=task_instance.state,
        )
    with Path(os.environ["AIP97_EVENT_LOG"]).open(mode="a") as output:
        output.write(json.dumps(payload, default=str) + "\n")


def record_callback(context: Context) -> None:
    record_event(event="callback", task_instance=context["task_instance"])


class LegacyListener:
    @hookimpl
    def on_task_instance_running(
        self, previous_state: TaskInstanceState | None, task_instance: Attempt
    ) -> None:
        record_event(event="running", task_instance=task_instance)

    @hookimpl
    def on_task_instance_failed(
        self, previous_state: TaskInstanceState | None, task_instance: Attempt, error: BaseException | str
    ) -> None:
        record_event(event="legacy_failure", task_instance=task_instance)


class MetadataListener:
    @hookimpl
    def on_task_instance_failed(
        self,
        previous_state: TaskInstanceState | None,
        task_instance: Attempt,
        error: BaseException | str,
        failure_kind: TaskFailureKind | None,
        reason: str | None,
    ) -> None:
        record_event(
            event="metadata_failure",
            task_instance=task_instance,
            failure_kind=failure_kind,
            reason=reason,
        )


class ReproPlugin(AirflowPlugin):
    name: str = "aip97_core_repro"
    listeners: list[object] = [LegacyListener()]
    if "failure_kind" in inspect.signature(hookspec.on_task_instance_failed).parameters:
        listeners.append(MetadataListener())

Was generative AI tooling used to co-author this PR?
  • Yes (please specify the tool below)

Generated-by: GitHub Copilot CLI (gpt-6.1-sol, claude-opus-5.5) following the guidelines


Expose known worker and executor causes to infrastructure listeners and telemetry while preserving ordinary retry and clear behavior.

Signed-off-by: 1fanwang <1fannnw@gmail.com>
When a Celery worker child disappears, the result backend records
WorkerLostError but Airflow drops it. Keep `WorkerLost` in the scheduler
failure report and listener event as a reason with no category, because a
lost worker alone does not establish an infrastructure cause. Ordinary
retry behavior is unchanged. The providers/celery tree matches the tested
source fbd551c.

Signed-off-by: 1fanwang <1fannnw@gmail.com>
Preserve Task.stopCode from the ECS task response and report
SpotInterruption as `infra`. Other stop codes stay diagnostic reasons
without a category and missing codes stay unclassified. Callback workloads
and older failure signatures keep their behavior, and no retries are
granted. The providers/amazon tree matches the tested source
5819598.

Signed-off-by: 1fanwang <1fannnw@gmail.com>
Resolves conflicts with the task attempt UUID and try number alignment
(apache#73554): notify_failure() now also carries failure_kind and reason to the
listener, _finalize_task_failure() keeps the new log parameter alongside
failure_kind, and the scheduler event loop keeps the imports from both
sides. The tested classification hunks are unchanged.

Signed-off-by: 1fanwang <1fannnw@gmail.com>
The listener now receives failure_kind and reason, so the recorder used by
test_failure_listener_receives_failed_try_before_rotation must accept them;
both are None on this path and the test asserts that.

Signed-off-by: 1fanwang <1fannnw@gmail.com>
@boring-cyborg boring-cyborg Bot added area:API Airflow's REST/HTTP API area:Executors-core LocalExecutor & SequentialExecutor area:providers area:scheduler area:task-sdk kind:documentation provider:amazon AWS/Amazon - related issues provider:celery provider:cncf-kubernetes Kubernetes (k8s) provider related issues labels Sep 27, 2026
Since the attempt UUID and try number alignment, a retry-eligible failure
allocates the next attempt at once, so the ECS classification test expects
try_number 2 when a retry remains. The heartbeat-timeout recorder also
accepts the two cause keywords the listener now passes.

Signed-off-by: 1fanwang <1fannnw@gmail.com>
Signed-off-by: 1fanwang <1fannnw@gmail.com>

# Conflicts:
#	task-sdk/src/airflow/sdk/execution_time/task_runner.py
#	task-sdk/tests/task_sdk/execution_time/test_task_runner.py
Signed-off-by: 1fanwang <1fannnw@gmail.com>
Signed-off-by: 1fanwang <1fannnw@gmail.com>

# Conflicts:
#	airflow-core/src/airflow/models/taskinstance.py
#	airflow-core/tests/unit/jobs/test_scheduler_job.py
#	providers/amazon/tests/unit/amazon/aws/executors/ecs/test_ecs_executor.py
#	providers/celery/tests/unit/celery/executors/test_celery_executor.py
Signed-off-by: 1fanwang <1fannnw@gmail.com>
Merge current main and retain the metadata contract with its SDK and
scheduler consumers. Leave provider adapters in the existing ancestor
commits. Preserve retry behavior and unknown causes.

Signed-off-by: 1fanwang <1fannnw@gmail.com>
@1fanwang 1fanwang changed the title AIP-97: Report task failure causes from Kubernetes, Celery and ECS Add optional task failure metadata in core (AIP-97 POC) Nov 13, 2026
@1fanwang
1fanwang marked this pull request as ready for review November 17, 2026 03:18
@1fanwang 1fanwang changed the title Add optional task failure metadata in core (AIP-97 POC) AIP-97: Add optional task failure metadata in core Nov 17, 2026
1fanwang added a commit to 1fanwang/airflow that referenced this pull request Nov 17, 2026
Pass the stop code of the last ECS attempt as the failure reason, with
SpotInterruption reported as infra, for attempt-UUID and legacy task
keys. Detect the contract from apache#73816
instead of gating on Airflow 3.4, which lacks it, and document it.

Signed-off-by: 1fanwang <1fannnw@gmail.com>
Signed-off-by: 1fanwang <1fannnw@gmail.com>

# Conflicts:
#	shared/listeners/src/airflow_shared/listeners/spec/taskinstance.py

@o-nikolas o-nikolas left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, the end-to-end repro is really thorough. The AIP-97 page still shows it as under discussion with the vote TBD. So this should not be merged until that VOTE happens. Maybe flip this back to DRAFT

Airflow reports a failure category when the worker or executor can establish the cause:
``infra``, ``application``, ``timeout``, or ``manual``. Otherwise the category remains unset.
Failure listeners and scheduler logs can also receive a short producer-owned reason,
such as Kubernetes ``PreemptionByScheduler``.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the provider adapters were dropped from this PR, no built-in executor reports a cause yet, but these paragraphs read as if Airflow already does this for Kubernetes (PreemptionByScheduler, Evicted, disruption conditions). Could we scope the docs to what ships here (application/timeout from the SDK, manual from the API, and causes a custom executor passes to fail()), and add the Kubernetes guidance with the K8s adapter PR?


Drafted-by: Kiro (claude-opus-5.5); reviewed by @o-nikolas before posting

error: None | str | BaseException,
):
"""Execute when task state changes to FAIL. previous_state can be None."""
failure_kind: TaskFailureKind | None,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How do you see listeners that support several Airflow versions (OpenLineage, say) adopting this? pluggy rejects a hookimpl argument that isn't in the hookspec, so declaring failure_kind/reason fails registration on current Airflow, and declaring them with defaults means they're never passed. The repro works around it with inspect.signature on the spec. A separate hook just for the cause would avoid that, since older versions would simply never call it. If we keep it on on_task_instance_failed, the listeners docs need a versionadded and a note about this.


Drafted-by: Kiro (claude-opus-5.5); reviewed by @o-nikolas before posting

def _get_task_failure_kind(error: BaseException | None) -> TaskFailureKind | None:
if error is None or isinstance(error, AirflowTaskTerminated):
return None
return TaskFailureKind.TIMEOUT if isinstance(error, AirflowTaskTimeout) else TaskFailureKind.APPLICATION

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Everything that isn't a timeout or AirflowTaskTerminated becomes application here. That includes AirflowRuntimeError, which also wraps API_SERVER_ERROR responses from the Execution API. The PR is careful not to call worker loss infra without proof. Should we be just as careful here and leave errors raised by the Airflow runtime itself (at least API_SERVER_ERROR) unset, rather than counting them as application?


Drafted-by: Kiro (claude-opus-5.5); reviewed by @o-nikolas before posting

Failure cause
"""""""""""""

``on_task_instance_failed`` can receive a :class:`~airflow.executors.base_executor.TaskFailureKind`:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This points listener authors to airflow.executors.base_executor.TaskFailureKind, but worker-side listeners run under the Task SDK and shouldn't import from airflow-core, and the SDK copy is in the private airflow.sdk._shared.state. Could we export it from a public SDK path and reference that? Or, since it's a str enum, just say that comparing against the string values is the supported way.


Drafted-by: Kiro (claude-opus-5.5); reviewed by @o-nikolas before posting

- name: "operator_failures"
description: "Operator ``{operator_name}`` failures."
description: "Operator ``{operator_name}`` failures. Tagged backends include ``failure_kind``:
``infra``, ``application``, ``timeout``, ``manual``, or ``unclassified``."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

manual never reaches these metrics: the API's mark-failed path only calls the listener, not handle_failure(). I'd drop it from this list or say it's listener-only.


Drafted-by: Kiro (claude-opus-5.5); reviewed by @o-nikolas before posting

("manual", (TaskFailureKind.MANUAL, None)),
*[
(f"reason_{reason}", (None, reason))
for reason in ("SIGTERM", "SIGKILL", "OOMKilled", "WorkerLostError", "Evicted")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file tests SchedulerJobRunner.process_executor_events, so I'd move it into tests/unit/jobs/test_scheduler_job.py. The matrix is also 40 DB tests, and the five reason-only cases all take the same path, so one would do. Small thing: the model_fields assertions at the end pass without this change too, and so does test_failure_cause_is_not_added_to_template_context in the Task SDK's test_task_runner.py.


Drafted-by: Kiro (claude-opus-5.5); reviewed by @o-nikolas before posting

@1fanwang
1fanwang marked this pull request as draft November 25, 2026 00:40
@1fanwang

Copy link
Copy Markdown
Contributor Author

Maybe flip this back to DRAFT

Done. Checked the cwiki page too, still under discussion with the vote thread TBD, so draft is the right state until that vote happens.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants