Skip to content

feat(workflow): allow infinite retries with -1 in RetryPolicy (closes #870) - #1369

Open
NaniToka wants to merge 3 commits into
dapr:mainfrom
NaniToka:fix/workflow-infinite-retry-policy-870
Open

NaniToka wants to merge 3 commits into
dapr:mainfrom
NaniToka:fix/workflow-infinite-retry-policy-870

Conversation

@NaniToka

Copy link
Copy Markdown

Description

Currently RetryPolicy requires max_number_of_attempts >= 1 and rejects -1, preventing workflows and activities from configuring infinite retries like other Dapr retry policies (as requested by @CasperGN in #870).

This PR:

  • Allows max_number_of_attempts = -1 in both dapr.ext.workflow.RetryPolicy and _durabletask.task.RetryPolicy to represent infinite retries.
  • Updates RetryableTask.compute_next_delay so that when max_number_of_attempts == -1, the attempt-count cutoff is skipped, continuing retries until retry_timeout (if configured) or indefinitely.
  • Guards against floating-point OverflowError during long retry sequences with exponential backoff.
  • Adds comprehensive unit tests in tests/ext/workflow/test_retry_policy.py verifying initialization, parameter validation, attempt bounds, infinite retry delays, and timeout capping.

RELEASE NOTE: ADD Allow infinite max retries for workflow execution

Issue reference

Please reference the issue this PR will close: Closes #870

Checklist

  • Code compiles correctly
  • Created/updated tests
  • Extended the documentation

…apr#870)

Currently RetryPolicy requires max_number_of_attempts >= 1 and rejects
-1, preventing workflows and activities from configuring infinite
retries like other Dapr retry policies.

This commit:
- Permits max_number_of_attempts = -1 to represent infinite retries in both
  dapr.ext.workflow.RetryPolicy and _durabletask.task.RetryPolicy.
- Updates compute_next_delay to bypass the attempt-count cutoff when
  max_number_of_attempts == -1, continuing until retry_timeout (if set)
  or indefinitely.
- Guards against backoff OverflowError during long retry sequences when
  exponential backoff exceeds floating-point limits.
- Adds comprehensive unit tests in tests/ext/workflow/test_retry_policy.py
  verifying initialization, parameter validation, attempt bounds, infinite
  retry delays, and timeout capping.

RELEASE NOTE: ADD Allow infinite max retries for workflow execution

Signed-off-by: NaniToka <tokananiy@gmail.com>
@CasperGN

Copy link
Copy Markdown
Contributor

Claude review · not a review sign-off.

Minor

  1. With unlimited attempts (-1), a backoff coefficient above 1 and no max_retry_interval, the new OverflowError guard sets the delay to inf, and the timedelta(seconds=...) just after it raises OverflowError anyway. At backoff_coefficient=2.0 this happens from roughly attempt 100 on (attempt 1100: "cannot convert float infinity to integer"). It only matters at absurd delays, but the guard does not hold in this case; capping the delay at timedelta.max would cover it.
    except OverflowError:
    next_delay_f = max_interval_s if max_interval_s is not None else float('inf')
    if max_interval_s is not None:
    next_delay_f = min(next_delay_f, max_interval_s)
    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)

tests/ext/workflow/test_retry_policy.py and tests/ext/workflow/durabletask/test_orchestration_executor.py pass at this head (86 passed). Only the DCO check has run on this head, so this is a comment rather than an approval.

Reviewed at c0421bc.
Disagree, or want to talk it through? Reply /human and Casper will pick it up.

…ckoff

When using unbounded attempts (-1) with exponential backoff and no max_retry_interval, very large attempt counts (e.g. attempt 100+) could produce delays exceeding Python timedelta bounds or raise math.pow OverflowError, which previously caused timedelta(seconds=...) to fail with OverflowError.

Cap the computed retry delay at timedelta.max, compare accumulated seconds directly against the configured retry_timeout to prevent date out-of-range overflows, and add tests covering attempts 100 and 1100.

Signed-off-by: NaniToka <tokananiy@gmail.com>
@NaniToka

Copy link
Copy Markdown
Author

Great catch @CasperGN, thanks for catching that edge case!

I've updated compute_next_delay so that:

  • Any unbounded exponential backoff delay is capped at timedelta.max (both when math.pow overflows and when the computed seconds exceed timedelta limits), returning timedelta.max directly.
  • The timeout check now compares accumulated elapsed seconds directly against retry_timeout.total_seconds() rather than constructing self._start_time + timedelta(total_elapsed_seconds), which avoids OverflowError: date value out of range when elapsed time is huge.
  • Added tests in test_retry_policy.py covering attempts 100 and 1100 to verify that both the C-int timedelta bound and math.pow overflow are cleanly handled.

@CasperGN CasperGN left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @NaniToka for your interest in the project and for picking up #870! 🙌 The validation change is clean: both RetryPolicy classes now accept -1. The new timeout check also stops adding elapsed time to start_time, which removes a quiet overflow risk. I left a few comments inline on the delay calculation, please take a look.

A few more notes:

  • So far only DCO has reported on this head. The build and test workflows haven't run yet.
  • timedelta.max doesn't make it all the way to the timer, because create_timer_internal adds the delay to current_utc_datetime (
    fire_at = self.current_utc_datetime + fire_at
    ). There are details on the inline comment.

Drafted with AI assistance and reviewed by me.

Comment thread dapr/ext/workflow/_durabletask/task.py Outdated
return None

