This is an automated email from the ASF dual-hosted git repository.
ferruzzi 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 2274e0c49bc Fix a DeadlineReference parsing race condition (#73299)
2274e0c49bc is described below
commit 2274e0c49bce33087bb14805783249106270c89c
Author: D. Ferruzzi <[email protected]>
AuthorDate: Tue Nov 24 11:31:43 2026 -0700
Fix a DeadlineReference parsing race condition (#73299)
Previously, if two custom references shared a name, the one parsed first
was silently overwritten, so which class a Dag got depended on parse order.
Now if there is a conflict then neither claimant gets the
``DeadlineReference.<Name>`` shorthand. A warning is logged, and using the
shorthand raises an ``AttributeError`` that names every claimant. Both classes
can still be imported directly. An invalid later claim no longer takes the
shorthand away from an earlier valid one.
A saved ``DeadlineReference.TYPES`` value, or a saved decorator such as
``queued = deadline_reference(DeadlineReference.TYPES.DAGRUN_QUEUED)``, can now
be reused across registrations instead of failing with "Invalid deadline
reference type".
``DeadlineReference.register_custom_reference`` is renamed to
``_add_custom_reference_to_namespace``. The old name suggested that calling it
registered the reference, when a plugin is also required. The
``@deadline_reference`` decorator is the documented entry point, so the helper
is now private. The old name still works but emits a deprecation warning.
---
airflow-core/docs/howto/deadline-alerts.rst | 33 ++++
airflow-core/tests/unit/models/test_deadline.py | 185 +++++++++++++++++++++--
task-sdk/src/airflow/sdk/definitions/deadline.py | 175 +++++++++++++++++----
3 files changed, 351 insertions(+), 42 deletions(-)
diff --git a/airflow-core/docs/howto/deadline-alerts.rst
b/airflow-core/docs/howto/deadline-alerts.rst
index 714397dafc0..60fb076b58b 100644
--- a/airflow-core/docs/howto/deadline-alerts.rst
+++ b/airflow-core/docs/howto/deadline-alerts.rst
@@ -511,6 +511,39 @@ other reference:
# Your tasks here
...
+The ``DeadlineReference.<ClassName>`` shorthand hands you an instance
constructed with no arguments,
+so a parameterized reference gets one carrying its defaults. You can also
import the class and
+instantiate it yourself. This works for any custom reference, and it is the
only way to pass values
+to a parameterized one:
+
+.. code-block:: python
+
+ from datetime import timedelta
+ from airflow.sdk import AsyncCallback, DAG, DeadlineAlert
+
+ from deadline_references import MyQueuedReference
+
+ with DAG(
+ dag_id="custom_reference_imported_directly",
+ deadline=DeadlineAlert(
+ reference=MyQueuedReference(),
+ interval=timedelta(hours=2),
+ callback=AsyncCallback(my_callback),
+ ),
+ ):
+ # Your tasks here
+ ...
+
+.. note::
+
+ The shorthand only goes by class name, so if two custom references in
different modules share a
+ class name, neither of them gets it and a warning naming both classes is
logged. Any Dag that
+ uses the shorthand for that name will fail to import with an error such as
+ ``AttributeError: DeadlineReference.MyQueuedReference is claimed by more
than one class``,
+ followed by the names of both classes. To fix it, import the class you
want directly, as shown
+ above. Both references still work and the scheduler can resolve either
one; only the shorthand
+ is unavailable.
+
Multiple Deadline Alerts
^^^^^^^^^^^^^^^^^^^^^^^^
diff --git a/airflow-core/tests/unit/models/test_deadline.py
b/airflow-core/tests/unit/models/test_deadline.py
index 29d7efb9ff0..68881948540 100644
--- a/airflow-core/tests/unit/models/test_deadline.py
+++ b/airflow-core/tests/unit/models/test_deadline.py
@@ -46,6 +46,7 @@ from airflow.sdk.definitions.deadline import (
FixedDatetimeDeadline,
deadline_reference,
)
+from airflow.sdk.exceptions import RemovedInAirflow4Warning
from airflow.serialization.definitions.deadline import
SerializedReferenceModels
from airflow.utils.state import CallbackState, DagRunState
@@ -756,6 +757,20 @@ class TestDeadlineReference:
class TestCustomDeadlineReference:
+ @staticmethod
+ def create_custom_ref_named(name, module):
+ """Build a valid reference class with a chosen ``__name__`` and module
path."""
+ reference = type(
+ name,
+ (BaseDeadlineReference,),
+ {
+ "_evaluate_with": lambda self, **kwargs: None,
+ "serialize_reference": lambda self: {},
+ },
+ )
+ reference.__module__ = module
+ return reference
+
class MyCustomRef(BaseDeadlineReference):
def _evaluate_with(self, *, session: Session, **kwargs) -> datetime:
return timezone.datetime(DEFAULT_DATE)
@@ -780,6 +795,9 @@ class TestCustomDeadlineReference:
DeadlineReference.TYPES.DAGRUN_QUEUED = self.original_dagrun_queued
DeadlineReference.TYPES.DAGRUN = self.original_dagrun
+ DeadlineReference._custom_reference_name_map.clear()
+ DeadlineReference._contested_reference_names.clear()
+
for attr in set(dir(DeadlineReference)):
if attr not in self.original_deadline_attrs:
delattr(DeadlineReference, attr)
@@ -799,12 +817,12 @@ class TestCustomDeadlineReference:
pytest.param(DeadlineReference.TYPES.DAGRUN_QUEUED,
DAGRUN_QUEUED_TIMING, id="dagrun_queued"),
],
)
- def test_register_custom_reference(self, timing,
expected_evaluation_timing, reference):
+ def test_add_custom_reference_to_namespace(self, timing,
expected_evaluation_timing, reference):
if timing is None:
- result = DeadlineReference.register_custom_reference(reference)
+ result =
DeadlineReference._add_custom_reference_to_namespace(reference)
expected_timing = DeadlineReference.TYPES.DAGRUN_CREATED
else:
- result = DeadlineReference.register_custom_reference(reference,
timing)
+ result =
DeadlineReference._add_custom_reference_to_namespace(reference, timing)
expected_timing = timing
assert result is reference
@@ -817,11 +835,11 @@ class TestCustomDeadlineReference:
DeadlineReference.TYPES.DAGRUN_QUEUED,
DeadlineReference.TYPES.DAGRUN_CREATED
)
- def test_register_custom_reference_invalid_inheritance(self):
+ def test_add_custom_reference_invalid_inheritance(self):
with pytest.raises(ValueError, match="must inherit from
BaseDeadlineReference"):
-
DeadlineReference.register_custom_reference(self.MyInvalidCustomRef)
+
DeadlineReference._add_custom_reference_to_namespace(self.MyInvalidCustomRef)
- def test_register_custom_reference_invalid_timing(self):
+ def test_add_custom_reference_invalid_timing(self):
invalid_timing = ("not", "a", "valid", "timing")
with pytest.raises(
@@ -831,18 +849,160 @@ class TestCustomDeadlineReference:
f"must be a valid DeadlineReference.TYPES option."
),
):
- DeadlineReference.register_custom_reference(self.MyCustomRef,
invalid_timing)
+
DeadlineReference._add_custom_reference_to_namespace(self.MyCustomRef,
invalid_timing)
def test_custom_reference_discoverable_on_deadline_reference(self):
# Custom references are only registered on DeadlineReference, not on
ReferenceModels.
# During deserialization, custom refs are discovered via __class_path
in the
# serialized data (using import_string), not through ReferenceModels
lookup.
- DeadlineReference.register_custom_reference(self.MyCustomRef)
+ DeadlineReference._add_custom_reference_to_namespace(self.MyCustomRef)
assert hasattr(DeadlineReference, self.MyCustomRef.__name__)
found_instance = getattr(DeadlineReference, self.MyCustomRef.__name__)
assert isinstance(found_instance, self.MyCustomRef)
+ def test_reparsing_the_same_reference_rebinds_the_shorthand(self):
+ """
+ A Dag re-parse builds a new class object for the same reference.
+
+ The shorthand must point at the new class's instance, not keep the one
belonging to the class
+ object the re-parse replaced.
+ """
+ first = self.create_custom_ref_named("Reparsed", "team_a.refs")
+ DeadlineReference._add_custom_reference_to_namespace(first)
+ assert DeadlineReference.Reparsed.__class__ is first
+
+ second = self.create_custom_ref_named("Reparsed", "team_a.refs")
+ assert second is not first
+ DeadlineReference._add_custom_reference_to_namespace(second)
+
+ assert DeadlineReference.Reparsed.__class__ is second
+
+ def test_reparsing_the_same_reference_replaces_its_types_entry(self):
+ """A re-parse must replace the reference's classification entry rather
than append beside it."""
+ first = self.create_custom_ref_named("Reparsed", "team_a.refs")
+ DeadlineReference._add_custom_reference_to_namespace(first)
+ after_first = DeadlineReference.TYPES.DAGRUN_CREATED
+
+ second = self.create_custom_ref_named("Reparsed", "team_a.refs")
+ DeadlineReference._add_custom_reference_to_namespace(second)
+
+ assert len(DeadlineReference.TYPES.DAGRUN_CREATED) == len(after_first)
+ assert second in DeadlineReference.TYPES.DAGRUN_CREATED
+ assert first not in DeadlineReference.TYPES.DAGRUN_CREATED
+
+ def test_reclassifying_a_reference_moves_it_between_types(self):
+ """Re-registering under a different classification must not leave it
in the one it left."""
+ first = self.create_custom_ref_named("Reclassified", "team_a.refs")
+ DeadlineReference._add_custom_reference_to_namespace(first)
+ assert first in DeadlineReference.TYPES.DAGRUN_CREATED
+
+ second = self.create_custom_ref_named("Reclassified", "team_a.refs")
+ DeadlineReference._add_custom_reference_to_namespace(second,
DeadlineReference.TYPES.DAGRUN_QUEUED)
+
+ assert second in DeadlineReference.TYPES.DAGRUN_QUEUED
+ assert second not in DeadlineReference.TYPES.DAGRUN_CREATED
+ assert first not in DeadlineReference.TYPES.DAGRUN_CREATED
+
+ def
test_a_saved_types_value_survives_a_registration_under_the_other_type(self):
+ """Registering under one classification must not invalidate a saved
copy of the other."""
+ queued = DeadlineReference.TYPES.DAGRUN_QUEUED
+ DeadlineReference._add_custom_reference_to_namespace(
+ self.create_custom_ref_named("Created", "team_a.refs")
+ )
+
+ later = self.create_custom_ref_named("Queued", "team_a.refs")
+ DeadlineReference._add_custom_reference_to_namespace(later, queued)
+
+ assert later in DeadlineReference.TYPES.DAGRUN_QUEUED
+
+ def test_a_saved_types_value_can_be_reused(self):
+ """A saved TYPES value must stay valid after a registration under that
same classification."""
+ queued = DeadlineReference.TYPES.DAGRUN_QUEUED
+ first = self.create_custom_ref_named("First", "team_a.refs")
+ second = self.create_custom_ref_named("Second", "team_a.refs")
+
+ DeadlineReference._add_custom_reference_to_namespace(first, queued)
+ DeadlineReference._add_custom_reference_to_namespace(second, queued)
+
+ assert {first, second} <= set(DeadlineReference.TYPES.DAGRUN_QUEUED)
+
+ def test_two_modules_claiming_one_name_leaves_it_bound_to_neither(self,
cap_structlog):
+ """
+ The shorthand is withheld from both rather than awarded by import
order.
+
+ A Dag file is written against the short name, so letting the last
import win means the same
+ Dag silently evaluates a different class after a restart.
+ """
+ first = self.create_custom_ref_named("Contested", "team_a.refs")
+ second = self.create_custom_ref_named("Contested", "team_b.reports")
+
+ # Queued rather than the default, so the timing check below cannot
pass on the class default.
+ DeadlineReference._add_custom_reference_to_namespace(first,
DeadlineReference.TYPES.DAGRUN_QUEUED)
+ assert DeadlineReference.Contested.__class__ is first
+
+ DeadlineReference._add_custom_reference_to_namespace(second,
DeadlineReference.TYPES.DAGRUN_QUEUED)
+
+ assert not hasattr(DeadlineReference, "Contested")
+ with pytest.raises(AttributeError, match=r"\(team_a\.refs\.Contested,
team_b\.reports\.Contested\)"):
+ DeadlineReference.Contested
+ assert {
+ "event":
re.compile(r".*team_a\.refs\.Contested.*team_b\.reports\.Contested"),
+ "level": "warning",
+ } in cap_structlog
+
+ # Both remain valid references; only the shorthand is gone.
+ assert first in DeadlineReference.TYPES.DAGRUN_QUEUED
+ assert second in DeadlineReference.TYPES.DAGRUN_QUEUED
+ assert first.evaluation_timing == second.evaluation_timing ==
DAGRUN_QUEUED_TIMING
+
+ def test_a_contested_name_is_not_rebound_by_a_later_claimant(self):
+ """A third claim is recorded alongside the others, and still does not
get the shorthand."""
+ for module in ("team_a.refs", "team_b.reports", "team_c.other"):
+ DeadlineReference._add_custom_reference_to_namespace(
+ self.create_custom_ref_named("Contested", module)
+ )
+
+ assert not hasattr(DeadlineReference, "Contested")
+ with pytest.raises(AttributeError, match=r"team_c\.other\.Contested"):
+ DeadlineReference.Contested
+ assert DeadlineReference._contested_reference_names["Contested"] == [
+ "team_a.refs.Contested",
+ "team_b.reports.Contested",
+ "team_c.other.Contested",
+ ]
+
+ def test_an_invalid_claim_does_not_unbind_the_existing_one(self):
+ """A claim that fails validation must leave the namespace as it found
it."""
+ first = self.create_custom_ref_named("Contested", "team_a.refs")
+ DeadlineReference._add_custom_reference_to_namespace(first)
+
+ with pytest.raises(ValueError, match="Invalid deadline reference
type"):
+ DeadlineReference._add_custom_reference_to_namespace(
+ self.create_custom_ref_named("Contested", "team_b.reports"),
("not", "a", "valid", "timing")
+ )
+
+ assert DeadlineReference.Contested.__class__ is first
+ assert "Contested" not in DeadlineReference._contested_reference_names
+
+ def test_shadowing_a_builtin_reference_raises(self):
+ """A builtin must never be unbound, so this is an error rather than a
contested name."""
+ with pytest.raises(ValueError,
match="DeadlineReference.DAGRUN_QUEUED_AT already exists"):
+ DeadlineReference._add_custom_reference_to_namespace(
+ self.create_custom_ref_named("DAGRUN_QUEUED_AT", "team_a.refs")
+ )
+
+ assert DeadlineReference.DAGRUN_QUEUED_AT is not None
+
+ def test_register_custom_reference_is_a_deprecated_shim(self):
+ reference = self.create_custom_ref_named("ViaShim", "team_a.refs")
+
+ with pytest.warns(RemovedInAirflow4Warning,
match="register_custom_reference is deprecated"):
+ result = DeadlineReference.register_custom_reference(reference)
+
+ assert result is reference
+ assert DeadlineReference.ViaShim.__class__ is reference
+
class TestDeadlineReferenceDecorator:
def setup_method(self):
@@ -856,6 +1016,9 @@ class TestDeadlineReferenceDecorator:
DeadlineReference.TYPES.DAGRUN_QUEUED = self.original_dagrun_queued
DeadlineReference.TYPES.DAGRUN = self.original_dagrun
+ DeadlineReference._custom_reference_name_map.clear()
+ DeadlineReference._contested_reference_names.clear()
+
for attr in set(dir(DeadlineReference)):
if attr not in self.original_deadline_attrs:
delattr(DeadlineReference, attr)
@@ -944,8 +1107,8 @@ class TestDeadlineReferenceDecorator:
def _evaluate_with(self, *, session: Session, **kwargs) ->
datetime:
return timezone.datetime(DEFAULT_DATE)
- @mock.patch.object(DeadlineReference, "register_custom_reference")
- def test_deadline_reference_decorator_calls_register_method(self,
mock_register):
+ @mock.patch.object(DeadlineReference, "_add_custom_reference_to_namespace")
+ def test_deadline_reference_decorator_calls_the_namespace_method(self,
mock_add):
timing = DeadlineReference.TYPES.DAGRUN_QUEUED
@deadline_reference(timing)
@@ -953,7 +1116,7 @@ class TestDeadlineReferenceDecorator:
def _evaluate_with(self, *, session: Session, **kwargs) ->
datetime:
return timezone.datetime(DEFAULT_DATE)
- mock_register.assert_called_once_with(DecoratedCustomRef, timing)
+ mock_add.assert_called_once_with(DecoratedCustomRef, timing)
def test_deadline_reference_decorator_without_parentheses(self):
@deadline_reference
diff --git a/task-sdk/src/airflow/sdk/definitions/deadline.py
b/task-sdk/src/airflow/sdk/definitions/deadline.py
index b0915acc5b3..cabee43fc32 100644
--- a/task-sdk/src/airflow/sdk/definitions/deadline.py
+++ b/task-sdk/src/airflow/sdk/definitions/deadline.py
@@ -25,6 +25,7 @@ from typing import TYPE_CHECKING, Any, overload
import attrs
+from airflow.sdk._shared.module_loading import qualname
from airflow.sdk.definitions.callback import DEADLINE_CALLBACK_TYPES,
AsyncCallback, SyncCallback
from airflow.sdk.definitions.variable import Variable
from airflow.sdk.exceptions import AirflowRuntimeError,
RemovedInAirflow4Warning
@@ -60,8 +61,8 @@ class BaseDeadlineReference(ABC):
attribute of an ``AirflowPlugin``; see
:external:doc:`howto/deadline-alerts`.
"""
- # Set by ``register_custom_reference`` and persisted by the serializer,
because the in-memory
- # ``DeadlineReference.TYPES`` registry only exists in the process that ran
the Dag file.
+ # Set by ``_add_custom_reference_to_namespace`` and persisted by the
serializer, because the
+ # in-memory ``DeadlineReference.TYPES`` registry only exists in the
process that ran the Dag file.
evaluation_timing: str = DAGRUN_CREATED_TIMING
@property
@@ -158,6 +159,32 @@ DeadlineReferenceType: TypeAlias = BaseDeadlineReference
DeadlineReferenceTypes: TypeAlias = tuple[type[BaseDeadlineReference], ...]
+class _ClassifiedReferenceTypes(tuple[type[BaseDeadlineReference], ...]):
+ """A ``DeadlineReference.TYPES`` tuple that carries the name of its
classification."""
+
+ classification: str
+
+ def __new__(cls, references, classification: str):
+ self = super().__new__(cls, references)
+ self.classification = classification
+ return self
+
+
+class _ContestedReferenceName:
+ """Stands in for a contested ``DeadlineReference`` shorthand, so using it
explains why it is missing."""
+
+ def __init__(self, name: str):
+ self.name = name
+
+ def __get__(self, instance: object, owner: type | None = None) -> Any:
+ # Read the claimants on access, because later claimants are recorded
without touching this.
+ claimants = ",
".join(sorted(DeadlineReference._contested_reference_names[self.name]))
+ raise AttributeError(
+ f"DeadlineReference.{self.name} is claimed by more than one class
({claimants}), so it is "
+ "not available as a shorthand. Import the class you want directly
instead."
+ )
+
+
class DeadlineAlert:
"""Store Deadline values needed to calculate the need-by timestamp and the
callback information."""
@@ -269,21 +296,31 @@ class DeadlineReference:
"""Collection of DeadlineReference types for type checking."""
# Deadlines that should be created when the DagRun is created.
- DAGRUN_CREATED: DeadlineReferenceTypes = (
- DagRunLogicalDateDeadline,
- FixedDatetimeDeadline,
- AverageRuntimeDeadline,
+ DAGRUN_CREATED: DeadlineReferenceTypes = _ClassifiedReferenceTypes(
+ (DagRunLogicalDateDeadline, FixedDatetimeDeadline,
AverageRuntimeDeadline),
+ DAGRUN_CREATED_TIMING,
)
# Deadlines that should be created when the DagRun is queued.
- DAGRUN_QUEUED: DeadlineReferenceTypes = (DagRunQueuedAtDeadline,)
+ DAGRUN_QUEUED: DeadlineReferenceTypes = _ClassifiedReferenceTypes(
+ (DagRunQueuedAtDeadline,), DAGRUN_QUEUED_TIMING
+ )
# All DagRun-related deadline types.
DAGRUN: DeadlineReferenceTypes = DAGRUN_CREATED + DAGRUN_QUEUED
+ # The attributes above that a custom reference can be classified
under. DAGRUN is their
+ # union rather than a classification of its own, so it is deliberately
absent. Each name
+ # is also the evaluation_timing value stored for references classified
under it.
+ _CLASSIFICATIONS = (DAGRUN_CREATED_TIMING, DAGRUN_QUEUED_TIMING)
+
DAGRUN_LOGICAL_DATE: DeadlineReferenceType = DagRunLogicalDateDeadline()
DAGRUN_QUEUED_AT: DeadlineReferenceType = DagRunQueuedAtDeadline()
+ # These map short class name to qualname(s); used to handle custom
reference name collisions.
+ _custom_reference_name_map: dict[str, str] = {}
+ _contested_reference_names: dict[str, list[str]] = {}
+
@classmethod
def AVERAGE_RUNTIME(cls, max_runs: int = 0, min_runs: int | None = None)
-> DeadlineReferenceType:
if max_runs == 0:
@@ -307,29 +344,33 @@ class DeadlineReference:
)()
@classmethod
- def register_custom_reference(
+ def _add_custom_reference_to_namespace(
cls,
reference_class: type[BaseDeadlineReference],
deadline_reference_type: DeadlineReferenceTypes | None = None,
) -> type[BaseDeadlineReference]:
"""
- Register a custom deadline reference class for use in Dag files.
+ Add a custom deadline reference class to the DeadlineReference
namespace for use in Dag files.
This makes the reference available to Dag authors as
``DeadlineReference.<ClassName>`` and
records when it should be evaluated.
- .. warning::
+ .. note::
- Registering the reference is **not** the same as registering the
plugin, despite the
- name of this method. This only affects the process that runs the
Dag file; it does not
- make the class resolvable when the scheduler deserializes the Dag.
The class must
- *also* be listed in the ``deadline_references`` attribute of an
``AirflowPlugin``, or
- deserialization raises ``DeadlineReferenceNotRegistered``. See
- :external:doc:`howto/deadline-alerts`.
+ Adding the reference to this namespace is **not** the same as
registering the plugin.
+ This only affects the process that runs the Dag file; it does not
make the class
+ resolvable when the scheduler deserializes the Dag. The class
must *also* be listed in
+ the ``deadline_references`` attribute of an ``AirflowPlugin``, or
deserialization raises
+ ``DeadlineReferenceNotRegistered``. See
:external:doc:`howto/deadline-alerts`.
+
+ If two classes share the same name but have different module paths,
the shorthand is
+ withheld from both and a warning names the competing classes. In that
case, users can
+ still import the class directly; the classes themselves remain valid
references either way.
:param reference_class: The custom reference class inheriting from
BaseDeadlineReference
- :param deadline_reference_type: A DeadlineReference.TYPES for when the
deadline should be evaluated ("DAGRUN_CREATED",
- "DAGRUN_QUEUED", etc.); defaults to
DeadlineReference.TYPES.DAGRUN_CREATED
+ :param deadline_reference_type: A DeadlineReference.TYPES for when the
deadline should be
+ evaluated ("DAGRUN_CREATED", "DAGRUN_QUEUED", etc.);
+ defaults to DeadlineReference.TYPES.DAGRUN_CREATED
"""
# Default to DAGRUN_CREATED if no deadline_reference_type specified
if deadline_reference_type is None:
@@ -351,27 +392,99 @@ class DeadlineReference:
f"registered as a deadline reference. If it takes parameters,
decorate it with "
f"@dataclass and give every field a default value. Original
error: {e}"
) from e
- setattr(cls, reference_class.__name__, reference_instance)
- logger.info("Registered DeadlineReference %s",
reference_class.__name__)
-
- # Add to appropriate deadline_reference_type classification
- if deadline_reference_type is cls.TYPES.DAGRUN_CREATED:
- cls.TYPES.DAGRUN_CREATED = cls.TYPES.DAGRUN_CREATED +
(reference_class,)
- reference_class.evaluation_timing = DAGRUN_CREATED_TIMING
- elif deadline_reference_type is cls.TYPES.DAGRUN_QUEUED:
- cls.TYPES.DAGRUN_QUEUED = cls.TYPES.DAGRUN_QUEUED +
(reference_class,)
- reference_class.evaluation_timing = DAGRUN_QUEUED_TIMING
- else:
+ name = reference_class.__name__
+ key = qualname(reference_class)
+
+ classification = getattr(deadline_reference_type, "classification",
None)
+ if classification not in cls.TYPES._CLASSIFICATIONS:
raise ValueError(
f"Invalid deadline reference type {deadline_reference_type}; "
"must be a valid DeadlineReference.TYPES option."
)
+ if name in cls._contested_reference_names:
+ claimed_names = cls._contested_reference_names[name]
+ if key not in claimed_names:
+ claimed_names.append(key)
+ logger.warning(
+ "DeadlineReference.%s is claimed by more than one class (%s),
so it is not available "
+ "as a shorthand. Import the class you want directly instead.",
+ name,
+ ", ".join(sorted(claimed_names)),
+ )
+ elif (previous := cls._custom_reference_name_map.get(name)) is not
None:
+ if previous == key:
+ # Class was registered in a previous parse, refresh the value
in case user code changed.
+ setattr(cls, name, reference_instance)
+ else:
+ # Two different classes want the same shorthand, reject BOTH.
+ # Without this, the import order arbitrarily decides which
gets the
+ # name and potentially breaks a Dag file which uses the short
name.
+ setattr(cls, name, _ContestedReferenceName(name))
+ cls._contested_reference_names[name] =
[cls._custom_reference_name_map.pop(name), key]
+ logger.warning(
+ "DeadlineReference.%s is claimed by more than one class
(%s), so it is no longer "
+ "available as a shorthand. Import the class you want
directly instead.",
+ name,
+ ", ".join(sorted((previous, key))),
+ )
+ elif hasattr(cls, name):
+ # Raise rather than contest the name: contesting replaces the
attribute, which would
+ # unbind a built-in for every Dag that uses it.
+ raise ValueError(
+ f"{key} cannot be added to the DeadlineReference namespace as
{name!r}, because "
+ f"DeadlineReference.{name} already exists. Rename the class."
+ )
+ else:
+ setattr(cls, name, reference_instance)
+ cls._custom_reference_name_map[name] = key
+
+ if cls._custom_reference_name_map.get(name) == key:
+ logger.info("Added DeadlineReference.%s (%s)", name, key)
+
+ # A contested class is still a valid reference: it serializes under
its own qualname and
+ # resolves through the plugin registry, so only the shorthand is
withheld. Drop any earlier
+ # registration of the same qualname rather than appending beside it,
because a re-parse
+ # produces a new class object for the same reference. Both tuples are
filtered so a reference
+ # whose classification changes gets pruned from the old one.
+ for attr in cls.TYPES._CLASSIFICATIONS:
+ kept = tuple(existing for existing in getattr(cls.TYPES, attr) if
qualname(existing) != key)
+ if attr == classification:
+ kept += (reference_class,)
+ setattr(cls.TYPES, attr, _ClassifiedReferenceTypes(kept, attr))
+
+ # Set on contested classes too, so the serializer records the right
timing for them.
+ reference_class.evaluation_timing = classification
+
# Refresh the combined DAGRUN tuple
cls.TYPES.DAGRUN = cls.TYPES.DAGRUN_CREATED + cls.TYPES.DAGRUN_QUEUED
return reference_class
+ @classmethod
+ def register_custom_reference(
+ cls,
+ reference_class: type[BaseDeadlineReference],
+ deadline_reference_type: DeadlineReferenceTypes | None = None,
+ ) -> type[BaseDeadlineReference]:
+ """
+ Add a custom deadline reference to the DeadlineReference namespace.
+
+ .. deprecated:: 3.5.0
+ Use the ``@deadline_reference`` decorator instead. Despite its
name this method never
+ registered anything with the scheduler; see
+ :meth:`_add_custom_reference_to_namespace`.
+ """
+ warnings.warn(
+ "DeadlineReference.register_custom_reference is deprecated and
will be removed in "
+ "Airflow 4. It does not register anything with the scheduler; use
the "
+ "@deadline_reference decorator, and list the class in an
AirflowPlugin's "
+ "deadline_references to make it resolvable.",
+ RemovedInAirflow4Warning,
+ stacklevel=2,
+ )
+ return cls._add_custom_reference_to_namespace(reference_class,
deadline_reference_type)
+
@overload
def deadline_reference(
@@ -431,12 +544,12 @@ def deadline_reference(deadline_reference_type=None):
"""
# Used bare, without parentheses: the decorated class is passed in
directly.
if isinstance(deadline_reference_type, type):
- return
DeadlineReference.register_custom_reference(deadline_reference_type)
+ return
DeadlineReference._add_custom_reference_to_namespace(deadline_reference_type)
def decorator(
reference_class: type[BaseDeadlineReference],
) -> type[BaseDeadlineReference]:
- DeadlineReference.register_custom_reference(reference_class,
deadline_reference_type)
+ DeadlineReference._add_custom_reference_to_namespace(reference_class,
deadline_reference_type)
return reference_class
return decorator