Skip to content

DAG on_failure_callback uses wrong context #26760

Closed

Description

@vgupta3

Apache Airflow version

2.4.0

What happened

When a task fails in a DAG, the on_failure_callback registered while creating the dag is triggered using the context of a random task instance.

What you think should happen instead

The expectation is that one of the task instances that caused the dag failure should be used instead of a random task instance.

How to reproduce

Run the below dag.

import datetime
from airflow.models.dag import DAG
from airflow.operators.python import PythonOperator
from airflow.operators.empty import EmptyOperator

def all_bad():
    raise Exception("I have failed")

def all_good():
    print("ALL GOOD")

def failure_callback_dag(context):
    print("Inside failure_callback_dag")
    print(context["task_instance"])
    print(context["task"])

with DAG(
        dag_id = "test_dag",
        schedule_interval=None,
        start_date=datetime.datetime(2021, 1, 1),
        catchup=False,
        on_failure_callback=failure_callback_dag
    ) as dag:

    start = EmptyOperator(
        task_id="start"
    )
    
    fail = PythonOperator(
        provide_context = True,
        task_id = "fail",
        python_callable = all_bad
    )

    passs = PythonOperator(
        provide_context = True,
        task_id = "pass",
        python_callable = all_good
    )

    start >> [passs, fail]

From the dag processor logs:

The context that is passed is from the task instance that has succeeded.

[2022-09-28T18:28:14.465+0000] {logging_mixin.py:117} INFO - [2022-09-28T18:28:14.463+0000] {dag.py:1292} INFO - Executing dag callback function: <function failure_callback_dag at 0x7fd17ca18560>
[2022-09-28T18:28:14.943+0000] {logging_mixin.py:117} INFO - Inside failure_callback_dag
[2022-09-28T18:28:14.944+0000] {logging_mixin.py:117} INFO - <TaskInstance: test_dag.pass manual__2022-09-28T18:27:59.612118+00:00 [success]>
[2022-09-28T18:28:14.944+0000] {logging_mixin.py:117} INFO - <Task(PythonOperator): pass>

Operating System

Debian GNU/Linux 10 (buster)

Versions of Apache Airflow Providers

Default providers that are present in the official airflow docker image.

Deployment

Docker-Compose

Deployment details

No response

Anything else

Not sure if it is an expected behaviour, incase it is it needs to be documented in Callbacks.

Are you willing to submit PR?

  • Yes I am willing to submit a PR!

Code of Conduct

