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..bfe856db0 --- /dev/null +++ b/packages/aws-durable-execution-sdk-python-examples/src/step/step_with_pause_every.py @@ -0,0 +1,52 @@ +"""Pause the execution after every third failed attempt of a step. + +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. 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 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, + 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..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 @@ -157,6 +157,22 @@ 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 + 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: + 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..658a439d3 --- /dev/null +++ b/packages/aws-durable-execution-sdk-python-testing/tests/e2e/step_pause_every_test.py @@ -0,0 +1,145 @@ +"""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(). + +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 ( + RetryDecision, + 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, + retry_strategy: Callable[[Exception, int], RetryDecision] | None = None, +) -> Callable[..., Any]: + config = StepConfig( + 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, + ) + ), + ) + + 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] + + +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 4c4f600d8..aee9c2717 100644 --- a/packages/aws-durable-execution-sdk-python/README.md +++ b/packages/aws-durable-execution-sdk-python/README.md @@ -170,6 +170,46 @@ def handler(event: dict, context: DurableContext) -> dict: `RetryPresets` in `aws_durable_execution_sdk_python.retries` holds ready-made strategies. +### Pause after repeated failures (experimental) + +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: + +```python +RETRY_AND_PAUSE = StepConfig( + retry_strategy=create_retry_strategy( + RetryStrategyConfig( + max_attempts=20, + initial_delay=Duration.from_seconds(60), + pause_every=5, + ) + ) +) +``` + +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. +- `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 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 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/lambda_service.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/lambda_service.py index e43c400cf..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 @@ -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,44 @@ 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, + *, + durable_execution_arn: str, + ) -> PauseExecutionRequest: + """Create the pause request for a failed step attempt. + + 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:{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}' + return cls(client_token=client_token, reason=reason[:_MAX_PAUSE_REASON]) + + # endregion model @@ -1194,7 +1241,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 + ``RetryDecision.pause`` 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 +1355,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..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 @@ -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, @@ -20,6 +22,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 +307,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 +317,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 RetryDecision.pause apply. Raises: SuspendExecution: If retry is scheduled @@ -380,8 +387,32 @@ def retry_handler( # 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 retry_decision.pause + and self._request_pause(retry_attempt + 1) + ) + + 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 +436,49 @@ def retry_handler( # exhausted StepInterruptedError surfaces the same way as any other # step failure.) error_object.raise_as_operation_error(StepError) + + 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 the service client + cannot pause or the request failed. + """ + request: PauseExecutionRequest = PauseExecutionRequest.create_for_step_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 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." + ) + self.context_logger.warning( + "Could not pause the execution after attempt %s of step %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/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..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 @@ -26,10 +26,41 @@ @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. 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 + 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. + 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 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 delay: Duration + pause: bool = False @property def delay_seconds(self) -> int: @@ -37,9 +68,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 +86,28 @@ 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.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 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. If the function uses a customer managed + AWS KMS key, the role also needs kms:Decrypt on that key. + """ + max_attempts: int = 3 initial_delay: Duration = field(default_factory=lambda: Duration.from_seconds(5)) max_delay: Duration = field( @@ -58,6 +117,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 +214,12 @@ def retry_strategy(error: Exception, attempts_made: int) -> RetryDecision: config.initial_delay_seconds * (config.backoff_rate ** (attempts_made - 1)), config.max_delay_seconds, ) + pause: bool = ( + config.pause_every is not None and attempts_made % config.pause_every == 0 + ) final_delay: int = config.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 @@ -302,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/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_test.py b/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_test.py new file mode 100644 index 000000000..384b883aa --- /dev/null +++ b/packages/aws-durable-execution-sdk-python/tests/operation/step_pause_test.py @@ -0,0 +1,592 @@ +"""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 +from botocore.exceptions import ClientError + +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 ( + CheckpointOutput, + CheckpointUpdatedExecutionState, + LambdaClient, + Operation, + OperationAction, + OperationStatus, + OperationSubType, + OperationType, + PausableDurableServiceClient, + PauseExecutionRequest, + StateOutput, + 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 ( + JitterStrategy, + RetryDecision, + RetryStrategyConfig, + create_retry_strategy, +) +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 _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: + return PauseExecutionRequest.create_for_step_attempt( + identifier, attempt, durable_execution_arn=arn + ) + + +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_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=_pause_on(2))) + + assert not isinstance(exc_info.value, TimedSuspendExecution) + state.pause_execution.assert_called_once_with(_request(_IDENTIFIER, 2)) + assert _actions(state) == [OperationAction.START, OperationAction.RETRY] + # The pause request follows the RETRY checkpoint. + names = [c[0] for c in order.mock_calls] + 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 + + +@pytest.mark.parametrize("previous_attempts", [3, 5]) +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=_pause_every(2))) + + assert not isinstance(exc_info.value, TimedSuspendExecution) + state.pause_execution.assert_called_once_with( + _request(_IDENTIFIER, previous_attempts + 1) + ) + + +@pytest.mark.parametrize("previous_attempts", [0, 2, 4]) +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=_pause_every(2))) + + state.pause_execution.assert_not_called() + assert _actions(state)[-1] is OperationAction.RETRY + + +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(): + """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)) + + 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] + + +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=_pause), logger) + + logger.warning.assert_called_once() + warning_args = logger.warning.call_args.args + 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=_pause), 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 closed or paused.""" + 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=_pause), logger) + + warning_args = logger.warning.call_args.args + message = warning_args[0] % warning_args[1:] + assert "Error: ResourceConflictException: " in message + assert "has closed (for example, stopped) or is already 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=_pause), 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] + + +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=_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 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=strategy, + step_semantics=StepSemantics.AT_MOST_ONCE_PER_RETRY, + ), + ) + + # 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] + + +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=_pause)) + + 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=_pause)) + + 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=_pause), + 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 on the execution ARN, operation id and attempt.""" + first = _request(_IDENTIFIER, 5) + again = _request(_IDENTIFIER, 5) + renamed = _request( + OperationIdentifier( + _OPERATION_ID, + OperationSubType.STEP, + None, + "other", + operation_type=OperationType.STEP, + ), + 5, + ) + next_attempt = _request(_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_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=_pause)) + + 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, + OperationSubType.STEP, + operation_type=OperationType.STEP, + ) + + request = _request(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 = _request(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" + ) 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..2cede4518 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 + + +@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_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) +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 + + +def test_pause_every_uses_backoff_delay_on_the_pausing_attempt(): + """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, + ) + ) + # 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