potiuk commented on code in PR #72475:
URL: https://github.com/apache/airflow/pull/72475#discussion_r4757176307
##########
airflow-core/src/airflow/timetables/_cron.py:
##########
@@ -174,6 +241,18 @@ def localize_partition_datetime(self, dt:
datetime.datetime) -> DateTime:
"""
return convert_to_utc(make_aware(dt.replace(tzinfo=None),
self._timezone))
+ def _tick_of(self, run: DateTime) -> DateTime:
+ """
+ Map a previous run time onto the cron tick it was scheduled for.
+
+ A run that already carries the current offset maps back to its own
tick. Anything else, such as
+ a run from before jitter was enabled or its settings changed, maps to
the latest tick at or before it.
+ """
+ stripped = self._strip(run)
+ if self._align_to_prev_cron(stripped) == stripped:
+ return stripped
+ return self._align_to_prev_cron(run)
Review Comment:
**`MultipleCronTriggerTimetable` skips a cron when the offset spans another
cron's tick**
All child timetables share one offset and `next_dagrun_info` hands each of
them the last run of the whole Dag. With `0 0 * * *` and `15 0 * * *` and an
offset over 15 minutes (`seed="my_dag"`, `max_jitter=1h` gives one), the 00:15
child receives `00:00 + offset`; stripped that is 00:00, not one of its ticks,
so `_tick_of` falls back to aligning the unstripped time, which is today's
00:15, and `_get_next` moves on to tomorrow's. Today's 00:15 run (at `00:15 +
offset`, still in the future) is skipped, every day. Map the previous run with
the offset removed for every child (the offset is shared, so `strip(run)` is
the right point on each child's timeline), or let the parent strip once and
pass the plain time down; add a test with two expressions closer together than
the offset.
*Flagged by codex and antigravity (adversarial review); cross-checked.*
---
Drafted-by: Claude Code (Opus 5.5); reviewed by @potiuk before posting
##########
airflow-core/src/airflow/timetables/_cron.py:
##########
@@ -82,15 +83,57 @@ def _covers_every_hour(cron: croniter) -> bool:
class CronMixin:
- """Mixin to provide interface to work with croniter."""
+ """
+ Mixin to provide interface to work with croniter.
+
+ Optionally applies a deterministic, per-Dag jitter to every scheduled time.
+ When ``max_jitter`` is set, each cron boundary is shifted by a fixed offset
+ derived from ``seed`` and spread across ``[0, max_jitter)``. This spreads
out
+ Dags that share a cron expression (e.g. every ``@daily`` Dag firing at
+ midnight) so they no longer all fire at the same instant. The offset is
stable
+ for a given seed, so runs stay predictable across scheduler restarts and
+ serialization.
+
+ The offset shifts every cron-derived time uniformly. For data-interval
+ timetables this means the whole interval moves by the offset (the window
keeps
+ its length and consecutive intervals stay contiguous), not just the fire
time.
+
+ :param cron: cron expression (or a preset such as ``@daily``) defining the
schedule.
+ :param timezone: timezone used to interpret the cron expression.
+ :param seed: stable, unique-per-Dag string the offset is derived from; the
Dag id
+ is a natural choice. Must be non-empty whenever ``max_jitter`` is set.
+ :param max_jitter: upper bound of the jitter window; the offset falls in
+ ``[0, max_jitter)``. Defaults to zero, i.e. no jitter. Keep it small
relative
+ to the gap between cron boundaries.
+ """
- def __init__(self, cron: str, timezone: str | Timezone | FixedTimezone) ->
None:
+ def __init__(
+ self,
+ cron: str,
+ timezone: str | Timezone | FixedTimezone,
+ *,
+ seed: str = "",
+ max_jitter: datetime.timedelta = datetime.timedelta(),
+ ) -> None:
self._expression = cron_presets.get(cron, cron)
if isinstance(timezone, str):
timezone = parse_timezone(timezone)
self._timezone = timezone
+ if max_jitter < datetime.timedelta(0):
+ raise ValueError("max_jitter must not be negative")
+ if max_jitter > datetime.timedelta(0) and not seed:
+ raise ValueError("seed must be a non-empty, unique-per-Dag string
when max_jitter > 0")
+ max_jitter_us = max_jitter // datetime.timedelta(microseconds=1)
+ if max_jitter_us > 0:
+ h = int(md5(seed.encode()).hexdigest(), 16)
+ self._offset = datetime.timedelta(microseconds=h % max_jitter_us)
Review Comment:
**Microsecond offsets put fractions of a second into run ids**
The offset is `h % max_jitter_us` microseconds, so almost every jittered
`run_after` has a fractional second, and `generate_run_id` formats it with
`isoformat()`, e.g. `scheduled__2026-03-06T00:35:12.483921+00:00`. That does
not match `RUN_ID_REGEX` (whole seconds only), so it is accepted only through
`[scheduler] allowed_run_id_pattern`: fine with the default, rejected where a
deployment tightened it. The same truncation makes a sub-second offset describe
itself as "jittered by 0:00:00". Round the offset to whole seconds
(`timedelta(seconds=h % max_jitter_seconds)`, with a sub-second `max_jitter`
meaning no jitter); sub-second spreading has no practical value for scheduling.
*Flagged by antigravity (adversarial review); cross-checked.*
---
Drafted-by: Claude Code (Opus 5.5); reviewed by @potiuk before posting
##########
airflow-core/newsfragments/72475.feature.rst:
##########
@@ -0,0 +1 @@
+Add opt-in deterministic jitter (``seed``/``max_jitter``) to all cron-based
timetables (``CronTriggerTimetable``, ``CronDataIntervalTimetable``,
``MultipleCronTriggerTimetable``, ``CronPartitionTimetable``) to spread out
Dags that share a cron expression.
Review Comment:
**airflow-core takes only significant newsfragments**
> In `airflow-core/` use only `significant` newsfragments, and only for a
change users must read before upgrading [...] Never add one for an ordinary bug
fix, feature, improvement or doc change
This is an opt-in feature, so it needs no newsfragment; the docs section
added to `timetable.rst` already describes it. Drop `72475.feature.rst`.
---
Drafted-by: Claude Code (Opus 5.5); reviewed by @potiuk before posting
##########
airflow-core/src/airflow/timetables/interval.py:
##########
@@ -143,16 +147,36 @@ class CronDataIntervalTimetable(CronMixin,
_DataIntervalTimetable):
when determining the next/previous time.
Don't pass ``@once`` in here; use ``OnceTimetable`` instead.
+
+ Optional ``seed``/``max_jitter`` jitter (see ``CronMixin``) shifts every
cron boundary by a
+ fixed per-Dag offset. Because the boundaries define the data interval, the
whole window moves
+ by that offset: it keeps its length and consecutive runs stay contiguous,
but it no longer
+ starts exactly on the cron time (e.g. 00:35 to 00:35 instead of 00:00 to
00:00). Keep
+ ``max_jitter`` small relative to the schedule period.
"""
+ def _align_last_end(self, end: DateTime) -> DateTime:
+ return self._apply(self._tick_of(end))
Review Comment:
**Jitter moves the data interval, not just the run**
For `CronDataIntervalTimetable` the offset shifts the interval boundaries
themselves, so a jittered `@daily` Dag gets intervals like `[00:58:51, next
00:58:51)` instead of calendar days. That changes what
`data_interval_start`/`end` mean for every task that partitions by them, and it
breaks continuity when the settings change: enabling jitter on an existing Dag
leaves `[T, T + offset)` uncovered by any run
(`test_enabling_jitter_does_not_overlap_last_data_interval` asserts that gap),
and disabling or reducing it makes the next interval overlap the last. The
point of jitter is to spread when runs start, and the interval and the run time
are separate in `DagRunInfo`. Keep the data intervals on the cron boundaries
and only delay `run_after` by the offset (`DagRunInfo(run_after=end + offset,
data_interval=DataInterval(start, end))`), as the partition timetable already
keeps its key on the boundary. Then switching jitter on or off cannot open a
gap or an overlap.
*Flagged by codex and antigravity (adversarial review); cross-checked.*
---
Drafted-by: Claude Code (Opus 5.5); reviewed by @potiuk before posting
##########
task-sdk/src/airflow/sdk/definitions/timetables/_cron.py:
##########
@@ -41,16 +42,35 @@
@attrs.define
class CronMixin:
- """Mixin to provide interface to work with croniter."""
+ """
+ Mixin to provide interface to work with croniter.
+
+ Optionally applies a deterministic, per-Dag jitter: when ``max_jitter`` is
set, every
+ cron boundary is shifted by a fixed offset derived from ``seed`` and
spread across
+ ``[0, max_jitter)``, so Dags sharing a cron expression no longer all fire
at the same
+ instant. The offset is computed scheduler-side; this class only carries
and validates
+ the settings.
+
+ :param seed: stable, unique-per-Dag string the offset is derived from (the
Dag id is a
+ natural choice). Must be non-empty whenever ``max_jitter`` is set.
+ :param max_jitter: upper bound of the jitter window; the offset falls in
+ ``[0, max_jitter)``. Defaults to zero, i.e. no jitter.
+ """
expression: str
timezone: str | Timezone | FixedTimezone
+ seed: str = attrs.field(kw_only=True, default="")
+ max_jitter: datetime.timedelta = attrs.field(kw_only=True,
default=datetime.timedelta())
def __attrs_post_init__(self) -> None:
Review Comment:
**The SDK side does not normalise or type-check `seed`**
Core drops `seed` when `max_jitter` is zero, the SDK keeps it, so two SDK
timetables that differ only in an unused seed compare unequal while core treats
them as equal. A non-string seed (e.g. an int) passes the SDK checks and is
serialized, and only fails later in the scheduler at `seed.encode()`. Normalise
`seed` to `""` when `max_jitter` is zero and reject a non-`str` seed in the SDK
too.
*Flagged by antigravity (adversarial review); cross-checked.*
---
Drafted-by: Claude Code (Opus 5.5); reviewed by @potiuk before posting
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]