Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,29 @@ synchronous and asynchronous orchestration scheduling, including legacy
`OrchestrationStatus.CANCELED`. Omission preserves backend defaults; existing
protobuf policies remain supported. See [ID reuse](docs/features.md#orchestration-id-reuse).

CHANGED

- `RetryPolicy.max_retry_interval` now defaults to one hour or
`first_retry_interval`, whichever is longer, so exponential backoff no longer
grows without bound by default. Pass `max_retry_interval=None` to keep
uncapped delays.

> [!WARNING]
> **Replay-affecting default change:** In-flight retries whose policy omits
> `max_retry_interval` and whose next delay exceeded the new cap can replay
> differently. Already-scheduled retry timers keep their recorded fire time.
> Retry delays longer than the worker's `maximum_timer_interval` (three days by
> default) are split into multiple timers. When the capped delay needs fewer
> parts than were recorded, the retry runs early after its last part fires, or
> replay fails with `NonDeterminismError` if an extra part was already recorded.
> `DurableTaskSchedulerWorker` does not split timers. Drain affected instances on
> the previous SDK, or set `max_retry_interval=None` on those policies before
> upgrading.

FIXED

- Exponential backoff that exceeds `max_retry_interval` no longer fails the
orchestration with `OverflowError`; the retry continues at the configured cap.
- Activity and sub-orchestration `retry_timeout` decisions now use replay-safe
orchestration time, preventing retries from expiring solely because history is
replayed later. Retry calculations also accept timezone-aware timestamps.
Expand Down
11 changes: 11 additions & 0 deletions azure-functions-durable/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,19 @@ Release coordination requires the corrected core replay-safe retry-timeout
behavior before this provider feature is published; version and dependency
minimum updates belong in the dedicated release PR.

CHANGED

