From eeef030d1dd9517b49156abeb73d8aa02c5fb040 Mon Sep 17 00:00:00 2001 From: Jake McGrath Date: Tue, 24 Nov 2026 10:39:25 -0500 Subject: [PATCH 1/6] feature/add-bundle-name-to-parsing-context: Adding DAG bundle name to parsing context to it can be used outside of get_current_context --- .../docs/howto/dynamic-dag-generation.rst | 16 ++++++ .../src/airflow/dag_processing/processor.py | 14 ++--- .../unit/dag_processing/test_processor.py | 20 +++++++ .../_internal/dag_parsing_context.py | 27 ++++++++-- .../src/airflow/sdk/definitions/context.py | 6 +++ .../airflow/sdk/execution_time/task_runner.py | 4 +- .../_internal/test_dag_parsing_context.py | 54 +++++++++++++++++++ .../execution_time/test_task_runner.py | 17 ++++-- 8 files changed, 144 insertions(+), 14 deletions(-) create mode 100644 task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py diff --git a/airflow-core/docs/howto/dynamic-dag-generation.rst b/airflow-core/docs/howto/dynamic-dag-generation.rst index 78c89db6ca84..b089d9a02072 100644 --- a/airflow-core/docs/howto/dynamic-dag-generation.rst +++ b/airflow-core/docs/howto/dynamic-dag-generation.rst @@ -213,3 +213,19 @@ of the context are set to ``None``. with DAG(dag_id=dag_id, ...): ... + +The context also has a ``bundle_name`` field holding the name of the Dag bundle the file is being parsed from. It is +set both when the Dag File Processor parses the file and when a task re-parses its Dag file before execution, and is +``None`` outside of those parses. 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: + +.. 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=MyTrigger(bundle_name=bundle_name))], + ) diff --git a/airflow-core/src/airflow/dag_processing/processor.py b/airflow-core/src/airflow/dag_processing/processor.py index 199b12edbb44..6661fd7b5c2a 100644 --- a/airflow-core/src/airflow/dag_processing/processor.py +++ b/airflow-core/src/airflow/dag_processing/processor.py @@ -43,6 +43,7 @@ from airflow.dag_processing.bundles.base import BundleVersionLock from airflow.dag_processing.dagbag import BundleDagBag, DagBag, LangSDKSerializedDAG from airflow.models.dag import DagModel +from airflow.sdk.definitions._internal.dag_parsing_context import _airflow_parsing_context_manager # noqa: SDK001 from airflow.sdk.exceptions import TaskNotFound from airflow.sdk.execution_time import supervisor from airflow.sdk.execution_time.comms import ( @@ -249,12 +250,13 @@ def _parse_file(msg: DagFileParseRequest, log: FilteringBoundLogger) -> DagFileP import_errors=stability_check_error_dict, ) - bag = BundleDagBag( - dag_folder=msg.file, - bundle_path=msg.bundle_path, - bundle_name=msg.bundle_name, - load_op_links=False, - ) + with _airflow_parsing_context_manager(bundle_name=msg.bundle_name): + bag = BundleDagBag( + dag_folder=msg.file, + bundle_path=msg.bundle_path, + bundle_name=msg.bundle_name, + load_op_links=False, + ) if msg.callback_requests: # If the request is for callback, we shouldn't serialize the Dags diff --git a/airflow-core/tests/unit/dag_processing/test_processor.py b/airflow-core/tests/unit/dag_processing/test_processor.py index d40ec9c7d07b..429d8504de3c 100644 --- a/airflow-core/tests/unit/dag_processing/test_processor.py +++ b/airflow-core/tests/unit/dag_processing/test_processor.py @@ -854,6 +854,26 @@ def fail_to_serialize_unserializable(dag): ] +def test_parse_file_sets_bundle_name_in_parsing_context(tmp_path, monkeypatch): + from airflow.sdk.definitions.context import _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME + + monkeypatch.delenv(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, raising=False) + 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" + ) + + result = _parse_file( + DagFileParseRequest(file=str(dag_file), bundle_path=tmp_path, bundle_name="my-bundle"), + log=structlog.get_logger(), + ) + + assert [dag.dag_id for dag in result.serialized_dags] == ["from_my-bundle"] + assert _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME not in os.environ + + def test_callback_processing_does_not_update_timestamps(): """Callback processing should not update last_finish_time to prevent stale DAG detection.""" stat = process_parse_results( diff --git a/task-sdk/src/airflow/sdk/definitions/_internal/dag_parsing_context.py b/task-sdk/src/airflow/sdk/definitions/_internal/dag_parsing_context.py index cad4f9918592..ad89bf975f69 100644 --- a/task-sdk/src/airflow/sdk/definitions/_internal/dag_parsing_context.py +++ b/task-sdk/src/airflow/sdk/definitions/_internal/dag_parsing_context.py @@ -19,18 +19,39 @@ import os from contextlib import contextmanager -from airflow.sdk.definitions.context import _AIRFLOW_PARSING_CONTEXT_DAG_ID, _AIRFLOW_PARSING_CONTEXT_TASK_ID +from airflow.sdk.definitions.context import ( + _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, + _AIRFLOW_PARSING_CONTEXT_DAG_ID, + _AIRFLOW_PARSING_CONTEXT_TASK_ID, +) @contextmanager -def _airflow_parsing_context_manager(dag_id: str | None = None, task_id: str | None = None): +def _airflow_parsing_context_manager( + dag_id: str | None = None, task_id: str | None = None, bundle_name: str | None = None +): old_dag_id = os.environ.get(_AIRFLOW_PARSING_CONTEXT_DAG_ID) old_task_id = os.environ.get(_AIRFLOW_PARSING_CONTEXT_TASK_ID) + old_bundle_name = os.environ.get(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME) + if dag_id is not None: os.environ[_AIRFLOW_PARSING_CONTEXT_DAG_ID] = dag_id if task_id is not None: os.environ[_AIRFLOW_PARSING_CONTEXT_TASK_ID] = task_id - yield + if bundle_name is not None: + os.environ[_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME] = bundle_name + + try: + yield + finally: + # dag_id/task_id intentionally keep their historical behaviour of staying set when there was no + # previous value; bundle_name is fully restored so it never leaks past the parse it describes. + if bundle_name is not None: + if old_bundle_name is None: + os.environ.pop(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, None) + else: + os.environ[_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME] = old_bundle_name + if old_task_id is not None: os.environ[_AIRFLOW_PARSING_CONTEXT_TASK_ID] = old_task_id if old_dag_id is not None: diff --git a/task-sdk/src/airflow/sdk/definitions/context.py b/task-sdk/src/airflow/sdk/definitions/context.py index df25019d7ea4..6f747694989d 100644 --- a/task-sdk/src/airflow/sdk/definitions/context.py +++ b/task-sdk/src/airflow/sdk/definitions/context.py @@ -176,15 +176,20 @@ class AirflowParsingContext(NamedTuple): If these values are not None, they will contain the specific Dag and Task ID that Airflow is requesting to execute. You can use these for optimizing dynamically generated Dag files. + ``bundle_name`` is the name of the Dag bundle the file is being parsed from. It is set both when the + Dag processor parses the file and when a task re-parses its Dag file before execution. + You can obtain the current values via :py:func:`.get_parsing_context`. """ dag_id: str | None task_id: str | None + bundle_name: str | None = None _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: @@ -192,6 +197,7 @@ def get_parsing_context() -> AirflowParsingContext: return AirflowParsingContext( dag_id=os.environ.get(_AIRFLOW_PARSING_CONTEXT_DAG_ID), task_id=os.environ.get(_AIRFLOW_PARSING_CONTEXT_TASK_ID), + bundle_name=os.environ.get(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME), ) diff --git a/task-sdk/src/airflow/sdk/execution_time/task_runner.py b/task-sdk/src/airflow/sdk/execution_time/task_runner.py index 303ae89b4654..6cf2d16304cd 100644 --- a/task-sdk/src/airflow/sdk/execution_time/task_runner.py +++ b/task-sdk/src/airflow/sdk/execution_time/task_runner.py @@ -1333,7 +1333,9 @@ def startup(msg: StartupDetails) -> tuple[RuntimeTaskInstance, Context, Logger]: set_current_team_name(msg.ti_context.dag_run.team_name) - with _airflow_parsing_context_manager(dag_id=msg.ti.dag_id, task_id=msg.ti.task_id): + with _airflow_parsing_context_manager( + dag_id=msg.ti.dag_id, task_id=msg.ti.task_id, bundle_name=msg.bundle_info.name + ): ti = parse(msg, log) log.debug("Dag file parsed", file=msg.dag_rel_path) diff --git a/task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py b/task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py new file mode 100644 index 000000000000..187bf8cb6e81 --- /dev/null +++ b/task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py @@ -0,0 +1,54 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from __future__ import annotations + +import os + +import pytest + +from airflow.sdk import get_parsing_context +from airflow.sdk.definitions._internal.dag_parsing_context import _airflow_parsing_context_manager +from airflow.sdk.definitions.context import _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, AirflowParsingContext + + +@pytest.fixture(autouse=True) +def _clear_bundle_name(monkeypatch): + monkeypatch.delenv(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, raising=False) + + +def test_bundle_name_defaults_to_none(): + assert get_parsing_context().bundle_name is None + assert AirflowParsingContext(dag_id="d", task_id="t").bundle_name is None + + +@pytest.mark.parametrize("previous", [None, "outer-bundle"]) +def test_context_manager_sets_and_restores_bundle_name(monkeypatch, previous): + if previous is not None: + monkeypatch.setenv(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, previous) + + with _airflow_parsing_context_manager(bundle_name="my-bundle"): + assert get_parsing_context().bundle_name == "my-bundle" + + assert os.environ.get(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME) == previous + + +def test_context_manager_restores_bundle_name_on_error(): + with pytest.raises(RuntimeError): + with _airflow_parsing_context_manager(bundle_name="my-bundle"): + raise RuntimeError("boom") + + assert _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME not in os.environ diff --git a/task-sdk/tests/task_sdk/execution_time/test_task_runner.py b/task-sdk/tests/task_sdk/execution_time/test_task_runner.py index 64beb9440575..4ed82d8732cc 100644 --- a/task-sdk/tests/task_sdk/execution_time/test_task_runner.py +++ b/task-sdk/tests/task_sdk/execution_time/test_task_runner.py @@ -952,10 +952,10 @@ def test_parse_module_in_bundle_root(tmp_path: Path, make_ti_context): @pytest.mark.parametrize( - ("use_startup", "expected_dag_id", "expected_task_id"), + ("use_startup", "expected_dag_id", "expected_task_id", "expected_bundle_name"), [ - pytest.param(True, "expected_dag", "my_task", id="startup"), - pytest.param(False, None, None, id="parse"), + pytest.param(True, "expected_dag", "my_task", "my-bundle", id="startup"), + pytest.param(False, None, None, None, id="parse"), ], ) @mock.patch("airflow.sdk.execution_time.task_runner.get_listener_manager") @@ -968,12 +968,14 @@ def test_bundle_initialize_parsing_context( use_startup, expected_dag_id, expected_task_id, + expected_bundle_name, make_ti_context, tmp_path: Path, monkeypatch, ): from airflow.sdk import get_parsing_context from airflow.sdk.definitions.context import ( + _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, _AIRFLOW_PARSING_CONTEXT_DAG_ID, _AIRFLOW_PARSING_CONTEXT_TASK_ID, ) @@ -986,6 +988,7 @@ def capture_parsing_context(): ctx = get_parsing_context() captured["dag_id"] = ctx.dag_id captured["task_id"] = ctx.task_id + captured["bundle_name"] = ctx.bundle_name mock_bundle.initialize.side_effect = capture_parsing_context mock_manager = mock_manager_cls.return_value @@ -1014,13 +1017,19 @@ def capture_parsing_context(): monkeypatch.delenv(_AIRFLOW_PARSING_CONTEXT_DAG_ID, raising=False) monkeypatch.delenv(_AIRFLOW_PARSING_CONTEXT_TASK_ID, raising=False) + monkeypatch.delenv(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, raising=False) if use_startup: startup(what) else: parse(what, mock.Mock()) - assert captured == {"dag_id": expected_dag_id, "task_id": expected_task_id} + assert captured == { + "dag_id": expected_dag_id, + "task_id": expected_task_id, + "bundle_name": expected_bundle_name, + } + assert _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME not in os.environ mock_bundle.initialize.assert_called_once() From 3a8d8abb6e5252d0cd1230ee730efd52881ad0c7 Mon Sep 17 00:00:00 2001 From: Jake McGrath Date: Tue, 24 Nov 2026 10:56:08 -0500 Subject: [PATCH 2/6] feature/add-bundle-name-to-parsing-context: Removing restore of old value --- .../docs/howto/dynamic-dag-generation.rst | 6 ++-- .../unit/dag_processing/test_processor.py | 6 ++-- .../_internal/dag_parsing_context.py | 13 ++------ .../_internal/test_dag_parsing_context.py | 31 ++++++++++--------- .../execution_time/test_task_runner.py | 4 ++- 5 files changed, 29 insertions(+), 31 deletions(-) diff --git a/airflow-core/docs/howto/dynamic-dag-generation.rst b/airflow-core/docs/howto/dynamic-dag-generation.rst index b089d9a02072..c655fb720602 100644 --- a/airflow-core/docs/howto/dynamic-dag-generation.rst +++ b/airflow-core/docs/howto/dynamic-dag-generation.rst @@ -215,9 +215,9 @@ of the context are set to ``None``. ... The context also has a ``bundle_name`` field holding the name of the Dag bundle the file is being parsed from. It is -set both when the Dag File Processor parses the file and when a task re-parses its Dag file before execution, and is -``None`` outside of those parses. 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: +set both when the Dag File Processor parses the file and when a task re-parses its Dag file before execution and, +like ``dag_id`` and ``task_id``, it stays set while the task runs. 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: .. code-block:: python diff --git a/airflow-core/tests/unit/dag_processing/test_processor.py b/airflow-core/tests/unit/dag_processing/test_processor.py index 429d8504de3c..d6cb58fd7a40 100644 --- a/airflow-core/tests/unit/dag_processing/test_processor.py +++ b/airflow-core/tests/unit/dag_processing/test_processor.py @@ -854,10 +854,11 @@ def fail_to_serialize_unserializable(dag): ] -def test_parse_file_sets_bundle_name_in_parsing_context(tmp_path, monkeypatch): +@patch.dict(os.environ) +def test_parse_file_sets_bundle_name_in_parsing_context(tmp_path): from airflow.sdk.definitions.context import _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME - monkeypatch.delenv(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, raising=False) + os.environ.pop(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, None) dag_file = tmp_path / "bundle_name_dag.py" dag_file.write_text( "from airflow.sdk import DAG, get_parsing_context\n" @@ -871,7 +872,6 @@ def test_parse_file_sets_bundle_name_in_parsing_context(tmp_path, monkeypatch): ) assert [dag.dag_id for dag in result.serialized_dags] == ["from_my-bundle"] - assert _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME not in os.environ def test_callback_processing_does_not_update_timestamps(): diff --git a/task-sdk/src/airflow/sdk/definitions/_internal/dag_parsing_context.py b/task-sdk/src/airflow/sdk/definitions/_internal/dag_parsing_context.py index ad89bf975f69..39cc99ca8a8c 100644 --- a/task-sdk/src/airflow/sdk/definitions/_internal/dag_parsing_context.py +++ b/task-sdk/src/airflow/sdk/definitions/_internal/dag_parsing_context.py @@ -41,17 +41,10 @@ def _airflow_parsing_context_manager( if bundle_name is not None: os.environ[_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME] = bundle_name - try: - yield - finally: - # dag_id/task_id intentionally keep their historical behaviour of staying set when there was no - # previous value; bundle_name is fully restored so it never leaks past the parse it describes. - if bundle_name is not None: - if old_bundle_name is None: - os.environ.pop(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, None) - else: - os.environ[_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME] = old_bundle_name + yield + if old_bundle_name is not None: + os.environ[_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME] = old_bundle_name if old_task_id is not None: os.environ[_AIRFLOW_PARSING_CONTEXT_TASK_ID] = old_task_id if old_dag_id is not None: diff --git a/task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py b/task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py index 187bf8cb6e81..56711423b0b6 100644 --- a/task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py +++ b/task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py @@ -17,6 +17,7 @@ from __future__ import annotations import os +from unittest import mock import pytest @@ -26,8 +27,12 @@ @pytest.fixture(autouse=True) -def _clear_bundle_name(monkeypatch): - monkeypatch.delenv(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, raising=False) +def _isolate_bundle_name(): + # patch.dict also undoes the variable the context manager leaves set, which monkeypatch.delenv + # would not track when the variable was absent to begin with. + with mock.patch.dict(os.environ): + os.environ.pop(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, None) + yield def test_bundle_name_defaults_to_none(): @@ -35,20 +40,18 @@ def test_bundle_name_defaults_to_none(): assert AirflowParsingContext(dag_id="d", task_id="t").bundle_name is None -@pytest.mark.parametrize("previous", [None, "outer-bundle"]) -def test_context_manager_sets_and_restores_bundle_name(monkeypatch, previous): +@pytest.mark.parametrize( + ("previous", "expected_after"), + [ + pytest.param(None, "my-bundle", id="stays-set-without-previous-value"), + pytest.param("outer-bundle", "outer-bundle", id="restores-previous-value"), + ], +) +def test_context_manager_sets_bundle_name(previous, expected_after): if previous is not None: - monkeypatch.setenv(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, previous) + os.environ[_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME] = previous with _airflow_parsing_context_manager(bundle_name="my-bundle"): assert get_parsing_context().bundle_name == "my-bundle" - assert os.environ.get(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME) == previous - - -def test_context_manager_restores_bundle_name_on_error(): - with pytest.raises(RuntimeError): - with _airflow_parsing_context_manager(bundle_name="my-bundle"): - raise RuntimeError("boom") - - assert _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME not in os.environ + assert get_parsing_context().bundle_name == expected_after diff --git a/task-sdk/tests/task_sdk/execution_time/test_task_runner.py b/task-sdk/tests/task_sdk/execution_time/test_task_runner.py index 4ed82d8732cc..60def1e2cefe 100644 --- a/task-sdk/tests/task_sdk/execution_time/test_task_runner.py +++ b/task-sdk/tests/task_sdk/execution_time/test_task_runner.py @@ -958,6 +958,7 @@ def test_parse_module_in_bundle_root(tmp_path: Path, make_ti_context): pytest.param(False, None, None, None, id="parse"), ], ) +@mock.patch.dict(os.environ) @mock.patch("airflow.sdk.execution_time.task_runner.get_listener_manager") @mock.patch("airflow.dag_processing.dagbag.BundleDagBag") @mock.patch("airflow.sdk.execution_time.bundles.DagBundlesManager") @@ -1029,7 +1030,8 @@ def capture_parsing_context(): "task_id": expected_task_id, "bundle_name": expected_bundle_name, } - assert _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME not in os.environ + # Like dag_id/task_id, bundle_name stays set after startup so it is visible during task execution. + assert os.environ.get(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME) == expected_bundle_name mock_bundle.initialize.assert_called_once() From cf2f59eed913ec85f01f24dcf6b5752dce19322e Mon Sep 17 00:00:00 2001 From: Jake McGrath Date: Tue, 24 Nov 2026 11:12:53 -0500 Subject: [PATCH 3/6] feature/add-bundle-name-to-parsing-context: Spacing, comments --- airflow-core/docs/howto/dynamic-dag-generation.rst | 7 ++++++- .../definitions/_internal/test_dag_parsing_context.py | 2 -- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/airflow-core/docs/howto/dynamic-dag-generation.rst b/airflow-core/docs/howto/dynamic-dag-generation.rst index c655fb720602..dec68826cccb 100644 --- a/airflow-core/docs/howto/dynamic-dag-generation.rst +++ b/airflow-core/docs/howto/dynamic-dag-generation.rst @@ -227,5 +227,10 @@ to triggers created at parse time, which otherwise have no way to know which bun asset = Asset( "my_asset", - watchers=[AssetWatcher(name="my_watcher", trigger=MyTrigger(bundle_name=bundle_name))], + watchers=[ + AssetWatcher( + name="my_watcher", + trigger=MyTrigger(bundle_name=bundle_name), # Pass in the bundle name to be used, as needed + ) + ], ) diff --git a/task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py b/task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py index 56711423b0b6..8b41f3de6180 100644 --- a/task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py +++ b/task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py @@ -28,8 +28,6 @@ @pytest.fixture(autouse=True) def _isolate_bundle_name(): - # patch.dict also undoes the variable the context manager leaves set, which monkeypatch.delenv - # would not track when the variable was absent to begin with. with mock.patch.dict(os.environ): os.environ.pop(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, None) yield From 280f4fcc69040ea60a5e733f2561388273fce4b8 Mon Sep 17 00:00:00 2001 From: Jake McGrath Date: Tue, 24 Nov 2026 11:50:30 -0500 Subject: [PATCH 4/6] feature/add-bundle-name-to-parsing-context: Updating docs, tests --- .../docs/howto/dynamic-dag-generation.rst | 24 +++++++++++++++---- .../unit/dag_processing/test_processor.py | 14 +++++++---- .../_internal/test_dag_parsing_context.py | 9 +++++++ .../execution_time/test_task_runner.py | 12 +++++++--- 4 files changed, 47 insertions(+), 12 deletions(-) diff --git a/airflow-core/docs/howto/dynamic-dag-generation.rst b/airflow-core/docs/howto/dynamic-dag-generation.rst index dec68826cccb..274c8a9095e6 100644 --- a/airflow-core/docs/howto/dynamic-dag-generation.rst +++ b/airflow-core/docs/howto/dynamic-dag-generation.rst @@ -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`` field, described below. .. code-block:: python @@ -214,10 +214,18 @@ of the context are set to ``None``. with DAG(dag_id=dag_id, ...): ... -The context also has a ``bundle_name`` field holding the name of the Dag bundle the file is being parsed from. It is -set both when the Dag File Processor parses the file and when a task re-parses its Dag file before execution and, -like ``dag_id`` and ``task_id``, it stays set while the task runs. 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: +The ``bundle_name`` field holds the configured name of the Dag bundle the file is being parsed from (not the +bundle version). It is set when the Dag File Processor parses the file (including when it runs Dag callbacks) +and when a task re-parses its Dag file before execution. 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`` everywhere else, including ``airflow dags test``, ``airflow dags reserialize``, ``DAG.test()`` +and a plain ``DagBag`` in your own scripts or tests. Airflow versions that predate this field do not have the +attribute 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 @@ -234,3 +242,9 @@ to triggers created at parse time, which otherwise have no way to know which bun ) ], ) + +.. warning:: + + In this example, the bundle name becomes part of the trigger's arguments. If the same file is also serialized + through a path where ``bundle_name`` is ``None`` (such as ``airflow dags reserialize``), the stored trigger + and Dag version change until the Dag File Processor parses the file again. diff --git a/airflow-core/tests/unit/dag_processing/test_processor.py b/airflow-core/tests/unit/dag_processing/test_processor.py index d6cb58fd7a40..69a5b0590029 100644 --- a/airflow-core/tests/unit/dag_processing/test_processor.py +++ b/airflow-core/tests/unit/dag_processing/test_processor.py @@ -78,6 +78,7 @@ from airflow.sdk.api.client import Client from airflow.sdk.api.datamodels._generated import ConnectionResponse, DagRunState, VariableResponse from airflow.sdk.definitions._internal.loop import create_loop +from airflow.sdk.definitions.context import _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, get_parsing_context from airflow.sdk.execution_time import comms, supervisor from airflow.sdk.execution_time.comms import ( GetConnection, @@ -144,6 +145,14 @@ def inprocess_client(): return client +@pytest.fixture(autouse=True) +def _isolated_bundle_name_env(): + # The parsing context deliberately leaves bundle_name set after parsing, so undo it per test. + with patch.dict(os.environ): + os.environ.pop(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, None) + yield + + @pytest.mark.usefixtures("disable_load_example") class TestDagFileProcessor: def _process_file( @@ -854,11 +863,8 @@ def fail_to_serialize_unserializable(dag): ] -@patch.dict(os.environ) def test_parse_file_sets_bundle_name_in_parsing_context(tmp_path): - from airflow.sdk.definitions.context import _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME - - os.environ.pop(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, None) + """The bundle_name should be set when the DAG is parsed.""" dag_file = tmp_path / "bundle_name_dag.py" dag_file.write_text( "from airflow.sdk import DAG, get_parsing_context\n" diff --git a/task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py b/task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py index 8b41f3de6180..4d33cb214094 100644 --- a/task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py +++ b/task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py @@ -53,3 +53,12 @@ def test_context_manager_sets_bundle_name(previous, expected_after): assert get_parsing_context().bundle_name == "my-bundle" assert get_parsing_context().bundle_name == expected_after + + +def test_context_manager_without_bundle_name_keeps_existing_value(): + os.environ[_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME] = "outer-bundle" + + with _airflow_parsing_context_manager(dag_id="my_dag"): + assert get_parsing_context().bundle_name == "outer-bundle" + + assert get_parsing_context().bundle_name == "outer-bundle" diff --git a/task-sdk/tests/task_sdk/execution_time/test_task_runner.py b/task-sdk/tests/task_sdk/execution_time/test_task_runner.py index 60def1e2cefe..7a384880fe9f 100644 --- a/task-sdk/tests/task_sdk/execution_time/test_task_runner.py +++ b/task-sdk/tests/task_sdk/execution_time/test_task_runner.py @@ -90,6 +90,7 @@ from airflow.sdk.definitions._internal.loop import create_loop from airflow.sdk.definitions._internal.types import NOTSET, SET_DURING_EXECUTION, is_arg_set from airflow.sdk.definitions.asset import Asset, AssetAlias, AssetUniqueKey, AssetUriRef, Dataset, Model +from airflow.sdk.definitions.context import _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME from airflow.sdk.definitions.param import DagParam from airflow.sdk.definitions.retry_policy import ( ExceptionRetryPolicy, @@ -222,6 +223,14 @@ import time_machine +@pytest.fixture(autouse=True) +def _isolated_bundle_name_env(): + # startup() deliberately leaves the parsing context bundle_name set, so undo it per test. + with mock.patch.dict(os.environ): + os.environ.pop(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, None) + yield + + @pytest.fixture(autouse=True) def _clear_structlog_contextvars(): # startup() binds TI identifiers for the life of the worker process; we need to clear them else other tests will be impacted. @@ -958,7 +967,6 @@ def test_parse_module_in_bundle_root(tmp_path: Path, make_ti_context): pytest.param(False, None, None, None, id="parse"), ], ) -@mock.patch.dict(os.environ) @mock.patch("airflow.sdk.execution_time.task_runner.get_listener_manager") @mock.patch("airflow.dag_processing.dagbag.BundleDagBag") @mock.patch("airflow.sdk.execution_time.bundles.DagBundlesManager") @@ -976,7 +984,6 @@ def test_bundle_initialize_parsing_context( ): from airflow.sdk import get_parsing_context from airflow.sdk.definitions.context import ( - _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, _AIRFLOW_PARSING_CONTEXT_DAG_ID, _AIRFLOW_PARSING_CONTEXT_TASK_ID, ) @@ -1018,7 +1025,6 @@ def capture_parsing_context(): monkeypatch.delenv(_AIRFLOW_PARSING_CONTEXT_DAG_ID, raising=False) monkeypatch.delenv(_AIRFLOW_PARSING_CONTEXT_TASK_ID, raising=False) - monkeypatch.delenv(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, raising=False) if use_startup: startup(what) From ec99d86e0b3d165f7ab0d654c7db5d12edfaecb7 Mon Sep 17 00:00:00 2001 From: Jake McGrath Date: Wed, 25 Nov 2026 13:07:25 -0500 Subject: [PATCH 5/6] feature/add-bundle-name-to-parsing-context: Fixing CI checks --- airflow-core/tests/unit/dag_processing/test_processor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/airflow-core/tests/unit/dag_processing/test_processor.py b/airflow-core/tests/unit/dag_processing/test_processor.py index 69a5b0590029..055fd3c8a7b7 100644 --- a/airflow-core/tests/unit/dag_processing/test_processor.py +++ b/airflow-core/tests/unit/dag_processing/test_processor.py @@ -78,7 +78,7 @@ from airflow.sdk.api.client import Client from airflow.sdk.api.datamodels._generated import ConnectionResponse, DagRunState, VariableResponse from airflow.sdk.definitions._internal.loop import create_loop -from airflow.sdk.definitions.context import _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, get_parsing_context +from airflow.sdk.definitions.context import _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME from airflow.sdk.execution_time import comms, supervisor from airflow.sdk.execution_time.comms import ( GetConnection, From 0abde91c9ad18dbb500e6103586a03bb130e2c0e Mon Sep 17 00:00:00 2001 From: Jake McGrath Date: Wed, 2 Dec 2026 11:45:01 -0500 Subject: [PATCH 6/6] feature/add-bundle-name-to-parsing-context: BundleDagBag now sets the parsing context --- .../docs/howto/dynamic-dag-generation.rst | 25 +++----- .../src/airflow/dag_processing/dagbag.py | 7 ++ .../src/airflow/dag_processing/processor.py | 14 ++-- .../tests/unit/dag_processing/test_dagbag.py | 25 ++++++++ .../unit/dag_processing/test_processor.py | 26 -------- .../_internal/dag_parsing_context.py | 18 +----- .../src/airflow/sdk/definitions/context.py | 11 ++-- .../airflow/sdk/execution_time/task_runner.py | 4 +- .../_internal/test_dag_parsing_context.py | 64 ------------------- .../task_sdk/definitions/test_context.py | 26 +++++++- .../execution_time/test_task_runner.py | 25 ++------ 11 files changed, 86 insertions(+), 159 deletions(-) delete mode 100644 task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py diff --git a/airflow-core/docs/howto/dynamic-dag-generation.rst b/airflow-core/docs/howto/dynamic-dag-generation.rst index 274c8a9095e6..007e956b6ada 100644 --- a/airflow-core/docs/howto/dynamic-dag-generation.rst +++ b/airflow-core/docs/howto/dynamic-dag-generation.rst @@ -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``. The context also has a ``bundle_name`` field, described below. +of the context are set to ``None``. The context also has a ``bundle_name`` property, described below. .. code-block:: python @@ -214,14 +214,15 @@ of the context are set to ``None``. The context also has a ``bundle_name`` field with DAG(dag_id=dag_id, ...): ... -The ``bundle_name`` field holds the configured name of the Dag bundle the file is being parsed from (not the -bundle version). It is set when the Dag File Processor parses the file (including when it runs Dag callbacks) -and when a task re-parses its Dag file before execution. Like ``dag_id`` and ``task_id``, it is not unset once -parsing finishes, so it is still available while the task runs. +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`` everywhere else, including ``airflow dags test``, ``airflow dags reserialize``, ``DAG.test()`` -and a plain ``DagBag`` in your own scripts or tests. Airflow versions that predate this field do not have the -attribute at all, so code that must run on them should use ``getattr(get_parsing_context(), "bundle_name", None)``. +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 @@ -238,13 +239,7 @@ no way to know which bundle they came from. ``MyEventTrigger`` below stands for watchers=[ AssetWatcher( name="my_watcher", - trigger=MyTrigger(bundle_name=bundle_name), # Pass in the bundle name to be used, as needed + trigger=MyEventTrigger(bundle_name=bundle_name), # Pass in the bundle name to be used, as needed ) ], ) - -.. warning:: - - In this example, the bundle name becomes part of the trigger's arguments. If the same file is also serialized - through a path where ``bundle_name`` is ``None`` (such as ``airflow dags reserialize``), the stored trigger - and Dag version change until the Dag File Processor parses the file again. diff --git a/airflow-core/src/airflow/dag_processing/dagbag.py b/airflow-core/src/airflow/dag_processing/dagbag.py index dc80433676ca..c93f88aab30c 100644 --- a/airflow-core/src/airflow/dag_processing/dagbag.py +++ b/airflow-core/src/airflow/dag_processing/dagbag.py @@ -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 @@ -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) diff --git a/airflow-core/src/airflow/dag_processing/processor.py b/airflow-core/src/airflow/dag_processing/processor.py index 6661fd7b5c2a..199b12edbb44 100644 --- a/airflow-core/src/airflow/dag_processing/processor.py +++ b/airflow-core/src/airflow/dag_processing/processor.py @@ -43,7 +43,6 @@ from airflow.dag_processing.bundles.base import BundleVersionLock from airflow.dag_processing.dagbag import BundleDagBag, DagBag, LangSDKSerializedDAG from airflow.models.dag import DagModel -from airflow.sdk.definitions._internal.dag_parsing_context import _airflow_parsing_context_manager # noqa: SDK001 from airflow.sdk.exceptions import TaskNotFound from airflow.sdk.execution_time import supervisor from airflow.sdk.execution_time.comms import ( @@ -250,13 +249,12 @@ def _parse_file(msg: DagFileParseRequest, log: FilteringBoundLogger) -> DagFileP import_errors=stability_check_error_dict, ) - with _airflow_parsing_context_manager(bundle_name=msg.bundle_name): - bag = BundleDagBag( - dag_folder=msg.file, - bundle_path=msg.bundle_path, - bundle_name=msg.bundle_name, - load_op_links=False, - ) + bag = BundleDagBag( + dag_folder=msg.file, + bundle_path=msg.bundle_path, + bundle_name=msg.bundle_name, + load_op_links=False, + ) if msg.callback_requests: # If the request is for callback, we shouldn't serialize the Dags diff --git a/airflow-core/tests/unit/dag_processing/test_dagbag.py b/airflow-core/tests/unit/dag_processing/test_dagbag.py index 7bcd745c24cd..f298ee87a039 100644 --- a/airflow-core/tests/unit/dag_processing/test_dagbag.py +++ b/airflow-core/tests/unit/dag_processing/test_dagbag.py @@ -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, @@ -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() diff --git a/airflow-core/tests/unit/dag_processing/test_processor.py b/airflow-core/tests/unit/dag_processing/test_processor.py index 055fd3c8a7b7..d40ec9c7d07b 100644 --- a/airflow-core/tests/unit/dag_processing/test_processor.py +++ b/airflow-core/tests/unit/dag_processing/test_processor.py @@ -78,7 +78,6 @@ from airflow.sdk.api.client import Client from airflow.sdk.api.datamodels._generated import ConnectionResponse, DagRunState, VariableResponse from airflow.sdk.definitions._internal.loop import create_loop -from airflow.sdk.definitions.context import _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME from airflow.sdk.execution_time import comms, supervisor from airflow.sdk.execution_time.comms import ( GetConnection, @@ -145,14 +144,6 @@ def inprocess_client(): return client -@pytest.fixture(autouse=True) -def _isolated_bundle_name_env(): - # The parsing context deliberately leaves bundle_name set after parsing, so undo it per test. - with patch.dict(os.environ): - os.environ.pop(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, None) - yield - - @pytest.mark.usefixtures("disable_load_example") class TestDagFileProcessor: def _process_file( @@ -863,23 +854,6 @@ def fail_to_serialize_unserializable(dag): ] -def test_parse_file_sets_bundle_name_in_parsing_context(tmp_path): - """The bundle_name should be set when the DAG is parsed.""" - 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" - ) - - result = _parse_file( - DagFileParseRequest(file=str(dag_file), bundle_path=tmp_path, bundle_name="my-bundle"), - log=structlog.get_logger(), - ) - - assert [dag.dag_id for dag in result.serialized_dags] == ["from_my-bundle"] - - def test_callback_processing_does_not_update_timestamps(): """Callback processing should not update last_finish_time to prevent stale DAG detection.""" stat = process_parse_results( diff --git a/task-sdk/src/airflow/sdk/definitions/_internal/dag_parsing_context.py b/task-sdk/src/airflow/sdk/definitions/_internal/dag_parsing_context.py index 39cc99ca8a8c..cad4f9918592 100644 --- a/task-sdk/src/airflow/sdk/definitions/_internal/dag_parsing_context.py +++ b/task-sdk/src/airflow/sdk/definitions/_internal/dag_parsing_context.py @@ -19,32 +19,18 @@ import os from contextlib import contextmanager -from airflow.sdk.definitions.context import ( - _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, - _AIRFLOW_PARSING_CONTEXT_DAG_ID, - _AIRFLOW_PARSING_CONTEXT_TASK_ID, -) +from airflow.sdk.definitions.context import _AIRFLOW_PARSING_CONTEXT_DAG_ID, _AIRFLOW_PARSING_CONTEXT_TASK_ID @contextmanager -def _airflow_parsing_context_manager( - dag_id: str | None = None, task_id: str | None = None, bundle_name: str | None = None -): +def _airflow_parsing_context_manager(dag_id: str | None = None, task_id: str | None = None): old_dag_id = os.environ.get(_AIRFLOW_PARSING_CONTEXT_DAG_ID) old_task_id = os.environ.get(_AIRFLOW_PARSING_CONTEXT_TASK_ID) - old_bundle_name = os.environ.get(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME) - if dag_id is not None: os.environ[_AIRFLOW_PARSING_CONTEXT_DAG_ID] = dag_id if task_id is not None: os.environ[_AIRFLOW_PARSING_CONTEXT_TASK_ID] = task_id - if bundle_name is not None: - os.environ[_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME] = bundle_name - yield - - if old_bundle_name is not None: - os.environ[_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME] = old_bundle_name if old_task_id is not None: os.environ[_AIRFLOW_PARSING_CONTEXT_TASK_ID] = old_task_id if old_dag_id is not None: diff --git a/task-sdk/src/airflow/sdk/definitions/context.py b/task-sdk/src/airflow/sdk/definitions/context.py index 6f747694989d..1b317ac4f0b7 100644 --- a/task-sdk/src/airflow/sdk/definitions/context.py +++ b/task-sdk/src/airflow/sdk/definitions/context.py @@ -176,15 +176,17 @@ class AirflowParsingContext(NamedTuple): If these values are not None, they will contain the specific Dag and Task ID that Airflow is requesting to execute. You can use these for optimizing dynamically generated Dag files. - ``bundle_name`` is the name of the Dag bundle the file is being parsed from. It is set both when the - Dag processor parses the file and when a task re-parses its Dag file before execution. - You can obtain the current values via :py:func:`.get_parsing_context`. """ dag_id: str | None task_id: str | None - bundle_name: str | None = 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" @@ -197,7 +199,6 @@ def get_parsing_context() -> AirflowParsingContext: return AirflowParsingContext( dag_id=os.environ.get(_AIRFLOW_PARSING_CONTEXT_DAG_ID), task_id=os.environ.get(_AIRFLOW_PARSING_CONTEXT_TASK_ID), - bundle_name=os.environ.get(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME), ) diff --git a/task-sdk/src/airflow/sdk/execution_time/task_runner.py b/task-sdk/src/airflow/sdk/execution_time/task_runner.py index 7e6ef17e558b..c1c40180554f 100644 --- a/task-sdk/src/airflow/sdk/execution_time/task_runner.py +++ b/task-sdk/src/airflow/sdk/execution_time/task_runner.py @@ -1347,9 +1347,7 @@ def startup(msg: StartupDetails) -> tuple[RuntimeTaskInstance, Context, Logger]: set_current_team_name(msg.ti_context.dag_run.team_name) - with _airflow_parsing_context_manager( - dag_id=msg.ti.dag_id, task_id=msg.ti.task_id, bundle_name=msg.bundle_info.name - ): + with _airflow_parsing_context_manager(dag_id=msg.ti.dag_id, task_id=msg.ti.task_id): ti = parse(msg, log) log.debug("Dag file parsed", file=msg.dag_rel_path) diff --git a/task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py b/task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py deleted file mode 100644 index 4d33cb214094..000000000000 --- a/task-sdk/tests/task_sdk/definitions/_internal/test_dag_parsing_context.py +++ /dev/null @@ -1,64 +0,0 @@ -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -from __future__ import annotations - -import os -from unittest import mock - -import pytest - -from airflow.sdk import get_parsing_context -from airflow.sdk.definitions._internal.dag_parsing_context import _airflow_parsing_context_manager -from airflow.sdk.definitions.context import _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, AirflowParsingContext - - -@pytest.fixture(autouse=True) -def _isolate_bundle_name(): - with mock.patch.dict(os.environ): - os.environ.pop(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, None) - yield - - -def test_bundle_name_defaults_to_none(): - assert get_parsing_context().bundle_name is None - assert AirflowParsingContext(dag_id="d", task_id="t").bundle_name is None - - -@pytest.mark.parametrize( - ("previous", "expected_after"), - [ - pytest.param(None, "my-bundle", id="stays-set-without-previous-value"), - pytest.param("outer-bundle", "outer-bundle", id="restores-previous-value"), - ], -) -def test_context_manager_sets_bundle_name(previous, expected_after): - if previous is not None: - os.environ[_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME] = previous - - with _airflow_parsing_context_manager(bundle_name="my-bundle"): - assert get_parsing_context().bundle_name == "my-bundle" - - assert get_parsing_context().bundle_name == expected_after - - -def test_context_manager_without_bundle_name_keeps_existing_value(): - os.environ[_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME] = "outer-bundle" - - with _airflow_parsing_context_manager(dag_id="my_dag"): - assert get_parsing_context().bundle_name == "outer-bundle" - - assert get_parsing_context().bundle_name == "outer-bundle" diff --git a/task-sdk/tests/task_sdk/definitions/test_context.py b/task-sdk/tests/task_sdk/definitions/test_context.py index dc25ec378bde..7cf1908ea93c 100644 --- a/task-sdk/tests/task_sdk/definitions/test_context.py +++ b/task-sdk/tests/task_sdk/definitions/test_context.py @@ -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: @@ -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 diff --git a/task-sdk/tests/task_sdk/execution_time/test_task_runner.py b/task-sdk/tests/task_sdk/execution_time/test_task_runner.py index 6c2f1b422679..109b3a9dff06 100644 --- a/task-sdk/tests/task_sdk/execution_time/test_task_runner.py +++ b/task-sdk/tests/task_sdk/execution_time/test_task_runner.py @@ -90,7 +90,6 @@ from airflow.sdk.definitions._internal.loop import create_loop from airflow.sdk.definitions._internal.types import NOTSET, SET_DURING_EXECUTION, is_arg_set from airflow.sdk.definitions.asset import Asset, AssetAlias, AssetUniqueKey, AssetUriRef, Dataset, Model -from airflow.sdk.definitions.context import _AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME from airflow.sdk.definitions.param import DagParam from airflow.sdk.definitions.retry_policy import ( ExceptionRetryPolicy, @@ -225,14 +224,6 @@ import time_machine -@pytest.fixture(autouse=True) -def _isolated_bundle_name_env(): - # startup() deliberately leaves the parsing context bundle_name set, so undo it per test. - with mock.patch.dict(os.environ): - os.environ.pop(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME, None) - yield - - @pytest.fixture(autouse=True) def _clear_structlog_contextvars(): # startup() binds TI identifiers for the life of the worker process; we need to clear them else other tests will be impacted. @@ -963,10 +954,10 @@ def test_parse_module_in_bundle_root(tmp_path: Path, make_ti_context): @pytest.mark.parametrize( - ("use_startup", "expected_dag_id", "expected_task_id", "expected_bundle_name"), + ("use_startup", "expected_dag_id", "expected_task_id"), [ - pytest.param(True, "expected_dag", "my_task", "my-bundle", id="startup"), - pytest.param(False, None, None, None, id="parse"), + pytest.param(True, "expected_dag", "my_task", id="startup"), + pytest.param(False, None, None, id="parse"), ], ) @mock.patch("airflow.sdk.execution_time.task_runner.get_listener_manager") @@ -979,7 +970,6 @@ def test_bundle_initialize_parsing_context( use_startup, expected_dag_id, expected_task_id, - expected_bundle_name, make_ti_context, tmp_path: Path, monkeypatch, @@ -998,7 +988,6 @@ def capture_parsing_context(): ctx = get_parsing_context() captured["dag_id"] = ctx.dag_id captured["task_id"] = ctx.task_id - captured["bundle_name"] = ctx.bundle_name mock_bundle.initialize.side_effect = capture_parsing_context mock_manager = mock_manager_cls.return_value @@ -1033,13 +1022,7 @@ def capture_parsing_context(): else: parse(what, mock.Mock()) - assert captured == { - "dag_id": expected_dag_id, - "task_id": expected_task_id, - "bundle_name": expected_bundle_name, - } - # Like dag_id/task_id, bundle_name stays set after startup so it is visible during task execution. - assert os.environ.get(_AIRFLOW_PARSING_CONTEXT_BUNDLE_NAME) == expected_bundle_name + assert captured == {"dag_id": expected_dag_id, "task_id": expected_task_id} mock_bundle.initialize.assert_called_once()