diff --git a/dapr/ext/workflow/AGENTS.md b/dapr/ext/workflow/AGENTS.md index ca242c8e3..21a44fa53 100644 --- a/dapr/ext/workflow/AGENTS.md +++ b/dapr/ext/workflow/AGENTS.md @@ -193,7 +193,7 @@ Passed to activity functions as the first argument: Retry configuration for activities and child workflows: - `first_retry_interval: timedelta` — initial retry delay -- `max_number_of_attempts: int` — maximum retries (>= 1) +- `max_number_of_attempts: int` — maximum retries (>= 1, or -1 for infinite retries) - `backoff_coefficient: Optional[float]` — exponential backoff multiplier (>= 1, default 1.0) - `max_retry_interval: Optional[timedelta]` — maximum delay between retries - `retry_timeout: Optional[timedelta]` — total time budget for retries diff --git a/dapr/ext/workflow/_durabletask/task.py b/dapr/ext/workflow/_durabletask/task.py index 6a3dc7451..854d94312 100644 --- a/dapr/ext/workflow/_durabletask/task.py +++ b/dapr/ext/workflow/_durabletask/task.py @@ -532,44 +532,78 @@ def increment_attempt_count(self) -> None: self._attempt_count += 1 def compute_next_delay(self) -> Optional[timedelta]: - if self._attempt_count >= self._retry_policy.max_number_of_attempts: - return None - - retry_expiration: datetime = datetime.max if ( - self._retry_policy.retry_timeout is not None - and self._retry_policy.retry_timeout != datetime.max + self._retry_policy.max_number_of_attempts != -1 + and self._attempt_count >= self._retry_policy.max_number_of_attempts ): - retry_expiration = self._start_time + self._retry_policy.retry_timeout + return None if self._retry_policy.backoff_coefficient is None: backoff_coefficient = 1.0 else: backoff_coefficient = self._retry_policy.backoff_coefficient - # Compute the next delay and the logical start time of the next attempt - # deterministically from accumulated delays, avoiding non-determinism during replay. - # range(1, attempt_count + 1) sums all delays up to and including the one about to - # be taken, so we're checking whether attempt N+1 would start within the timeout. + # Determine the maximum safe delay that can be added to worker.current_utc_datetime + # without raising OverflowError: date value out of range (datetime.max is year 9999). + # We leave a small margin (e.g. 1 day) so current_utc_datetime (which may be slightly + # ahead of start_time) + delay never exceeds datetime.max. + start_naive = ( + self._start_time.replace(tzinfo=None) + if self._start_time.tzinfo is not None + else self._start_time + ) + max_safe_delay = max(timedelta(0), (datetime.max - start_naive) - timedelta(days=1)) + max_safe_delay_s = max_safe_delay.total_seconds() + + max_interval_s = ( + self._retry_policy.max_retry_interval.total_seconds() + if self._retry_policy.max_retry_interval is not None + else None + ) + max_delay_cap_s = ( + min(max_interval_s, max_safe_delay_s) + if max_interval_s is not None + else max_safe_delay_s + ) + first_interval_s = self._retry_policy.first_retry_interval.total_seconds() + + timeout_s = ( + self._retry_policy.retry_timeout.total_seconds() + if self._retry_policy.retry_timeout is not None + and self._retry_policy.retry_timeout != datetime.max + else None + ) + + # Compute the next delay and total elapsed time deterministically by summing + # scheduled retry delays rather than consulting the wall clock, ensuring + # reproducible behavior during workflow replay. total_elapsed_seconds = 0.0 next_delay_f = 0.0 for i in range(1, self._attempt_count + 1): - next_delay_f = ( - math.pow(backoff_coefficient, i - 1) - * self._retry_policy.first_retry_interval.total_seconds() - ) - 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(), - ) + try: + next_delay_f = math.pow(backoff_coefficient, i - 1) * first_interval_s + except OverflowError: + next_delay_f = max_delay_cap_s + + if next_delay_f >= max_delay_cap_s: + next_delay_f = max_delay_cap_s + if backoff_coefficient >= 1.0: + # Once the cap is reached with a non-decreasing backoff coefficient, all + # remaining attempts (attempt_count - i + 1) will also equal max_delay_cap_s. + # Break early to avoid O(attempt_count) iteration per failure during replay. + remaining_attempts = self._attempt_count - i + 1 + total_elapsed_seconds += max_delay_cap_s * remaining_attempts + break + total_elapsed_seconds += next_delay_f - logical_next_attempt_start = self._start_time + timedelta(seconds=total_elapsed_seconds) - if logical_next_attempt_start < retry_expiration: - return timedelta(seconds=next_delay_f) + if timeout_s is not None and total_elapsed_seconds >= timeout_s: + return None + + if next_delay_f >= max_safe_delay_s: + return max_safe_delay - return None + return timedelta(seconds=next_delay_f) class TimerTask(CompletableTask[T]): @@ -747,7 +781,9 @@ def __init__( first_retry_interval : timedelta The retry interval to use for the first retry attempt. max_number_of_attempts : int - The maximum number of retry attempts. + The maximum number of retry attempts. Use -1 for infinite retries. + When using -1, pairing with max_retry_interval or retry_timeout is + recommended as workflow execution history continues to grow with each attempt. backoff_coefficient : Optional[float] The backoff coefficient to use for calculating the next retry interval. max_retry_interval : Optional[timedelta] @@ -763,8 +799,8 @@ def __init__( # validate inputs if first_retry_interval < timedelta(seconds=0): raise ValueError('first_retry_interval must be >= 0') - if max_number_of_attempts < 1: - raise ValueError('max_number_of_attempts must be >= 1') + if max_number_of_attempts < 1 and max_number_of_attempts != -1: + raise ValueError('max_number_of_attempts must be >= 1 or -1 for infinite retries') if backoff_coefficient is not None and backoff_coefficient < 1: raise ValueError('backoff_coefficient must be >= 1') if max_retry_interval is not None and max_retry_interval < timedelta(seconds=0): diff --git a/dapr/ext/workflow/retry_policy.py b/dapr/ext/workflow/retry_policy.py index 255e7bc6c..8e8adfc1a 100644 --- a/dapr/ext/workflow/retry_policy.py +++ b/dapr/ext/workflow/retry_policy.py @@ -39,7 +39,9 @@ def __init__( Args: first_retry_interval(timedelta): The retry interval to use for the first retry attempt. - max_number_of_attempts(int): The maximum number of retry attempts. + max_number_of_attempts(int): The maximum number of retry attempts. Use -1 for infinite + retries. When using -1, pairing with max_retry_interval or retry_timeout is + recommended as workflow execution history continues to grow with each attempt. backoff_coefficient(Optional[float]): The backoff coefficient to use for calculating the next retry interval. max_retry_interval(Optional[timedelta]): The maximum retry interval to use for any @@ -50,8 +52,8 @@ def __init__( # validate inputs if first_retry_interval < timedelta(seconds=0): raise ValueError('first_retry_interval must be >= 0') - if max_number_of_attempts < 1: - raise ValueError('max_number_of_attempts must be >= 1') + if max_number_of_attempts < 1 and max_number_of_attempts != -1: + raise ValueError('max_number_of_attempts must be >= 1 or -1 for infinite retries') if backoff_coefficient is not None and backoff_coefficient < 1: raise ValueError('backoff_coefficient must be >= 1') if max_retry_interval is not None and max_retry_interval < timedelta(seconds=0): diff --git a/tests/ext/workflow/test_retry_policy.py b/tests/ext/workflow/test_retry_policy.py new file mode 100644 index 000000000..626f2839e --- /dev/null +++ b/tests/ext/workflow/test_retry_policy.py @@ -0,0 +1,208 @@ +# -*- coding: utf-8 -*- + +""" +Copyright 2026 The Dapr Authors +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +from datetime import datetime, timedelta + +import pytest + +from dapr.ext.workflow import RetryPolicy +from dapr.ext.workflow._durabletask import task + + +def test_retry_policy_positive_attempts(): + policy = RetryPolicy( + first_retry_interval=timedelta(seconds=1), + max_number_of_attempts=5, + backoff_coefficient=2.0, + max_retry_interval=timedelta(seconds=30), + retry_timeout=timedelta(minutes=5), + ) + assert policy.max_number_of_attempts == 5 + assert policy.first_retry_interval == timedelta(seconds=1) + assert policy.backoff_coefficient == 2.0 + assert policy.max_retry_interval == timedelta(seconds=30) + assert policy.retry_timeout == timedelta(minutes=5) + + +def test_retry_policy_infinite_attempts_allowed(): + policy = RetryPolicy( + first_retry_interval=timedelta(seconds=2), + max_number_of_attempts=-1, + ) + assert policy.max_number_of_attempts == -1 + assert policy.obj.max_number_of_attempts == -1 + + +def test_task_retry_policy_infinite_attempts_allowed(): + policy = task.RetryPolicy( + first_retry_interval=timedelta(seconds=2), + max_number_of_attempts=-1, + ) + assert policy.max_number_of_attempts == -1 + + +@pytest.mark.parametrize('invalid_attempts', [0, -2, -10]) +def test_retry_policy_invalid_attempts_raise(invalid_attempts): + with pytest.raises(ValueError, match='max_number_of_attempts must be >= 1 or -1'): + RetryPolicy( + first_retry_interval=timedelta(seconds=1), + max_number_of_attempts=invalid_attempts, + ) + + with pytest.raises(ValueError, match='max_number_of_attempts must be >= 1 or -1'): + task.RetryPolicy( + first_retry_interval=timedelta(seconds=1), + max_number_of_attempts=invalid_attempts, + ) + + +def test_compute_next_delay_stops_at_bounded_attempts(): + policy = task.RetryPolicy( + first_retry_interval=timedelta(seconds=1), + max_number_of_attempts=3, + ) + retryable: task.RetryableTask[object] = task.RetryableTask( + retry_policy=policy, + start_time=datetime.now(), + is_sub_orch=False, + task_name='dummy', + encoded_input=None, + task_execution_id='1', + ) + + # Attempt 1: delay computed for attempt 2 + delay1 = retryable.compute_next_delay() + assert delay1 == timedelta(seconds=1) + + # Attempt 2: delay computed for attempt 3 + retryable.increment_attempt_count() + delay2 = retryable.compute_next_delay() + assert delay2 == timedelta(seconds=1) + + # Attempt 3: reached max_number_of_attempts (3), no more retries + retryable.increment_attempt_count() + assert retryable.compute_next_delay() is None + + +def test_compute_next_delay_infinite_retries(): + policy = task.RetryPolicy( + first_retry_interval=timedelta(seconds=1), + max_number_of_attempts=-1, + backoff_coefficient=1.0, + ) + retryable: task.RetryableTask[object] = task.RetryableTask( + retry_policy=policy, + start_time=datetime.now(), + is_sub_orch=False, + task_name='dummy', + encoded_input=None, + task_execution_id='1', + ) + + # Verify that it continues returning delay across many attempts without stopping + for attempt in range(1, 50): + delay = retryable.compute_next_delay() + assert delay == timedelta(seconds=1), f'Failed on attempt {attempt}' + retryable.increment_attempt_count() + + +def test_compute_next_delay_infinite_retry_respects_timeout(): + policy = task.RetryPolicy( + first_retry_interval=timedelta(seconds=2), + max_number_of_attempts=-1, + retry_timeout=timedelta(seconds=5), + ) + retryable: task.RetryableTask[object] = task.RetryableTask( + retry_policy=policy, + start_time=datetime.now(), + is_sub_orch=False, + task_name='dummy', + encoded_input=None, + task_execution_id='1', + ) + + # Attempt 1 (elapsed 2s <= 5s) + assert retryable.compute_next_delay() == timedelta(seconds=2) + retryable.increment_attempt_count() + + # Attempt 2 (elapsed 4s <= 5s) + assert retryable.compute_next_delay() == timedelta(seconds=2) + retryable.increment_attempt_count() + + # Attempt 3 (elapsed 6s > 5s timeout) -> should return None + assert retryable.compute_next_delay() is None + + +def test_compute_next_delay_infinite_retry_exponential_backoff_large_attempts(): + policy = task.RetryPolicy( + first_retry_interval=timedelta(seconds=1), + max_number_of_attempts=-1, + backoff_coefficient=2.0, + ) + start = datetime(2026, 1, 1, 0, 0, 0) + retryable: task.RetryableTask[object] = task.RetryableTask( + retry_policy=policy, + start_time=start, + is_sub_orch=False, + task_name='dummy', + encoded_input=None, + task_execution_id='1', + ) + + # Attempt 100 exceeds standard timedelta seconds bounds without max_retry_interval + retryable._attempt_count = 100 + delay100 = retryable.compute_next_delay() + assert delay100 is not None + # Verify the delay can be safely added to worker.current_utc_datetime without OverflowError + current_utc = start + timedelta(hours=1) + fire_at = current_utc + delay100 + assert fire_at <= datetime.max + + # Attempt 1100 triggers math.pow OverflowError, capped at the same safe datetime limit + retryable._attempt_count = 1100 + delay1100 = retryable.compute_next_delay() + assert delay1100 == delay100 + fire_at_1100 = current_utc + delay1100 + assert fire_at_1100 <= datetime.max + + +def test_compute_next_delay_infinite_retry_loop_break_optimization(): + policy = task.RetryPolicy( + first_retry_interval=timedelta(seconds=1), + max_number_of_attempts=-1, + backoff_coefficient=2.0, + max_retry_interval=timedelta(seconds=16), + retry_timeout=timedelta(seconds=100), + ) + retryable: task.RetryableTask[object] = task.RetryableTask( + retry_policy=policy, + start_time=datetime.now(), + is_sub_orch=False, + task_name='dummy', + encoded_input=None, + task_execution_id='1', + ) + + # At attempt 5: intervals are 1, 2, 4, 8, 16. Total elapsed = 31s. Next delay = 16s. + retryable._attempt_count = 5 + assert retryable.compute_next_delay() == timedelta(seconds=16) + + # At attempt 9: intervals are 1, 2, 4, 8, 16, 16, 16, 16, 16. Total = 31 + 4*16 = 95s <= 100s. + retryable._attempt_count = 9 + assert retryable.compute_next_delay() == timedelta(seconds=16) + + # At attempt 10: total elapsed = 95 + 16 = 111s > 100s timeout -> None + retryable._attempt_count = 10 + assert retryable.compute_next_delay() is None