This is an automated email from the ASF dual-hosted git repository.
o-nikolas pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new 5bd82adc714 Add a shared deprecation helper to the Amazon provider
(#77574)
5bd82adc714 is described below
commit 5bd82adc7140a28cb678e9b63492fda8ca6714d8
Author: Ramit Kataria <[email protected]>
AuthorDate: Fri Nov 27 12:20:16 2026 -0700
Add a shared deprecation helper to the Amazon provider (#77574)
Airflow shows a DeprecationWarning only when it is attributed to an
`airflow` module. An inline `warnings.warn(..., stacklevel=2)` in an
operator `__init__` or a hook method is attributed to the Dag file or
the hook's caller, so Python's default filters drop it and users first
hear of the change when the old behaviour is removed.
`warn_deprecated()` gives the filters the provider module's name, so the
warning is shown on Airflow 2.11 and 3. It points at the user's line
when user code called the provider directly, and at the provider code
otherwise.
The helper also has a switch for the 10.0.0 changes, off in every 9.x
release. With it on, a deprecation due in 10.0.0 raises
`RemovedFeatureError` (an `AirflowException` and a `TypeError`) instead
of warning. Removals can then merge to `main` early without forcing the
next release to be 10.0.0; one last PR turns the switch on.
Nothing uses the helper yet. The deprecation policy page's example now
uses it. The upgrade guide page the warning links to is added in its own
PR, before the first such warning is released.
related: #77273
---
providers/amazon/docs/deprecation-policy.rst | 11 +-
.../src/airflow/providers/amazon/aws/exceptions.py | 8 +
.../providers/amazon/aws/utils/deprecation.py | 133 +++++++++++
.../tests/unit/amazon/aws/test_exceptions.py | 2 +
.../unit/amazon/aws/utils/test_deprecation.py | 244 +++++++++++++++++++++
5 files changed, 391 insertions(+), 7 deletions(-)
diff --git a/providers/amazon/docs/deprecation-policy.rst
b/providers/amazon/docs/deprecation-policy.rst
index 49e7c745a76..cb348fed545 100644
--- a/providers/amazon/docs/deprecation-policy.rst
+++ b/providers/amazon/docs/deprecation-policy.rst
@@ -40,15 +40,12 @@ A class, method, parameter or behaviour is deprecated
before it is removed or ch
.. code-block:: python
- import warnings
-
- from airflow.exceptions import AirflowProviderDeprecationWarning
+ from airflow.providers.amazon.aws.utils.deprecation import
NEXT_MAJOR_VERSION, warn_deprecated
if region is not None:
- warnings.warn(
- message="Parameter `region` is deprecated. Use the parameter
`region_name` instead",
- category=AirflowProviderDeprecationWarning,
- stacklevel=2,
+ warn_deprecated(
+ "Parameter `region` is deprecated. Use the parameter
`region_name` instead.",
+ removal_version=NEXT_MAJOR_VERSION,
)
kwargs["region_name"] = region
diff --git a/providers/amazon/src/airflow/providers/amazon/aws/exceptions.py
b/providers/amazon/src/airflow/providers/amazon/aws/exceptions.py
index 457f0ae69c1..6a09b799228 100644
--- a/providers/amazon/src/airflow/providers/amazon/aws/exceptions.py
+++ b/providers/amazon/src/airflow/providers/amazon/aws/exceptions.py
@@ -50,6 +50,14 @@ class EcsOperatorError(Exception):
return EcsOperatorError, (self.failures, self.message)
+class RemovedFeatureError(AirflowException, TypeError):
+ """
+ Raise when code uses something that this version of the Amazon provider
has removed.
+
+ ``TypeError`` is what Airflow 3 raises for an operator argument that does
not exist.
+ """
+
+
class S3HookUriParseFailure(AirflowException):
"""When parse_s3_url fails to parse URL, this error is thrown."""
diff --git
a/providers/amazon/src/airflow/providers/amazon/aws/utils/deprecation.py
b/providers/amazon/src/airflow/providers/amazon/aws/utils/deprecation.py
new file mode 100644
index 00000000000..092e0f50093
--- /dev/null
+++ b/providers/amazon/src/airflow/providers/amazon/aws/utils/deprecation.py
@@ -0,0 +1,133 @@
+# 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 sys
+import warnings
+from typing import TYPE_CHECKING
+
+from airflow.exceptions import AirflowProviderDeprecationWarning
+from airflow.providers.amazon.aws.exceptions import RemovedFeatureError
+
+if TYPE_CHECKING:
+ from types import FrameType
+
+UPGRADE_GUIDE_URL =
"https://airflow.apache.org/docs/apache-airflow-providers-amazon/stable/upgrading.html"
+
+NEXT_MAJOR_VERSION = "10.0.0"
+
+# Off in every release before ``NEXT_MAJOR_VERSION``; the pull request that
releases that version turns it
+# on. It is not derived from the provider version, which can be bumped to a
major for an unrelated
+# breaking change. Tests patch it to cover both settings.
+_NEXT_MAJOR_ENABLED = False
+
+
+def is_next_major_enabled() -> bool:
+ """
+ Tell whether provider code behaves the way it does in
``NEXT_MAJOR_VERSION``.
+
+ Code whose behaviour changes in that version carries both behaviours and
asks this each time it
+ runs. Reading it at import time would fix the answer before a test can
change it.
+ """
+ return _NEXT_MAJOR_ENABLED
+
+
+def _get_module_name(frame: FrameType) -> str:
+ return frame.f_globals.get("__name__", "")
+
+
+def _is_provider_code(frame: FrameType) -> bool:
+ return _get_module_name(frame).startswith("airflow.providers.")
+
+
+def _is_airflow_code(frame: FrameType) -> bool:
+ name = _get_module_name(frame)
+ return name == "airflow" or name.startswith("airflow.")
+
+
+def _is_user_code(frame: FrameType) -> bool:
+ if _is_airflow_code(frame) or _get_module_name(frame).partition(".")[0] in
sys.stdlib_module_names:
+ return False
+ filename = frame.f_code.co_filename
+ return "site-packages" not in filename and "dist-packages" not in filename
+
+
+def _find_user_caller(provider_frame: FrameType) -> FrameType | None:
+ """
+ Return the frame of the user code that called the provider directly, if
there is one.
+
+ There is none when Airflow calls the provider code, as it does for
``execute``, ``poke`` and a
+ trigger's ``run``, or when the call comes through the standard library or
an installed library. The
+ frame that would be found by walking further up in those cases is whatever
started the task or the
+ wrapper that made the call, not the code that has to change.
+ """
+ caller: FrameType | None = provider_frame
+ while caller and _is_provider_code(caller):
+ called, caller = caller, caller.f_back
+ # ``BaseOperatorMeta`` wraps every operator ``__init__``, which puts
one frame of Airflow's own
+ # between a provider ``__init__`` and the code that instantiates the
operator.
+ if (
+ caller
+ and called.f_code.co_name == "__init__"
+ and _is_airflow_code(caller)
+ and not _is_provider_code(caller)
+ ):
+ caller = caller.f_back
+ return caller if caller and _is_user_code(caller) else None
+
+
+def warn_deprecated(message: str, *, removal_version: str) -> None:
+ """
+ Warn that the calling provider code ran a deprecated behaviour.
+
+ Call this from the provider function that implements the deprecated
behaviour, instead of calling
+ ``warnings.warn`` there. Airflow shows a ``DeprecationWarning`` only when
it is attributed to an
+ ``airflow`` module, so one that ``stacklevel`` attributes to a Dag file or
to other user code is
+ dropped by Python's default filters. This warning always passes those
filters. It points at the line
+ of user code that called the provider when there is one, and at the
calling provider code otherwise.
+
+ Once ``is_next_major_enabled()`` is true, a deprecation that names
``NEXT_MAJOR_VERSION`` raises
+ instead, so the deprecated code acts as removed until it is deleted.
+
+ :param message: What is deprecated and what to use instead. The removal
release and a link to the
+ upgrade guide are appended.
+ :param removal_version: The Amazon provider release that removes the
deprecated behaviour. Pass
+ ``NEXT_MAJOR_VERSION`` instead of a literal: searching for it lists
everything that release
+ removes, and if that release has to move, one line moves every removal
with it.
+ :raises RemovedFeatureError: When ``removal_version`` is
``NEXT_MAJOR_VERSION`` and
+ ``is_next_major_enabled()`` is true.
+ """
+ if removal_version == NEXT_MAJOR_VERSION and is_next_major_enabled():
+ raise RemovedFeatureError(
+ f"{message} The deprecated behaviour was removed in version
{removal_version} of the "
+ f"Amazon provider. See {UPGRADE_GUIDE_URL}"
+ )
+ provider_frame = sys._getframe(1)
+ frame = _find_user_caller(provider_frame) or provider_frame
+ warnings.warn_explicit(
+ f"{message} The deprecated behaviour will be removed in version
{removal_version} of the "
+ f"Amazon provider. See {UPGRADE_GUIDE_URL}",
+ AirflowProviderDeprecationWarning,
+ filename=frame.f_code.co_filename,
+ lineno=frame.f_lineno,
+ # The filters match on this name and not on the file, so the provider
module gets the warning
+ # shown even when the line it points at is in user code.
+ module=_get_module_name(provider_frame),
+ # Without a registry every call is shown, including each iteration of
a loop.
+ registry=frame.f_globals.setdefault("__warningregistry__", {}),
+ module_globals=frame.f_globals,
+ )
diff --git a/providers/amazon/tests/unit/amazon/aws/test_exceptions.py
b/providers/amazon/tests/unit/amazon/aws/test_exceptions.py
index 3714019eedb..5ce685f33d7 100644
--- a/providers/amazon/tests/unit/amazon/aws/test_exceptions.py
+++ b/providers/amazon/tests/unit/amazon/aws/test_exceptions.py
@@ -36,6 +36,7 @@ from airflow.providers.amazon.aws.exceptions import (
NeptuneImportTaskFailedError,
NeptunePrivateEndpointCreationFailedError,
NeptunePrivateEndpointDeletionFailedError,
+ RemovedFeatureError,
S3HookPathTraversalError,
S3HookUriParseFailure,
WaiterMaxAttemptsError,
@@ -52,6 +53,7 @@ ECS_FAILURES = [
LAST_RESPONSE = {"Cluster": {"Status": "FAILED", "StatusReason": "Insufficient
capacity"}}
AIRFLOW_EXCEPTION_SUBCLASSES = [
+ RemovedFeatureError,
S3HookUriParseFailure,
S3HookPathTraversalError,
NeptuneGraphCreationFailedError,
diff --git a/providers/amazon/tests/unit/amazon/aws/utils/test_deprecation.py
b/providers/amazon/tests/unit/amazon/aws/utils/test_deprecation.py
new file mode 100644
index 00000000000..3e99f7a58f2
--- /dev/null
+++ b/providers/amazon/tests/unit/amazon/aws/utils/test_deprecation.py
@@ -0,0 +1,244 @@
+# 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 importlib.util
+import re
+import sys
+import warnings
+from collections.abc import Iterator
+from contextlib import contextmanager
+from typing import TYPE_CHECKING
+from unittest import mock
+
+import pytest
+
+from airflow.exceptions import AirflowProviderDeprecationWarning
+from airflow.providers.amazon.aws.exceptions import RemovedFeatureError
+from airflow.providers.amazon.aws.utils import deprecation
+from airflow.providers.amazon.aws.utils.deprecation import (
+ NEXT_MAJOR_VERSION,
+ UPGRADE_GUIDE_URL,
+ is_next_major_enabled,
+ warn_deprecated,
+)
+from airflow.providers.common.compat.sdk import AirflowException
+
+from tests_common.test_utils.version_compat import AIRFLOW_V_3_2_PLUS
+
+if AIRFLOW_V_3_2_PLUS:
+ from airflow.dag_processing.dagbag import DagBag
+else:
+ from airflow.models.dagbag import DagBag # type: ignore[no-redef,
attribute-defined]
+
+if TYPE_CHECKING:
+ from pathlib import Path
+ from types import ModuleType
+
+PROVIDER_MODULE = "airflow.providers.amazon.aws.deprecation_probe"
+PROVIDER_SOURCE = """
+from airflow.providers.amazon.aws.utils.deprecation import NEXT_MAJOR_VERSION,
warn_deprecated
+from airflow.providers.common.compat.sdk import BaseOperator
+
+
+class ProbeOperator(BaseOperator):
+ def __init__(self, *, old=None, **kwargs):
+ super().__init__(**kwargs)
+ if old is not None:
+ warn_deprecated("`old` is deprecated. Use `new` instead.",
removal_version=NEXT_MAJOR_VERSION)
+
+
+class ProbeSubclassOperator(ProbeOperator):
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+
+def probe_hook_method():
+ warn_deprecated("`probe_hook_method` is deprecated.",
removal_version=NEXT_MAJOR_VERSION)
+"""
+
+DAG_SOURCE = f"""
+from {PROVIDER_MODULE} import ProbeOperator
+from airflow.providers.common.compat.sdk import DAG
+
+with DAG("deprecation_probe", schedule=None):
+ ProbeOperator(task_id="probe", old="value")
+"""
+DAG_OPERATOR_LINE = DAG_SOURCE.splitlines().index('
ProbeOperator(task_id="probe", old="value")') + 1
+
+CALLER_SOURCE = """
+def call(deprecated, **kwargs):
+ return deprecated(**kwargs)
+
+
+def call_twice(deprecated, **kwargs):
+ for _ in range(2):
+ deprecated(**kwargs)
+"""
+CALL_LINE = CALLER_SOURCE.splitlines().index(" return
deprecated(**kwargs)") + 1
+
+OPERATOR_KWARGS = {"task_id": "probe", "old": "value"}
+
+
+def build_message(message: str, *, removal: str, version: str =
NEXT_MAJOR_VERSION) -> str:
+ return (
+ f"{message} The deprecated behaviour {removal} in version {version} of
the Amazon provider. "
+ f"See {UPGRADE_GUIDE_URL}"
+ )
+
+
+def load_module(name: str, path: Path, source: str) -> ModuleType:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(source)
+ spec = importlib.util.spec_from_file_location(name, path)
+ assert spec
+ assert spec.loader
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
[email protected](autouse=True)
+def disable_next_major(monkeypatch):
+ """Pin the switch off, so the tests of the warning also pass once the
switch is turned on."""
+ monkeypatch.setattr(deprecation, "_NEXT_MAJOR_ENABLED", False)
+
+
[email protected]
+def provider(tmp_path) -> ModuleType:
+ return load_module(PROVIDER_MODULE, tmp_path / "deprecation_probe.py",
PROVIDER_SOURCE)
+
+
+@contextmanager
+def airflow_default_filters() -> Iterator[list[warnings.WarningMessage]]:
+ with warnings.catch_warnings(record=True) as recorded:
+ warnings.resetwarnings()
+ # Python ignores DeprecationWarning outside ``__main__``, and Airflow
turns it back on for
+ # ``airflow`` modules only.
+ warnings.simplefilter("ignore", DeprecationWarning)
+ warnings.filterwarnings("default", category=DeprecationWarning,
module="airflow")
+ yield recorded
+
+
[email protected]("enabled", [True, False])
+def test_is_next_major_enabled_reads_the_switch_when_called(monkeypatch,
enabled):
+ monkeypatch.setattr(deprecation, "_NEXT_MAJOR_ENABLED", enabled)
+
+ assert is_next_major_enabled() is enabled
+
+
+def test_warn_deprecated_names_removal_release_and_upgrade_guide():
+ with pytest.warns(AirflowProviderDeprecationWarning) as recorded:
+ warn_deprecated("`old` is deprecated. Use `new` instead.",
removal_version=NEXT_MAJOR_VERSION)
+
+ assert [str(w.message) for w in recorded] == [
+ build_message("`old` is deprecated. Use `new` instead.", removal="will
be removed")
+ ]
+
+
[email protected](deprecation, "_NEXT_MAJOR_ENABLED", new=True)
[email protected]("caught_as", [RemovedFeatureError, AirflowException,
TypeError])
+def
test_warn_deprecated_raises_for_the_next_major_once_it_is_enabled(caught_as):
+ expected = build_message("`old` is deprecated. Use `new` instead.",
removal="was removed")
+
+ with pytest.raises(caught_as, match=re.escape(expected)):
+ warn_deprecated("`old` is deprecated. Use `new` instead.",
removal_version=NEXT_MAJOR_VERSION)
+
+
[email protected](deprecation, "_NEXT_MAJOR_ENABLED", new=True)
+def
test_warn_deprecated_keeps_warning_for_a_later_release_once_next_major_is_enabled():
+ with pytest.warns(AirflowProviderDeprecationWarning) as recorded:
+ warn_deprecated("`old` is deprecated. Use `new` instead.",
removal_version="999.0.0")
+
+ assert [str(w.message) for w in recorded] == [
+ build_message("`old` is deprecated. Use `new` instead.", removal="will
be removed", version="999.0.0")
+ ]
+
+
+def
test_operator_warning_reaches_the_dag_importer_at_the_dag_file_line(tmp_path,
monkeypatch, provider):
+ monkeypatch.setitem(sys.modules, PROVIDER_MODULE, provider)
+ dag_file = tmp_path / "dags" / "my_dag.py"
+ dag_file.parent.mkdir()
+ dag_file.write_text(DAG_SOURCE)
+ dagbag = DagBag(dag_folder=str(dag_file.parent), collect_dags=False)
+
+ with airflow_default_filters():
+ dagbag.process_file(str(dag_file), only_if_updated=False)
+
+ assert dagbag.import_errors == {}
+ assert [warning for captured in dagbag.captured_warnings.values() for
warning in captured] == [
+ f"{dag_file}:{DAG_OPERATOR_LINE}:
airflow.exceptions.AirflowProviderDeprecationWarning: "
+ + build_message("`old` is deprecated. Use `new` instead.",
removal="will be removed")
+ ]
+
+
[email protected](
+ ("deprecated", "kwargs"),
+ [
+ pytest.param("ProbeSubclassOperator", OPERATOR_KWARGS,
id="operator_subclass_param"),
+ pytest.param("probe_hook_method", {}, id="hook_method"),
+ ],
+)
+def test_warning_triggered_by_user_code_is_shown_at_the_user_line(tmp_path,
provider, deprecated, kwargs):
+ # Named the way the Dag importer names a Dag file's module.
+ user_code = load_module("unusual_prefix_0123_my_dag", tmp_path /
"my_dag.py", CALLER_SOURCE)
+
+ with airflow_default_filters() as recorded:
+ user_code.call(getattr(provider, deprecated), **kwargs)
+
+ assert [(w.category, w.filename, w.lineno) for w in recorded] == [
+ (AirflowProviderDeprecationWarning, user_code.__file__, CALL_LINE)
+ ]
+
+
[email protected](
+ ("caller_name", "caller_path", "deprecated", "kwargs"),
+ [
+ pytest.param("airflow.probe_task_runner", "runner.py",
"probe_hook_method", {}, id="airflow"),
+ pytest.param(
+ "airflow.probe_mapped_operator", "mapped.py", "ProbeOperator",
OPERATOR_KWARGS, id="airflow_init"
+ ),
+ pytest.param("functools", "functools.py", "probe_hook_method", {},
id="standard_library"),
+ pytest.param(
+ "probe_retry_library",
+ "site-packages/probe_retry_library.py",
+ "probe_hook_method",
+ {},
+ id="installed_library",
+ ),
+ ],
+)
+def test_warning_not_triggered_by_user_code_is_shown_at_the_provider_code(
+ tmp_path, provider, caller_name, caller_path, deprecated, kwargs
+):
+ caller = load_module(caller_name, tmp_path / caller_path, CALLER_SOURCE)
+
+ with airflow_default_filters() as recorded:
+ caller.call(getattr(provider, deprecated), **kwargs)
+
+ assert [(w.category, w.filename) for w in recorded] == [
+ (AirflowProviderDeprecationWarning, provider.__file__)
+ ]
+
+
+def test_warning_repeated_from_the_same_line_is_shown_once(tmp_path, provider):
+ user_code = load_module("unusual_prefix_0123_my_dag", tmp_path /
"my_dag.py", CALLER_SOURCE)
+
+ with airflow_default_filters() as recorded:
+ user_code.call_twice(provider.probe_hook_method)
+
+ assert len(recorded) == 1