Skip to content

Task-level failure callbacks are not triggered when tasks are SIGKILLed #60858

Open

Description

@manipatnam

Apache Airflow version

3.1.6

If "Other Airflow 3 version" selected, which one?

3.1.2

What happened?

When a task is OOM-killed (container/process terminated with SIGKILL), the task appears to fail silently:

Task-level on_failure_callback is not executed

In logs/behavior, the executor reports the task as SUCCESS

Because the scheduler never observes a FAILED state (and no mismatch is detected), it does not trigger task-level failure handling/callbacks

What you think should happen instead?

When a task process is terminated with SIGKILL:

The executor should report the task as FAILED (or otherwise indicate abnormal termination)
Airflow should then trigger task-level on_failure_callback (and any related failure handling)

How to reproduce

Create a task which can OOM and has task level failure call back and it wont be triggered

from airflow.operators.python import PythonOperator
from datetime import datetime

def func():
    a = "asd"
    while True:
        a += a*100000

def task_failure_callback(context):
    """Callback function called when a task fails."""
    task_instance = context.get('task_instance')
    dag_run = context.get('dag_run')
    print(f"Task {task_instance.task_id} failed in DAG {dag_run.dag_id} with run_id {dag_run.run_id}")


with DAG(
    dag_id="oom_example",
    start_date=datetime(2024, 1, 1),
    schedule="@daily",
    catchup=False,
    doc_md=__doc__,
    tags=["oom"],
) as dag:
    oom_task = PythonOperator(
        task_id="oom_task",
        python_callable=func,
        retries=0,
        on_failure_callback=task_failure_callback,
    )

Operating System

debian

Versions of Apache Airflow Providers

No response

Deployment

Astronomer

Deployment details

No response

Anything else?

No response

Are you willing to submit PR?

  • Yes I am willing to submit a PR!

Code of Conduct

