From 31c8f81ee1d340e814039fc51586dc55b9aebafc Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 11:55:45 -0700 Subject: [PATCH 1/3] Default RetryPolicy max_retry_interval and prevent capped backoff overflow RetryPolicy.max_retry_interval now defaults to one hour or first_retry_interval, whichever is longer; passing None keeps uncapped delays. Backoff calculations that overflow now saturate at the configured cap instead of failing the orchestration with OverflowError. Fixes #367 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 19 +++++++ azure-functions-durable/CHANGELOG.md | 10 ++++ docs/features.md | 4 ++ durabletask-azuremanaged/CHANGELOG.md | 11 ++++ durabletask/task.py | 31 +++++++++-- tests/durabletask/test_retry_backoff.py | 69 +++++++++++++++++++++++++ 6 files changed, 139 insertions(+), 5 deletions(-) create mode 100644 tests/durabletask/test_retry_backoff.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 40aa2e88..01d475d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,27 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## Unreleased +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: if the first part has fired, the +> retry runs early; if a later part was already scheduled, replay fails with +> `NonDeterminismError`. 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. diff --git a/azure-functions-durable/CHANGELOG.md b/azure-functions-durable/CHANGELOG.md index 4dd19e87..fb3f8609 100644 --- a/azure-functions-durable/CHANGELOG.md +++ b/azure-functions-durable/CHANGELOG.md @@ -21,8 +21,18 @@ 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`; 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) diff --git a/docs/features.md b/docs/features.md index 8573aa0d..8058c80c 100644 --- a/docs/features.md +++ b/docs/features.md @@ -225,6 +225,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, diff --git a/durabletask-azuremanaged/CHANGELOG.md b/durabletask-azuremanaged/CHANGELOG.md index 1b327beb..be7c57e5 100644 --- a/durabletask-azuremanaged/CHANGELOG.md +++ b/durabletask-azuremanaged/CHANGELOG.md @@ -7,8 +7,19 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## Unreleased +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. Durable Task Scheduler +workers do not split long timers, so 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) diff --git a/durabletask/task.py b/durabletask/task.py index df2e03a2..bc0870ba 100644 --- a/durabletask/task.py +++ b/durabletask/task.py @@ -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 @@ -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()) @@ -960,6 +966,16 @@ 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.""" @@ -967,7 +983,8 @@ 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. @@ -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. """ @@ -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) 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): @@ -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 diff --git a/tests/durabletask/test_retry_backoff.py b/tests/durabletask/test_retry_backoff.py new file mode 100644 index 00000000..f8333904 --- /dev/null +++ b/tests/durabletask/test_retry_backoff.py @@ -0,0 +1,69 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from datetime import datetime, timedelta +from typing import Any + +import pytest + +from durabletask import task +from durabletask.internal import orchestrator_service_pb2 as pb + +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_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) From 03f9ea8403fad0f84755c6951cd615411d188fd3 Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 12:45:15 -0700 Subject: [PATCH 2/3] Narrow retry default replay warnings Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 10 ++++++---- durabletask-azuremanaged/CHANGELOG.md | 4 ++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01d475d3..687be9d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,10 +19,12 @@ uncapped delays. > `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: if the first part has fired, the -> retry runs early; if a later part was already scheduled, replay fails with -> `NonDeterminismError`. Drain affected instances on the previous SDK, or set -> `max_retry_interval=None` on those policies before upgrading. +> 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 diff --git a/durabletask-azuremanaged/CHANGELOG.md b/durabletask-azuremanaged/CHANGELOG.md index be7c57e5..43087f78 100644 --- a/durabletask-azuremanaged/CHANGELOG.md +++ b/durabletask-azuremanaged/CHANGELOG.md @@ -11,8 +11,8 @@ 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. Durable Task Scheduler -workers do not split long timers, so in-flight retries replay without +`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). From f1e432227ad35cfefc431648b9b498b9fd77839d Mon Sep 17 00:00:00 2001 From: Andy Staples Date: Mon, 23 Nov 2026 13:11:17 -0700 Subject: [PATCH 3/3] Test uncapped retry replay with explicit max_retry_interval=None Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/durabletask/test_retry_backoff.py | 57 ++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/tests/durabletask/test_retry_backoff.py b/tests/durabletask/test_retry_backoff.py index f8333904..170ba6df 100644 --- a/tests/durabletask/test_retry_backoff.py +++ b/tests/durabletask/test_retry_backoff.py @@ -1,13 +1,17 @@ # 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 +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) @@ -58,6 +62,57 @@ def test_capped_backoff_does_not_overflow(coefficient: float, attempt: int, 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),