- With the corresponding core SDK update, `RetryPolicy.max_retry_interval`
defaults to one hour or `first_retry_interval`, whichever is longer. Pass
`max_retry_interval=None` to keep uncapped delays. In-flight retries with
backoff delays beyond the new cap can replay differently or fail with
`NonDeterminismError`, including in apps that use Durable Task Scheduler; see
the [core upgrade warning](../CHANGELOG.md#unreleased).

FIXED

- With the corresponding core SDK update, exponential backoff that exceeds
`max_retry_interval` no longer fails the orchestration with `OverflowError`.
- With the corresponding core SDK update, activity and sub-orchestration
`retry_timeout` decisions use replay-safe orchestration time rather than
wall-clock time. See the [core upgrade guidance](../CHANGELOG.md#unreleased)
Expand Down
4 changes: 4 additions & 0 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,10 @@ Orchestrations can specify retry policies for activities and sub-orchestrations.
control how many times and how frequently an activity or sub-orchestration will be retried in the
event of a transient error.

Exponential backoff delays are capped by `max_retry_interval`. When omitted, the cap defaults to
one hour or `first_retry_interval`, whichever is longer. Pass `max_retry_interval=None` to remove
the cap.

### Replay-safe logging

Orchestrator functions replay their history each time they are resumed,
Expand Down
11 changes: 11 additions & 0 deletions durabletask-azuremanaged/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,19 @@ accept public `OrchestrationIdReusePolicy` values to control duplicate instance
IDs without changing backend defaults. See [ID reuse](../docs/features.md#orchestration-id-reuse).
Core release and dependency minimum updates are coordinated in the dedicated release PR.

CHANGED

- With the corresponding core SDK update, `RetryPolicy.max_retry_interval`
defaults to one hour or `first_retry_interval`, whichever is longer. Pass
`max_retry_interval=None` to keep uncapped delays. `DurableTaskSchedulerWorker`
does not split long timers, so its in-flight retries replay without
`NonDeterminismError`, but retries already past the new cap use it for
subsequent attempts. See the [core upgrade warning](../CHANGELOG.md#unreleased).

FIXED

- With the corresponding core SDK update, exponential backoff that exceeds
`max_retry_interval` no longer fails the orchestration with `OverflowError`.
- With the corresponding core SDK update, activity and sub-orchestration
`retry_timeout` decisions use replay-safe orchestration time rather than
wall-clock time. See the [core upgrade guidance](../CHANGELOG.md#unreleased)
Expand Down
31 changes: 26 additions & 5 deletions durabletask/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
from collections.abc import Callable, Generator, Sequence
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import Any, Generic, TypeAlias, TypeVar, cast, overload
from enum import Enum
from typing import Any, Generic, Literal, TypeAlias, TypeVar, cast, overload

from durabletask.entities import DurableEntity, EntityInstanceId, EntityLock, EntityContext
import durabletask.internal.helpers as pbh
Expand Down Expand Up @@ -851,7 +852,12 @@ def compute_next_delay(self, current_time: datetime | None = None) -> timedelta
else:
backoff_coefficient = self._retry_policy.backoff_coefficient

next_delay_f = math.pow(backoff_coefficient, self._attempt_count - 1) * self._retry_policy.first_retry_interval.total_seconds()
first_retry_seconds = self._retry_policy.first_retry_interval.total_seconds()
try:
next_delay_f = math.pow(backoff_coefficient, self._attempt_count - 1) * first_retry_seconds
except OverflowError:
# The uncapped delay is unrepresentable; let max_retry_interval bound it.
next_delay_f = math.inf if first_retry_seconds > 0 else 0.0

if self._retry_policy.max_retry_interval is not None:
next_delay_f = min(next_delay_f, self._retry_policy.max_retry_interval.total_seconds())
Expand Down Expand Up @@ -960,14 +966,25 @@ def task_id(self) -> int:
Entity: TypeAlias = Callable[[EntityContext, TInput], TOutput] | type[DurableEntity]


class _DefaultMaxRetryInterval(Enum):
DEFAULT = 'default'

def __repr__(self) -> str:
return 'DEFAULT'


_DEFAULT_MAX_RETRY_INTERVAL = timedelta(hours=1)


class RetryPolicy:
"""Represents the retry policy for an orchestration or activity function."""

def __init__(self, *,
first_retry_interval: timedelta,
max_number_of_attempts: int,
backoff_coefficient: float | None = 1.0,
max_retry_interval: timedelta | None = None,
max_retry_interval: timedelta | None | Literal[_DefaultMaxRetryInterval.DEFAULT] = (
_DefaultMaxRetryInterval.DEFAULT),
retry_timeout: timedelta | None = None):
"""Creates a new RetryPolicy instance.

Expand All @@ -980,7 +997,9 @@ def __init__(self, *,
backoff_coefficient : float | None
The backoff coefficient to use for calculating the next retry interval.
max_retry_interval : timedelta | None
The maximum retry interval to use for any retry attempt.
The maximum retry interval to use for any retry attempt. If omitted,
defaults to one hour or ``first_retry_interval``, whichever is longer.
Pass ``None`` to remove the cap.
retry_timeout : timedelta | None
The maximum amount of time to spend retrying the operation.
"""
Expand All @@ -991,6 +1010,8 @@ def __init__(self, *,
raise ValueError('max_number_of_attempts must be >= 1')
if backoff_coefficient is not None and backoff_coefficient < 1:
raise ValueError('backoff_coefficient must be >= 1')
if max_retry_interval is _DefaultMaxRetryInterval.DEFAULT:
max_retry_interval = max(_DEFAULT_MAX_RETRY_INTERVAL, first_retry_interval)
Comment thread
andystaples marked this conversation as resolved.
Resolved
if max_retry_interval is not None and max_retry_interval < timedelta(seconds=0):
raise ValueError('max_retry_interval must be >= 0')
if retry_timeout is not None and retry_timeout < timedelta(seconds=0):
Expand Down Expand Up @@ -1019,7 +1040,7 @@ def backoff_coefficient(self) -> float | None:

@property
def max_retry_interval(self) -> timedelta | None:
"""The maximum retry interval to use for any retry attempt."""
"""The maximum retry interval to use for any retry attempt, or ``None`` if uncapped."""
return self._max_retry_interval

@property
Expand Down
124 changes: 124 additions & 0 deletions tests/durabletask/test_retry_backoff.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

import logging
from collections.abc import Generator
from datetime import datetime, timedelta
from typing import Any

import pytest

from durabletask import task, worker
from durabletask.internal import helpers
from durabletask.internal import orchestrator_service_pb2 as pb
from durabletask.serialization import JsonDataConverter

START = datetime(2020, 1, 1)


def _delay_at_attempt(policy: task.RetryPolicy, attempt: int) -> timedelta | None:
retry = task.RetryableTask[Any](policy, pb.OrchestratorAction(), START, is_sub_orch=False)
for _ in range(attempt - 1):
retry.increment_attempt_count()
return retry.compute_next_delay(START)


@pytest.mark.parametrize(("first", "expected_cap"), [
(timedelta(seconds=1), timedelta(hours=1)),
(timedelta(hours=6), timedelta(hours=6)),
])
def test_omitted_max_retry_interval_defaults_to_one_hour_or_first_interval(
first: timedelta, expected_cap: timedelta,
) -> None:
policy = task.RetryPolicy(first_retry_interval=first, max_number_of_attempts=30, backoff_coefficient=2)

assert policy.max_retry_interval == expected_cap
assert _delay_at_attempt(policy, 1) == first
assert _delay_at_attempt(policy, 20) == expected_cap


def test_explicit_none_max_retry_interval_is_uncapped() -> None:
policy = task.RetryPolicy(
first_retry_interval=timedelta(seconds=1),
max_number_of_attempts=30,
backoff_coefficient=2,
max_retry_interval=None,
)

assert policy.max_retry_interval is None
assert _delay_at_attempt(policy, 20) == timedelta(seconds=2 ** 19)


@pytest.mark.parametrize(("coefficient", "attempt"), [(2.0, 1100), (1e200, 3)])
@pytest.mark.parametrize("cap", [timedelta(milliseconds=1), timedelta(0)])
def test_capped_backoff_does_not_overflow(coefficient: float, attempt: int, cap: timedelta) -> None:
policy = task.RetryPolicy(
first_retry_interval=timedelta(milliseconds=1),
max_number_of_attempts=attempt + 1,
backoff_coefficient=coefficient,
max_retry_interval=cap,
)

assert _delay_at_attempt(policy, attempt) == cap


def test_explicit_none_replays_recorded_uncapped_split_retry_timers() -> None:
"""Histories recorded with the previous uncapped default replay unchanged with ``None``."""
hour = timedelta(hours=1)

def orchestrator(ctx: task.OrchestrationContext, _: Any) -> Generator[task.Task[Any], Any, Any]:
return (yield ctx.call_activity("flaky", retry_policy=task.RetryPolicy(
first_retry_interval=hour,
max_number_of_attempts=3,
backoff_coefficient=100,
max_retry_interval=None,
)))

registry = worker._Registry() # pyright: ignore[reportPrivateUsage]
name = registry.add_orchestrator(orchestrator)
retried_at = START + hour
# The second retry waited 100 hours uncapped, split into 72-hour and 28-hour timers.
history = [
helpers.new_orchestrator_started_event(START),
helpers.new_execution_started_event(name, "instance", encoded_input=None),
helpers.new_task_scheduled_event(1, "flaky"),
helpers.new_task_failed_event(1, ValueError("transient")),
helpers.new_timer_created_event(2, retried_at),
helpers.new_orchestrator_started_event(retried_at),
helpers.new_timer_fired_event(2, retried_at),
helpers.new_task_scheduled_event(1, "flaky"),
helpers.new_task_failed_event(1, ValueError("transient")),
helpers.new_timer_created_event(3, retried_at + 72 * hour),
]

def execute(new_events: list[pb.HistoryEvent]) -> list[pb.OrchestratorAction]:
executor = worker._OrchestrationExecutor( # pyright: ignore[reportPrivateUsage]
registry, logging.getLogger(__name__), JsonDataConverter())
return list(executor.execute("instance", history, new_events).actions)

first_part_fired = [
helpers.new_orchestrator_started_event(retried_at + 72 * hour),
helpers.new_timer_fired_event(3, retried_at + 72 * hour),
]
actions = execute(first_part_fired)
assert [a.WhichOneof("orchestratorActionType") for a in actions] == ["createTimer"]
assert actions[0].id == 4
assert actions[0].createTimer.fireAt.ToDatetime() == retried_at + 100 * hour

history += first_part_fired + [helpers.new_timer_created_event(4, retried_at + 100 * hour)]
actions = execute([
helpers.new_orchestrator_started_event(retried_at + 100 * hour),
helpers.new_timer_fired_event(4, retried_at + 100 * hour),
])
assert [(a.id, a.WhichOneof("orchestratorActionType")) for a in actions] == [(1, "scheduleTask")]


def test_zero_first_interval_with_overflowing_backoff_is_zero() -> None:
policy = task.RetryPolicy(
first_retry_interval=timedelta(0),
max_number_of_attempts=5,
backoff_coefficient=1e200,
max_retry_interval=None,
)

assert _delay_at_attempt(policy, 3) == timedelta(0)