Skip to content
32 changes: 31 additions & 1 deletion airflow-core/docs/howto/dynamic-dag-generation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ a single Dag object (when executing the task).
context. The context is an :py:class:`~airflow.utils.dag_parsing_context.AirflowParsingContext` and
when only a single Dag/task is needed, it contains ``dag_id`` and ``task_id`` fields set.
When "full" parsing is needed (for example in Dag File Processor), ``dag_id`` and ``task_id``
of the context are set to ``None``.
of the context are set to ``None``. The context also has a ``bundle_name`` property, described below.


.. code-block:: python
Expand All @@ -213,3 +213,33 @@ of the context are set to ``None``.

with DAG(dag_id=dag_id, ...):
...

The ``bundle_name`` property holds the configured name of the Dag bundle the file is being parsed from (not
the bundle version). It is set whenever Airflow parses a file from a bundle: in the Dag File Processor, when a
task re-parses its Dag file before execution, and in CLI commands such as ``airflow dags test`` and
``airflow dags reserialize``. Like ``dag_id`` and ``task_id``, it is not unset once parsing finishes, so it is
still available while the task runs.

It is ``None`` when the file is not loaded from a bundle, for example when you import or run the Dag file
directly in your own scripts or tests. Airflow versions that predate this property do not have it at all, so
code that must run on them should use ``getattr(get_parsing_context(), "bundle_name", None)``.

For example, you can use it to pass the bundle name to triggers created at parse time, which otherwise have
no way to know which bundle they came from. ``MyEventTrigger`` below stands for your own subclass of
``BaseEventTrigger`` (see :doc:`/authoring-and-scheduling/event-scheduling`):

.. code-block:: python

from airflow.sdk import Asset, AssetWatcher, get_parsing_context

bundle_name = get_parsing_context().bundle_name

asset = Asset(
"my_asset",
watchers=[
AssetWatcher(
name="my_watcher",
trigger=MyEventTrigger(bundle_name=bundle_name), # Pass in the bundle name to be used, as needed
)
],
)
7 changes: 7 additions & 0 deletions airflow-core/src/airflow/dag_processing/dagbag.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
from airflow.executors.executor_loader import ExecutorLoader
from airflow.listeners.listener import get_listener_manager
from airflow.models.pool import Pool
from airflow.sdk.definitions.context import _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME # noqa: SDK001
from airflow.sdk.exceptions import AirflowDagCycleException, TaskGroupCycleDeprecationWarning
from airflow.sdk.importers import DagImportError, get_importer_registry
from airflow.serialization.definitions.dag import SerializedDAG
Expand Down Expand Up @@ -656,6 +657,12 @@ def __init__(self, *args, bundle_path: Path | None = None, **kwargs):
if str(bundle_path) not in sys.path:
sys.path.append(str(bundle_path))

# Left set after parsing, like the Dag and task IDs, so it is still readable while a task runs.
if bundle_name := kwargs.get("bundle_name"):
os.environ[_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME] = bundle_name
else:
os.environ.pop(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, None)

kwargs["bundle_path"] = bundle_path
super().__init__(*args, **kwargs)

Expand Down
25 changes: 25 additions & 0 deletions airflow-core/tests/unit/dag_processing/test_dagbag.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
from airflow.models.pool import Pool
from airflow.models.serialized_dag import SerializedDagModel
from airflow.sdk import DAG, BaseOperator, TaskGroup
from airflow.sdk.definitions.context import _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME
from airflow.sdk.exceptions import AirflowConfigException, TaskGroupCycleDeprecationWarning
from airflow.sdk.importers import (
AbstractDagImporter,
Expand Down Expand Up @@ -1629,6 +1630,30 @@ def test_dagbag_no_bundle_path_no_syspath_modification(self, tmp_path):
assert sys.path == syspath_before


class TestBundleDagBagParsingContext:
@pytest.mark.parametrize(
("bundle_name", "expected_dag_id"),
[
pytest.param("my-bundle", "from_my-bundle", id="sets-bundle-name"),
pytest.param(None, "from_None", id="clears-stale-bundle-name"),
],
)
@mock.patch.dict(os.environ, {_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME: "stale-bundle"})
def test_bundle_name_in_parsing_context(self, tmp_path, bundle_name, expected_dag_id):
dag_file = tmp_path / "bundle_name_dag.py"
dag_file.write_text(
"from airflow.sdk import DAG, get_parsing_context\n"
"\n"
"dag = DAG(f'from_{get_parsing_context().bundle_name}', schedule=None)\n"
)

dagbag = BundleDagBag(dag_folder=str(dag_file), bundle_path=tmp_path, bundle_name=bundle_name)

assert list(dagbag.dags) == [expected_dag_id]
assert os.environ.get(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME) == bundle_name
sys.path.remove(str(tmp_path))


@pytest.fixture
def clean_import_errors():
db.clear_db_import_errors()
Expand Down
7 changes: 7 additions & 0 deletions task-sdk/src/airflow/sdk/definitions/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,16 @@ class AirflowParsingContext(NamedTuple):
dag_id: str | None
task_id: str | None

# A property rather than a field so existing positional unpacking of the tuple keeps working.
@property
def bundle_name(self) -> str | None:
"""Name of the Dag bundle the file is being parsed from, or ``None`` outside a bundle."""
return os.environ.get(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME)


_AIRFLOW_PARSING_CONTEXT_DAG_ID = "_AIRFLOW_PARSING_CONTEXT_DAG_ID"
_AIRFLOW_PARSING_CONTEXT_TASK_ID = "_AIRFLOW_PARSING_CONTEXT_TASK_ID"
_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME = "_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME"


def get_parsing_context() -> AirflowParsingContext:
Expand Down
26 changes: 25 additions & 1 deletion task-sdk/tests/task_sdk/definitions/test_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,18 @@
# under the License.
from __future__ import annotations

import os
from unittest import mock

import pytest

from airflow.sdk.definitions.context import get_current_context
from airflow.sdk.definitions.context import (
_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME,
_AIRFLOW_PARSING_CONTEXT_DAG_ID,
_AIRFLOW_PARSING_CONTEXT_TASK_ID,
get_current_context,
get_parsing_context,
)


class TestCurrentContext:
Expand All @@ -39,3 +48,18 @@ def test_get_current_context_without_context(self, monkeypatch):
monkeypatch.setattr("airflow.sdk.definitions._internal.contextmanager._CURRENT_CONTEXT", [])
with pytest.raises(RuntimeError, match="Current context was requested but no context was found!"):
get_current_context()


class TestParsingContext:
@pytest.mark.parametrize("bundle_name", ["my-bundle", None])
def test_bundle_name_is_read_without_changing_tuple_shape(self, bundle_name):
env = {_AIRFLOW_PARSING_CONTEXT_DAG_ID: "my_dag", _AIRFLOW_PARSING_CONTEXT_TASK_ID: "my_task"}
with mock.patch.dict(os.environ, env):
os.environ.pop(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, None)
if bundle_name is not None:
os.environ[_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME] = bundle_name
context = get_parsing_context()

dag_id, task_id = context
assert (dag_id, task_id) == ("my_dag", "my_task")
assert context.bundle_name == bundle_name