Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 17.7k
Add FanOutMapper for one-to-many partition fan-out#66030
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Uh oh!
There was an error while loading. Please reload this page.
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Add ``FanOutMapper`` for one-to-many partition mapping (e.g. one weekly upstream key to seven daily downstream Dag runs). It composes ``upstream_mapper + window + downstream_mapper``, mirroring the shape of ``RollupMapper`` and reusing the existing ``Window`` classes (``DayWindow``, ``WeekWindow``, ``MonthWindow``, ``QuarterWindow``, ``YearWindow``). A new ``[scheduler] partition_mapper_max_downstream_keys`` config caps the number of downstream keys produced per upstream event by any ``PartitionMapper`` (built-in or custom). When the cap is exceeded, no Dag runs are queued for that upstream event and a ``Log`` row with ``event="partition fan-out exceeded"`` is written against the source task instance, recording the asset, target Dag, key count, and cap value. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
52 changes: 52 additions & 0 deletions
52 airflow-core/src/airflow/example_dags/example_asset_partition.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -18,15 +18,18 @@ | ||
| import re | ||
| from abc import abstractmethod | ||
| from collections.abc import Iterable | ||
| from datetime import datetime, timedelta | ||
| from typing import TYPE_CHECKING, Any | ||
| from typing import TYPE_CHECKING, Any, ClassVar | ||
| from airflow._shared.timezones.timezone import make_aware, parse_timezone | ||
| from airflow.partition_mappers.base import PartitionMapper | ||
| if TYPE_CHECKING: | ||
| from pendulum import FixedTimezone, Timezone | ||
| from airflow.partition_mappers.window import Window | ||
| _STRPTIME_PATTERNS: dict[str, str] = { | ||
| "%Y": r"\d{4}", | ||
| @@ -419,3 +422,132 @@ def normalize(self, dt: datetime) -> datetime: | ||
| second=0, | ||
| microsecond=0, | ||
| ) | ||
| class FanOutMapper(PartitionMapper): | ||
| """ | ||
| Partition mapper that fans one upstream key out into multiple downstream keys. | ||
| Compose an ``upstream_mapper`` (parses the coarse upstream key and | ||
| normalizes it to its period start) with a ``window`` (enumerates the | ||
| members of that period). ``downstream_mapper`` formats each member into a | ||
| downstream key string; if omitted, a default is chosen from the window | ||
| class. | ||
| ``downstream_mapper`` must be passed explicitly for any window without an | ||
| entry in the default table — currently ``HourWindow`` and any custom | ||
| ``Window`` subclass. Constructing a ``FanOutMapper`` for those windows | ||
| without a ``downstream_mapper`` raises ``ValueError`` at Dag-parse time. | ||
| Symmetric to :class:`~airflow.partition_mappers.base.RollupMapper`: rollup | ||
| is N→1 (downstream waits until all members arrive), fan-out is 1→N (one | ||
| upstream event creates one downstream Dag run per member). | ||
| .. code-block:: python | ||
| # Weekly upstream → 7 daily downstream Dag runs | ||
| FanOutMapper(upstream_mapper=StartOfWeekMapper(), window=WeekWindow()) | ||
| """ | ||
| # Keep ``FanOutMapper.default_downstream_mapper_by_window_name`` in sync with | ||
| # the SDK copy in | ||
| # ``task-sdk/src/airflow/sdk/definitions/partition_mappers/temporal.py`` — | ||
| # the SDK and core class hierarchies are independent (the SDK cannot import | ||
| # core), so both sides carry the same defaults and the lookup is by class | ||
| # name. When adding a new ``Window`` subclass, extend the table on both | ||
| # sides; a missing entry raises ``ValueError`` at ``FanOutMapper.__init__`` | ||
| # (see ``FanOutMapper._resolve_default_downstream_mapper``). The | ||
| # ``check-partition-mapper-defaults-in-sync`` prek hook enforces that the | ||
| # two tables stay identical. | ||
| default_downstream_mapper_by_window_name: ClassVar[dict[str, type[_BaseTemporalMapper]]] = { | ||
| "DayWindow": StartOfHourMapper, | ||
| "WeekWindow": StartOfDayMapper, | ||
| "MonthWindow": StartOfDayMapper, | ||
| "QuarterWindow": StartOfMonthMapper, | ||
| "YearWindow": StartOfMonthMapper, | ||
| } | ||
| @classmethod | ||
| def _resolve_default_downstream_mapper(cls, window: Window) -> PartitionMapper: | ||
| """ | ||
| Return the conventional downstream mapper for *window*. | ||
| Looked up by the window's class **name** rather than identity so that | ||
| the SDK ``Window`` classes (used in Dag-author code) and the core | ||
| ``Window`` classes (used after deserialization) both resolve to the | ||
| same default. Subclasses can extend or override the defaults by | ||
| setting :attr:`default_downstream_mapper_by_window_name` on the | ||
| subclass. | ||
| """ | ||
| mapper_cls = cls.default_downstream_mapper_by_window_name.get(type(window).__name__) | ||
Lee-W marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| if mapper_cls is None: | ||
| raise ValueError( | ||
| f"{cls.__name__} has no default downstream_mapper for window type " | ||
| f"{type(window).__name__}; pass downstream_mapper explicitly." | ||
| ) | ||
| return mapper_cls() | ||
| def __init__( | ||
| self, | ||
| *, | ||
| upstream_mapper: PartitionMapper, | ||
| window: Window, | ||
| downstream_mapper: PartitionMapper | None = None, | ||
| ) -> None: | ||
| self.upstream_mapper = upstream_mapper | ||
| self.window = window | ||
| self.downstream_mapper = downstream_mapper or self._resolve_default_downstream_mapper(window) | ||
| def to_downstream(self, key: str) -> Iterable[str]: | ||
| # Round-trip the upstream key through its mapper to obtain the | ||
| # period-start datetime (decoded form). This keeps the upstream_mapper | ||
| # opaque — we don't need to know whether it's temporal or segment. | ||
| formatted = self.upstream_mapper.to_downstream(key) | ||
| if not isinstance(formatted, str): | ||
| raise TypeError( | ||
| "FanOutMapper.upstream_mapper must produce a single key from " | ||
| "to_downstream; chained fan-out (mapper that itself returns multiple keys) " | ||
| "is not supported." | ||
| ) | ||
| coarse = self.upstream_mapper.decode_downstream(formatted) | ||
| return [_format_with(self.downstream_mapper, item) for item in self.window.to_upstream(coarse)] | ||
| def serialize(self) -> dict[str, Any]: | ||
| from airflow.serialization.encoders import encode_partition_mapper, encode_window | ||
| return { | ||
| "upstream_mapper": encode_partition_mapper(self.upstream_mapper), | ||
| "window": encode_window(self.window), | ||
| "downstream_mapper": encode_partition_mapper(self.downstream_mapper), | ||
| } | ||
| @classmethod | ||
| def deserialize(cls, data: dict[str, Any]) -> PartitionMapper: | ||
| from airflow.serialization.decoders import decode_partition_mapper, decode_window | ||
| return cls( | ||
| upstream_mapper=decode_partition_mapper(data["upstream_mapper"]), | ||
| window=decode_window(data["window"]), | ||
| downstream_mapper=decode_partition_mapper(data["downstream_mapper"]), | ||
| ) | ||
| def _format_with(mapper: PartitionMapper, decoded: Any) -> str: | ||
| """ | ||
| Format *decoded* using *mapper*'s downstream format. | ||
| Three-layer fallback, in order: | ||
| 1. *mapper* exposes a callable ``format`` attribute (all temporal mappers do) | ||
| — delegates to ``mapper.format(decoded)``, which uses ``output_format``. | ||
| 2. *decoded* is a ``datetime`` instance — returns ``decoded.isoformat()``, | ||
| producing a stable ISO-8601 string that round-trips via | ||
| ``datetime.fromisoformat``. | ||
| 3. Anything else — ``str(decoded)`` as a last-resort fallback. | ||
| """ | ||
| formatter = getattr(mapper, "format", None) | ||
| if callable(formatter): | ||
| return formatter(decoded) | ||
| if isinstance(decoded, datetime): | ||
| return decoded.isoformat() | ||
| return str(decoded) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.