if next_delay_f >= max_timedelta_seconds:
return timedelta.max

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this moves the OverflowError rather than preventing it. The worker passes this delay to create_timer_internal, which runs fire_at = self.current_utc_datetime + fire_at (

fire_at = self.current_utc_datetime + fire_at
). So with timedelta.max it raises OverflowError: date value out of range there. Any delay of more than about 8,000 years does the same. In real time that takes a very long backoff to reach, but test_compute_next_delay_infinite_retry_exponential_backoff_large_attempts currently pins a value the caller can't use. What do you think about capping max_delay_cap_s at something that can be added to a datetime (for example the time left until datetime.max, or a fixed sane ceiling)? Then this branch and the test would describe behaviour that actually works end to end.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Terrific catch! You're completely right — timedelta.max (~2.7M years) can never be added to any Python datetime (year 9999 limit), so passing it to create_timer_internal would immediately fail with OverflowError: date value out of range.

I've updated max_safe_delay to cap at (datetime.max - start_naive) - timedelta(days=1). The 1-day safety margin ensures that self.current_utc_datetime + fire_at in the worker is always strictly within datetime.max, even when the worker timer is scheduled slightly after _start_time. Updated the large-attempt tests to assert end-to-end that current_utc + delay <= datetime.max.


total_elapsed_seconds = 0.0
next_delay_f = 0.0
for i in range(1, self._attempt_count + 1):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With -1, this loop is O(attempt_count) per call. It also runs again for each failure event when history replays, so the total cost grows quadratically with the number of attempts. A short first_retry_interval and no retry_timeout can rack up a lot of attempts. Once next_delay_f reaches max_delay_cap_s, every later term is the cap. So we could break there and add max_delay_cap_s * (self._attempt_count - i) to total_elapsed_seconds instead of iterating. It might also help to mention in the docstring that infinite retries keep growing the workflow history, so pairing -1 with max_retry_interval or retry_timeout is a good idea.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Brilliant observation on the replay complexity! In long-running workflows with lots of attempts, running an $O(N)$ loop on every replayed failure event was definitely an $O(N^2)$ trap.

Implemented the early break: once next_delay_f >= max_delay_cap_s (with non-decreasing backoff), we multiply max_delay_cap_s * (self._attempt_count - i + 1) and break immediately, dropping the replay cost to $O(1)$ once capped. Also added the recommendation in the RetryPolicy docstrings (in both workflow and _durabletask) advising users to pair -1 with max_retry_interval or retry_timeout to avoid unbounded history growth.

else None
)

total_elapsed_seconds = 0.0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: the removed comment explained why delays are summed from accumulated values rather than taken from the wall clock (determinism during replay). That's a real gotcha for the next person who edits this, so could we keep a short version of it here?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call. Restored and clarified the replay determinism comment right above the calculation loop so future maintainers understand why delays are accumulated deterministically rather than queried from the wall clock.

…replay loop

- Cap computed retry delay at datetime.max - start_time with a safety margin so that worker.current_utc_datetime + fire_at in create_timer_internal never raises OverflowError: date value out of range.
- Break the retry delay calculation loop early once next_delay reaches max_delay_cap_s, converting O(attempt_count) iteration into O(1) once capped to eliminate quadratic replay overhead.
- Restore replay determinism comment explaining why delays are accumulated rather than queried from wall-clock time.
- Note in docstrings that infinite retries grow workflow history and are best paired with max_retry_interval or retry_timeout.
- Add regression tests verifying end-to-end fire_at datetime safety and loop break accumulation.

Signed-off-by: NaniToka <tokananiy@gmail.com>
@NaniToka

Copy link
Copy Markdown
Author

Hey @CasperGN, pushed an update addressing all your feedback!

  1. End-to-End Safe Datetime Capping: Replaced timedelta.max with max_safe_delay = max(timedelta(0), (datetime.max - start_naive) - timedelta(days=1)). This ensures that when the delay is passed to worker.create_timer_internal, self.current_utc_datetime + fire_at is guaranteed to stay within datetime.max without raising OverflowError: date value out of range.
  2. Replay Loop Optimization: Added early break logic so once next_delay_f hits max_delay_cap_s, remaining intervals are added in $O(1)$ rather than looping through all attempts. This prevents quadratic overhead during orchestration history replay.
  3. Docstring Advice & Determinism Comment: Documented the history-growth recommendation when using -1 in both RetryPolicy classes, and restored the comment highlighting why delays are accumulated deterministically.
  4. Test Coverage: Added tests for the $O(1)$ loop break calculation and updated the large-attempt tests (100 and 1100 attempts) to assert that the computed delay adds cleanly to current_utc_datetime without overflow.

All 88 workflow and retry tests pass cleanly locally, and ruff linting and formatting are 100% green. Whenever you have a moment, please feel free to take another look!

@CasperGN CasperGN left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 3 of 3: follow-up on the changes since e596e49.

Every earlier blocker is resolved and the new changes add none.

Resolved since the last round: 3.

Nits, not blocking:

  • F3: backoff_coefficient >= 1.0 condition is always true after validation (dapr/ext/workflow/_durabletask/task.py)

Drafted with AI assistance and reviewed by me.

@NaniToka

Copy link
Copy Markdown
Author

Glad the loop optimization and the safe calendar delay did the trick, @CasperGN! Haha, fair point on the backoff check being redundant after the validator runs—we can drop that defensive guard in a future cleanup. Thanks again for the sharp review and the approval!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[WORKFLOW SDK FEATURE REQUEST] Allow infinite retries for workflows

2 participants