From d63f934a81a566e6ef275859775493ec1c4bd5ae Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Tue, 17 Nov 2026 21:38:22 +0000 Subject: [PATCH 1/6] feat(sdk): add pause_every step option Add the experimental StepConfig.pause_every option. When a step function raises and the retry strategy retries, the SDK checks the attempt. If the attempt is a multiple of pause_every, the SDK calls the Lambda PauseDurableExecution API. It then sends the normal RETRY checkpoint and ends the invocation with PENDING. The next attempt runs after an operator resumes the execution. - pause_every does not change how many attempts run. When the retry strategy stops, the step fails as usual. - An interrupted AT_MOST_ONCE_PER_RETRY attempt does not pause. - A failed pause call logs a warning, and the step retries as usual. - A service client without pause_durable_execution retries as usual. The method lives on a separate PausableDurableServiceClient protocol. - The client token is a hash of the operation id and the attempt. The in-memory test client pauses the execution, so local tests can resume it with DurableFunctionTestRunner.resume_execution(). Raise the boto3 minimum to 1.44.5, the first release with the pause API. Add the step_with_pause_every example. --- .../examples-catalog.json | 11 + .../src/step/step_with_pause_every.py | 51 +++ .../test/step/test_step_with_pause_every.py | 56 +++ .../checkpoint/processor.py | 15 + .../client.py | 31 ++ .../tests/checkpoint/processor_test.py | 30 ++ .../tests/client_test.py | 18 + .../tests/e2e/step_pause_every_test.py | 114 ++++++ .../README.md | 16 + .../pyproject.toml | 2 +- .../config.py | 23 ++ .../lambda_service.py | 84 ++++- .../operation/step.py | 53 ++- .../aws_durable_execution_sdk_python/state.py | 20 + .../tests/operation/step_pause_every_test.py | 346 ++++++++++++++++++ 15 files changed, 866 insertions(+), 4 deletions(-) create mode 100644 packages/aws-durable-execution-sdk-python-examples/src/step/step_with_pause_every.py create mode 100644 packages/aws-durable-execution-sdk-python-examples/test/step/test_step_with_pause_every.py create mode 100644 packages/aws-durable-execution-sdk-python-testing/tests/e2e/step_pause_every_test.py create mode 100644 packages/aws-durable-execution-sdk-python/tests/operation/step_pause_every_test.py diff --git a/packages/aws-durable-execution-sdk-python-examples/examples-catalog.json b/packages/aws-durable-execution-sdk-python-examples/examples-catalog.json index b1811fa6d..43e5e7905 100644 --- a/packages/aws-durable-execution-sdk-python-examples/examples-catalog.json +++ b/packages/aws-durable-execution-sdk-python-examples/examples-catalog.json @@ -45,6 +45,17 @@ }, "path": "./src/step/step_with_retry.py" }, + { + "name": "Step with Pause Every", + "description": "Experimental: pause the execution after every third failed attempt of a step, until an operator resumes it", + "handler": "step_with_pause_every.handler", + "integration": false, + "durableConfig": { + "RetentionPeriodInDays": 7, + "ExecutionTimeout": 300 + }, + "path": "./src/step/step_with_pause_every.py" + }, { "name": "Custom SerDes Round-Trip", "description": "One function proving the first-run/replay result-equality guarantee with a non-identity SerDes across step, wait_for_condition, and run_in_child_context (normal, virtual, large-payload)", diff --git a/packages/aws-durable-execution-sdk-python-examples/src/step/step_with_pause_every.py b/packages/aws-durable-execution-sdk-python-examples/src/step/step_with_pause_every.py new file mode 100644 index 000000000..7bbca996a --- /dev/null +++ b/packages/aws-durable-execution-sdk-python-examples/src/step/step_with_pause_every.py @@ -0,0 +1,51 @@ +"""Pause the execution after every third failed attempt of a step. + +Experimental: StepConfig.pause_every may change or be removed in a future +release. + +The function's execution role needs lambda:PauseDurableExecution on its own +durable executions. Without it, the step logs a warning and retries as usual. +An operator resumes a paused execution with ResumeDurableExecution. +""" + +from typing import Any + +from aws_durable_execution_sdk_python.config import Duration, StepConfig +from aws_durable_execution_sdk_python.context import ( + DurableContext, + StepContext, + durable_step, +) +from aws_durable_execution_sdk_python.execution import durable_execution +from aws_durable_execution_sdk_python.retries import ( + RetryStrategyConfig, + create_retry_strategy, +) + + +@durable_step +def call_partner_api(step_context: StepContext) -> str: + # Fail on the first four attempts and succeed on attempt 5. + if step_context.attempt < 5: + msg = f"Partner API unavailable on attempt {step_context.attempt}" + raise RuntimeError(msg) + return "Partner API answered" + + +@durable_execution +def handler(_event: Any, context: DurableContext) -> str: + config = StepConfig( + retry_strategy=create_retry_strategy( + RetryStrategyConfig( + max_attempts=10, + initial_delay=Duration.from_seconds(1), + retryable_error_types=[RuntimeError], + ) + ), + # Pause after attempts 3, 6, 9. An operator can inspect the error + # and resume the execution when the partner API is back. + pause_every=3, + ) + + result: str = context.step(call_partner_api(), config=config) + return result diff --git a/packages/aws-durable-execution-sdk-python-examples/test/step/test_step_with_pause_every.py b/packages/aws-durable-execution-sdk-python-examples/test/step/test_step_with_pause_every.py new file mode 100644 index 000000000..571235856 --- /dev/null +++ b/packages/aws-durable-execution-sdk-python-examples/test/step/test_step_with_pause_every.py @@ -0,0 +1,56 @@ +"""Tests for the step_with_pause_every example. + +The local runner pauses the execution when the step asks it to. The test +resumes it, like an operator would with ResumeDurableExecution. +""" + +import threading +import time + +from aws_durable_execution_sdk_python_testing.runner import ( + DurableFunctionTestRunner, +) + +from aws_durable_execution_sdk_python.execution import InvocationStatus +from src.step import step_with_pause_every +from test.conftest import deserialize_operation_payload + + +def _count_events(runner: DurableFunctionTestRunner, arn: str, event_type: str) -> int: + return sum( + 1 + for event in runner.get_execution_history(arn).events + if event.event_type == event_type + ) + + +def _wait_for_failed_attempts( + runner: DurableFunctionTestRunner, arn: str, count: int +) -> None: + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + if _count_events(runner, arn, "StepFailed") >= count: + return + threading.Event().wait(0.01) + assert _count_events(runner, arn, "StepFailed") >= count + + +def test_step_with_pause_every_pauses_after_third_attempt(): + """The execution pauses after attempt 3 and finishes after resume.""" + with DurableFunctionTestRunner( + handler=step_with_pause_every.handler, execution_timeout=30 + ) as runner: + arn = runner.run_async(input="{}") + + _wait_for_failed_attempts(runner, arn, 3) + threading.Event().wait(0.3) + # Paused: attempt 4 does not start until the execution is resumed. + assert _count_events(runner, arn, "StepFailed") == 3 + assert _count_events(runner, arn, "ExecutionSucceeded") == 0 + + runner.resume_execution(arn) + result = runner.wait_for_result(arn) + + assert result.status is InvocationStatus.SUCCEEDED + assert deserialize_operation_payload(result.result) == "Partner API answered" + assert result.get_step("call_partner_api").attempt == 5 diff --git a/packages/aws-durable-execution-sdk-python-testing/src/aws_durable_execution_sdk_python_testing/checkpoint/processor.py b/packages/aws-durable-execution-sdk-python-testing/src/aws_durable_execution_sdk_python_testing/checkpoint/processor.py index 42ea9333b..0c35ece70 100644 --- a/packages/aws-durable-execution-sdk-python-testing/src/aws_durable_execution_sdk_python_testing/checkpoint/processor.py +++ b/packages/aws-durable-execution-sdk-python-testing/src/aws_durable_execution_sdk_python_testing/checkpoint/processor.py @@ -157,6 +157,21 @@ def get_execution_state( next_marker=None, ) + def pause_execution(self, durable_execution_arn: str) -> None: + """Experimental; may change or be removed in a future release. + + Pause an execution without waiting for its invocation to stop. + + The running invocation's next checkpoint is answered without a + token, like Lambda does after PauseDurableExecution. Completed or + already paused executions are unchanged. + """ + execution: Execution = self._store.load(durable_execution_arn) + if execution.is_complete or execution.is_paused: + return + execution.pause() + self._store.update(execution) + def _maybe_replay_cached( execution: Execution, diff --git a/packages/aws-durable-execution-sdk-python-testing/src/aws_durable_execution_sdk_python_testing/client.py b/packages/aws-durable-execution-sdk-python-testing/src/aws_durable_execution_sdk_python_testing/client.py index 38dbf701b..db692d640 100644 --- a/packages/aws-durable-execution-sdk-python-testing/src/aws_durable_execution_sdk_python_testing/client.py +++ b/packages/aws-durable-execution-sdk-python-testing/src/aws_durable_execution_sdk_python_testing/client.py @@ -1,6 +1,9 @@ """An in-memory service client, that can replace the boto lambda service client.""" +from __future__ import annotations + import datetime +from typing import TYPE_CHECKING from aws_durable_execution_sdk_python.lambda_service import ( CheckpointOutput, @@ -14,12 +17,21 @@ CheckpointProcessor, ) from aws_durable_execution_sdk_python_testing.worker.checkpoint_tasks import ( + CallableTask, CheckpointTask, GetStateTask, ) from aws_durable_execution_sdk_python_testing.worker.registry import ExecutionRegistry +if TYPE_CHECKING: + # Imported for typing only, so the client still loads with a core SDK + # that predates pause support. + from aws_durable_execution_sdk_python.lambda_service import ( + PauseExecutionRequest, + ) + + class InMemoryServiceClient(DurableServiceClient): """An in-memory service client, that can replace the boto lambda service client.""" @@ -55,6 +67,25 @@ def get_execution_state( ) return self._registry.submit(durable_execution_arn, task).result() + def pause_durable_execution( + self, + durable_execution_arn: str, + request: PauseExecutionRequest, # noqa: ARG002 + ) -> None: + """Experimental; may change or be removed in a future release. + + Pause the execution, like the Lambda PauseDurableExecution API. + + Returns without waiting for the running invocation to stop. Its next + checkpoint is answered without a token. Resume the execution with + DurableFunctionTestRunner.resume_execution(). The client token and + the reason are not recorded. + """ + task: CallableTask[None] = CallableTask( + lambda: self._checkpoint_processor.pause_execution(durable_execution_arn) + ) + self._registry.submit(durable_execution_arn, task).result() + def stop(self, execution_arn: str, payload: bytes | None) -> datetime.datetime: # noqa: ARG002 # TODO: implement # Return current time for in-memory testing diff --git a/packages/aws-durable-execution-sdk-python-testing/tests/checkpoint/processor_test.py b/packages/aws-durable-execution-sdk-python-testing/tests/checkpoint/processor_test.py index 97cfd489b..9d76f2fd1 100644 --- a/packages/aws-durable-execution-sdk-python-testing/tests/checkpoint/processor_test.py +++ b/packages/aws-durable-execution-sdk-python-testing/tests/checkpoint/processor_test.py @@ -536,3 +536,33 @@ def test_paused_checkpoint_retry_is_rejected_even_after_resume( ): processor.process_checkpoint(token, [], retry_client_token) assert store.load(arn).to_json_dict() == before_retry + + +def test_pause_execution_answers_next_checkpoint_without_token() -> None: + processor, store, execution, token = _make_processor_with_started_execution() + + processor.pause_execution(execution.durable_execution_arn) + + assert store.load(execution.durable_execution_arn).is_paused + assert processor.process_checkpoint(token, [], "c1").checkpoint_token is None + + +def test_pause_execution_leaves_existing_pause_unchanged() -> None: + processor, store, execution, _token = _make_processor_with_started_execution() + execution.pause() + execution.defer_invocation() + store.save(execution) + + processor.pause_execution(execution.durable_execution_arn) + + assert store.load(execution.durable_execution_arn).has_deferred_invocation + + +def test_pause_execution_leaves_completed_execution_unchanged() -> None: + processor, store, execution, _token = _make_processor_with_started_execution() + execution.complete_success(result=None) + store.save(execution) + + processor.pause_execution(execution.durable_execution_arn) + + assert not store.load(execution.durable_execution_arn).is_paused diff --git a/packages/aws-durable-execution-sdk-python-testing/tests/client_test.py b/packages/aws-durable-execution-sdk-python-testing/tests/client_test.py index d0da1ba27..cab60d55d 100644 --- a/packages/aws-durable-execution-sdk-python-testing/tests/client_test.py +++ b/packages/aws-durable-execution-sdk-python-testing/tests/client_test.py @@ -8,6 +8,8 @@ OperationAction, OperationType, OperationUpdate, + PausableDurableServiceClient, + PauseExecutionRequest, StateOutput, ) @@ -107,3 +109,19 @@ def test_stop_with_none_payload(): result = client.stop("arn:aws:states:us-east-1:123456789012:execution:test", None) assert isinstance(result, datetime.datetime) + + +def test_pause_durable_execution_delegates_to_processor(): + """pause_durable_execution pauses through the processor on the lane.""" + processor = Mock() + client = _client(processor) + request = PauseExecutionRequest(client_token="token", reason="why") # noqa: S106 + + client.pause_durable_execution("arn", request) + + processor.pause_execution.assert_called_once_with("arn") + + +def test_in_memory_client_supports_pause(): + """The SDK finds the pause method on the in-memory client.""" + assert isinstance(_client(Mock()), PausableDurableServiceClient) diff --git a/packages/aws-durable-execution-sdk-python-testing/tests/e2e/step_pause_every_test.py b/packages/aws-durable-execution-sdk-python-testing/tests/e2e/step_pause_every_test.py new file mode 100644 index 000000000..19008ce4d --- /dev/null +++ b/packages/aws-durable-execution-sdk-python-testing/tests/e2e/step_pause_every_test.py @@ -0,0 +1,114 @@ +"""End-to-end tests for StepConfig.pause_every with the local runner. + +The in-memory service client pauses the execution when the SDK asks it to. +The execution then stays paused until the test calls resume_execution(). + +Experimental; may change or be removed in a future release. +""" + +from __future__ import annotations + +import json +import threading +import time +from collections.abc import Callable +from typing import Any + +from aws_durable_execution_sdk_python.config import Duration, StepConfig +from aws_durable_execution_sdk_python.context import DurableContext, StepContext +from aws_durable_execution_sdk_python.execution import ( + InvocationStatus, + durable_execution, +) +from aws_durable_execution_sdk_python.retries import ( + RetryStrategyConfig, + create_retry_strategy, +) + +from aws_durable_execution_sdk_python_testing.runner import ( + DurableFunctionTestResult, + DurableFunctionTestRunner, +) + + +def _wait_until(predicate: Callable[[], bool], timeout: float = 5) -> None: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if predicate(): + return + threading.Event().wait(0.01) + assert predicate() + + +def _has_succeeded(runner: DurableFunctionTestRunner, arn: str) -> bool: + return any( + event.event_type == "ExecutionSucceeded" + for event in runner.get_execution_history(arn).events + ) + + +def _handler(attempts: list[int], succeed_on: int) -> Callable[..., Any]: + config = StepConfig( + retry_strategy=create_retry_strategy( + RetryStrategyConfig( + max_attempts=10, + initial_delay=Duration.from_seconds(1), + retryable_error_types=[RuntimeError], + ) + ), + pause_every=2, + ) + + def flaky(step_context: StepContext) -> str: + attempts.append(step_context.attempt) + if step_context.attempt < succeed_on: + msg = f"attempt {step_context.attempt} failed" + raise RuntimeError(msg) + return "done" + + def handler(_event: Any, context: DurableContext) -> str: + return context.step(flaky, name="flaky", config=config) + + return durable_execution(handler) + + +def test_step_pauses_after_every_second_failed_attempt() -> None: + """Attempts 2 and 4 pause the execution until it is resumed.""" + attempts: list[int] = [] + + with DurableFunctionTestRunner( + handler=_handler(attempts, succeed_on=5), execution_timeout=15 + ) as runner: + arn = runner.run_async(input="{}") + + _wait_until(lambda: attempts == [1, 2]) + threading.Event().wait(0.3) + assert attempts == [1, 2] + assert not _has_succeeded(runner, arn) + + runner.resume_execution(arn) + _wait_until(lambda: attempts == [1, 2, 3, 4]) + threading.Event().wait(0.3) + assert attempts == [1, 2, 3, 4] + assert not _has_succeeded(runner, arn) + + runner.resume_execution(arn) + result: DurableFunctionTestResult = runner.wait_for_result(arn) + + assert result.status is InvocationStatus.SUCCEEDED + assert result.result == json.dumps("done") + assert attempts == [1, 2, 3, 4, 5] + assert result.get_step("flaky").attempt == 5 + + +def test_step_does_not_pause_when_it_succeeds_before_a_multiple() -> None: + """A step that succeeds on attempt 2 never reaches a pause.""" + attempts: list[int] = [] + + with DurableFunctionTestRunner( + handler=_handler(attempts, succeed_on=2), execution_timeout=15 + ) as runner: + result: DurableFunctionTestResult = runner.run(input="{}") + + assert result.status is InvocationStatus.SUCCEEDED + assert attempts == [1, 2] diff --git a/packages/aws-durable-execution-sdk-python/README.md b/packages/aws-durable-execution-sdk-python/README.md index 4c4f600d8..ae11405bf 100644 --- a/packages/aws-durable-execution-sdk-python/README.md +++ b/packages/aws-durable-execution-sdk-python/README.md @@ -170,6 +170,22 @@ def handler(event: dict, context: DurableContext) -> dict: `RetryPresets` in `aws_durable_execution_sdk_python.retries` holds ready-made strategies. +### Pause after repeated failures (experimental) + +`StepConfig(pause_every=N)` pauses the durable execution after every Nth failed attempt that the retry strategy retries. For example, `pause_every=5` pauses after attempts 5, 10, 15, and so on. The step records its normal retry, and the invocation ends. An operator resumes the execution with the Lambda `ResumeDurableExecution` API, and the next attempt runs. + +```python +RETRY_AND_PAUSE = StepConfig( + retry_strategy=create_retry_strategy(RetryStrategyConfig(max_attempts=20)), + pause_every=5, +) +``` + +- The option does not change how many attempts run. When the retry strategy stops, the step fails as usual. +- Give the function's execution role `lambda:PauseDurableExecution` on its own durable executions. Without the permission, the SDK logs a warning and the step retries as usual. +- The pause is asynchronous. So one more attempt can start before Lambda applies it. +- This option is experimental. It may change or be removed in a future release. + ### Replay rules The function runs again from the start after each wait, retry, or resume. So: diff --git a/packages/aws-durable-execution-sdk-python/pyproject.toml b/packages/aws-durable-execution-sdk-python/pyproject.toml index 0245f480f..5a2446c6e 100644 --- a/packages/aws-durable-execution-sdk-python/pyproject.toml +++ b/packages/aws-durable-execution-sdk-python/pyproject.toml @@ -21,7 +21,7 @@ classifiers = [ "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", ] -dependencies = ["boto3>=1.43.114"] +dependencies = ["boto3>=1.44.5"] [project.urls] Documentation = "https://github.com/aws/aws-durable-execution-sdk-python#readme" diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py index 199d4e89f..9bc17f824 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py @@ -535,12 +535,35 @@ class StepConfig: Replay compares the subtype with the checkpoint. So changing the subtype of an existing step is a breaking change for executions in flight. + + pause_every: Experimental; may change or be removed in a future + release. Pause the durable execution after every Nth failed + attempt that the retry strategy retries. For example, 5 pauses + after attempts 5, 10, 15, and so on. None (the default) never + pauses. Use a positive integer. The SDK does not validate the + value. + On a pause, the SDK calls the Lambda PauseDurableExecution API, + records the normal retry checkpoint, and ends the invocation with + PENDING. The step resumes with its next attempt after an operator + calls ResumeDurableExecution. The option does not change how many + attempts run. When the retry strategy stops, the step fails as + usual and does not pause. + Only an attempt that raised in the current invocation counts. An + AT_MOST_ONCE_PER_RETRY attempt that was interrupted does not pause. + You must give the function's execution role permission for + lambda:PauseDurableExecution on its own durable executions. If + the pause call fails, for example because the permission is + missing, the SDK logs a warning and the step retries as usual. + A service client without pause support also retries as usual. + The pause is asynchronous. So one more attempt can start before + Lambda applies it. """ retry_strategy: Callable[[Exception, int], RetryDecision] | None = None step_semantics: StepSemantics = StepSemantics.AT_LEAST_ONCE_PER_RETRY serdes: SerDes | None = None sub_type: str | None = field(default=None, kw_only=True) + pause_every: int | None = field(default=None, kw_only=True) def __post_init__(self) -> None: _validate_sub_type(self.sub_type) diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/lambda_service.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/lambda_service.py index e43c400cf..18eaa0347 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/lambda_service.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/lambda_service.py @@ -3,11 +3,20 @@ import builtins import copy import datetime +import hashlib import logging from collections.abc import MutableMapping from dataclasses import dataclass, field from enum import Enum, StrEnum -from typing import TYPE_CHECKING, Any, NoReturn, Protocol, TypeAlias, cast +from typing import ( + TYPE_CHECKING, + Any, + NoReturn, + Protocol, + TypeAlias, + cast, + runtime_checkable, +) import boto3 from botocore.config import Config @@ -1170,6 +1179,38 @@ def from_dict(cls, data: MutableMapping[str, Any]) -> StateOutput: return cls(operations=operations, next_marker=data.get("NextMarker")) +# The PauseDurableExecution API accepts a reason of at most 1024 characters. +_MAX_PAUSE_REASON = 1024 + + +@dataclass(frozen=True) +class PauseExecutionRequest: + """Input for the PauseDurableExecution API, without the execution ARN. + + Experimental; may change or be removed in a future release. + """ + + client_token: str + reason: str + + @classmethod + def create_for_step_attempt( + cls, identifier: OperationIdentifier, attempt: int + ) -> PauseExecutionRequest: + """Create the pause request for a failed step attempt. + + The client token is a 64-character hash of the operation id and the + attempt. So a repeated request for the same attempt is idempotent, + and each attempt gets its own token. + """ + client_token: str = hashlib.blake2b( + f"pause:{identifier.operation_id}:{attempt}".encode(), digest_size=32 + ).hexdigest() + step_label: str = identifier.name or identifier.operation_id + reason: str = f'Step "{step_label}" failed attempt {attempt}' + return cls(client_token=client_token, reason=reason[:_MAX_PAUSE_REASON]) + + # endregion model @@ -1194,7 +1235,25 @@ def get_execution_state( ) -> StateOutput: ... # pragma: no cover -class LambdaClient(DurableServiceClient): +@runtime_checkable +class PausableDurableServiceClient(Protocol): + """A Durable Service client that can pause a durable execution. + + Experimental; may change or be removed in a future release. + + This method is optional. The SDK pauses an execution for + ``StepConfig.pause_every`` only when the client implements it. + Otherwise the step retries as usual. + """ + + def pause_durable_execution( + self, + durable_execution_arn: str, + request: PauseExecutionRequest, + ) -> None: ... # pragma: no cover + + +class LambdaClient(DurableServiceClient, PausableDurableServiceClient): """Persist durable operations to the Lambda Durable Function APIs.""" _cached_boto_client: Boto3LambdaClient | None = None @@ -1290,5 +1349,26 @@ def get_execution_state( ) raise error from None + def pause_durable_execution( + self, + durable_execution_arn: str, + request: PauseExecutionRequest, + ) -> None: + """Call the Lambda PauseDurableExecution API. + + Experimental; may change or be removed in a future release. + + The execution timeout pauses too (the API default). Errors from the + client propagate unchanged to the caller. + """ + # boto3-stubs for Lambda does not have this operation yet. botocore + # 1.44.5 and later has it. + client: Any = self.client + client.pause_durable_execution( + DurableExecutionArn=durable_execution_arn, + ClientToken=request.client_token, + Reason=request.reason, + ) + # endregion client diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/step.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/step.py index a9b9151e3..2aa9b378f 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/step.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/step.py @@ -20,6 +20,7 @@ from aws_durable_execution_sdk_python.lambda_service import ( ErrorObject, OperationUpdate, + PauseExecutionRequest, ) from aws_durable_execution_sdk_python.logger import Logger, LogInfo from aws_durable_execution_sdk_python.operation.base import ( @@ -304,7 +305,7 @@ def execute(self, checkpointed_result: CheckpointedResult) -> T: self.operation_identifier.name, ) - self.retry_handler(e, checkpointed_result) + self.retry_handler(e, checkpointed_result, may_pause=True) # If we've failed to raise an exception from the retry_handler, then we are in a # weird state, and should crash terminate the execution msg = "retry handler should have raised an exception, but did not." @@ -314,12 +315,16 @@ def retry_handler( self, error: Exception, checkpointed_result: CheckpointedResult, + *, + may_pause: bool = False, ): """Checkpoint and suspend for replay if retry required, otherwise raise error. Args: error: The exception that occurred during step execution checkpointed_result: The checkpoint data containing operation state + may_pause: True when the step function raised in this invocation. + Only then does StepConfig.pause_every apply. Raises: SuspendExecution: If retry is scheduled @@ -377,11 +382,26 @@ def retry_handler( next_attempt_delay_seconds=delay_seconds, ) + # Request the pause before the RETRY checkpoint. Lambda then + # answers that checkpoint without a token once the pause applies. + paused: bool = may_pause and self._pause_if_due(retry_attempt + 1) + # Checkpoint RETRY operation with blocking (is_sync=True, default). # Must ensure retry state is persisted before suspending execution. # This guarantees the retry attempt count and next attempt timestamp are durable. self.state.create_checkpoint(operation_update=retry_operation) + if paused: + # Suspend without a resume time. The next attempt runs after + # the execution is resumed, in a new invocation. + suspend_with_optional_resume_delay( + msg=( + f"Paused execution after attempt {retry_attempt + 1} of " + f"step {self.operation_identifier.operation_id}" + ), + delay_seconds=None, + ) + suspend_with_optional_resume_delay( msg=( f"Retry scheduled for {self.operation_identifier.operation_id}" @@ -405,3 +425,34 @@ def retry_handler( # exhausted StepInterruptedError surfaces the same way as any other # step failure.) error_object.raise_as_operation_error(StepError) + + def _pause_if_due(self, attempt: int) -> bool: + """Request a pause when attempt is a multiple of pause_every. + + Args: + attempt: The 1-based attempt that just failed. + + Returns: + True if the pause request was sent. False if no pause is due, the + service client cannot pause, or the request failed. + """ + pause_every: int | None = self.config.pause_every + if pause_every is None or attempt % pause_every != 0: + return False + + request: PauseExecutionRequest = PauseExecutionRequest.create_for_step_attempt( + self.operation_identifier, attempt + ) + try: + return self.state.pause_execution(request) + except Exception as e: # noqa: BLE001 - a failed pause falls back to a normal retry + self.context_logger.warning( + "Could not pause the execution after attempt %s of step %s. " + "Retrying as usual. Check that the execution role allows " + "lambda:PauseDurableExecution. Error: %s", + attempt, + self.operation_identifier.name + or self.operation_identifier.operation_id, + e, + ) + return False diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/state.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/state.py index 0518f0f87..0cb53471d 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/state.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/state.py @@ -34,6 +34,8 @@ OperationStatus, OperationType, OperationUpdate, + PausableDurableServiceClient, + PauseExecutionRequest, StateOutput, ) from aws_durable_execution_sdk_python.plugin import ( @@ -744,6 +746,24 @@ def is_checkpoint_token_revoked(self) -> bool: """Return whether the service has withdrawn this invocation's checkpoint token.""" return self._checkpoint_token_revoked.is_set() + def pause_execution(self, request: PauseExecutionRequest) -> bool: + """Ask the service to pause this durable execution. + + Experimental; may change or be removed in a future release. + + Returns: + True if the service client sent the request. False if the client + does not support pausing. + + Raises: + Exception: Any error from the service client, unchanged. + """ + client = self._service_client + if not isinstance(client, PausableDurableServiceClient): + return False + client.pause_durable_execution(self.durable_execution_arn, request) + return True + def _reject_if_checkpoint_token_revoked(self) -> None: """Raise SuspendExecution if the checkpoint token is gone.""" if not self._checkpoint_token_revoked.is_set(): diff --git a/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_every_test.py b/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_every_test.py new file mode 100644 index 000000000..41d1cb0c1 --- /dev/null +++ b/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_every_test.py @@ -0,0 +1,346 @@ +"""Unit tests for the StepConfig.pause_every option.""" + +from __future__ import annotations + +from unittest.mock import Mock + +import pytest + +from aws_durable_execution_sdk_python.config import ( + Duration, + StepConfig, + StepSemantics, +) +from aws_durable_execution_sdk_python.exceptions import ( + StepError, + SuspendExecution, + TimedSuspendExecution, +) +from aws_durable_execution_sdk_python.identifier import OperationIdentifier +from aws_durable_execution_sdk_python.lambda_service import ( + LambdaClient, + Operation, + OperationAction, + OperationStatus, + OperationSubType, + OperationType, + PausableDurableServiceClient, + PauseExecutionRequest, + StepDetails, +) +from aws_durable_execution_sdk_python.logger import Logger +from aws_durable_execution_sdk_python.operation.step import StepOperationExecutor +from aws_durable_execution_sdk_python.plugin import PluginExecutor +from aws_durable_execution_sdk_python.retries import RetryDecision +from aws_durable_execution_sdk_python.state import CheckpointedResult, ExecutionState + + +_OPERATION_ID = "a" * 64 +_IDENTIFIER = OperationIdentifier( + _OPERATION_ID, + OperationSubType.STEP, + None, + "charge", + operation_type=OperationType.STEP, +) + + +def _checkpoint(status: OperationStatus, previous_attempts: int) -> CheckpointedResult: + """A checkpoint for a step that has already failed previous_attempts times.""" + return CheckpointedResult.create_from_operation( + Operation( + operation_id=_OPERATION_ID, + operation_type=OperationType.STEP, + sub_type=OperationSubType.STEP, + name="charge", + status=status, + step_details=StepDetails(attempt=previous_attempts), + ) + ) + + +def _state(checkpoint: CheckpointedResult) -> Mock: + state = Mock(spec=ExecutionState) + state.durable_execution_arn = "test_arn" + state.get_checkpoint_result.return_value = checkpoint + state.wrap_user_function.side_effect = lambda func, *_args: func + state.pause_execution.return_value = True + return state + + +def _logger() -> Mock: + logger = Mock(spec=Logger) + logger.with_log_info.return_value = logger + return logger + + +def _run( + state: Mock, + config: StepConfig, + logger: Mock | None = None, +) -> None: + def failing_step(_ctx: object) -> str: + msg = "boom" + raise RuntimeError(msg) + + StepOperationExecutor( + func=failing_step, + config=config, + state=state, + operation_identifier=_IDENTIFIER, + context_logger=logger or _logger(), + ).process() + + +def _retry(_error: Exception, _attempt: int) -> RetryDecision: + return RetryDecision.retry(Duration.from_seconds(5)) + + +def _stop(_error: Exception, _attempt: int) -> RetryDecision: + return RetryDecision.no_retry() + + +def _actions(state: Mock) -> list[OperationAction]: + return [ + c.kwargs["operation_update"].action + for c in state.create_checkpoint.call_args_list + ] + + +def test_pauses_on_attempt_multiple_then_checkpoints_retry_and_suspends(): + """Attempt 2 with pause_every=2 pauses, sends RETRY, and suspends untimed.""" + state = _state(_checkpoint(OperationStatus.READY, previous_attempts=1)) + order = Mock() + order.attach_mock(state.pause_execution, "pause") + order.attach_mock(state.create_checkpoint, "checkpoint") + + with pytest.raises(SuspendExecution) as exc_info: + _run(state, StepConfig(retry_strategy=_retry, pause_every=2)) + + assert not isinstance(exc_info.value, TimedSuspendExecution) + state.pause_execution.assert_called_once_with( + PauseExecutionRequest.create_for_step_attempt(_IDENTIFIER, 2) + ) + assert _actions(state) == [OperationAction.START, OperationAction.RETRY] + # The pause request precedes the RETRY checkpoint. + names = [c[0] for c in order.mock_calls] + assert names == ["checkpoint", "pause", "checkpoint"] + retry_update = state.create_checkpoint.call_args_list[1].kwargs["operation_update"] + assert retry_update.error.type == "RuntimeError" + assert retry_update.step_options.next_attempt_delay_seconds == 5 + + +@pytest.mark.parametrize("previous_attempts", [3, 5]) +def test_pauses_on_later_multiples(previous_attempts: int): + """Attempts 4 and 6 are multiples of 2, so they pause too.""" + state = _state(_checkpoint(OperationStatus.READY, previous_attempts)) + + with pytest.raises(SuspendExecution) as exc_info: + _run(state, StepConfig(retry_strategy=_retry, pause_every=2)) + + assert not isinstance(exc_info.value, TimedSuspendExecution) + state.pause_execution.assert_called_once_with( + PauseExecutionRequest.create_for_step_attempt( + _IDENTIFIER, previous_attempts + 1 + ) + ) + + +@pytest.mark.parametrize("previous_attempts", [0, 2, 4]) +def test_no_pause_on_other_attempts(previous_attempts: int): + """Attempts 1, 3 and 5 are not multiples of 2, so they retry as usual.""" + state = _state(_checkpoint(OperationStatus.READY, previous_attempts)) + + with pytest.raises(TimedSuspendExecution): + _run(state, StepConfig(retry_strategy=_retry, pause_every=2)) + + state.pause_execution.assert_not_called() + assert _actions(state)[-1] is OperationAction.RETRY + + +def test_no_pause_by_default(): + """pause_every defaults to None and never pauses.""" + state = _state(_checkpoint(OperationStatus.READY, previous_attempts=0)) + + with pytest.raises(TimedSuspendExecution): + _run(state, StepConfig(retry_strategy=_retry)) + + state.pause_execution.assert_not_called() + + +def test_no_pause_when_retry_strategy_stops(): + """The step fails as usual when the retry strategy stops.""" + state = _state(_checkpoint(OperationStatus.READY, previous_attempts=0)) + + with pytest.raises(StepError): + _run(state, StepConfig(retry_strategy=_stop, pause_every=1)) + + state.pause_execution.assert_not_called() + assert _actions(state) == [OperationAction.START, OperationAction.FAIL] + + +def test_pause_failure_logs_warning_and_retries_as_usual(): + """A failed pause call logs a warning and falls back to a timed retry.""" + state = _state(_checkpoint(OperationStatus.READY, previous_attempts=0)) + state.pause_execution.side_effect = RuntimeError("AccessDeniedException") + logger = _logger() + + with pytest.raises(TimedSuspendExecution): + _run(state, StepConfig(retry_strategy=_retry, pause_every=1), logger) + + logger.warning.assert_called_once() + warning_args = logger.warning.call_args.args + assert "lambda:PauseDurableExecution" in warning_args[0] + assert warning_args[1:3] == (1, "charge") + assert _actions(state) == [OperationAction.START, OperationAction.RETRY] + + +def test_client_without_pause_support_retries_as_usual(): + """When the client cannot pause, the step retries as usual.""" + state = _state(_checkpoint(OperationStatus.READY, previous_attempts=0)) + state.pause_execution.return_value = False + + with pytest.raises(TimedSuspendExecution): + _run(state, StepConfig(retry_strategy=_retry, pause_every=1)) + + state.pause_execution.assert_called_once() + assert _actions(state) == [OperationAction.START, OperationAction.RETRY] + + +def test_no_pause_on_interrupted_at_most_once_replay(): + """An interrupted AT_MOST_ONCE attempt goes to retry without pausing.""" + state = _state(_checkpoint(OperationStatus.STARTED, previous_attempts=0)) + + with pytest.raises(TimedSuspendExecution): + _run( + state, + StepConfig( + retry_strategy=_retry, + step_semantics=StepSemantics.AT_MOST_ONCE_PER_RETRY, + pause_every=1, + ), + ) + + state.pause_execution.assert_not_called() + assert _actions(state) == [OperationAction.RETRY] + + +def test_revoked_token_on_retry_checkpoint_suspends(): + """A tokenless answer to the RETRY checkpoint suspends the invocation.""" + state = _state(_checkpoint(OperationStatus.READY, previous_attempts=0)) + revoked = SuspendExecution("Checkpoint token revoked") + state.create_checkpoint.side_effect = [None, revoked] + + with pytest.raises(SuspendExecution) as exc_info: + _run(state, StepConfig(retry_strategy=_retry, pause_every=1)) + + assert exc_info.value is revoked + state.pause_execution.assert_called_once() + + +def test_pause_request_client_token_is_stable_per_attempt(): + """The client token depends only on the operation id and the attempt.""" + first = PauseExecutionRequest.create_for_step_attempt(_IDENTIFIER, 5) + again = PauseExecutionRequest.create_for_step_attempt(_IDENTIFIER, 5) + renamed = PauseExecutionRequest.create_for_step_attempt( + OperationIdentifier( + _OPERATION_ID, + OperationSubType.STEP, + None, + "other", + operation_type=OperationType.STEP, + ), + 5, + ) + next_attempt = PauseExecutionRequest.create_for_step_attempt(_IDENTIFIER, 10) + + assert first == again + assert first.client_token == renamed.client_token + assert first.client_token != next_attempt.client_token + assert len(first.client_token) == 64 + assert first.client_token.isascii() + assert first.client_token.isalnum() + assert first.reason == 'Step "charge" failed attempt 5' + + +def test_pause_request_reason_uses_operation_id_without_name(): + identifier = OperationIdentifier( + _OPERATION_ID, + OperationSubType.STEP, + operation_type=OperationType.STEP, + ) + + request = PauseExecutionRequest.create_for_step_attempt(identifier, 3) + + assert request.reason == f'Step "{_OPERATION_ID}" failed attempt 3' + + +def test_pause_request_reason_fits_api_limit(): + identifier = OperationIdentifier( + _OPERATION_ID, + OperationSubType.STEP, + None, + "n" * 2000, + operation_type=OperationType.STEP, + ) + + request = PauseExecutionRequest.create_for_step_attempt(identifier, 1) + + assert len(request.reason) == 1024 + + +def _execution_state(client: object) -> ExecutionState: + return ExecutionState( + durable_execution_arn="test_arn", + initial_checkpoint_token="token", # noqa: S106 + operations={}, + service_client=client, # type: ignore[arg-type] + plugin_executor=PluginExecutor(plugins=None), + ) + + +def test_execution_state_pause_calls_client(): + client = Mock(spec=LambdaClient) + request = PauseExecutionRequest(client_token="t", reason="r") # noqa: S106 + + assert _execution_state(client).pause_execution(request) is True + + client.pause_durable_execution.assert_called_once_with("test_arn", request) + + +def test_execution_state_pause_without_client_support(): + class CheckpointOnlyClient: + def checkpoint(self, *args: object, **kwargs: object) -> None: ... + + def get_execution_state(self, *args: object, **kwargs: object) -> None: ... + + client = CheckpointOnlyClient() + request = PauseExecutionRequest(client_token="t", reason="r") # noqa: S106 + + assert not isinstance(client, PausableDurableServiceClient) + assert _execution_state(client).pause_execution(request) is False + + +def test_execution_state_pause_propagates_client_error(): + client = Mock(spec=LambdaClient) + client.pause_durable_execution.side_effect = RuntimeError("denied") + request = PauseExecutionRequest(client_token="t", reason="r") # noqa: S106 + + with pytest.raises(RuntimeError, match="denied"): + _execution_state(client).pause_execution(request) + + +def test_lambda_client_pause_durable_execution(): + boto_client = Mock() + request = PauseExecutionRequest(client_token="token", reason="why") # noqa: S106 + + LambdaClient(boto_client).pause_durable_execution("arn", request) + + boto_client.pause_durable_execution.assert_called_once_with( + DurableExecutionArn="arn", ClientToken="token", Reason="why" + ) + + +def test_step_config_pause_every_is_keyword_only_and_defaults_to_none(): + assert StepConfig().pause_every is None + assert StepConfig(pause_every=3).pause_every == 3 From 9bf3a54f0e73a497eb4fdda4166307a43710b56d Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Tue, 17 Nov 2026 22:58:02 +0000 Subject: [PATCH 2/6] fix(sdk): save the retry before pausing in pause_every The step now saves the RETRY checkpoint first. Only after Lambda accepts it does the SDK call PauseDurableExecution and suspend the invocation. Before, the pause came first. So Lambda could answer this step's RETRY, its earlier START, or a sibling's checkpoint without a token, and that update was lost. - If the RETRY answer has no token, the execution is already pausing. The step then suspends and does not request a pause. - The client token now hashes the durable execution ARN, the operation id and the attempt. So two executions never share a token. - The pause warning names the error. It says a missing permission is one possible cause. A ResourceConflictException says the execution is already pausing or paused. - Docs: use pause_every with long retry delays (30 seconds or more) and no full jitter. A short delay can let one more attempt run before the pause applies. A step in a map or parallel branch can still pause the execution after the map has finished. - The example uses a 60 second delay with no jitter and no backoff. - The testing checkpoint processor drops a redundant is_paused check. --- .../src/step/step_with_pause_every.py | 15 +- .../checkpoint/processor.py | 7 +- .../README.md | 18 +- .../config.py | 36 ++- .../lambda_service.py | 16 +- .../operation/step.py | 40 +++- .../tests/operation/step_pause_every_test.py | 210 ++++++++++++++++-- 7 files changed, 292 insertions(+), 50 deletions(-) diff --git a/packages/aws-durable-execution-sdk-python-examples/src/step/step_with_pause_every.py b/packages/aws-durable-execution-sdk-python-examples/src/step/step_with_pause_every.py index 7bbca996a..d54ed6b7a 100644 --- a/packages/aws-durable-execution-sdk-python-examples/src/step/step_with_pause_every.py +++ b/packages/aws-durable-execution-sdk-python-examples/src/step/step_with_pause_every.py @@ -10,7 +10,11 @@ from typing import Any -from aws_durable_execution_sdk_python.config import Duration, StepConfig +from aws_durable_execution_sdk_python.config import ( + Duration, + JitterStrategy, + StepConfig, +) from aws_durable_execution_sdk_python.context import ( DurableContext, StepContext, @@ -38,7 +42,14 @@ def handler(_event: Any, context: DurableContext) -> str: retry_strategy=create_retry_strategy( RetryStrategyConfig( max_attempts=10, - initial_delay=Duration.from_seconds(1), + # pause_every needs a long retry delay. Lambda saves the retry + # first, and the pause takes effect a short time later. A short + # delay can let one more attempt run before the pause. No + # jitter and no backoff keep every delay at 60 seconds. The + # local test runner skips the delays, so tests stay fast. + initial_delay=Duration.from_seconds(60), + backoff_rate=1, + jitter_strategy=JitterStrategy.NONE, retryable_error_types=[RuntimeError], ) ), diff --git a/packages/aws-durable-execution-sdk-python-testing/src/aws_durable_execution_sdk_python_testing/checkpoint/processor.py b/packages/aws-durable-execution-sdk-python-testing/src/aws_durable_execution_sdk_python_testing/checkpoint/processor.py index 0c35ece70..ef919fdb9 100644 --- a/packages/aws-durable-execution-sdk-python-testing/src/aws_durable_execution_sdk_python_testing/checkpoint/processor.py +++ b/packages/aws-durable-execution-sdk-python-testing/src/aws_durable_execution_sdk_python_testing/checkpoint/processor.py @@ -163,11 +163,12 @@ def pause_execution(self, durable_execution_arn: str) -> None: Pause an execution without waiting for its invocation to stop. The running invocation's next checkpoint is answered without a - token, like Lambda does after PauseDurableExecution. Completed or - already paused executions are unchanged. + token, like Lambda does after PauseDurableExecution. Completed + executions are unchanged. An already paused execution stays as it is, + because Execution.pause() does nothing then. """ execution: Execution = self._store.load(durable_execution_arn) - if execution.is_complete or execution.is_paused: + if execution.is_complete: return execution.pause() self._store.update(execution) diff --git a/packages/aws-durable-execution-sdk-python/README.md b/packages/aws-durable-execution-sdk-python/README.md index ae11405bf..086b5871e 100644 --- a/packages/aws-durable-execution-sdk-python/README.md +++ b/packages/aws-durable-execution-sdk-python/README.md @@ -172,18 +172,28 @@ def handler(event: dict, context: DurableContext) -> dict: ### Pause after repeated failures (experimental) -`StepConfig(pause_every=N)` pauses the durable execution after every Nth failed attempt that the retry strategy retries. For example, `pause_every=5` pauses after attempts 5, 10, 15, and so on. The step records its normal retry, and the invocation ends. An operator resumes the execution with the Lambda `ResumeDurableExecution` API, and the next attempt runs. +`StepConfig(pause_every=N)` pauses the durable execution after every Nth failed attempt that the retry strategy retries. For example, `pause_every=5` pauses after attempts 5, 10, 15, and so on. The step saves its normal retry, then the SDK asks Lambda to pause, and the invocation ends. An operator resumes the execution with the Lambda `ResumeDurableExecution` API, and the next attempt runs. ```python RETRY_AND_PAUSE = StepConfig( - retry_strategy=create_retry_strategy(RetryStrategyConfig(max_attempts=20)), + retry_strategy=create_retry_strategy( + RetryStrategyConfig( + max_attempts=20, + initial_delay=Duration.from_seconds(60), + jitter_strategy=JitterStrategy.NONE, + ) + ), pause_every=5, ) ``` - The option does not change how many attempts run. When the retry strategy stops, the step fails as usual. -- Give the function's execution role `lambda:PauseDurableExecution` on its own durable executions. Without the permission, the SDK logs a warning and the step retries as usual. -- The pause is asynchronous. So one more attempt can start before Lambda applies it. +- Use a retry strategy whose delay is much longer than the pause call, for example 30 seconds or more. Do not use `pause_every` with short delays of a few seconds. +- The reason: Lambda saves the retry first, and then the SDK asks to pause. The pause takes effect a short time later. If the retry delay ends first, Lambda can run one more attempt before the execution pauses. +- The default `JitterStrategy.FULL` can pick any delay from zero up. So use `JitterStrategy.HALF` or `JitterStrategy.NONE`. +- For short waits between attempts, retry without `pause_every`. The SDK then waits inside the invocation. +- The pause applies to the whole execution. A step in a `map` or `parallel` branch can still pause the execution after the map or parallel operation has finished. No checkpointed data is lost. Resume the execution to continue. +- Give the function's execution role `lambda:PauseDurableExecution` on its own durable executions. If the pause call fails, the SDK logs a warning with the error and the step retries as usual. A missing permission is one possible cause. - This option is experimental. It may change or be removed in a future release. ### Replay rules diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py index 9bc17f824..645d20e68 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py @@ -542,21 +542,35 @@ class StepConfig: after attempts 5, 10, 15, and so on. None (the default) never pauses. Use a positive integer. The SDK does not validate the value. - On a pause, the SDK calls the Lambda PauseDurableExecution API, - records the normal retry checkpoint, and ends the invocation with - PENDING. The step resumes with its next attempt after an operator - calls ResumeDurableExecution. The option does not change how many - attempts run. When the retry strategy stops, the step fails as - usual and does not pause. + On a pause, the SDK records the normal retry checkpoint, then + calls the Lambda PauseDurableExecution API, and ends the + invocation with PENDING. The step resumes with its next attempt + after an operator calls ResumeDurableExecution. The option does + not change how many attempts run. When the retry strategy stops, + the step fails as usual and does not pause. Only an attempt that raised in the current invocation counts. An AT_MOST_ONCE_PER_RETRY attempt that was interrupted does not pause. + Use pause_every with a retry strategy whose delay is much longer + than the pause call, for example 30 seconds or more. Do not use + it with short delays of a few seconds. The default FULL jitter + can pick any delay from zero up, so use HALF or NONE jitter. + Lambda saves the retry + first, and then the SDK asks to pause. The pause takes effect a + short time later. If the retry delay ends first, Lambda can run + one more attempt before the execution pauses. For short waits + between attempts, retry without pause_every. The SDK then waits + inside the invocation. + The pause applies to the whole durable execution. A step in a map + or parallel branch can still pause the execution after the map or + parallel operation has finished, for example when its completion + config needs only some branches. No checkpointed data is lost. + Resume the execution to continue. You must give the function's execution role permission for lambda:PauseDurableExecution on its own durable executions. If - the pause call fails, for example because the permission is - missing, the SDK logs a warning and the step retries as usual. - A service client without pause support also retries as usual. - The pause is asynchronous. So one more attempt can start before - Lambda applies it. + the pause call fails, the SDK logs a warning with the error and + the step retries as usual. A missing permission is one possible + cause. A service client without pause support also retries as + usual. """ retry_strategy: Callable[[Exception, int], RetryDecision] | None = None diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/lambda_service.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/lambda_service.py index 18eaa0347..5c782ce41 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/lambda_service.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/lambda_service.py @@ -1195,16 +1195,22 @@ class PauseExecutionRequest: @classmethod def create_for_step_attempt( - cls, identifier: OperationIdentifier, attempt: int + cls, + identifier: OperationIdentifier, + attempt: int, + *, + durable_execution_arn: str, ) -> PauseExecutionRequest: """Create the pause request for a failed step attempt. - The client token is a 64-character hash of the operation id and the - attempt. So a repeated request for the same attempt is idempotent, - and each attempt gets its own token. + The client token is a 64-character hash of the durable execution ARN, + the operation id and the attempt. So a repeated request for the same + attempt of the same execution is idempotent. Each attempt and each + execution gets its own token. """ client_token: str = hashlib.blake2b( - f"pause:{identifier.operation_id}:{attempt}".encode(), digest_size=32 + f"pause:{durable_execution_arn}:{identifier.operation_id}:{attempt}".encode(), + digest_size=32, ).hexdigest() step_label: str = identifier.name or identifier.operation_id reason: str = f'Step "{step_label}" failed attempt {attempt}' diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/step.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/step.py index 2aa9b378f..37481a0ef 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/step.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/step.py @@ -5,6 +5,8 @@ import logging from typing import TYPE_CHECKING, TypeVar +from botocore.exceptions import ClientError + from aws_durable_execution_sdk_python.config import ( StepConfig, StepSemantics, @@ -382,15 +384,20 @@ def retry_handler( next_attempt_delay_seconds=delay_seconds, ) - # Request the pause before the RETRY checkpoint. Lambda then - # answers that checkpoint without a token once the pause applies. - paused: bool = may_pause and self._pause_if_due(retry_attempt + 1) - # Checkpoint RETRY operation with blocking (is_sync=True, default). # Must ensure retry state is persisted before suspending execution. # This guarantees the retry attempt count and next attempt timestamp are durable. + # The batcher sends updates in queue order, so this also sends + # this step's earlier asynchronous START. If the response has no + # checkpoint token (the execution is already pausing), this call + # raises SuspendExecution and no pause is requested. self.state.create_checkpoint(operation_update=retry_operation) + # Request the pause only after Lambda accepted the RETRY. So no + # checkpoint of this invocation can be saved without a token + # before this step's RETRY is saved. + paused: bool = may_pause and self._pause_if_due(retry_attempt + 1) + if paused: # Suspend without a resume time. The next attempt runs after # the execution is resumed, in a new invocation. @@ -441,18 +448,37 @@ def _pause_if_due(self, attempt: int) -> bool: return False request: PauseExecutionRequest = PauseExecutionRequest.create_for_step_attempt( - self.operation_identifier, attempt + self.operation_identifier, + attempt, + durable_execution_arn=self.state.durable_execution_arn, ) try: return self.state.pause_execution(request) except Exception as e: # noqa: BLE001 - a failed pause falls back to a normal retry + error_name: str = _pause_error_name(e) + hint: str = ( + "The execution is already pausing or paused." + if error_name == "ResourceConflictException" + else "A missing lambda:PauseDurableExecution permission on the " + "execution role is one possible cause." + ) self.context_logger.warning( "Could not pause the execution after attempt %s of step %s. " - "Retrying as usual. Check that the execution role allows " - "lambda:PauseDurableExecution. Error: %s", + "Retrying as usual. Error: %s: %s. %s", attempt, self.operation_identifier.name or self.operation_identifier.operation_id, + error_name, e, + hint, ) return False + + +def _pause_error_name(error: Exception) -> str: + """Return the service error code of a botocore ClientError, else the type name.""" + if isinstance(error, ClientError): + code: str | None = error.response.get("Error", {}).get("Code") + if code: + return code + return type(error).__name__ diff --git a/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_every_test.py b/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_every_test.py index 41d1cb0c1..4cd6554d7 100644 --- a/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_every_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_every_test.py @@ -2,9 +2,11 @@ from __future__ import annotations +import threading from unittest.mock import Mock import pytest +from botocore.exceptions import ClientError from aws_durable_execution_sdk_python.config import ( Duration, @@ -18,6 +20,8 @@ ) from aws_durable_execution_sdk_python.identifier import OperationIdentifier from aws_durable_execution_sdk_python.lambda_service import ( + CheckpointOutput, + CheckpointUpdatedExecutionState, LambdaClient, Operation, OperationAction, @@ -26,6 +30,7 @@ OperationType, PausableDurableServiceClient, PauseExecutionRequest, + StateOutput, StepDetails, ) from aws_durable_execution_sdk_python.logger import Logger @@ -96,6 +101,14 @@ def _retry(_error: Exception, _attempt: int) -> RetryDecision: return RetryDecision.retry(Duration.from_seconds(5)) +def _request( + identifier: OperationIdentifier, attempt: int, arn: str = "test_arn" +) -> PauseExecutionRequest: + return PauseExecutionRequest.create_for_step_attempt( + identifier, attempt, durable_execution_arn=arn + ) + + def _stop(_error: Exception, _attempt: int) -> RetryDecision: return RetryDecision.no_retry() @@ -107,8 +120,8 @@ def _actions(state: Mock) -> list[OperationAction]: ] -def test_pauses_on_attempt_multiple_then_checkpoints_retry_and_suspends(): - """Attempt 2 with pause_every=2 pauses, sends RETRY, and suspends untimed.""" +def test_checkpoints_retry_then_pauses_on_attempt_multiple_and_suspends(): + """Attempt 2 with pause_every=2 sends RETRY, pauses, and suspends untimed.""" state = _state(_checkpoint(OperationStatus.READY, previous_attempts=1)) order = Mock() order.attach_mock(state.pause_execution, "pause") @@ -118,13 +131,11 @@ def test_pauses_on_attempt_multiple_then_checkpoints_retry_and_suspends(): _run(state, StepConfig(retry_strategy=_retry, pause_every=2)) assert not isinstance(exc_info.value, TimedSuspendExecution) - state.pause_execution.assert_called_once_with( - PauseExecutionRequest.create_for_step_attempt(_IDENTIFIER, 2) - ) + state.pause_execution.assert_called_once_with(_request(_IDENTIFIER, 2)) assert _actions(state) == [OperationAction.START, OperationAction.RETRY] - # The pause request precedes the RETRY checkpoint. + # The pause request follows the RETRY checkpoint. names = [c[0] for c in order.mock_calls] - assert names == ["checkpoint", "pause", "checkpoint"] + assert names == ["checkpoint", "checkpoint", "pause"] retry_update = state.create_checkpoint.call_args_list[1].kwargs["operation_update"] assert retry_update.error.type == "RuntimeError" assert retry_update.step_options.next_attempt_delay_seconds == 5 @@ -140,9 +151,7 @@ def test_pauses_on_later_multiples(previous_attempts: int): assert not isinstance(exc_info.value, TimedSuspendExecution) state.pause_execution.assert_called_once_with( - PauseExecutionRequest.create_for_step_attempt( - _IDENTIFIER, previous_attempts + 1 - ) + _request(_IDENTIFIER, previous_attempts + 1) ) @@ -190,8 +199,63 @@ def test_pause_failure_logs_warning_and_retries_as_usual(): logger.warning.assert_called_once() warning_args = logger.warning.call_args.args - assert "lambda:PauseDurableExecution" in warning_args[0] + message = warning_args[0] % warning_args[1:] assert warning_args[1:3] == (1, "charge") + assert "Error: RuntimeError: AccessDeniedException." in message + assert "missing lambda:PauseDurableExecution permission" in message + assert "one possible cause" in message + assert _actions(state) == [OperationAction.START, OperationAction.RETRY] + + +def test_pause_client_error_warning_names_the_service_error_code(): + """A botocore ClientError is named by its service error code.""" + state = _state(_checkpoint(OperationStatus.READY, previous_attempts=0)) + state.pause_execution.side_effect = ClientError( + {"Error": {"Code": "AccessDeniedException", "Message": "not allowed"}}, + "PauseDurableExecution", + ) + logger = _logger() + + with pytest.raises(TimedSuspendExecution): + _run(state, StepConfig(retry_strategy=_retry, pause_every=1), logger) + + warning_args = logger.warning.call_args.args + message = warning_args[0] % warning_args[1:] + assert "Error: AccessDeniedException: " in message + assert "not allowed" in message + assert "one possible cause" in message + + +def test_pause_conflict_warning_does_not_blame_permissions(): + """A ResourceConflictException says the execution is already pausing.""" + state = _state(_checkpoint(OperationStatus.READY, previous_attempts=0)) + state.pause_execution.side_effect = ClientError( + {"Error": {"Code": "ResourceConflictException", "Message": "paused"}}, + "PauseDurableExecution", + ) + logger = _logger() + + with pytest.raises(TimedSuspendExecution): + _run(state, StepConfig(retry_strategy=_retry, pause_every=1), logger) + + warning_args = logger.warning.call_args.args + message = warning_args[0] % warning_args[1:] + assert "Error: ResourceConflictException: " in message + assert "already pausing or paused" in message + assert "permission" not in message + + +def test_pause_client_error_without_code_uses_type_name(): + """A ClientError without an error code falls back to the type name.""" + state = _state(_checkpoint(OperationStatus.READY, previous_attempts=0)) + state.pause_execution.side_effect = ClientError({}, "PauseDurableExecution") + logger = _logger() + + with pytest.raises(TimedSuspendExecution): + _run(state, StepConfig(retry_strategy=_retry, pause_every=1), logger) + + warning_args = logger.warning.call_args.args + assert "Error: ClientError: " in warning_args[0] % warning_args[1:] assert _actions(state) == [OperationAction.START, OperationAction.RETRY] @@ -235,14 +299,98 @@ def test_revoked_token_on_retry_checkpoint_suspends(): _run(state, StepConfig(retry_strategy=_retry, pause_every=1)) assert exc_info.value is revoked + # The execution is already pausing, so the step does not pause it again. + state.pause_execution.assert_not_called() + + +def test_pause_waits_until_retry_checkpoint_is_accepted(): + """The pause request starts only after the blocking RETRY checkpoint returns.""" + state = _state(_checkpoint(OperationStatus.READY, previous_attempts=0)) + accepted: list[OperationAction] = [] + + def checkpoint(operation_update: object, **_kwargs: object) -> None: + accepted.append(operation_update.action) # type: ignore[attr-defined] + + def pause(_request: PauseExecutionRequest) -> bool: + assert accepted == [OperationAction.START, OperationAction.RETRY] + return True + + state.create_checkpoint.side_effect = checkpoint + state.pause_execution.side_effect = pause + + with pytest.raises(SuspendExecution) as exc_info: + _run(state, StepConfig(retry_strategy=_retry, pause_every=1)) + + assert not isinstance(exc_info.value, TimedSuspendExecution) state.pause_execution.assert_called_once() +class _RecordingClient: + """Checkpoint client that records each request and when pause is called.""" + + def __init__(self) -> None: + self.events: list[str] = [] + + def checkpoint( + self, + durable_execution_arn: str, # noqa: ARG002 + checkpoint_token: str, # noqa: ARG002 + updates: list[object], + client_token: str | None, # noqa: ARG002 + ) -> CheckpointOutput: + actions = ",".join(u.action.value for u in updates) # type: ignore[attr-defined] + self.events.append(f"checkpoint[{actions}]") + return CheckpointOutput( + checkpoint_token="next", # noqa: S106 + new_execution_state=CheckpointUpdatedExecutionState(operations=[]), + ) + + def get_execution_state(self, *args: object, **kwargs: object) -> StateOutput: + return StateOutput(operations=[], next_marker=None) + + def pause_durable_execution( + self, + durable_execution_arn: str, # noqa: ARG002 + request: PauseExecutionRequest, # noqa: ARG002 + ) -> None: + self.events.append("pause") + + +def test_real_state_sends_start_and_retry_before_pause(): + """With the real batcher, the async START and the RETRY are sent before the pause.""" + client = _RecordingClient() + state = _execution_state(client) + thread = threading.Thread(target=state.checkpoint_batches_forever, daemon=True) + thread.start() + + def failing_step(_ctx: object) -> str: + msg = "boom" + raise RuntimeError(msg) + + try: + with pytest.raises(SuspendExecution) as exc_info: + StepOperationExecutor( + func=failing_step, + config=StepConfig(retry_strategy=_retry, pause_every=1), + state=state, + operation_identifier=_IDENTIFIER, + context_logger=_logger(), + ).process() + finally: + state.stop_checkpointing() + thread.join(2) + + assert not isinstance(exc_info.value, TimedSuspendExecution) + assert client.events[-1] == "pause" + sent = "".join(client.events[:-1]) + assert sent.index("START") < sent.index("RETRY") + + def test_pause_request_client_token_is_stable_per_attempt(): - """The client token depends only on the operation id and the attempt.""" - first = PauseExecutionRequest.create_for_step_attempt(_IDENTIFIER, 5) - again = PauseExecutionRequest.create_for_step_attempt(_IDENTIFIER, 5) - renamed = PauseExecutionRequest.create_for_step_attempt( + """The client token depends on the execution ARN, operation id and attempt.""" + first = _request(_IDENTIFIER, 5) + again = _request(_IDENTIFIER, 5) + renamed = _request( OperationIdentifier( _OPERATION_ID, OperationSubType.STEP, @@ -252,7 +400,7 @@ def test_pause_request_client_token_is_stable_per_attempt(): ), 5, ) - next_attempt = PauseExecutionRequest.create_for_step_attempt(_IDENTIFIER, 10) + next_attempt = _request(_IDENTIFIER, 10) assert first == again assert first.client_token == renamed.client_token @@ -263,6 +411,32 @@ def test_pause_request_client_token_is_stable_per_attempt(): assert first.reason == 'Step "charge" failed attempt 5' +def test_pause_request_client_token_differs_per_execution(): + """The same step attempt in two executions gets two different tokens.""" + first = _request(_IDENTIFIER, 5, arn="arn:aws:lambda:us-west-2:1:function:f/a") + second = _request(_IDENTIFIER, 5, arn="arn:aws:lambda:us-west-2:1:function:f/b") + + assert first.client_token != second.client_token + assert len(second.client_token) == 64 + assert first == _request( + _IDENTIFIER, 5, arn="arn:aws:lambda:us-west-2:1:function:f/a" + ) + + +def test_step_pause_request_uses_the_execution_arn(): + """The step builds the pause request from the state's execution ARN.""" + state = _state(_checkpoint(OperationStatus.READY, previous_attempts=0)) + state.durable_execution_arn = "other_arn" + + with pytest.raises(SuspendExecution): + _run(state, StepConfig(retry_strategy=_retry, pause_every=1)) + + state.pause_execution.assert_called_once_with( + _request(_IDENTIFIER, 1, arn="other_arn") + ) + assert state.pause_execution.call_args.args[0] != _request(_IDENTIFIER, 1) + + def test_pause_request_reason_uses_operation_id_without_name(): identifier = OperationIdentifier( _OPERATION_ID, @@ -270,7 +444,7 @@ def test_pause_request_reason_uses_operation_id_without_name(): operation_type=OperationType.STEP, ) - request = PauseExecutionRequest.create_for_step_attempt(identifier, 3) + request = _request(identifier, 3) assert request.reason == f'Step "{_OPERATION_ID}" failed attempt 3' @@ -284,7 +458,7 @@ def test_pause_request_reason_fits_api_limit(): operation_type=OperationType.STEP, ) - request = PauseExecutionRequest.create_for_step_attempt(identifier, 1) + request = _request(identifier, 1) assert len(request.reason) == 1024 From 1291c36dd2338d41b7287dc8753b4890d2e770cc Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Wed, 18 Nov 2026 04:00:49 +0000 Subject: [PATCH 3/6] docs(sdk): drop the in-invocation wait claim from pause_every A retry of a step that runs alone suspends the invocation while it waits. Only map and parallel branches wait inside the invocation. So the docs no longer say the SDK waits inside the invocation. Also fix an early line break in the pause_every docstring. --- packages/aws-durable-execution-sdk-python/README.md | 2 +- .../src/aws_durable_execution_sdk_python/config.py | 11 +++++------ 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/packages/aws-durable-execution-sdk-python/README.md b/packages/aws-durable-execution-sdk-python/README.md index 086b5871e..b02bded04 100644 --- a/packages/aws-durable-execution-sdk-python/README.md +++ b/packages/aws-durable-execution-sdk-python/README.md @@ -191,7 +191,7 @@ RETRY_AND_PAUSE = StepConfig( - Use a retry strategy whose delay is much longer than the pause call, for example 30 seconds or more. Do not use `pause_every` with short delays of a few seconds. - The reason: Lambda saves the retry first, and then the SDK asks to pause. The pause takes effect a short time later. If the retry delay ends first, Lambda can run one more attempt before the execution pauses. - The default `JitterStrategy.FULL` can pick any delay from zero up. So use `JitterStrategy.HALF` or `JitterStrategy.NONE`. -- For short waits between attempts, retry without `pause_every`. The SDK then waits inside the invocation. +- For short waits between attempts, retry without `pause_every`. - The pause applies to the whole execution. A step in a `map` or `parallel` branch can still pause the execution after the map or parallel operation has finished. No checkpointed data is lost. Resume the execution to continue. - Give the function's execution role `lambda:PauseDurableExecution` on its own durable executions. If the pause call fails, the SDK logs a warning with the error and the step retries as usual. A missing permission is one possible cause. - This option is experimental. It may change or be removed in a future release. diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py index 645d20e68..075ab7658 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py @@ -554,12 +554,11 @@ class StepConfig: than the pause call, for example 30 seconds or more. Do not use it with short delays of a few seconds. The default FULL jitter can pick any delay from zero up, so use HALF or NONE jitter. - Lambda saves the retry - first, and then the SDK asks to pause. The pause takes effect a - short time later. If the retry delay ends first, Lambda can run - one more attempt before the execution pauses. For short waits - between attempts, retry without pause_every. The SDK then waits - inside the invocation. + Lambda saves the retry first, and then the SDK asks to pause. + The pause takes effect a short time later. If the retry delay + ends first, Lambda can run one more attempt before the execution + pauses. For short waits between attempts, retry without + pause_every. The pause applies to the whole durable execution. A step in a map or parallel branch can still pause the execution after the map or parallel operation has finished, for example when its completion From a392b1cb020208181aa98a9128276092dd06ba03 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Wed, 18 Nov 2026 04:27:42 +0000 Subject: [PATCH 4/6] fix(sdk): correct the pause conflict warning Lambda returns ResourceConflictException for a pause only when the execution has closed or is already paused. A second pause call while the execution is pausing has no effect. So the warning no longer says "already pausing". --- .../src/aws_durable_execution_sdk_python/operation/step.py | 2 +- .../tests/operation/step_pause_every_test.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/step.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/step.py index 37481a0ef..3b52b3d79 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/step.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/step.py @@ -457,7 +457,7 @@ def _pause_if_due(self, attempt: int) -> bool: except Exception as e: # noqa: BLE001 - a failed pause falls back to a normal retry error_name: str = _pause_error_name(e) hint: str = ( - "The execution is already pausing or paused." + "The execution has closed (for example, stopped) or is already paused." if error_name == "ResourceConflictException" else "A missing lambda:PauseDurableExecution permission on the " "execution role is one possible cause." diff --git a/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_every_test.py b/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_every_test.py index 4cd6554d7..7d66e10f6 100644 --- a/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_every_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_every_test.py @@ -227,7 +227,7 @@ def test_pause_client_error_warning_names_the_service_error_code(): def test_pause_conflict_warning_does_not_blame_permissions(): - """A ResourceConflictException says the execution is already pausing.""" + """A ResourceConflictException says the execution is closed or paused.""" state = _state(_checkpoint(OperationStatus.READY, previous_attempts=0)) state.pause_execution.side_effect = ClientError( {"Error": {"Code": "ResourceConflictException", "Message": "paused"}}, @@ -241,7 +241,7 @@ def test_pause_conflict_warning_does_not_blame_permissions(): warning_args = logger.warning.call_args.args message = warning_args[0] % warning_args[1:] assert "Error: ResourceConflictException: " in message - assert "already pausing or paused" in message + assert "has closed (for example, stopped) or is already paused" in message assert "permission" not in message From 2de4692c2b941b18b556d10d8191f41c3f99267d Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Wed, 18 Nov 2026 18:32:23 +0000 Subject: [PATCH 5/6] feat(sdk): pause the execution from a retry decision Move the pause from StepConfig.pause_every to the retry decision. RetryDecision gets pause: bool = False. A step pauses the execution when the decision retries with pause=True and the step function raised in this invocation. The interrupted AT_MOST_ONCE_PER_RETRY replay path ignores pause. A decision with should_retry=False never pauses. RetryStrategyConfig gets pause_every. create_retry_strategy returns pause=True on attempts that are multiples of pause_every. The pausing attempt uses the delay without jitter, so its delay is never near zero. Other attempts keep their jitter. StepConfig.pause_every is removed. It was never released. --- .../src/step/step_with_pause_every.py | 17 +-- .../tests/e2e/step_pause_every_test.py | 39 ++++- .../README.md | 35 +++-- .../config.py | 36 ----- .../lambda_service.py | 2 +- .../operation/step.py | 20 +-- .../retries.py | 87 ++++++++++- ...pause_every_test.py => step_pause_test.py} | 136 ++++++++++++++---- .../tests/retries_test.py | 104 ++++++++++++++ 9 files changed, 372 insertions(+), 104 deletions(-) rename packages/aws-durable-execution-sdk-python/tests/operation/{step_pause_every_test.py => step_pause_test.py} (77%) diff --git a/packages/aws-durable-execution-sdk-python-examples/src/step/step_with_pause_every.py b/packages/aws-durable-execution-sdk-python-examples/src/step/step_with_pause_every.py index d54ed6b7a..879f3db98 100644 --- a/packages/aws-durable-execution-sdk-python-examples/src/step/step_with_pause_every.py +++ b/packages/aws-durable-execution-sdk-python-examples/src/step/step_with_pause_every.py @@ -1,7 +1,7 @@ """Pause the execution after every third failed attempt of a step. -Experimental: StepConfig.pause_every may change or be removed in a future -release. +Experimental: RetryStrategyConfig.pause_every may change or be removed in a +future release. The function's execution role needs lambda:PauseDurableExecution on its own durable executions. Without it, the step logs a warning and retries as usual. @@ -44,18 +44,19 @@ def handler(_event: Any, context: DurableContext) -> str: max_attempts=10, # pause_every needs a long retry delay. Lambda saves the retry # first, and the pause takes effect a short time later. A short - # delay can let one more attempt run before the pause. No - # jitter and no backoff keep every delay at 60 seconds. The - # local test runner skips the delays, so tests stay fast. + # delay can let one more attempt run before the pause. The + # pausing attempt never uses jitter. No jitter and no backoff + # keep every delay at 60 seconds. The local test runner skips + # the delays, so tests stay fast. initial_delay=Duration.from_seconds(60), backoff_rate=1, jitter_strategy=JitterStrategy.NONE, retryable_error_types=[RuntimeError], + # Pause after attempts 3, 6, 9. An operator can inspect the + # error and resume the execution when the partner API is back. + pause_every=3, ) ), - # Pause after attempts 3, 6, 9. An operator can inspect the error - # and resume the execution when the partner API is back. - pause_every=3, ) result: str = context.step(call_partner_api(), config=config) diff --git a/packages/aws-durable-execution-sdk-python-testing/tests/e2e/step_pause_every_test.py b/packages/aws-durable-execution-sdk-python-testing/tests/e2e/step_pause_every_test.py index 19008ce4d..658a439d3 100644 --- a/packages/aws-durable-execution-sdk-python-testing/tests/e2e/step_pause_every_test.py +++ b/packages/aws-durable-execution-sdk-python-testing/tests/e2e/step_pause_every_test.py @@ -1,4 +1,4 @@ -"""End-to-end tests for StepConfig.pause_every with the local runner. +"""End-to-end tests for pausing a step from the retry decision with the local runner. The in-memory service client pauses the execution when the SDK asks it to. The execution then stays paused until the test calls resume_execution(). @@ -21,6 +21,7 @@ durable_execution, ) from aws_durable_execution_sdk_python.retries import ( + RetryDecision, RetryStrategyConfig, create_retry_strategy, ) @@ -47,16 +48,21 @@ def _has_succeeded(runner: DurableFunctionTestRunner, arn: str) -> bool: ) -def _handler(attempts: list[int], succeed_on: int) -> Callable[..., Any]: +def _handler( + attempts: list[int], + succeed_on: int, + retry_strategy: Callable[[Exception, int], RetryDecision] | None = None, +) -> Callable[..., Any]: config = StepConfig( - retry_strategy=create_retry_strategy( + retry_strategy=retry_strategy + or create_retry_strategy( RetryStrategyConfig( max_attempts=10, initial_delay=Duration.from_seconds(1), retryable_error_types=[RuntimeError], + pause_every=2, ) ), - pause_every=2, ) def flaky(step_context: StepContext) -> str: @@ -112,3 +118,28 @@ def test_step_does_not_pause_when_it_succeeds_before_a_multiple() -> None: assert result.status is InvocationStatus.SUCCEEDED assert attempts == [1, 2] + + +def test_custom_strategy_pauses_when_its_decision_says_so() -> None: + """A custom strategy that returns pause=True on attempt 3 pauses there only.""" + attempts: list[int] = [] + + def pause_on_third(_error: Exception, attempt: int) -> RetryDecision: + return RetryDecision.retry(Duration.from_seconds(1), pause=attempt == 3) + + with DurableFunctionTestRunner( + handler=_handler(attempts, succeed_on=5, retry_strategy=pause_on_third), + execution_timeout=15, + ) as runner: + arn = runner.run_async(input="{}") + + _wait_until(lambda: attempts == [1, 2, 3]) + threading.Event().wait(0.3) + assert attempts == [1, 2, 3] + assert not _has_succeeded(runner, arn) + + runner.resume_execution(arn) + result: DurableFunctionTestResult = runner.wait_for_result(arn) + + assert result.status is InvocationStatus.SUCCEEDED + assert attempts == [1, 2, 3, 4, 5] diff --git a/packages/aws-durable-execution-sdk-python/README.md b/packages/aws-durable-execution-sdk-python/README.md index b02bded04..166533913 100644 --- a/packages/aws-durable-execution-sdk-python/README.md +++ b/packages/aws-durable-execution-sdk-python/README.md @@ -172,7 +172,9 @@ def handler(event: dict, context: DurableContext) -> dict: ### Pause after repeated failures (experimental) -`StepConfig(pause_every=N)` pauses the durable execution after every Nth failed attempt that the retry strategy retries. For example, `pause_every=5` pauses after attempts 5, 10, 15, and so on. The step saves its normal retry, then the SDK asks Lambda to pause, and the invocation ends. An operator resumes the execution with the Lambda `ResumeDurableExecution` API, and the next attempt runs. +A retry decision can pause the durable execution. When the retry strategy returns `RetryDecision(pause=True)` for a failed attempt, the step saves its normal retry, then the SDK asks Lambda to pause, and the invocation ends. An operator resumes the execution with the Lambda `ResumeDurableExecution` API, and the next attempt runs. + +The built-in strategy pauses after every Nth failed attempt with `pause_every`. For example, `pause_every=5` pauses after attempts 5, 10, 15, and so on: ```python RETRY_AND_PAUSE = StepConfig( @@ -180,21 +182,34 @@ RETRY_AND_PAUSE = StepConfig( RetryStrategyConfig( max_attempts=20, initial_delay=Duration.from_seconds(60), - jitter_strategy=JitterStrategy.NONE, + pause_every=5, ) - ), - pause_every=5, + ) ) ``` -- The option does not change how many attempts run. When the retry strategy stops, the step fails as usual. -- Use a retry strategy whose delay is much longer than the pause call, for example 30 seconds or more. Do not use `pause_every` with short delays of a few seconds. -- The reason: Lambda saves the retry first, and then the SDK asks to pause. The pause takes effect a short time later. If the retry delay ends first, Lambda can run one more attempt before the execution pauses. -- The default `JitterStrategy.FULL` can pick any delay from zero up. So use `JitterStrategy.HALF` or `JitterStrategy.NONE`. -- For short waits between attempts, retry without `pause_every`. +A custom strategy sets `pause` itself. This one pauses on attempt 5 only when the error is a `PartnerUnavailableError`: + +```python +def retry_and_pause(error: Exception, attempt: int) -> RetryDecision: + if attempt >= 20: + return RetryDecision.no_retry() + return RetryDecision.retry( + Duration.from_seconds(60), + pause=attempt == 5 and isinstance(error, PartnerUnavailableError), + ) + + +RETRY_AND_PAUSE = StepConfig(retry_strategy=retry_and_pause) +``` + +- `pause` does not change how many attempts run. When the decision has `should_retry=False`, the step fails as usual and does not pause. +- Use a long delay on the pausing attempt, for example 30 seconds or more. Lambda saves the retry first, and then the SDK asks to pause. The pause takes effect a short time later. If the delay ends first, Lambda can run one more attempt before the execution pauses. +- `pause_every` uses the delay without jitter on the pausing attempt. So jitter never makes that delay near zero. In a custom strategy, do not apply jitter that can reach zero to the pausing attempt. +- Only an attempt that raised in the current invocation can pause. An `AT_MOST_ONCE_PER_RETRY` attempt that was interrupted retries without a pause. - The pause applies to the whole execution. A step in a `map` or `parallel` branch can still pause the execution after the map or parallel operation has finished. No checkpointed data is lost. Resume the execution to continue. - Give the function's execution role `lambda:PauseDurableExecution` on its own durable executions. If the pause call fails, the SDK logs a warning with the error and the step retries as usual. A missing permission is one possible cause. -- This option is experimental. It may change or be removed in a future release. +- This feature is experimental. It may change or be removed in a future release. ### Replay rules diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py index 075ab7658..199d4e89f 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/config.py @@ -535,48 +535,12 @@ class StepConfig: Replay compares the subtype with the checkpoint. So changing the subtype of an existing step is a breaking change for executions in flight. - - pause_every: Experimental; may change or be removed in a future - release. Pause the durable execution after every Nth failed - attempt that the retry strategy retries. For example, 5 pauses - after attempts 5, 10, 15, and so on. None (the default) never - pauses. Use a positive integer. The SDK does not validate the - value. - On a pause, the SDK records the normal retry checkpoint, then - calls the Lambda PauseDurableExecution API, and ends the - invocation with PENDING. The step resumes with its next attempt - after an operator calls ResumeDurableExecution. The option does - not change how many attempts run. When the retry strategy stops, - the step fails as usual and does not pause. - Only an attempt that raised in the current invocation counts. An - AT_MOST_ONCE_PER_RETRY attempt that was interrupted does not pause. - Use pause_every with a retry strategy whose delay is much longer - than the pause call, for example 30 seconds or more. Do not use - it with short delays of a few seconds. The default FULL jitter - can pick any delay from zero up, so use HALF or NONE jitter. - Lambda saves the retry first, and then the SDK asks to pause. - The pause takes effect a short time later. If the retry delay - ends first, Lambda can run one more attempt before the execution - pauses. For short waits between attempts, retry without - pause_every. - The pause applies to the whole durable execution. A step in a map - or parallel branch can still pause the execution after the map or - parallel operation has finished, for example when its completion - config needs only some branches. No checkpointed data is lost. - Resume the execution to continue. - You must give the function's execution role permission for - lambda:PauseDurableExecution on its own durable executions. If - the pause call fails, the SDK logs a warning with the error and - the step retries as usual. A missing permission is one possible - cause. A service client without pause support also retries as - usual. """ retry_strategy: Callable[[Exception, int], RetryDecision] | None = None step_semantics: StepSemantics = StepSemantics.AT_LEAST_ONCE_PER_RETRY serdes: SerDes | None = None sub_type: str | None = field(default=None, kw_only=True) - pause_every: int | None = field(default=None, kw_only=True) def __post_init__(self) -> None: _validate_sub_type(self.sub_type) diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/lambda_service.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/lambda_service.py index 5c782ce41..21e5b2d5d 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/lambda_service.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/lambda_service.py @@ -1248,7 +1248,7 @@ class PausableDurableServiceClient(Protocol): Experimental; may change or be removed in a future release. This method is optional. The SDK pauses an execution for - ``StepConfig.pause_every`` only when the client implements it. + ``RetryDecision.pause`` only when the client implements it. Otherwise the step retries as usual. """ diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/step.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/step.py index 3b52b3d79..6fed0d72e 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/step.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/operation/step.py @@ -326,7 +326,7 @@ def retry_handler( error: The exception that occurred during step execution checkpointed_result: The checkpoint data containing operation state may_pause: True when the step function raised in this invocation. - Only then does StepConfig.pause_every apply. + Only then does RetryDecision.pause apply. Raises: SuspendExecution: If retry is scheduled @@ -396,7 +396,11 @@ def retry_handler( # Request the pause only after Lambda accepted the RETRY. So no # checkpoint of this invocation can be saved without a token # before this step's RETRY is saved. - paused: bool = may_pause and self._pause_if_due(retry_attempt + 1) + paused: bool = ( + may_pause + and retry_decision.pause + and self._request_pause(retry_attempt + 1) + ) if paused: # Suspend without a resume time. The next attempt runs after @@ -433,20 +437,16 @@ def retry_handler( # step failure.) error_object.raise_as_operation_error(StepError) - def _pause_if_due(self, attempt: int) -> bool: - """Request a pause when attempt is a multiple of pause_every. + def _request_pause(self, attempt: int) -> bool: + """Request a pause of the durable execution after a failed attempt. Args: attempt: The 1-based attempt that just failed. Returns: - True if the pause request was sent. False if no pause is due, the - service client cannot pause, or the request failed. + True if the pause request was sent. False if the service client + cannot pause or the request failed. """ - pause_every: int | None = self.config.pause_every - if pause_every is None or attempt % pause_every != 0: - return False - request: PauseExecutionRequest = PauseExecutionRequest.create_for_step_attempt( self.operation_identifier, attempt, diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/retries.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/retries.py index 6b32704b7..79f40e34b 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/retries.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/retries.py @@ -26,10 +26,46 @@ @dataclass class RetryDecision: - """Decision about whether to retry a step and with what delay.""" + """Decision about whether to retry a step and with what delay. + + Attributes: + should_retry: True to run another attempt. + delay: The time to wait before the next attempt. + pause: Experimental; may change or be removed in a future release. + True pauses the durable execution after this failed attempt. + The default False never pauses. Only context.step uses this + field, and only when should_retry is True. The field does not + change how many attempts run. + On a pause, the SDK records the normal retry checkpoint, then + calls the Lambda PauseDurableExecution API, and ends the + invocation with PENDING. The step resumes with its next attempt + after an operator calls ResumeDurableExecution. + Only an attempt that raised in the current invocation can pause. + An AT_MOST_ONCE_PER_RETRY attempt that was interrupted does not + pause. + Use a long delay on the pausing attempt, for example 30 seconds + or more. Lambda saves the retry first, and then the SDK asks to + pause. The pause takes effect a short time later. If the delay + ends first, Lambda can run one more attempt before the execution + pauses. In a custom strategy, do not apply jitter that can reach + zero to the pausing attempt. The pause_every option of + create_retry_strategy already skips jitter on that attempt. + The pause applies to the whole durable execution. A step in a map + or parallel branch can still pause the execution after the map or + parallel operation has finished, for example when its completion + config needs only some branches. No checkpointed data is lost. + Resume the execution to continue. + You must give the function's execution role permission for + lambda:PauseDurableExecution on its own durable executions. If + the pause call fails, the SDK logs a warning with the error and + the step retries as usual. A missing permission is one possible + cause. A service client without pause support also retries as + usual. + """ should_retry: bool delay: Duration + pause: bool = False @property def delay_seconds(self) -> int: @@ -37,9 +73,15 @@ def delay_seconds(self) -> int: return self.delay.to_seconds() @classmethod - def retry(cls, delay: Duration) -> RetryDecision: - """Create a retry decision.""" - return cls(should_retry=True, delay=delay) + def retry(cls, delay: Duration, *, pause: bool = False) -> RetryDecision: + """Create a retry decision. + + Args: + delay: The time to wait before the next attempt. + pause: Experimental. True pauses the durable execution after + this attempt. See the pause attribute. + """ + return cls(should_retry=True, delay=delay, pause=pause) @classmethod def no_retry(cls) -> RetryDecision: @@ -49,6 +91,31 @@ def no_retry(cls) -> RetryDecision: @dataclass class RetryStrategyConfig: + """Configuration for create_retry_strategy. + + Attributes: + pause_every: Experimental; may change or be removed in a future + release. Pause the durable execution after every Nth failed + attempt that the strategy retries. For example, 5 pauses after + attempts 5, 10, 15, and so on. None (the default) never pauses. + Use a positive integer. The SDK does not validate the value. + The strategy returns RetryDecision(pause=True) on these attempts. + So the step behaves as the RetryDecision.pause attribute + describes. The option does not change how many attempts run. + When the strategy stops, the step fails as usual and does not + pause. + The pausing attempt uses the delay without jitter, so jitter + never makes that delay near zero. The other attempts use + jitter_strategy as usual. Use a long delay, for example 30 + seconds or more. If the delay ends before the pause takes effect, + Lambda can run one more attempt before the execution pauses. + The pause applies to the whole durable execution. A step in a map + or parallel branch can still pause the execution after the map or + parallel operation has finished. You must give the function's + execution role permission for lambda:PauseDurableExecution on its + own durable executions. + """ + max_attempts: int = 3 initial_delay: Duration = field(default_factory=lambda: Duration.from_seconds(5)) max_delay: Duration = field( @@ -58,6 +125,7 @@ class RetryStrategyConfig: jitter_strategy: JitterStrategy = field(default=JitterStrategy.FULL) retryable_errors: list[str | re.Pattern] | None = None retryable_error_types: list[type[Exception]] | None = None + pause_every: int | None = field(default=None, kw_only=True) @property def initial_delay_seconds(self) -> int: @@ -154,9 +222,16 @@ def retry_strategy(error: Exception, attempts_made: int) -> RetryDecision: config.initial_delay_seconds * (config.backoff_rate ** (attempts_made - 1)), config.max_delay_seconds, ) - final_delay: int = config.jitter_strategy.finalize_delay(base_delay) + pause: bool = ( + config.pause_every is not None and attempts_made % config.pause_every == 0 + ) + # The pausing attempt skips jitter, so its delay is never near zero. + jitter_strategy: JitterStrategy = ( + JitterStrategy.NONE if pause else config.jitter_strategy + ) + final_delay: int = jitter_strategy.finalize_delay(base_delay) - return RetryDecision.retry(Duration(seconds=final_delay)) + return RetryDecision.retry(Duration(seconds=final_delay), pause=pause) return retry_strategy diff --git a/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_every_test.py b/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_test.py similarity index 77% rename from packages/aws-durable-execution-sdk-python/tests/operation/step_pause_every_test.py rename to packages/aws-durable-execution-sdk-python/tests/operation/step_pause_test.py index 7d66e10f6..ceb1ae7fa 100644 --- a/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_every_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_test.py @@ -1,8 +1,9 @@ -"""Unit tests for the StepConfig.pause_every option.""" +"""Unit tests for pausing a step from the retry decision.""" from __future__ import annotations import threading +from collections.abc import Callable from unittest.mock import Mock import pytest @@ -36,7 +37,12 @@ from aws_durable_execution_sdk_python.logger import Logger from aws_durable_execution_sdk_python.operation.step import StepOperationExecutor from aws_durable_execution_sdk_python.plugin import PluginExecutor -from aws_durable_execution_sdk_python.retries import RetryDecision +from aws_durable_execution_sdk_python.retries import ( + JitterStrategy, + RetryDecision, + RetryStrategyConfig, + create_retry_strategy, +) from aws_durable_execution_sdk_python.state import CheckpointedResult, ExecutionState @@ -101,6 +107,32 @@ def _retry(_error: Exception, _attempt: int) -> RetryDecision: return RetryDecision.retry(Duration.from_seconds(5)) +def _pause(_error: Exception, _attempt: int) -> RetryDecision: + return RetryDecision.retry(Duration.from_seconds(5), pause=True) + + +def _pause_on(*attempts: int) -> Callable[[Exception, int], RetryDecision]: + """A custom strategy that pauses only on the given attempts.""" + + def strategy(_error: Exception, attempt: int) -> RetryDecision: + return RetryDecision.retry(Duration.from_seconds(5), pause=attempt in attempts) + + return strategy + + +def _pause_every(n: int) -> Callable[[Exception, int], RetryDecision]: + """The built-in strategy with pause_every and no jitter.""" + return create_retry_strategy( + RetryStrategyConfig( + max_attempts=10, + initial_delay=Duration.from_seconds(5), + backoff_rate=1, + jitter_strategy=JitterStrategy.NONE, + pause_every=n, + ) + ) + + def _request( identifier: OperationIdentifier, attempt: int, arn: str = "test_arn" ) -> PauseExecutionRequest: @@ -120,15 +152,15 @@ def _actions(state: Mock) -> list[OperationAction]: ] -def test_checkpoints_retry_then_pauses_on_attempt_multiple_and_suspends(): - """Attempt 2 with pause_every=2 sends RETRY, pauses, and suspends untimed.""" +def test_checkpoints_retry_then_pauses_when_decision_pauses(): + """A strategy that pauses on attempt 2 sends RETRY, pauses, and suspends untimed.""" state = _state(_checkpoint(OperationStatus.READY, previous_attempts=1)) order = Mock() order.attach_mock(state.pause_execution, "pause") order.attach_mock(state.create_checkpoint, "checkpoint") with pytest.raises(SuspendExecution) as exc_info: - _run(state, StepConfig(retry_strategy=_retry, pause_every=2)) + _run(state, StepConfig(retry_strategy=_pause_on(2))) assert not isinstance(exc_info.value, TimedSuspendExecution) state.pause_execution.assert_called_once_with(_request(_IDENTIFIER, 2)) @@ -142,12 +174,12 @@ def test_checkpoints_retry_then_pauses_on_attempt_multiple_and_suspends(): @pytest.mark.parametrize("previous_attempts", [3, 5]) -def test_pauses_on_later_multiples(previous_attempts: int): - """Attempts 4 and 6 are multiples of 2, so they pause too.""" +def test_helper_pause_every_pauses_on_later_multiples(previous_attempts: int): + """With the helper's pause_every=2, attempts 4 and 6 pause too.""" state = _state(_checkpoint(OperationStatus.READY, previous_attempts)) with pytest.raises(SuspendExecution) as exc_info: - _run(state, StepConfig(retry_strategy=_retry, pause_every=2)) + _run(state, StepConfig(retry_strategy=_pause_every(2))) assert not isinstance(exc_info.value, TimedSuspendExecution) state.pause_execution.assert_called_once_with( @@ -156,25 +188,53 @@ def test_pauses_on_later_multiples(previous_attempts: int): @pytest.mark.parametrize("previous_attempts", [0, 2, 4]) -def test_no_pause_on_other_attempts(previous_attempts: int): - """Attempts 1, 3 and 5 are not multiples of 2, so they retry as usual.""" +def test_helper_pause_every_does_not_pause_other_attempts(previous_attempts: int): + """With the helper's pause_every=2, attempts 1, 3 and 5 retry as usual.""" state = _state(_checkpoint(OperationStatus.READY, previous_attempts)) with pytest.raises(TimedSuspendExecution): - _run(state, StepConfig(retry_strategy=_retry, pause_every=2)) + _run(state, StepConfig(retry_strategy=_pause_every(2))) state.pause_execution.assert_not_called() assert _actions(state)[-1] is OperationAction.RETRY -def test_no_pause_by_default(): - """pause_every defaults to None and never pauses.""" +def test_no_pause_when_decision_has_no_pause(): + """A decision without pause (the default) retries as usual.""" state = _state(_checkpoint(OperationStatus.READY, previous_attempts=0)) with pytest.raises(TimedSuspendExecution): _run(state, StepConfig(retry_strategy=_retry)) state.pause_execution.assert_not_called() + assert _actions(state) == [OperationAction.START, OperationAction.RETRY] + + +def test_no_pause_when_decision_pause_is_false(): + """A strategy that returns pause=False on this attempt retries as usual.""" + state = _state(_checkpoint(OperationStatus.READY, previous_attempts=0)) + + with pytest.raises(TimedSuspendExecution): + _run(state, StepConfig(retry_strategy=_pause_on(2))) + + state.pause_execution.assert_not_called() + assert _actions(state) == [OperationAction.START, OperationAction.RETRY] + + +def test_strategy_without_pause_still_retries(): + """An existing strategy that builds RetryDecision(should_retry, delay) works unchanged.""" + + def existing(_error: Exception, _attempt: int) -> RetryDecision: + return RetryDecision(True, Duration.from_seconds(7)) # noqa: FBT003 + + state = _state(_checkpoint(OperationStatus.READY, previous_attempts=0)) + + with pytest.raises(TimedSuspendExecution): + _run(state, StepConfig(retry_strategy=existing)) + + state.pause_execution.assert_not_called() + retry_update = state.create_checkpoint.call_args_list[1].kwargs["operation_update"] + assert retry_update.step_options.next_attempt_delay_seconds == 7 def test_no_pause_when_retry_strategy_stops(): @@ -182,7 +242,22 @@ def test_no_pause_when_retry_strategy_stops(): state = _state(_checkpoint(OperationStatus.READY, previous_attempts=0)) with pytest.raises(StepError): - _run(state, StepConfig(retry_strategy=_stop, pause_every=1)) + _run(state, StepConfig(retry_strategy=_stop)) + + state.pause_execution.assert_not_called() + assert _actions(state) == [OperationAction.START, OperationAction.FAIL] + + +def test_pause_is_ignored_when_should_retry_is_false(): + """pause=True with should_retry=False fails the step and does not pause.""" + + def stop_and_pause(_error: Exception, _attempt: int) -> RetryDecision: + return RetryDecision(should_retry=False, delay=Duration(), pause=True) + + state = _state(_checkpoint(OperationStatus.READY, previous_attempts=0)) + + with pytest.raises(StepError): + _run(state, StepConfig(retry_strategy=stop_and_pause)) state.pause_execution.assert_not_called() assert _actions(state) == [OperationAction.START, OperationAction.FAIL] @@ -195,7 +270,7 @@ def test_pause_failure_logs_warning_and_retries_as_usual(): logger = _logger() with pytest.raises(TimedSuspendExecution): - _run(state, StepConfig(retry_strategy=_retry, pause_every=1), logger) + _run(state, StepConfig(retry_strategy=_pause), logger) logger.warning.assert_called_once() warning_args = logger.warning.call_args.args @@ -217,7 +292,7 @@ def test_pause_client_error_warning_names_the_service_error_code(): logger = _logger() with pytest.raises(TimedSuspendExecution): - _run(state, StepConfig(retry_strategy=_retry, pause_every=1), logger) + _run(state, StepConfig(retry_strategy=_pause), logger) warning_args = logger.warning.call_args.args message = warning_args[0] % warning_args[1:] @@ -236,7 +311,7 @@ def test_pause_conflict_warning_does_not_blame_permissions(): logger = _logger() with pytest.raises(TimedSuspendExecution): - _run(state, StepConfig(retry_strategy=_retry, pause_every=1), logger) + _run(state, StepConfig(retry_strategy=_pause), logger) warning_args = logger.warning.call_args.args message = warning_args[0] % warning_args[1:] @@ -252,7 +327,7 @@ def test_pause_client_error_without_code_uses_type_name(): logger = _logger() with pytest.raises(TimedSuspendExecution): - _run(state, StepConfig(retry_strategy=_retry, pause_every=1), logger) + _run(state, StepConfig(retry_strategy=_pause), logger) warning_args = logger.warning.call_args.args assert "Error: ClientError: " in warning_args[0] % warning_args[1:] @@ -265,26 +340,28 @@ def test_client_without_pause_support_retries_as_usual(): state.pause_execution.return_value = False with pytest.raises(TimedSuspendExecution): - _run(state, StepConfig(retry_strategy=_retry, pause_every=1)) + _run(state, StepConfig(retry_strategy=_pause)) state.pause_execution.assert_called_once() assert _actions(state) == [OperationAction.START, OperationAction.RETRY] def test_no_pause_on_interrupted_at_most_once_replay(): - """An interrupted AT_MOST_ONCE attempt goes to retry without pausing.""" + """An interrupted AT_MOST_ONCE attempt ignores pause=True and retries.""" state = _state(_checkpoint(OperationStatus.STARTED, previous_attempts=0)) + strategy = Mock(side_effect=_pause) with pytest.raises(TimedSuspendExecution): _run( state, StepConfig( - retry_strategy=_retry, + retry_strategy=strategy, step_semantics=StepSemantics.AT_MOST_ONCE_PER_RETRY, - pause_every=1, ), ) + # The replay path asks the strategy, and the strategy returns pause=True. + strategy.assert_called_once() state.pause_execution.assert_not_called() assert _actions(state) == [OperationAction.RETRY] @@ -296,7 +373,7 @@ def test_revoked_token_on_retry_checkpoint_suspends(): state.create_checkpoint.side_effect = [None, revoked] with pytest.raises(SuspendExecution) as exc_info: - _run(state, StepConfig(retry_strategy=_retry, pause_every=1)) + _run(state, StepConfig(retry_strategy=_pause)) assert exc_info.value is revoked # The execution is already pausing, so the step does not pause it again. @@ -319,7 +396,7 @@ def pause(_request: PauseExecutionRequest) -> bool: state.pause_execution.side_effect = pause with pytest.raises(SuspendExecution) as exc_info: - _run(state, StepConfig(retry_strategy=_retry, pause_every=1)) + _run(state, StepConfig(retry_strategy=_pause)) assert not isinstance(exc_info.value, TimedSuspendExecution) state.pause_execution.assert_called_once() @@ -371,7 +448,7 @@ def failing_step(_ctx: object) -> str: with pytest.raises(SuspendExecution) as exc_info: StepOperationExecutor( func=failing_step, - config=StepConfig(retry_strategy=_retry, pause_every=1), + config=StepConfig(retry_strategy=_pause), state=state, operation_identifier=_IDENTIFIER, context_logger=_logger(), @@ -429,7 +506,7 @@ def test_step_pause_request_uses_the_execution_arn(): state.durable_execution_arn = "other_arn" with pytest.raises(SuspendExecution): - _run(state, StepConfig(retry_strategy=_retry, pause_every=1)) + _run(state, StepConfig(retry_strategy=_pause)) state.pause_execution.assert_called_once_with( _request(_IDENTIFIER, 1, arn="other_arn") @@ -515,6 +592,7 @@ def test_lambda_client_pause_durable_execution(): ) -def test_step_config_pause_every_is_keyword_only_and_defaults_to_none(): - assert StepConfig().pause_every is None - assert StepConfig(pause_every=3).pause_every == 3 +def test_step_config_has_no_pause_every(): + """Pausing comes from the retry decision, not from StepConfig.""" + with pytest.raises(TypeError): + StepConfig(pause_every=3) # type: ignore[call-arg] diff --git a/packages/aws-durable-execution-sdk-python/tests/retries_test.py b/packages/aws-durable-execution-sdk-python/tests/retries_test.py index b82d3ed7d..e3b364d48 100644 --- a/packages/aws-durable-execution-sdk-python/tests/retries_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/retries_test.py @@ -89,6 +89,20 @@ def test_no_retry_factory(): decision = RetryDecision.no_retry() assert decision.should_retry is False assert decision.delay_seconds == 0 + assert decision.pause is False + + +def test_retry_decision_pause_defaults_to_false(): + """Existing callers that pass only should_retry and delay get pause=False.""" + assert RetryDecision(True, Duration.from_seconds(3)).pause is False # noqa: FBT003 + assert RetryDecision.retry(Duration.from_seconds(3)).pause is False + + +def test_retry_factory_with_pause(): + decision = RetryDecision.retry(Duration.from_seconds(30), pause=True) + assert decision.should_retry is True + assert decision.delay_seconds == 30 + assert decision.pause is True # endregion @@ -721,3 +735,93 @@ def test_retry_presets_fixed_stops_at_max_attempts(): # endregion + + +# region pause_every + + +def _pausing_strategy(jitter: JitterStrategy = JitterStrategy.NONE, pause_every=5): + return create_retry_strategy( + RetryStrategyConfig( + max_attempts=20, + initial_delay=Duration.from_seconds(60), + backoff_rate=1, + jitter_strategy=jitter, + pause_every=pause_every, + ) + ) + + +def test_pause_every_defaults_to_none_and_never_pauses(): + assert RetryStrategyConfig().pause_every is None + strategy = create_retry_strategy(RetryStrategyConfig(max_attempts=20)) + assert not any(strategy(Exception("e"), n).pause for n in range(1, 20)) + + +@pytest.mark.parametrize( + ("attempt", "pause"), + [(1, False), (4, False), (5, True), (6, False), (9, False), (10, True), (15, True)], +) +def test_pause_every_pauses_on_multiples_only(attempt, pause): + decision = _pausing_strategy()(Exception("e"), attempt) + assert decision.should_retry is True + assert decision.pause is pause + + +def test_pause_every_does_not_pause_when_attempts_are_exhausted(): + """The strategy stops at max_attempts, so a multiple there does not pause.""" + strategy = _pausing_strategy(pause_every=20) + decision = strategy(Exception("e"), 20) + assert decision.should_retry is False + assert decision.pause is False + + +def test_pause_every_does_not_pause_non_retryable_errors(): + strategy = create_retry_strategy( + RetryStrategyConfig(retryable_errors=["timeout"], pause_every=1) + ) + decision = strategy(Exception("permission denied"), 1) + assert decision.should_retry is False + assert decision.pause is False + + +@patch("random.random", return_value=0.0) +def test_pause_every_skips_full_jitter_on_the_pausing_attempt(_mock_random): + """FULL jitter with random 0 gives 1 s, but the pausing attempt keeps 60 s.""" + strategy = _pausing_strategy(JitterStrategy.FULL) + assert strategy(Exception("e"), 5).delay_seconds == 60 + assert strategy(Exception("e"), 10).delay_seconds == 60 + + +@patch("random.random", return_value=0.0) +def test_pause_every_keeps_jitter_on_other_attempts(_mock_random): + strategy = _pausing_strategy(JitterStrategy.FULL) + assert strategy(Exception("e"), 4).delay_seconds == 1 + assert strategy(Exception("e"), 6).delay_seconds == 1 + + +@patch("random.random", return_value=0.0) +def test_pause_every_skips_half_jitter_on_the_pausing_attempt(_mock_random): + strategy = _pausing_strategy(JitterStrategy.HALF) + assert strategy(Exception("e"), 5).delay_seconds == 60 + assert strategy(Exception("e"), 6).delay_seconds == 30 + + +def test_pause_every_uses_backoff_delay_on_the_pausing_attempt(): + """The pausing attempt uses the backoff and max_delay cap, without jitter.""" + strategy = create_retry_strategy( + RetryStrategyConfig( + max_attempts=10, + initial_delay=Duration.from_seconds(10), + max_delay=Duration.from_seconds(100), + backoff_rate=2, + pause_every=2, + ) + ) + # attempt 2: 10 * 2 = 20; attempt 4: 10 * 8 = 80; attempt 6: capped at 100. + assert strategy(Exception("e"), 2).delay_seconds == 20 + assert strategy(Exception("e"), 4).delay_seconds == 80 + assert strategy(Exception("e"), 6).delay_seconds == 100 + + +# endregion From 6ca306bd82639da689b5ab487a2373584f5ad781 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Wed, 18 Nov 2026 20:51:26 +0000 Subject: [PATCH 6/6] fix(sdk): keep jitter on the pausing attempt A live test against Lambda showed that Lambda holds the next invocation after the PauseDurableExecution call succeeds. So no extra attempt can run before the pause takes effect. The pause_every helper no longer skips jitter on the pausing attempt. That attempt uses jitter_strategy like every other attempt. The docs no longer ask for long delays or jitter limits. The docs now name kms:Decrypt for functions that use a customer managed AWS KMS key. They say that with_retry ignores pause and that the wait_for_callback submitter uses it. The examples of a pausing decision use RetryDecision.retry(delay, pause=True). The test test_step_config_has_no_pause_every is removed. It passed on main too. --- .../src/step/step_with_pause_every.py | 19 ++------ .../README.md | 7 ++- .../retries.py | 46 ++++++++----------- .../tests/operation/step_pause_test.py | 6 --- .../tests/retries_test.py | 26 +++++------ 5 files changed, 38 insertions(+), 66 deletions(-) diff --git a/packages/aws-durable-execution-sdk-python-examples/src/step/step_with_pause_every.py b/packages/aws-durable-execution-sdk-python-examples/src/step/step_with_pause_every.py index 879f3db98..bfe856db0 100644 --- a/packages/aws-durable-execution-sdk-python-examples/src/step/step_with_pause_every.py +++ b/packages/aws-durable-execution-sdk-python-examples/src/step/step_with_pause_every.py @@ -4,17 +4,15 @@ future release. The function's execution role needs lambda:PauseDurableExecution on its own -durable executions. Without it, the step logs a warning and retries as usual. +durable executions. A function that uses a customer managed AWS KMS key also +needs kms:Decrypt on that key. Without these permissions, the step logs a +warning and retries as usual. An operator resumes a paused execution with ResumeDurableExecution. """ from typing import Any -from aws_durable_execution_sdk_python.config import ( - Duration, - JitterStrategy, - StepConfig, -) +from aws_durable_execution_sdk_python.config import StepConfig from aws_durable_execution_sdk_python.context import ( DurableContext, StepContext, @@ -42,15 +40,6 @@ def handler(_event: Any, context: DurableContext) -> str: retry_strategy=create_retry_strategy( RetryStrategyConfig( max_attempts=10, - # pause_every needs a long retry delay. Lambda saves the retry - # first, and the pause takes effect a short time later. A short - # delay can let one more attempt run before the pause. The - # pausing attempt never uses jitter. No jitter and no backoff - # keep every delay at 60 seconds. The local test runner skips - # the delays, so tests stay fast. - initial_delay=Duration.from_seconds(60), - backoff_rate=1, - jitter_strategy=JitterStrategy.NONE, retryable_error_types=[RuntimeError], # Pause after attempts 3, 6, 9. An operator can inspect the # error and resume the execution when the partner API is back. diff --git a/packages/aws-durable-execution-sdk-python/README.md b/packages/aws-durable-execution-sdk-python/README.md index 166533913..aee9c2717 100644 --- a/packages/aws-durable-execution-sdk-python/README.md +++ b/packages/aws-durable-execution-sdk-python/README.md @@ -172,7 +172,7 @@ def handler(event: dict, context: DurableContext) -> dict: ### Pause after repeated failures (experimental) -A retry decision can pause the durable execution. When the retry strategy returns `RetryDecision(pause=True)` for a failed attempt, the step saves its normal retry, then the SDK asks Lambda to pause, and the invocation ends. An operator resumes the execution with the Lambda `ResumeDurableExecution` API, and the next attempt runs. +A retry decision can pause the durable execution. When the retry strategy returns `RetryDecision.retry(delay, pause=True)` for a failed attempt, the step saves its normal retry, then the SDK asks Lambda to pause, and the invocation ends. An operator resumes the execution with the Lambda `ResumeDurableExecution` API, and the next attempt runs. The built-in strategy pauses after every Nth failed attempt with `pause_every`. For example, `pause_every=5` pauses after attempts 5, 10, 15, and so on: @@ -204,11 +204,10 @@ RETRY_AND_PAUSE = StepConfig(retry_strategy=retry_and_pause) ``` - `pause` does not change how many attempts run. When the decision has `should_retry=False`, the step fails as usual and does not pause. -- Use a long delay on the pausing attempt, for example 30 seconds or more. Lambda saves the retry first, and then the SDK asks to pause. The pause takes effect a short time later. If the delay ends first, Lambda can run one more attempt before the execution pauses. -- `pause_every` uses the delay without jitter on the pausing attempt. So jitter never makes that delay near zero. In a custom strategy, do not apply jitter that can reach zero to the pausing attempt. +- `context.step` uses `pause`, including the `wait_for_callback` submitter. `with_retry` ignores `pause`. - Only an attempt that raised in the current invocation can pause. An `AT_MOST_ONCE_PER_RETRY` attempt that was interrupted retries without a pause. - The pause applies to the whole execution. A step in a `map` or `parallel` branch can still pause the execution after the map or parallel operation has finished. No checkpointed data is lost. Resume the execution to continue. -- Give the function's execution role `lambda:PauseDurableExecution` on its own durable executions. If the pause call fails, the SDK logs a warning with the error and the step retries as usual. A missing permission is one possible cause. +- Give the function's execution role `lambda:PauseDurableExecution` on its own durable executions. If the function uses a customer managed AWS KMS key, the role also needs `kms:Decrypt` on that key, as the [Lambda pause and resume prerequisites](https://docs.aws.amazon.com/lambda/latest/dg/durable-pause-resume.html#durable-pause-resume-prerequisites) require. If the pause call fails, the SDK logs a warning with the error and the step retries as usual. A missing permission is one possible cause. - This feature is experimental. It may change or be removed in a future release. ### Replay rules diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/retries.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/retries.py index 79f40e34b..36fc5a850 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/retries.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/retries.py @@ -33,9 +33,10 @@ class RetryDecision: delay: The time to wait before the next attempt. pause: Experimental; may change or be removed in a future release. True pauses the durable execution after this failed attempt. - The default False never pauses. Only context.step uses this - field, and only when should_retry is True. The field does not - change how many attempts run. + The default False never pauses. context.step uses this field, + including the wait_for_callback submitter. with_retry ignores + it. The field applies only when should_retry is True. It does + not change how many attempts run. On a pause, the SDK records the normal retry checkpoint, then calls the Lambda PauseDurableExecution API, and ends the invocation with PENDING. The step resumes with its next attempt @@ -43,13 +44,6 @@ class RetryDecision: Only an attempt that raised in the current invocation can pause. An AT_MOST_ONCE_PER_RETRY attempt that was interrupted does not pause. - Use a long delay on the pausing attempt, for example 30 seconds - or more. Lambda saves the retry first, and then the SDK asks to - pause. The pause takes effect a short time later. If the delay - ends first, Lambda can run one more attempt before the execution - pauses. In a custom strategy, do not apply jitter that can reach - zero to the pausing attempt. The pause_every option of - create_retry_strategy already skips jitter on that attempt. The pause applies to the whole durable execution. A step in a map or parallel branch can still pause the execution after the map or parallel operation has finished, for example when its completion @@ -57,10 +51,11 @@ class RetryDecision: Resume the execution to continue. You must give the function's execution role permission for lambda:PauseDurableExecution on its own durable executions. If - the pause call fails, the SDK logs a warning with the error and - the step retries as usual. A missing permission is one possible - cause. A service client without pause support also retries as - usual. + the function uses a customer managed AWS KMS key, the role also + needs kms:Decrypt on that key. If the pause call fails, the SDK + logs a warning with the error and the step retries as usual. A + missing permission is one possible cause. A service client + without pause support also retries as usual. """ should_retry: bool @@ -99,21 +94,18 @@ class RetryStrategyConfig: attempt that the strategy retries. For example, 5 pauses after attempts 5, 10, 15, and so on. None (the default) never pauses. Use a positive integer. The SDK does not validate the value. - The strategy returns RetryDecision(pause=True) on these attempts. - So the step behaves as the RetryDecision.pause attribute - describes. The option does not change how many attempts run. + The strategy returns RetryDecision.retry(delay, pause=True) on + these attempts. So the step behaves as the RetryDecision.pause + attribute describes. The option does not change how many + attempts run, and it does not change the delay or the jitter. When the strategy stops, the step fails as usual and does not pause. - The pausing attempt uses the delay without jitter, so jitter - never makes that delay near zero. The other attempts use - jitter_strategy as usual. Use a long delay, for example 30 - seconds or more. If the delay ends before the pause takes effect, - Lambda can run one more attempt before the execution pauses. The pause applies to the whole durable execution. A step in a map or parallel branch can still pause the execution after the map or parallel operation has finished. You must give the function's execution role permission for lambda:PauseDurableExecution on its - own durable executions. + own durable executions. If the function uses a customer managed + AWS KMS key, the role also needs kms:Decrypt on that key. """ max_attempts: int = 3 @@ -225,11 +217,7 @@ def retry_strategy(error: Exception, attempts_made: int) -> RetryDecision: pause: bool = ( config.pause_every is not None and attempts_made % config.pause_every == 0 ) - # The pausing attempt skips jitter, so its delay is never near zero. - jitter_strategy: JitterStrategy = ( - JitterStrategy.NONE if pause else config.jitter_strategy - ) - final_delay: int = jitter_strategy.finalize_delay(base_delay) + final_delay: int = config.jitter_strategy.finalize_delay(base_delay) return RetryDecision.retry(Duration(seconds=final_delay), pause=pause) @@ -377,6 +365,8 @@ class WithRetryConfig(Generic[T]): child_context_config: Optional ChildConfig forwarded to run_in_child_context when wrapping is enabled. Ignored when wrap_with_run_in_child_context is False. + + with_retry ignores RetryDecision.pause, so it never pauses the execution. """ retry_strategy: Callable[[Exception, int], RetryDecision] | None = None diff --git a/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_test.py b/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_test.py index ceb1ae7fa..384b883aa 100644 --- a/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_test.py @@ -590,9 +590,3 @@ def test_lambda_client_pause_durable_execution(): boto_client.pause_durable_execution.assert_called_once_with( DurableExecutionArn="arn", ClientToken="token", Reason="why" ) - - -def test_step_config_has_no_pause_every(): - """Pausing comes from the retry decision, not from StepConfig.""" - with pytest.raises(TypeError): - StepConfig(pause_every=3) # type: ignore[call-arg] diff --git a/packages/aws-durable-execution-sdk-python/tests/retries_test.py b/packages/aws-durable-execution-sdk-python/tests/retries_test.py index e3b364d48..2cede4518 100644 --- a/packages/aws-durable-execution-sdk-python/tests/retries_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/retries_test.py @@ -785,12 +785,18 @@ def test_pause_every_does_not_pause_non_retryable_errors(): assert decision.pause is False +@pytest.mark.parametrize( + ("jitter", "delay"), + [(JitterStrategy.FULL, 1), (JitterStrategy.HALF, 30), (JitterStrategy.NONE, 60)], +) @patch("random.random", return_value=0.0) -def test_pause_every_skips_full_jitter_on_the_pausing_attempt(_mock_random): - """FULL jitter with random 0 gives 1 s, but the pausing attempt keeps 60 s.""" - strategy = _pausing_strategy(JitterStrategy.FULL) - assert strategy(Exception("e"), 5).delay_seconds == 60 - assert strategy(Exception("e"), 10).delay_seconds == 60 +def test_pause_every_keeps_configured_jitter_on_the_pausing_attempt( + _mock_random, jitter, delay +): + """The pausing attempt uses jitter_strategy like every other attempt.""" + decision = _pausing_strategy(jitter)(Exception("e"), 5) + assert decision.pause is True + assert decision.delay_seconds == delay @patch("random.random", return_value=0.0) @@ -800,21 +806,15 @@ def test_pause_every_keeps_jitter_on_other_attempts(_mock_random): assert strategy(Exception("e"), 6).delay_seconds == 1 -@patch("random.random", return_value=0.0) -def test_pause_every_skips_half_jitter_on_the_pausing_attempt(_mock_random): - strategy = _pausing_strategy(JitterStrategy.HALF) - assert strategy(Exception("e"), 5).delay_seconds == 60 - assert strategy(Exception("e"), 6).delay_seconds == 30 - - def test_pause_every_uses_backoff_delay_on_the_pausing_attempt(): - """The pausing attempt uses the backoff and max_delay cap, without jitter.""" + """The pausing attempt uses the backoff and the max_delay cap.""" strategy = create_retry_strategy( RetryStrategyConfig( max_attempts=10, initial_delay=Duration.from_seconds(10), max_delay=Duration.from_seconds(100), backoff_rate=2, + jitter_strategy=JitterStrategy.NONE, pause_every=2, ) )