Activity

  1. added
    kind:bug
    on Sep 28, 2022
  2. boring-cyborg commented on Sep 28, 2022

    @boring-cyborg

    Thanks for opening your first issue here! Be sure to follow the issue template!

  3. josh-fell commented on Sep 28, 2022

    @josh-fell
    Contributor

    Hey @vgupta3! Have you tried applying your on_failure_callback to default_args instead? Setting on_failure_callback at the DAG level applies to the DagRun failing not tasks specifically.

    on_failure_callback (DagStateChangeCallback | None) – A function to be called when a DagRun of this dag fails. A context dictionary is passed as a single parameter to this function.

    If you want to gain the context from the failed task, you can set on_failure_callback at the task level or, I presume you'd like the same callback to apply to all tasks, within default_args.

    on_failure_callback (TaskStateChangeCallback | None) – a function to be called when a task instance of this task fails. a context dictionary is passed as a single parameter to this function. Context contains references to related objects to the task instance and is documented under the macros section of the API.

    And, of course, if the documentation isn't clear enough you are absolutely welcomed and encouraged to open a PR to clarify concepts!

  4. josh-fell commented on Sep 28, 2022

    @josh-fell
    Contributor

    Yeah, looking at the Callbacks documentation, I definitely agree it's misleading and could be improved.

  5. added and removed
    kind:bug
    on Sep 28, 2022
  6. uranusjr commented on Sep 29, 2022

    @uranusjr
    Member

    Perhaps we should rename the DAG-level argument to on_dag_failure_callback instead?

  7. eladkal commented on Sep 30, 2022

    @eladkal
    Contributor

    Yeah, looking at the Callbacks documentation, I definitely agree it's misleading and could be improved.

    Actually both options are mentioned:
    https://airflow.apache.org/docs/apache-airflow/stable/logging-monitoring/callbacks.html

  8. josh-fell commented on Oct 1, 2022

    @josh-fell
    Contributor

    Actually both options are mentioned: https://airflow.apache.org/docs/apache-airflow/stable/logging-monitoring/callbacks.html

    Callbacks are set at both the DAG and task level in the code snippets, but the copy in the doc only mentions tasks. Even the callback callable of on_failure_callback=task_failure_alert set at the DAG is named in a misleading way. The callback will be triggered when the DagRun fails. Which is similar to a task failing but the context provided to the callable wouldn't necessarily be related to the task that failed. IIRC the context passed to the DAG-level callback is either the first task's context or just whatever is returned from the metadatabase first. IMO the doc can use a glow-up to help with these distinctions.

    Perhaps we should rename the DAG-level argument to on_dag_failure_callback instead?

    +1

  9. self-assigned this
    on Feb 2, 2023
  10. josh-fell commented on Feb 2, 2023

    @josh-fell
    Contributor

    This has been coming up more frequently for users. I can take on related improvements here.

  11. viniciusdsmello commented on Mar 12, 2023

    @viniciusdsmello
    Contributor

    Hello everyone. Could you let me know if there are any updates on this issue?

    I had the same issue with the following DAG
    image

    I'm creating an on_failure_callback to send events to Pagerduty. In one of my tests, I noticed that the context contains information from the first task.

    Here is the callback function
    image

  12. 10 remaining items

  13. ManiBharataraju commented on May 8, 2024

    @ManiBharataraju

    Hey @vgupta3! Have you tried applying your on_failure_callback to default_args instead? Setting on_failure_callback at the DAG level applies to the DagRun failing not tasks specifically.

    on_failure_callback (DagStateChangeCallback | None) – A function to be called when a DagRun of this dag fails. A context dictionary is passed as a single parameter to this function.

    @josh-fell - This doesn't appear to be happening. I have on_failure_callback set in default_args but it gets fired as soon as the task fails while the DAG is still in running state. I have also encountered instances where it fired twice for a failed DAG, one for the DAG(where the task name was wrong) and other for the task that actually failed. So I am assuming there is some issue the way callbacks are handled.

  14. kyoshi-warrior commented on Jun 21, 2024

    @kyoshi-warrior

    @josh-fell
    on_failure_callback appears to pass incorrect context with postgres as backend. works as intended when using sqlite i.e with callback defined at DAG level, returns context of the failed task_instance.

    Tested with Airflow V2.6.3

            Dag_id =  { context.get('task_instance').dag_id }
            Task = { context.get('task_instance').task_id } 
            Execution_date = { context.get('ds') }
            Log = { context.get('task_instance').log_url }
    
  15. fjmacagno commented on Mar 26, 2025

    @fjmacagno
    Contributor

    Wanted to bump this as i just ran into it as well, I assumed that the dag callback would get the ti for the task that actually failed.

  16. added this to the Airflow 3.1+ milestone on May 8, 2025
  17. IndiTheo commented on Jan 27, 2026

    @IndiTheo
    Contributor

    Did some research on this, here is what happens exactly.

    The context you see in DAG-level callbacks is constructed here:

    if ctx_from_server is not None and ctx_from_server.last_ti is not None:
    task = dag.get_task(ctx_from_server.last_ti.task_id)
    runtime_ti = RuntimeTaskInstance.model_construct(
    **ctx_from_server.last_ti.model_dump(exclude_unset=True),
    task=task,
    _ti_context_from_server=TIRunContext.model_construct(
    dag_run=ctx_from_server.dag_run,
    max_tries=task.retries,
    ),
    )
    context = runtime_ti.get_template_context()
    context["reason"] = request.msg
    else:
    context: Context = { # type: ignore[no-redef]
    "dag": dag,
    "run_id": request.run_id,
    "reason": request.msg,
    }

    In normal case, the task details you see in context are of last_ti coming from scheduler's request:

    runtime_ti = RuntimeTaskInstance.model_construct(
    **ctx_from_server.last_ti.model_dump(exclude_unset=True),
    task=task,
    _ti_context_from_server=TIRunContext.model_construct(
    dag_run=ctx_from_server.dag_run,
    max_tries=task.retries,
    ),
    )

    callback_to_execute = DagCallbackRequest(
    filepath=dag_model.relative_fileloc or "",
    dag_id=dag.dag_id,
    run_id=dag_run.run_id,
    bundle_name=dag_model.bundle_name,
    bundle_version=dag_run.bundle_version,
    context_from_server=DagRunContext(
    dag_run=dag_run,
    last_ti=dag_run.get_last_ti(dag=dag, session=session),
    ),
    is_failure_callback=True,
    msg="timed_out",
    )

    The last_ti is computed here:

    def get_last_ti(self, dag: SerializedDAG, session: Session = NEW_SESSION) -> TI | None:
    """Get Last TI from the dagrun to build and pass Execution context object from server to then run callbacks."""
    tis = self.get_task_instances(session=session)
    # tis from a dagrun may not be a part of dag.partial_subset,
    # since dag.partial_subset is a subset of the dag.
    # This ensures that we will only use the accessible TI
    # context for the callback.
    if dag.partial:
    tis = [ti for ti in tis if not ti.state == State.NONE]
    # filter out removed tasks
    tis = natsorted(
    (ti for ti in tis if ti.state != TaskInstanceState.REMOVED),
    key=lambda ti: ti.task_id,
    )
    if not tis:
    return None
    ti = tis[-1] # get last TaskInstance of DagRun
    return ti

    Which just selects the last task in lexicographical order from the entire DAG.

    I could reproduce it by creating a DAG with several tasks a, b, c,... and no matter which task actually failed the execution or what order between the tasks was, the last one alphabetically was passed to the callback context.

    I think we need to change this behavior to include a task or multiple tasks in failed state from the DAG, or just pass nothing. Actually, if you wanted to know which task failed, you'd probably use task-level callbacks injected with default_args, so passing no task info to DAG-level callbacks is pretty logical here, though backcomp breaks this way. I want to submit a PR to fix this and #61119 soon. Still got to figure out if we can select only one task as the "culprit" of the DAG failure.

  18. IndiTheo commented on Jan 28, 2026

    @IndiTheo
    Contributor

    The code above is actually just one use of dag_run.get_last_ti when there are multiple of them. Some failures (DAG timeouts or tasks deadlocked) can't be associated with a task failure, while other ones can be. If the dag is fail_fast, then one specific task can be pointed at. If not, we can prbly take the first failed task for backcomp (the two cases are pretty equivalent in code, just slightly different conceptually)

    Summary:

    1. If DAG failed due to a task failure (for leaf or fail_fast, pass the first failed task's context)
    2. If DAG failed not due to task failure, pass no context at all
  19. IndiTheo commented on Feb 4, 2026

    @IndiTheo
    Contributor

    Tried to improve this behavior by passing a task that is somehow relevant to failure, in general case it's one of the tasks causing the DAG to fail:

    #61274

    I'd like to get a review on this, thank you!

  20. removed this from the Airflow 3.2.0 milestone on Feb 27, 2026
  21. potiuk commented on Mar 2, 2026

    @potiuk
    Member

    @Asquator We are unassigning you from this issue as part of our updated assignment policy.

    This is not meant to discourage your contribution — quite the opposite! You are still very welcome to work on this issue and submit a PR for it. Simply comment that you are working on it and open a PR when ready.

    We found that formal assignments were not working well, as they often prevented others from contributing when the assignee was not actively working on the issue.

  22. IndiTheo commented on Mar 7, 2026

    @IndiTheo
    Contributor

    @potiuk Should be probably included back into 3.2.0 milestone.

  23. eladkal commented on Mar 8, 2026

    @eladkal
    Contributor

    @potiuk Should be probably included back into 3.2.0 milestone.

    Milestone on issues are not so meaningful. It's mostly for issue triage.
    We mostly use milestones or PRs

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions