You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "benitezfede (via GitHub)" <gi...@apache.org> on 2025/07/22 02:43:12 UTC
[D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
GitHub user benitezfede created a discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
Hi,
In the previous versions of airflow I was able to get the `dag_run` information from the `on_success_callback` context when a DAG succeeded.
Now in Airflow 3 I see that the `dag_run` is no longer populated in the context and in my opinion this is a bug, as it is obviously needed and in the task callbacks context it is populated.
I created this DAG to reproduce the issue:
```
from datetime import datetime, timedelta
import logging
from airflow import DAG
from airflow.operators.python import PythonOperator
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Debug callback functions
def debug_task_success_callback(context):
"""Debug callback for task success - prints all context information"""
print("=" * 80)
print("TASK SUCCESS CALLBACK DEBUG")
print("=" * 80)
print(f"Context keys: {list(context.keys())}")
print(f"Context type: {type(context)}")
# Print each context key and its value
for key, value in context.items():
print(f" {key}: {type(value)} = {value}")
if hasattr(value, '__dict__'):
print(f" Attributes: {[attr for attr in dir(value) if not attr.startswith('_')]}")
# Specifically check for dag_run
if 'dag_run' in context:
print(f"\nDAG_RUN FOUND:")
print(f" Type: {type(context['dag_run'])}")
print(f" Attributes: {[attr for attr in dir(context['dag_run']) if not attr.startswith('_')]}")
print(f" Dict: {context['dag_run'].__dict__}")
else:
print(f"\nDAG_RUN NOT FOUND in context!")
print("=" * 80)
def debug_dag_success_callback(context):
"""Debug callback for DAG success - prints all context information"""
print("=" * 80)
print("DAG SUCCESS CALLBACK DEBUG")
print("=" * 80)
print(f"Context keys: {list(context.keys())}")
print(f"Context type: {type(context)}")
# Print each context key and its value
for key, value in context.items():
print(f" {key}: {type(value)} = {value}")
if hasattr(value, '__dict__'):
print(f" Attributes: {[attr for attr in dir(value) if not attr.startswith('_')]}")
# Specifically check for dag_run
if 'dag_run' in context:
print(f"\nDAG_RUN FOUND:")
print(f" Type: {type(context['dag_run'])}")
print(f" Attributes: {[attr for attr in dir(context['dag_run']) if not attr.startswith('_')]}")
print(f" Dict: {context['dag_run'].__dict__}")
else:
print(f"\nDAG_RUN NOT FOUND in context!")
print("=" * 80)
def simple_task():
"""Simple task that just prints a message"""
print("Hello from simple task!")
return "task completed"
# Define the DAG
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2023, 1, 1),
'email': ['airflow@example.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(seconds=10),
# Add task-level callback
'on_success_callback': debug_task_success_callback,
}
dag = DAG(
'debug_context_dag',
default_args=default_args,
description='A simple DAG to debug context in Airflow 3.0',
schedule=timedelta(days=1),
catchup=False,
tags=['debug', 'context'],
# Add DAG-level callback
on_success_callback=debug_dag_success_callback,
)
# Define the task
task1 = PythonOperator(
task_id='simple_task',
python_callable=simple_task,
dag=dag,
)
# Set task dependencies (none needed for single task)
task1
```
The output of running this DAG shows that for the DAG callback the `dag_run` is not present:
```
DAG_RUN NOT FOUND in context!
```
The context for DAG callbacks has only these keys:
```
"Context keys: ['dag', 'run_id', 'reason']"
```
For the task callback we see the following keys:
```
Context keys: ['dag', 'inlets', 'map_index_template', 'outlets', 'run_id', 'task', 'task_instance', 'ti', 'outlet_events', 'inlet_events', 'macros', 'params', 'var', 'conn', 'dag_run', 'triggering_asset_events', 'task_instance_key_str', 'task_reschedule_count', 'prev_start_date_success', 'prev_end_date_success', 'logical_date', 'ds', 'ds_nodash', 'ts', 'ts_nodash', 'ts_nodash_with_tz', 'data_interval_end', 'data_interval_start', 'prev_data_interval_start_success', 'prev_data_interval_end_success', 'templates_dict', 'exception']
```
And it has the `dag_run` as well:
```
DAG_RUN FOUND:: chan="stdout": source="task"
[2025-07-21, 23:28:17] INFO - Type: <class 'airflow.sdk.api.datamodels._generated.DagRun'>: chan="stdout": source="task"
[2025-07-21, 23:28:17] INFO - Attributes: ['clear_number', 'conf', 'construct', 'consumed_asset_events', 'copy', 'dag_id', 'data_interval_end', 'data_interval_start', 'dict', 'end_date', 'from_orm', 'json', 'logical_date', 'model_computed_fields', 'model_config', 'model_construct', 'model_copy', 'model_dump', 'model_dump_json', 'model_extra', 'model_fields', 'model_fields_set', 'model_json_schema', 'model_parametrized_name', 'model_post_init', 'model_rebuild', 'model_validate', 'model_validate_json', 'model_validate_strings', 'parse_file', 'parse_obj', 'parse_raw', 'run_after', 'run_id', 'run_type', 'schema', 'schema_json', 'start_date', 'update_forward_refs', 'validate']
```
So there is a massive difference in the information loaded for the task callbacks vs the DAG callback. Is this expected or is it a bug?
Thanks,
Fede
GitHub link: https://github.com/apache/airflow/discussions/53618
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "davidsteinar (via GitHub)" <gi...@apache.org>.
GitHub user davidsteinar added a comment to the discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
@potiuk thank you for your reply. In my case I was accessing these objects from the DAG callback context in Airflow 2:
context['data_interval_start']
context["dag_run"].get_task_instances()
how would you access these now in airflow 3 from only the limited context object ?
GitHub link: https://github.com/apache/airflow/discussions/53618#discussioncomment-13863937
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "benitezfede (via GitHub)" <gi...@apache.org>.
GitHub user benitezfede closed a discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
Hi,
In the previous versions of airflow I was able to get the `dag_run` information from the `on_success_callback` `context` when a DAG succeeded callback was triggered.
Now, in Airflow 3, I see that the `dag_run` is no longer populated in the callback `context`. In my opinion this is a bug, also it is inconsistent with the `tasks` callbacks as IT IS populated there.
I read the documentation about callbacks [here](https://airflow.apache.org/docs/apache-airflow/stable/templates-ref.html) and it points to [this](https://airflow.apache.org/docs/apache-airflow/stable/templates-ref.html) the `context` template variables which have the `dag_run`. Also the code [here](https://github.com/apache/airflow/blob/main/task-sdk/src/airflow/sdk/definitions/context.py#L42C14-L42C28) shows the `dag_run` so I cannot understand why it is not being populated.
The fix seems to be a matter of adding `dag_run: self,` [here](https://github.com/apache/airflow/blob/6b618efa91b4ef80c4821537b30f14a49c2badb6/airflow-core/src/airflow/models/dagrun.py#L1356).
In order to reproduce the issue, I created this DAG which prints the keys of the `context` for DAG and tasks callbacks:
```
from datetime import datetime, timedelta
import logging
from airflow import DAG
from airflow.operators.python import PythonOperator
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Debug callback functions
def debug_task_success_callback(context):
"""Debug callback for task success - prints all context information"""
print("=" * 80)
print("TASK SUCCESS CALLBACK DEBUG")
print("=" * 80)
print(f"Context keys: {list(context.keys())}")
print(f"Context type: {type(context)}")
# Print each context key and its value
for key, value in context.items():
print(f" {key}: {type(value)} = {value}")
if hasattr(value, '__dict__'):
print(f" Attributes: {[attr for attr in dir(value) if not attr.startswith('_')]}")
# Specifically check for dag_run
if 'dag_run' in context:
print(f"\nDAG_RUN FOUND:")
print(f" Type: {type(context['dag_run'])}")
print(f" Attributes: {[attr for attr in dir(context['dag_run']) if not attr.startswith('_')]}")
print(f" Dict: {context['dag_run'].__dict__}")
else:
print(f"\nDAG_RUN NOT FOUND in context!")
print("=" * 80)
def debug_dag_success_callback(context):
"""Debug callback for DAG success - prints all context information"""
print("=" * 80)
print("DAG SUCCESS CALLBACK DEBUG")
print("=" * 80)
print(f"Context keys: {list(context.keys())}")
print(f"Context type: {type(context)}")
# Print each context key and its value
for key, value in context.items():
print(f" {key}: {type(value)} = {value}")
if hasattr(value, '__dict__'):
print(f" Attributes: {[attr for attr in dir(value) if not attr.startswith('_')]}")
# Specifically check for dag_run
if 'dag_run' in context:
print(f"\nDAG_RUN FOUND:")
print(f" Type: {type(context['dag_run'])}")
print(f" Attributes: {[attr for attr in dir(context['dag_run']) if not attr.startswith('_')]}")
print(f" Dict: {context['dag_run'].__dict__}")
else:
print(f"\nDAG_RUN NOT FOUND in context!")
print("=" * 80)
def simple_task():
"""Simple task that just prints a message"""
print("Hello from simple task!")
return "task completed"
# Define the DAG
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2023, 1, 1),
'email': ['airflow@example.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(seconds=10),
# Add task-level callback
'on_success_callback': debug_task_success_callback,
}
dag = DAG(
'debug_context_dag',
default_args=default_args,
description='A simple DAG to debug context in Airflow 3.0',
schedule=timedelta(days=1),
catchup=False,
tags=['debug', 'context'],
# Add DAG-level callback
on_success_callback=debug_dag_success_callback,
)
# Define the task
task1 = PythonOperator(
task_id='simple_task',
python_callable=simple_task,
dag=dag,
)
# Set task dependencies (none needed for single task)
task1
```
The output of running this DAG shows that for the DAG callback the `dag_run` is not present:
```
DAG_RUN NOT FOUND in context!
```
The context for DAG callbacks has only these keys:
```
"Context keys: ['dag', 'run_id', 'reason']"
```
For the task callback we see the following keys:
```
Context keys: ['dag', 'inlets', 'map_index_template', 'outlets', 'run_id', 'task', 'task_instance', 'ti', 'outlet_events', 'inlet_events', 'macros', 'params', 'var', 'conn', 'dag_run', 'triggering_asset_events', 'task_instance_key_str', 'task_reschedule_count', 'prev_start_date_success', 'prev_end_date_success', 'logical_date', 'ds', 'ds_nodash', 'ts', 'ts_nodash', 'ts_nodash_with_tz', 'data_interval_end', 'data_interval_start', 'prev_data_interval_start_success', 'prev_data_interval_end_success', 'templates_dict', 'exception']
```
And it has the `dag_run` as well:
```
DAG_RUN FOUND:: chan="stdout": source="task"
[2025-07-21, 23:28:17] INFO - Type: <class 'airflow.sdk.api.datamodels._generated.DagRun'>: chan="stdout": source="task"
[2025-07-21, 23:28:17] INFO - Attributes: ['clear_number', 'conf', 'construct', 'consumed_asset_events', 'copy', 'dag_id', 'data_interval_end', 'data_interval_start', 'dict', 'end_date', 'from_orm', 'json', 'logical_date', 'model_computed_fields', 'model_config', 'model_construct', 'model_copy', 'model_dump', 'model_dump_json', 'model_extra', 'model_fields', 'model_fields_set', 'model_json_schema', 'model_parametrized_name', 'model_post_init', 'model_rebuild', 'model_validate', 'model_validate_json', 'model_validate_strings', 'parse_file', 'parse_obj', 'parse_raw', 'run_after', 'run_id', 'run_type', 'schema', 'schema_json', 'start_date', 'update_forward_refs', 'validate']
```
So there is a massive difference in the information loaded in the `context` for the task callbacks vs the DAG callback. Is this expected or is it a bug? As I said it seems to be a bug.
Thanks,
Fede
GitHub link: https://github.com/apache/airflow/discussions/53618
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "matthewblock (via GitHub)" <gi...@apache.org>.
GitHub user matthewblock added a comment to the discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
I'm running into similar issues - I have been using `airflow.models.XXX` for type hints, so I could tell which information was available in each object. Is there a drop in replacement via `airflow.sdk` or are we expected to memorize which fields are in which object?
Where can we find what each `context` contains, for each callback?
GitHub link: https://github.com/apache/airflow/discussions/53618#discussioncomment-14651133
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
GitHub user potiuk added a comment to the discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
> Where can we find what each context contains, for each callback?
Maybe in the [Documentation](https://airflow.apache.org/docs/task-sdk/stable/api.html) ? Who knows. Also this is an open-source project run by volunteers, and if you need any information missing in docs - you can always look at the source code. Some users also decide to give back and if they find missing or imprecise, or difficult to find documentation, look for it (also in the code) and help the whole community and other users by contributing missing docs and links. Highly recommended as a thank you for the software that they get for free.
BTW. We have 3500 contributors. Many of them users who contributed missing docs and generally - gave back.
GitHub link: https://github.com/apache/airflow/discussions/53618#discussioncomment-14669853
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
GitHub user potiuk added a comment to the discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
Yes. That's deliberate change described in the changelog - one of the hallmark features of Airflow 3 where we isolated DB access from worker. Previously you could do more things with `dag` because it was an ORM object representing database DAG table. Now it is just an "object" that is passed through HTTP Task SDK.
You should look at the changelog and see the recommendation and explanations in documentation. Including the advise to use Airflow's REST API to access the information about Dags, DagRuns and other airflow properties. This has been recommended for about 4 years now and the DB access was marked as not part of the publlc API since generally the beginning of Airflow 2 - Airflow 3 now enforces it and does not allow direct database access.
If you feel like some things (from the logical point of view) should be available via task-sdk and you would think that accessing it in your worker without having to use public REST API, I recommend you to open an issue explainig the use pattern you want to have, why you think it is a common pattern that others will want to use, and possibly look at task SDK and propose where and how it could be implemented. We are doing it already when some of the "often used" access methods were commonly used and are missing now - for example https://github.com/apache/airflow/issues/53628 - and we might consider adding it (but it's not like to follow previous access pattern where you could directly access "Database ORM objects) - you need to explain what exactly you need to access (specific logic you want to use it for) and explain why current REST API is not enough (basically what makes you think that the useage is common enough and "task" bound - so that you think it shoudl be built-in).
GitHub link: https://github.com/apache/airflow/discussions/53618#discussioncomment-13863386
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "gopidesupavan (via GitHub)" <gi...@apache.org>.
GitHub user gopidesupavan added a comment to the discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
can you please test on the latest RC https://github.com/apache/airflow/issues/54124 there is fix for this https://github.com/apache/airflow/pull/53058
GitHub link: https://github.com/apache/airflow/discussions/53618#discussioncomment-14035333
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
GitHub user potiuk added a comment to the discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
Open a new issue and describe it.
GitHub link: https://github.com/apache/airflow/discussions/53618#discussioncomment-13867737
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "davidsteinar (via GitHub)" <gi...@apache.org>.
GitHub user davidsteinar added a comment to the discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
Just wanted to say that I am facing the same issue when trying to update my code base from Airflow 2 to 3. I have multiple DAG level callback functions that access the context for posting to Teams channels. I am only getting context object of this type
```
{'dag': <class 'airflow.sdk.definitions.dag.DAG'>, 'run_id': str, 'reason': str}
```
but am unable to find the keys I am interested in logging in the 'dag' object.
GitHub link: https://github.com/apache/airflow/discussions/53618#discussioncomment-13861725
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "DonHaul (via GitHub)" <gi...@apache.org>.
GitHub user DonHaul added a comment to the discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
@benitezfede a workaround I found that works for me is using [Notifiers](https://airflow.apache.org/docs/apache-airflow/stable/howto/notifications.html) , and pass the extra parameters I need through it. Might also work for your usecase
GitHub link: https://github.com/apache/airflow/discussions/53618#discussioncomment-13960617
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "benitezfede (via GitHub)" <gi...@apache.org>.
GitHub user benitezfede edited a discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
Hi,
In the previous versions of airflow I was able to get the `dag_run` information from the `on_success_callback` `context` when a DAG succeeded callback was triggered.
Now, in Airflow 3, I see that the `dag_run` is no longer populated in the callback `context`. In my opinion this is a bug, also it is inconsistent with the `tasks` callbacks as IT IS populated there.
I read the documentation about callbacks [here](https://airflow.apache.org/docs/apache-airflow/stable/templates-ref.html) and it points to [this](https://airflow.apache.org/docs/apache-airflow/stable/templates-ref.html) the `context` template variables which have the `dag_run`. Also the code [here](https://github.com/apache/airflow/blob/main/task-sdk/src/airflow/sdk/definitions/context.py#L42C14-L42C28) shows the `dag_run` so I cannot understand why it is not being populated.
In order to reproduce the issue, I created this DAG which prints the keys of the `context` for DAG and tasks callbacks:
```
from datetime import datetime, timedelta
import logging
from airflow import DAG
from airflow.operators.python import PythonOperator
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Debug callback functions
def debug_task_success_callback(context):
"""Debug callback for task success - prints all context information"""
print("=" * 80)
print("TASK SUCCESS CALLBACK DEBUG")
print("=" * 80)
print(f"Context keys: {list(context.keys())}")
print(f"Context type: {type(context)}")
# Print each context key and its value
for key, value in context.items():
print(f" {key}: {type(value)} = {value}")
if hasattr(value, '__dict__'):
print(f" Attributes: {[attr for attr in dir(value) if not attr.startswith('_')]}")
# Specifically check for dag_run
if 'dag_run' in context:
print(f"\nDAG_RUN FOUND:")
print(f" Type: {type(context['dag_run'])}")
print(f" Attributes: {[attr for attr in dir(context['dag_run']) if not attr.startswith('_')]}")
print(f" Dict: {context['dag_run'].__dict__}")
else:
print(f"\nDAG_RUN NOT FOUND in context!")
print("=" * 80)
def debug_dag_success_callback(context):
"""Debug callback for DAG success - prints all context information"""
print("=" * 80)
print("DAG SUCCESS CALLBACK DEBUG")
print("=" * 80)
print(f"Context keys: {list(context.keys())}")
print(f"Context type: {type(context)}")
# Print each context key and its value
for key, value in context.items():
print(f" {key}: {type(value)} = {value}")
if hasattr(value, '__dict__'):
print(f" Attributes: {[attr for attr in dir(value) if not attr.startswith('_')]}")
# Specifically check for dag_run
if 'dag_run' in context:
print(f"\nDAG_RUN FOUND:")
print(f" Type: {type(context['dag_run'])}")
print(f" Attributes: {[attr for attr in dir(context['dag_run']) if not attr.startswith('_')]}")
print(f" Dict: {context['dag_run'].__dict__}")
else:
print(f"\nDAG_RUN NOT FOUND in context!")
print("=" * 80)
def simple_task():
"""Simple task that just prints a message"""
print("Hello from simple task!")
return "task completed"
# Define the DAG
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2023, 1, 1),
'email': ['airflow@example.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(seconds=10),
# Add task-level callback
'on_success_callback': debug_task_success_callback,
}
dag = DAG(
'debug_context_dag',
default_args=default_args,
description='A simple DAG to debug context in Airflow 3.0',
schedule=timedelta(days=1),
catchup=False,
tags=['debug', 'context'],
# Add DAG-level callback
on_success_callback=debug_dag_success_callback,
)
# Define the task
task1 = PythonOperator(
task_id='simple_task',
python_callable=simple_task,
dag=dag,
)
# Set task dependencies (none needed for single task)
task1
```
The output of running this DAG shows that for the DAG callback the `dag_run` is not present:
```
DAG_RUN NOT FOUND in context!
```
The context for DAG callbacks has only these keys:
```
"Context keys: ['dag', 'run_id', 'reason']"
```
For the task callback we see the following keys:
```
Context keys: ['dag', 'inlets', 'map_index_template', 'outlets', 'run_id', 'task', 'task_instance', 'ti', 'outlet_events', 'inlet_events', 'macros', 'params', 'var', 'conn', 'dag_run', 'triggering_asset_events', 'task_instance_key_str', 'task_reschedule_count', 'prev_start_date_success', 'prev_end_date_success', 'logical_date', 'ds', 'ds_nodash', 'ts', 'ts_nodash', 'ts_nodash_with_tz', 'data_interval_end', 'data_interval_start', 'prev_data_interval_start_success', 'prev_data_interval_end_success', 'templates_dict', 'exception']
```
And it has the `dag_run` as well:
```
DAG_RUN FOUND:: chan="stdout": source="task"
[2025-07-21, 23:28:17] INFO - Type: <class 'airflow.sdk.api.datamodels._generated.DagRun'>: chan="stdout": source="task"
[2025-07-21, 23:28:17] INFO - Attributes: ['clear_number', 'conf', 'construct', 'consumed_asset_events', 'copy', 'dag_id', 'data_interval_end', 'data_interval_start', 'dict', 'end_date', 'from_orm', 'json', 'logical_date', 'model_computed_fields', 'model_config', 'model_construct', 'model_copy', 'model_dump', 'model_dump_json', 'model_extra', 'model_fields', 'model_fields_set', 'model_json_schema', 'model_parametrized_name', 'model_post_init', 'model_rebuild', 'model_validate', 'model_validate_json', 'model_validate_strings', 'parse_file', 'parse_obj', 'parse_raw', 'run_after', 'run_id', 'run_type', 'schema', 'schema_json', 'start_date', 'update_forward_refs', 'validate']
```
So there is a massive difference in the information loaded in the `context` for the task callbacks vs the DAG callback. Is this expected or is it a bug? As I said it seems to be a bug.
Thanks,
Fede
GitHub link: https://github.com/apache/airflow/discussions/53618
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "kaxil (via GitHub)" <gi...@apache.org>.
GitHub user kaxil edited a comment on the discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
It's here: https://airflow.apache.org/docs/task-sdk/stable/api.html#airflow.sdk.Context:~:text=airflow.sdk.Context-,Jinja2%20template%20context%20for%20task%20rendering.,-conn
and
https://github.com/apache/airflow/blob/9ef4f12a5bcad1f7940d0f3fa8238a2ba4096114/task-sdk/src/airflow/sdk/definitions/context.py#L40-L83
GitHub link: https://github.com/apache/airflow/discussions/53618#discussioncomment-14711978
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "benitezfede (via GitHub)" <gi...@apache.org>.
GitHub user benitezfede edited a discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
Hi,
In the previous versions of airflow I was able to get the `dag_run` information from the `on_success_callback` `context` when a DAG succeeded callback was triggered.
Now, in Airflow 3, I see that the `dag_run` is no longer populated in the callback `context`. In my opinion this is a bug, also it is inconsistent with the `tasks` callbacks as IT IS populated there.
I read the documentation about callbacks [here](https://airflow.apache.org/docs/apache-airflow/stable/templates-ref.html) and it points to [this](https://airflow.apache.org/docs/apache-airflow/stable/templates-ref.html) the `context` template variables which have the `dag_run`. Also the code [here](https://github.com/apache/airflow/blob/main/task-sdk/src/airflow/sdk/definitions/context.py#L42C14-L42C28) shows the `dag_run` so I cannot understand why it is not being populated.
The fix seems to be a matter of adding `dag_run: self,` [here](https://github.com/apache/airflow/blob/6b618efa91b4ef80c4821537b30f14a49c2badb6/airflow-core/src/airflow/models/dagrun.py#L1356).
In order to reproduce the issue, I created this DAG which prints the keys of the `context` for DAG and tasks callbacks:
```
from datetime import datetime, timedelta
import logging
from airflow import DAG
from airflow.operators.python import PythonOperator
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Debug callback functions
def debug_task_success_callback(context):
"""Debug callback for task success - prints all context information"""
print("=" * 80)
print("TASK SUCCESS CALLBACK DEBUG")
print("=" * 80)
print(f"Context keys: {list(context.keys())}")
print(f"Context type: {type(context)}")
# Print each context key and its value
for key, value in context.items():
print(f" {key}: {type(value)} = {value}")
if hasattr(value, '__dict__'):
print(f" Attributes: {[attr for attr in dir(value) if not attr.startswith('_')]}")
# Specifically check for dag_run
if 'dag_run' in context:
print(f"\nDAG_RUN FOUND:")
print(f" Type: {type(context['dag_run'])}")
print(f" Attributes: {[attr for attr in dir(context['dag_run']) if not attr.startswith('_')]}")
print(f" Dict: {context['dag_run'].__dict__}")
else:
print(f"\nDAG_RUN NOT FOUND in context!")
print("=" * 80)
def debug_dag_success_callback(context):
"""Debug callback for DAG success - prints all context information"""
print("=" * 80)
print("DAG SUCCESS CALLBACK DEBUG")
print("=" * 80)
print(f"Context keys: {list(context.keys())}")
print(f"Context type: {type(context)}")
# Print each context key and its value
for key, value in context.items():
print(f" {key}: {type(value)} = {value}")
if hasattr(value, '__dict__'):
print(f" Attributes: {[attr for attr in dir(value) if not attr.startswith('_')]}")
# Specifically check for dag_run
if 'dag_run' in context:
print(f"\nDAG_RUN FOUND:")
print(f" Type: {type(context['dag_run'])}")
print(f" Attributes: {[attr for attr in dir(context['dag_run']) if not attr.startswith('_')]}")
print(f" Dict: {context['dag_run'].__dict__}")
else:
print(f"\nDAG_RUN NOT FOUND in context!")
print("=" * 80)
def simple_task():
"""Simple task that just prints a message"""
print("Hello from simple task!")
return "task completed"
# Define the DAG
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2023, 1, 1),
'email': ['airflow@example.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(seconds=10),
# Add task-level callback
'on_success_callback': debug_task_success_callback,
}
dag = DAG(
'debug_context_dag',
default_args=default_args,
description='A simple DAG to debug context in Airflow 3.0',
schedule=timedelta(days=1),
catchup=False,
tags=['debug', 'context'],
# Add DAG-level callback
on_success_callback=debug_dag_success_callback,
)
# Define the task
task1 = PythonOperator(
task_id='simple_task',
python_callable=simple_task,
dag=dag,
)
# Set task dependencies (none needed for single task)
task1
```
The output of running this DAG shows that for the DAG callback the `dag_run` is not present:
```
DAG_RUN NOT FOUND in context!
```
The context for DAG callbacks has only these keys:
```
"Context keys: ['dag', 'run_id', 'reason']"
```
For the task callback we see the following keys:
```
Context keys: ['dag', 'inlets', 'map_index_template', 'outlets', 'run_id', 'task', 'task_instance', 'ti', 'outlet_events', 'inlet_events', 'macros', 'params', 'var', 'conn', 'dag_run', 'triggering_asset_events', 'task_instance_key_str', 'task_reschedule_count', 'prev_start_date_success', 'prev_end_date_success', 'logical_date', 'ds', 'ds_nodash', 'ts', 'ts_nodash', 'ts_nodash_with_tz', 'data_interval_end', 'data_interval_start', 'prev_data_interval_start_success', 'prev_data_interval_end_success', 'templates_dict', 'exception']
```
And it has the `dag_run` as well:
```
DAG_RUN FOUND:: chan="stdout": source="task"
[2025-07-21, 23:28:17] INFO - Type: <class 'airflow.sdk.api.datamodels._generated.DagRun'>: chan="stdout": source="task"
[2025-07-21, 23:28:17] INFO - Attributes: ['clear_number', 'conf', 'construct', 'consumed_asset_events', 'copy', 'dag_id', 'data_interval_end', 'data_interval_start', 'dict', 'end_date', 'from_orm', 'json', 'logical_date', 'model_computed_fields', 'model_config', 'model_construct', 'model_copy', 'model_dump', 'model_dump_json', 'model_extra', 'model_fields', 'model_fields_set', 'model_json_schema', 'model_parametrized_name', 'model_post_init', 'model_rebuild', 'model_validate', 'model_validate_json', 'model_validate_strings', 'parse_file', 'parse_obj', 'parse_raw', 'run_after', 'run_id', 'run_type', 'schema', 'schema_json', 'start_date', 'update_forward_refs', 'validate']
```
So there is a massive difference in the information loaded in the `context` for the task callbacks vs the DAG callback. Is this expected or is it a bug? As I said it seems to be a bug.
Thanks,
Fede
GitHub link: https://github.com/apache/airflow/discussions/53618
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "mbarugelCA (via GitHub)" <gi...@apache.org>.
GitHub user mbarugelCA added a comment to the discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
I am having a similar issue too. I used `context["dag_run"].task_instances` within `on_failure_callback` to report some stats (e.g., list the failed tasks). I also used DagRun.find() to report additional stats on failure, such as how often the DAG has failed over the past X days.
The recommended pattern now is to use the REST API? Does this mean I need to set up API auth to get access to this info? Additionally, does that mean I need to have the API server running to run `airflow dags test my_dag` and access the DagRun info?
Looking at the available methods in the objects, I found that the DagRun is still accessible with the following code.
```
dag_run = context["dag"].fetch_dagrun(context["dag"].safe_dag_id, context["run_id"])
tis = dag_run.get_task_instances()
```
Is this pattern OK to use, or is it expected to go away in future releases of Airflow 3?
GitHub link: https://github.com/apache/airflow/discussions/53618#discussioncomment-14026340
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "benitezfede (via GitHub)" <gi...@apache.org>.
GitHub user benitezfede edited a discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
Hi,
In the previous versions of airflow I was able to get the `dag_run` information from the `on_success_callback` `context` when a DAG succeeded callback was triggered.
Now, in Airflow 3, I see that the `dag_run` is no longer populated in the callback `context`. In my opinion this is a bug, also it is inconsistent with the `tasks` callbacks as IT IS populated there.
I read the documentation about callbacks [here](https://airflow.apache.org/docs/apache-airflow/stable/templates-ref.html) and it points to [this](https://airflow.apache.org/docs/apache-airflow/stable/templates-ref.html) the `context` template variables which have the `dag_run`. Also the code [here](https://github.com/apache/airflow/blob/main/task-sdk/src/airflow/sdk/definitions/context.py#L42C14-L42C28) shows the `dag_run` so I cannot understand why it is not being populated.
In order to reproduce the issue, I created this DAG which prints the keys of the `context` for DAG and tasks callbacks:
```
from datetime import datetime, timedelta
import logging
from airflow import DAG
from airflow.operators.python import PythonOperator
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Debug callback functions
def debug_task_success_callback(context):
"""Debug callback for task success - prints all context information"""
print("=" * 80)
print("TASK SUCCESS CALLBACK DEBUG")
print("=" * 80)
print(f"Context keys: {list(context.keys())}")
print(f"Context type: {type(context)}")
# Print each context key and its value
for key, value in context.items():
print(f" {key}: {type(value)} = {value}")
if hasattr(value, '__dict__'):
print(f" Attributes: {[attr for attr in dir(value) if not attr.startswith('_')]}")
# Specifically check for dag_run
if 'dag_run' in context:
print(f"\nDAG_RUN FOUND:")
print(f" Type: {type(context['dag_run'])}")
print(f" Attributes: {[attr for attr in dir(context['dag_run']) if not attr.startswith('_')]}")
print(f" Dict: {context['dag_run'].__dict__}")
else:
print(f"\nDAG_RUN NOT FOUND in context!")
print("=" * 80)
def debug_dag_success_callback(context):
"""Debug callback for DAG success - prints all context information"""
print("=" * 80)
print("DAG SUCCESS CALLBACK DEBUG")
print("=" * 80)
print(f"Context keys: {list(context.keys())}")
print(f"Context type: {type(context)}")
# Print each context key and its value
for key, value in context.items():
print(f" {key}: {type(value)} = {value}")
if hasattr(value, '__dict__'):
print(f" Attributes: {[attr for attr in dir(value) if not attr.startswith('_')]}")
# Specifically check for dag_run
if 'dag_run' in context:
print(f"\nDAG_RUN FOUND:")
print(f" Type: {type(context['dag_run'])}")
print(f" Attributes: {[attr for attr in dir(context['dag_run']) if not attr.startswith('_')]}")
print(f" Dict: {context['dag_run'].__dict__}")
else:
print(f"\nDAG_RUN NOT FOUND in context!")
print("=" * 80)
def simple_task():
"""Simple task that just prints a message"""
print("Hello from simple task!")
return "task completed"
# Define the DAG
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2023, 1, 1),
'email': ['airflow@example.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(seconds=10),
# Add task-level callback
'on_success_callback': debug_task_success_callback,
}
dag = DAG(
'debug_context_dag',
default_args=default_args,
description='A simple DAG to debug context in Airflow 3.0',
schedule=timedelta(days=1),
catchup=False,
tags=['debug', 'context'],
# Add DAG-level callback
on_success_callback=debug_dag_success_callback,
)
# Define the task
task1 = PythonOperator(
task_id='simple_task',
python_callable=simple_task,
dag=dag,
)
# Set task dependencies (none needed for single task)
task1
```
The output of running this DAG shows that for the DAG callback the `dag_run` is not present:
```
DAG_RUN NOT FOUND in context!
```
The context for DAG callbacks has only these keys:
```
"Context keys: ['dag', 'run_id', 'reason']"
```
For the task callback we see the following keys:
```
Context keys: ['dag', 'inlets', 'map_index_template', 'outlets', 'run_id', 'task', 'task_instance', 'ti', 'outlet_events', 'inlet_events', 'macros', 'params', 'var', 'conn', 'dag_run', 'triggering_asset_events', 'task_instance_key_str', 'task_reschedule_count', 'prev_start_date_success', 'prev_end_date_success', 'logical_date', 'ds', 'ds_nodash', 'ts', 'ts_nodash', 'ts_nodash_with_tz', 'data_interval_end', 'data_interval_start', 'prev_data_interval_start_success', 'prev_data_interval_end_success', 'templates_dict', 'exception']
```
And it has the `dag_run` as well:
```
DAG_RUN FOUND:: chan="stdout": source="task"
[2025-07-21, 23:28:17] INFO - Type: <class 'airflow.sdk.api.datamodels._generated.DagRun'>: chan="stdout": source="task"
[2025-07-21, 23:28:17] INFO - Attributes: ['clear_number', 'conf', 'construct', 'consumed_asset_events', 'copy', 'dag_id', 'data_interval_end', 'data_interval_start', 'dict', 'end_date', 'from_orm', 'json', 'logical_date', 'model_computed_fields', 'model_config', 'model_construct', 'model_copy', 'model_dump', 'model_dump_json', 'model_extra', 'model_fields', 'model_fields_set', 'model_json_schema', 'model_parametrized_name', 'model_post_init', 'model_rebuild', 'model_validate', 'model_validate_json', 'model_validate_strings', 'parse_file', 'parse_obj', 'parse_raw', 'run_after', 'run_id', 'run_type', 'schema', 'schema_json', 'start_date', 'update_forward_refs', 'validate']
```
So there is a massive difference in the information loaded in the `context` for the task callbacks vs the DAG callback. Is this expected or is it a bug? As I said it seems to be a bug.
It seems to be a matter of adding `dag_run: self,` [here](https://github.com/apache/airflow/blob/6b618efa91b4ef80c4821537b30f14a49c2badb6/airflow-core/src/airflow/models/dagrun.py#L1356).
Thanks,
Fede
GitHub link: https://github.com/apache/airflow/discussions/53618
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
GitHub user potiuk added a comment to the discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
Or if you have specific use case and can describe why and how you want to access the data from callback - open an issue and I am sure it will be evaluated. But you have to describe your use case in detail.
GitHub link: https://github.com/apache/airflow/discussions/53618#discussioncomment-13867727
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "matthewblock (via GitHub)" <gi...@apache.org>.
GitHub user matthewblock edited a comment on the discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
I'm running into similar issues - I have been using `airflow.models.XXX` for type hints, so I could tell which information was available in each object.
```
from airflow.models.task_instance import TaskInstance
def my_on_success_callback(context):
ti = context["task_instance"]
print(f"{ti=}")
```
The above now gives me ```RuntimeError: Direct database access via the ORM is not allowed in Airflow 3.0.```
Is there a drop in replacement via `airflow.sdk` or are we expected to memorize which fields are in which object?
Where can we find what each `context` contains, for each callback?
GitHub link: https://github.com/apache/airflow/discussions/53618#discussioncomment-14651133
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "matthewblock (via GitHub)" <gi...@apache.org>.
GitHub user matthewblock added a comment to the discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
> > Where can we find what each context contains, for each callback?
>
> Maybe in the [Documentation](https://airflow.apache.org/docs/task-sdk/stable/api.html) ? Who knows. Also this is an open-source project run by volunteers, and if you need any information missing in docs - you can always look at the source code. Some users also decide to give back and if they find missing or imprecise, or difficult to find documentation, look for it (also in the code) and help the whole community and other users by contributing missing docs and links. Highly recommended as a thank you for the software that they get for free.
>
> BTW. We have 3500 contributors. Many of them users who contributed missing docs and generally - gave back.
Thanks - I assumed it existed and I missed it.
GitHub link: https://github.com/apache/airflow/discussions/53618#discussioncomment-14711903
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "kaxil (via GitHub)" <gi...@apache.org>.
GitHub user kaxil added a comment to the discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
It's here: https://airflow.apache.org/docs/task-sdk/stable/api.html#airflow.sdk.Context:~:text=airflow.sdk.Context-,Jinja2%20template%20context%20for%20task%20rendering.,-conn
and
https://github.com/apache/airflow/blob/main/task-sdk/src/airflow/sdk/definitions/context.py#L40-L83
GitHub link: https://github.com/apache/airflow/discussions/53618#discussioncomment-14711978
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "matthewblock (via GitHub)" <gi...@apache.org>.
GitHub user matthewblock edited a comment on the discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
I'm running into similar issues - I have been using `airflow.models.XXX` for type hints, so I could tell which information was available in each object.
```
from airflow.models.task_instance import TaskInstance
def my_on_success_callback(context):
ti: TaskInstance = context["task_instance"]
print(f"{ti=}")
```
The above now gives me ```RuntimeError: Direct database access via the ORM is not allowed in Airflow 3.0.```
Is there a drop in replacement via `airflow.sdk` or are we expected to memorize which fields are in which object?
Where can we find what each `context` contains, for each callback?
GitHub link: https://github.com/apache/airflow/discussions/53618#discussioncomment-14651133
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "benitezfede (via GitHub)" <gi...@apache.org>.
GitHub user benitezfede edited a discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
Hi,
In the previous versions of airflow I was able to get the `dag_run` information from the `on_success_callback` context when a DAG succeeded.
Now in Airflow 3 I see that the `dag_run` is no longer populated in the context and in my opinion this is a bug, as it is obviously needed and in the task callbacks context it is populated.
I created this DAG to reproduce the issue:
```
from datetime import datetime, timedelta
import logging
from airflow import DAG
from airflow.operators.python import PythonOperator
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Debug callback functions
def debug_task_success_callback(context):
"""Debug callback for task success - prints all context information"""
print("=" * 80)
print("TASK SUCCESS CALLBACK DEBUG")
print("=" * 80)
print(f"Context keys: {list(context.keys())}")
print(f"Context type: {type(context)}")
# Print each context key and its value
for key, value in context.items():
print(f" {key}: {type(value)} = {value}")
if hasattr(value, '__dict__'):
print(f" Attributes: {[attr for attr in dir(value) if not attr.startswith('_')]}")
# Specifically check for dag_run
if 'dag_run' in context:
print(f"\nDAG_RUN FOUND:")
print(f" Type: {type(context['dag_run'])}")
print(f" Attributes: {[attr for attr in dir(context['dag_run']) if not attr.startswith('_')]}")
print(f" Dict: {context['dag_run'].__dict__}")
else:
print(f"\nDAG_RUN NOT FOUND in context!")
print("=" * 80)
def debug_dag_success_callback(context):
"""Debug callback for DAG success - prints all context information"""
print("=" * 80)
print("DAG SUCCESS CALLBACK DEBUG")
print("=" * 80)
print(f"Context keys: {list(context.keys())}")
print(f"Context type: {type(context)}")
# Print each context key and its value
for key, value in context.items():
print(f" {key}: {type(value)} = {value}")
if hasattr(value, '__dict__'):
print(f" Attributes: {[attr for attr in dir(value) if not attr.startswith('_')]}")
# Specifically check for dag_run
if 'dag_run' in context:
print(f"\nDAG_RUN FOUND:")
print(f" Type: {type(context['dag_run'])}")
print(f" Attributes: {[attr for attr in dir(context['dag_run']) if not attr.startswith('_')]}")
print(f" Dict: {context['dag_run'].__dict__}")
else:
print(f"\nDAG_RUN NOT FOUND in context!")
print("=" * 80)
def simple_task():
"""Simple task that just prints a message"""
print("Hello from simple task!")
return "task completed"
# Define the DAG
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2023, 1, 1),
'email': ['airflow@example.com'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(seconds=10),
# Add task-level callback
'on_success_callback': debug_task_success_callback,
}
dag = DAG(
'debug_context_dag',
default_args=default_args,
description='A simple DAG to debug context in Airflow 3.0',
schedule=timedelta(days=1),
catchup=False,
tags=['debug', 'context'],
# Add DAG-level callback
on_success_callback=debug_dag_success_callback,
)
# Define the task
task1 = PythonOperator(
task_id='simple_task',
python_callable=simple_task,
dag=dag,
)
# Set task dependencies (none needed for single task)
task1
```
The output of running this DAG shows that for the DAG callback the `dag_run` is not present:
```
DAG_RUN NOT FOUND in context!
```
The context for DAG callbacks has only these keys:
```
"Context keys: ['dag', 'run_id', 'reason']"
```
For the task callback we see the following keys:
```
Context keys: ['dag', 'inlets', 'map_index_template', 'outlets', 'run_id', 'task', 'task_instance', 'ti', 'outlet_events', 'inlet_events', 'macros', 'params', 'var', 'conn', 'dag_run', 'triggering_asset_events', 'task_instance_key_str', 'task_reschedule_count', 'prev_start_date_success', 'prev_end_date_success', 'logical_date', 'ds', 'ds_nodash', 'ts', 'ts_nodash', 'ts_nodash_with_tz', 'data_interval_end', 'data_interval_start', 'prev_data_interval_start_success', 'prev_data_interval_end_success', 'templates_dict', 'exception']
```
And it has the `dag_run` as well:
```
DAG_RUN FOUND:: chan="stdout": source="task"
[2025-07-21, 23:28:17] INFO - Type: <class 'airflow.sdk.api.datamodels._generated.DagRun'>: chan="stdout": source="task"
[2025-07-21, 23:28:17] INFO - Attributes: ['clear_number', 'conf', 'construct', 'consumed_asset_events', 'copy', 'dag_id', 'data_interval_end', 'data_interval_start', 'dict', 'end_date', 'from_orm', 'json', 'logical_date', 'model_computed_fields', 'model_config', 'model_construct', 'model_copy', 'model_dump', 'model_dump_json', 'model_extra', 'model_fields', 'model_fields_set', 'model_json_schema', 'model_parametrized_name', 'model_post_init', 'model_rebuild', 'model_validate', 'model_validate_json', 'model_validate_strings', 'parse_file', 'parse_obj', 'parse_raw', 'run_after', 'run_id', 'run_type', 'schema', 'schema_json', 'start_date', 'update_forward_refs', 'validate']
```
So there is a massive difference in the information loaded for the task callbacks vs the DAG callback. Is this expected or is it a bug?
I read the documentation about callbacks [here](https://airflow.apache.org/docs/apache-airflow/stable/templates-ref.html) and it points to [this](https://airflow.apache.org/docs/apache-airflow/stable/templates-ref.html) list of template variables which have the `dag_run`. Also the code [here](https://github.com/apache/airflow/blob/main/task-sdk/src/airflow/sdk/definitions/context.py#L42C14-L42C28) shows the `dag_run` so I cannot understand why it is not being populated.
Thanks,
Fede
GitHub link: https://github.com/apache/airflow/discussions/53618
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
GitHub user potiuk added a comment to the discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
Also see the PR in progress here https://github.com/apache/airflow/pull/53655 which brings back "get_previous_run" functionality to TaskSDK but with a slightly modified API and usage pattern,
So we expect the same from you @davidsteinar @benitezfede -> if you have some concrete access patterns other than "access the whole data model of airflow easily" and it's a "reusable pattern that others might use as well" - feel absolutely free to open an issue describing the pattern and use case, and explaining why it would be useful to have it in task sdk and we will take a look and decide if it is worth to implement it in 3.1 or 3.2.
GitHub link: https://github.com/apache/airflow/discussions/53618#discussioncomment-13863621
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org
Re: [D] DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2. [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
GitHub user potiuk added a comment to the discussion: DAG callback `context` does not have `dag_run` set in Airflow 3 but it is set in Airflow 2.
REST API
GitHub link: https://github.com/apache/airflow/discussions/53618#discussioncomment-13867715
----
This is an automatically sent email for commits@airflow.apache.org.
To unsubscribe, please send an email to: commits-unsubscribe@airflow.apache.org