Activity

  1. added
    kind:bug
    needs-triage
    on Jan 21, 2026
  2. Prajwal7842 commented on Jan 21, 2026

    @Prajwal7842
    Contributor

    I think on_failure_callback is meant to be used for a graceful exit, but given SIGKILL is meant to be non-graceful and we cannot catch it in python, the behavior seems consistent with force exit.

    Update: When trying out this dag, I am able to see that event logs show a state mismatch.

    Image
  3. jroachgolf84 commented on Jan 21, 2026

    @jroachgolf84
    Collaborator

    @RNHTTR might be able to provide a bit more detail around this.

  4. removed
    needs-triage
    on Jan 21, 2026
  5. Prajwal7842 commented on Jan 21, 2026

    @Prajwal7842
    Contributor

    I would like to investigate and work on this. I found this similar discussion related to task retries: #55753

  6. potiuk commented on Jan 21, 2026

    @potiuk
    Member

    There is not much to investigate - the on_failure_callback is not going to be called when task is killed - this is a given because the interpreter is killed without any chance for reaction.

    The only way to handle that is to make completely new flow where the supervisor should see if the task has been killed forecefully and **start a "run on_failure_callback" new task that will only do that. Supervisor cannot do it on it's own because supervisor does not parse the Dag that has on_failure_callback defined, so effectively it will need to run a new child task that will again parse the dag and only runs on_failure_callback. This has a number of edge cases to look at - for example handling the case where OOM happens during parsing the dag,

    This is quite clear what's going on here, it just needs quite complex implementation of handling this special flow.

  7. jroachgolf84 commented on Jan 21, 2026

    @jroachgolf84
    Collaborator

    @potiuk, I've always wondered about this. What do you think about an on_kill_callback? I assume that would follow the framework of what you mentioned above. But curious your thoughts.

  8. potiuk commented on Jan 21, 2026

    @potiuk
    Member

    @potiuk, I've always wondered about this. What do you think about an on_kill_callback? I assume that would follow the framework of what you mentioned above. But curious your thoughts.

    Yes it could be posible, though I would rather extend the on_failure_callback and add type of failure there if possible.

    Actually .. I think it will not work in all cases anyway. If the task process is just killed with -9 or SEGV, this might work - but it is not likely to work with OOM - because generally OOM kills the whole Pod - which means that both task and supervisor wil get -9 (there might be some races) and neither of them will have a chance to react. What you really want to do in this case is to have an executor and deployment dependent behaviour - for example K8S executor should monitor reason for POD failue - and then not even start another task, but even start another POD to run on_task_failure (or on_task_kill) - and in case of Celery Executor for example you would have to track which celery workers run which tasks, and do similar thing for alltasks that were runnning in the same worker .. Etc. etc.

    And it will look differently if airflow is run using different cluster technoloty - for example Nomad.

    There are lots and lots of flows that would need to be considered to make it robust and it's I think impossible to have a working solution without close coupling the solutions with deployment or limiting to single deployment configuration (say K8S executor).

    I would say that this one is "won't fix" kind of issues - and we need to simply accept there is no on_failure_callback generated in case of SIGKILL

  9. DonHaul commented on Feb 9, 2026

    @DonHaul
    Contributor

    I see there are times where a task goes out of memory, but does not get SIGKILLed (at least on in the same way) , referenced here #61521, so at times they do get killed and in that case the on_failure_callback does execute. So I wonder what changes between these two cases, and if would be possible to uniformize them

  10. hkc-8010 commented on Oct 8, 2026

    @hkc-8010
    Contributor

    @potiuk, I'd like to propose a narrower approach than a new callback-runner process, and get your thoughts before writing a PR.

    OOM often does not kill the whole pod. On cgroup v2 with memory.oom.group=0 (the Kubernetes default), the kernel kills only the largest process in the container. That is the task process, not the supervisor. We see this in production on 3.3 with the KubernetesExecutor:

    • The supervisor logs Process terminated by signal. Likely out of memory error (OOM). signal=-9.
    • It reports the TI as failed about 30 ms later.
    • The pod exits Succeeded.

    So the case where the supervisor survives is the common one. It is also the only case that is broken.

    The whole-pod case already works. If both processes die, the TI stays running. The scheduler then catches the mismatch, either from the executor event or the heartbeat timeout, and sends a TaskCallbackRequest to the DAG processor. The DAG processor already parses the DAG and runs on_failure_callback. The callback goes missing only because the surviving supervisor reports failed itself. After that the scheduler sees no mismatch, so no callback request is ever created. In the same case no on_task_instance_failed listener fires either, so OpenLineage gets no task-level FAIL event for that try.

    Proposal: route the case where the supervisor survives into the callback path that already exists, instead of having the supervisor run the callback.

    1. When the child exits without reporting a terminal state and the supervisor sends the final state itself (update_task_state_if_needed in supervisor.py), it marks the request as a supervisor-originated failure. For example, an optional field on the terminal-state payload, set only on that path.
    2. When ti_update_state receives that marker, it does two things in the same transaction:
      • Enqueues a TaskCallbackRequest (task_callback_type=FAILED) via DbCallbackRequest. That is the same sink the scheduler uses, and the DAG processor runs the callback with the full TI context.
      • Fires on_task_instance_failed, the same way _emit_state_listener_hooks already does for manual state changes in core_api/services/public/task_instances.py.

    The worker stays DB-less. The supervisor only adds one field to the HTTP call it already makes. The DB writes and the listener call both happen in the API server, which already writes the TI state in that same handler.

    This needs no new process, no DAG parsing in the supervisor, and nothing specific to an executor or deployment. Whether the task was killed by OOM, SIGKILL or SEGV, it takes the same path. The "OOM during DAG parsing" edge case is handled the way it already is for the whole-pod case, because the callback runs in the DAG processor rather than the worker.

    A related gap with the same root cause: when retries remain, the supervisor classifies the exit as up_for_retry. That state is in STATES_SENT_DIRECTLY, so it sends nothing, and the TI sits in running until the 300s heartbeat timeout. The same marker could let the supervisor send up_for_retry and enqueue an UP_FOR_RETRY callback right away. That would remove the 5-minute delay. I'd keep it as a separate follow-up unless you'd rather address both together.

    Costs I'm aware of:

    • The new payload field is an execution API change, so it needs a new versioned API change. Older Task SDK clients simply don't send the field and keep today's behaviour.
    • Listeners would fire in the API server process for this case, the same as for manual state changes today. OpenLineage would emit the task FAIL event from the API server, not the worker.

    Open questions:

    • Is it acceptable for the execution API to enqueue callback requests, or should this go through the scheduler instead? One alternative: write a marker on the TI that the scheduler picks up in _process_executor_events.
    • Should the failure type be visible to callbacks, as you suggested earlier ("extend on_failure_callback and add type of failure")? The marker would make that easy to expose in the context.

    If this direction looks reasonable, I'm happy to open a PR.

  11. egotist0 commented on Oct 8, 2026

    @egotist0
    Contributor

    @potiuk, I'd like to propose a narrower approach than a new callback-runner process, and get your thoughts before writing a PR.

    OOM often does not kill the whole pod. On cgroup v2 with memory.oom.group=0 (the Kubernetes default), the kernel kills only the largest process in the container. That is the task process, not the supervisor. We see this in production on 3.3 with the KubernetesExecutor:

    • The supervisor logs Process terminated by signal. Likely out of memory error (OOM). signal=-9.
    • It reports the TI as failed about 30 ms later.
    • The pod exits Succeeded.

    So the case where the supervisor survives is the common one. It is also the only case that is broken.

    The whole-pod case already works. If both processes die, the TI stays running. The scheduler then catches the mismatch, either from the executor event or the heartbeat timeout, and sends a TaskCallbackRequest to the DAG processor. The DAG processor already parses the DAG and runs on_failure_callback. The callback goes missing only because the surviving supervisor reports failed itself. After that the scheduler sees no mismatch, so no callback request is ever created. In the same case no on_task_instance_failed listener fires either, so OpenLineage gets no task-level FAIL event for that try.

    Proposal: route the case where the supervisor survives into the callback path that already exists, instead of having the supervisor run the callback.

    1. When the child exits without reporting a terminal state and the supervisor sends the final state itself (update_task_state_if_needed in supervisor.py), it marks the request as a supervisor-originated failure. For example, an optional field on the terminal-state payload, set only on that path.

    2. When ti_update_state receives that marker, it does two things in the same transaction:

      • Enqueues a TaskCallbackRequest (task_callback_type=FAILED) via DbCallbackRequest. That is the same sink the scheduler uses, and the DAG processor runs the callback with the full TI context.
      • Fires on_task_instance_failed, the same way _emit_state_listener_hooks already does for manual state changes in core_api/services/public/task_instances.py.

    The worker stays DB-less. The supervisor only adds one field to the HTTP call it already makes. The DB writes and the listener call both happen in the API server, which already writes the TI state in that same handler.

    This needs no new process, no DAG parsing in the supervisor, and nothing specific to an executor or deployment. Whether the task was killed by OOM, SIGKILL or SEGV, it takes the same path. The "OOM during DAG parsing" edge case is handled the way it already is for the whole-pod case, because the callback runs in the DAG processor rather than the worker.

    A related gap with the same root cause: when retries remain, the supervisor classifies the exit as up_for_retry. That state is in STATES_SENT_DIRECTLY, so it sends nothing, and the TI sits in running until the 300s heartbeat timeout. The same marker could let the supervisor send up_for_retry and enqueue an UP_FOR_RETRY callback right away. That would remove the 5-minute delay. I'd keep it as a separate follow-up unless you'd rather address both together.

    Costs I'm aware of:

    • The new payload field is an execution API change, so it needs a new versioned API change. Older Task SDK clients simply don't send the field and keep today's behaviour.
    • Listeners would fire in the API server process for this case, the same as for manual state changes today. OpenLineage would emit the task FAIL event from the API server, not the worker.

    Open questions:

    • Is it acceptable for the execution API to enqueue callback requests, or should this go through the scheduler instead? One alternative: write a marker on the TI that the scheduler picks up in _process_executor_events.
    • Should the failure type be visible to callbacks, as you suggested earlier ("extend on_failure_callback and add type of failure")? The marker would make that easy to expose in the context.

    If this direction looks reasonable, I'm happy to open a PR.

    @hkc-8010 thanks for writing this up. The production case above is ours (Airflow 3.3.2, Python 3.12, KubernetesExecutor), and +1 on this direction over a separate callback-runner process, it can fix both the missing callback and the missing listener

    @potiuk on the concern that this has to be executor or deployment specific: the broken case isn't tied to OOM or to memory.oom.group. It's any try where the task process exits non-zero without sending a terminal state while the supervisor is still alive in the worker pod.
    The supervisor then infers the state from the exit code in update_task_state_if_needed and calls finish(FAILED) itself when no retries remain. Besides OOM, the same path is hit by a SIGSEGV in native code, a SIGKILL from any other source, and (on main) execution_timeout when the task is stuck in native code and the supervisor has to SIGKILL it. In all of these the supervisor sees the task process exit non-zero without a terminal state, and this handling is the same on every executor.
    If the whole pod is killed, the TI stays running. The scheduler notices this from the executor event or the heartbeat timeout and asks the dag processor to run on_failure_callback via a TaskCallbackRequest, , and handle_failure fires on_task_instance_failed.
    The callback and listener are only lost when the supervisor survives and writes failed itself, so the scheduler never notices anything wrong. That write is where the marker goes.

    A few things I'd want in the PR:

    • _fail_task_before_runtime also writes failed when the task runtime fails to start (TaskLaunchError), and no callback runs there either. It could set the same marker.
    • Fire on_task_instance_failed after the commit, so OpenLineage never gets a FAIL event for a state update that rolled back.

    On the retry gap, I'd prefer fixing it in the same PR. We hit it too: the TI stayed running until the heartbeat timeout. _fail_task_before_runtime already calls retry() when retries remain, so when the supervisor infers up_for_retry it could do the same with the same marker. Otherwise fixing the delay would also drop the on_retry_callback and listener that the heartbeat-timeout path runs today.

  12. seanmuth commented on Oct 13, 2026

    @seanmuth
    Contributor

    @eladkal @potiuk following up on the pushback on #74458. I'd like to settle whether this is a bug before anyone writes another PR, because I think the current behavior is inconsistent with what Airflow already does, not just a missing feature.

    Airflow already runs on_failure_callback for infrastructure failures. The scheduler builds a TaskCallbackRequest for the dag processor in three cases, and none of them is necessarily a business failure:

    The callbacks docs also pitch callbacks as monitoring ("you may wish to alert when certain tasks have failed"), with the only documented exception being state changes from the CLI/UI.

    So the same OOM fires the callback or not, depending on which process the kernel picks. On the "OOM kills the whole pod" point: that's the kubelet default on cgroup v2 since 1.28, which sets memory.oom.group so the whole container goes down together. But it's only a default. Since 1.32 kubelet has singleProcessOOMKill to opt out, nodes still on cgroup v1 never had group kill, and end users or managed Airflow providers can and do change it. Outside containers entirely (bare metal, VMs, LocalExecutor on a box) there's no group kill at all. In all of those cases the kernel kills a single process, whichever PID has the highest oom_score, and that can be either one:

    • Supervisor killed: nothing records the final state, the TI stays running, and one of the scheduler paths above picks it up and the dag processor runs on_failure_callback.
    • Task process killed, supervisor survives: the supervisor reports FAILED through finish(), and the FAILED branch on the API server only handles fail-fast. The DB is now terminal, so the scheduler sees no mismatch. No callback, no on_task_instance_failed listener, no OpenLineage FAIL event.

    Dag authors can't control or even see which of those happened. That's the bug: whether the callback runs is decided by a race between OOM victims, not by any design intent. It's also a regression: #15537 fixed exactly this OOM case for Airflow 2 in 2021.

    There's a smaller related gap with retries left. UP_FOR_RETRY is in STATES_SENT_DIRECTLY, which assumes the task process already sent RetryTask. A killed process never did, so the supervisor reports nothing and the TI sits in running until the scheduler catches it.

    On the "needs a whole new flow" concern: the flow already exists. The dag processor already runs task callbacks for tasks whose process died, via TaskCallbackRequest, and nothing new has to parse the dag. The fix is to use that same path when the supervisor itself reports a signal kill:

    1. The supervisor marks the terminal payload as a signal kill when the task's exit code is negative and it didn't initiate the kill (i.e. not an overtime/heartbeat/server-requested termination).
    2. In the FAILED branch, the API server enqueues the same TaskCallbackRequest the scheduler builds (FAILED or UP_FOR_RETRY by retry eligibility) and fires the failure listener.

    That works on every executor, keeps the supervisor fast, and avoids the KubernetesExecutor heartbeat-timeout delay (and the pool slot held during it) that #74458 had. It's option 2 from that PR's description. The cost is a small execution API change.

    If you agree this is a bug, @manipatnam can pick the PR back up, since #74458 already covers most of the supervisor side. If the position is still that on_failure_callback shouldn't cover infra failures, I think the scheduler paths above should change to match, because right now the behavior depends on which process loses an OOM race.

    🤖 Generated with Claude Code — Claude Opus 5.5

  13. ashb commented on Oct 14, 2026

    @ashb
    Member

    At the very least, I agree that no OL fail event depending on the path is a bug. Can we send it multiple times, or does OL expect/require that it is at-most once delivery of the event?

    And while I find needing to go to dag processor for task events very annoying, I think the same thing should happen for on_fail callbacks. However: If the task process is killed, what should the supervisor do? Try to spawn new process to run the failured callback there, or somehow signal to the supervisor "I didn't run the callback" and let it go via the dag processor callbacks.

    When you say "when the supervisor itself reports a signal kill", what did you have in mind?

    So if we can resolve how to ensure it is run an appropriate, and documented number of times (1? exactly-once delivery of a message is captial-H Hard problem) then yes, this is a bug to fix.

  14. seanmuth commented on Oct 14, 2026

    @seanmuth
    Contributor

    Update: @ashb and I went a few rounds on this internally after his comment above, so that comment is a bit behind where we ended up. Below is the design we converged on. It also replaces the "signal kill" proposal in my earlier comment. @eladkal @potiuk, we'd like your weigh-in before anyone starts on a PR.

    Two things changed from my earlier proposal:

    • No exit-code inference. Keying on a negative exit code is Python-specific, and with multiple language SDKs that doesn't hold. It also isn't correct today: the fail-closed path in the runner exits 1 after finalize() has already run callbacks.
    • Nothing extra runs in the API server. Listeners (OpenLineage especially) can block, and the API server has no executor. send_callback() is a property of the executor and is meant to be overridable, so routing has to happen in the scheduler.

    We also ruled out the supervisor spawning a new process to run the callback. If the task was OOM-killed, a second process in the same pod can just get OOM-killed again.

    Design

    1. Task SDK. The runner sends a FinalizeStarted message to the supervisor when it enters finalize(). If the task process exits with no terminal state, no FinalizeStarted, and no kill the supervisor started itself (overtime, heartbeat loss, server-requested), the supervisor reports FAILED, or UP_FOR_RETRY if should_retry, with failure_handling_ran=False. Sending UP_FOR_RETRY explicitly also closes the STATES_SENT_DIRECTLY gap.
    2. Execution API. Add failure_handling_ran: bool = True to the terminal and retry payloads, so old SDKs behave as today. When it's False, the API server builds the same TaskCallbackRequest the scheduler builds today (plus the email request if configured) and inserts it into the callback table as a DbCallbackRequest with state=PENDING, in the same transaction as the state change. It's built before prepare_db_for_next_try, so it describes the failed try. DB writes only, no listeners, no executor.
    3. Scheduler. A new loop, modelled on the ExecutorCallback router, selects PENDING rows with SKIP LOCKED. For each row it calls send_callback() on the TI's executor, calls notify_failure() (so on_task_instance_failed and the OL FAIL event fire where they already fire for the existing scheduler paths), and deletes the row in the same transaction.
    4. Dag processor. Its callback fetch gets .where(state IS NULL), so it only picks up rows the scheduler has routed. Callback execution itself doesn't change.

    No migration. The callback table already has a state column, and dag processor rows always have state=NULL today. I checked the other readers of the table (the executor callback router, airflow db clean, the deadline and trigger joins) and none of them are affected by PENDING dag processor rows.

    Before any of that, a no-op refactor: pull the callback-building block that's duplicated in the executor-mismatch and heartbeat-purge paths into one helper, so the API server and both scheduler paths build identical requests.

    Delivery count (re: Ash's question above)

    • Callback: at most once per failed try. If finalize() started, the supervisor doesn't flag the try, even if finalize() died partway through. Each pending row is claimed under a row lock and deleted in the same transaction that hands it on. With the default DatabaseCallbackSink that hand-off is an insert in the same transaction, so in practice it's exactly once.
    • Listener / OL FAIL: once in the normal case. The only window for a duplicate is the scheduler dying after notify_failure() and before commit, which is the same exposure the existing scheduler paths already have. If OL needs strict at-most-once we can move the listener call after commit, which flips that window to "missed" instead.

    Other properties

    • Latency: one scheduler loop. Today it's the heartbeat timeout for the retry case, and never for the FAILED case.
    • If the scheduler is down, pending rows wait. If the supervisor dies too, the existing scheduler paths still cover it.
    • Rolling upgrade: an old dag processor could pick up a PENDING row directly. The callback still runs, it just skips executor routing, which is still better than today.
    • Release: the Execution API change means a Cadwyn version bump, so this targets the next minor.

    Open questions

    1. Should the routing loop get its own timer, or run alongside the ExecutorCallback router?
    2. Should listener calls on the scheduler paths (existing and new) move off the main loop as a follow-up?

    🤖 Generated with Claude Code — Claude Opus 5.5

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:corekind:bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions