From 826829fe87e763b705503766562fab4d35c12112 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Thu, 26 Nov 2026 23:09:54 +0000 Subject: [PATCH 01/17] feat(sdk): add AT_LEAST_ONCE_ASYNC step semantics An AT_LEAST_ONCE_ASYNC step queues its SUCCEED checkpoint and returns at once. RETRY and FAIL are still awaited. The batcher now sends the checkpoints still queued when it is told to stop. So the SUCCEED is saved before the invocation returns. A batch that fails without the handler seeing it fails the invocation instead of reporting SUCCEEDED. --- .../config.py | 26 ++ .../execution.py | 7 + .../operation/step.py | 23 +- .../aws_durable_execution_sdk_python/state.py | 31 +- .../step_at_least_once_async_test.py | 327 ++++++++++++++++++ .../tests/state_test.py | 29 +- 6 files changed, 413 insertions(+), 30 deletions(-) create mode 100644 packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py 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..2e33dcd49 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 @@ -477,8 +477,32 @@ def __call__(self, *args, **kwargs): class StepSemantics(Enum): + """How often one step attempt may run its function. See StepConfig. + + AT_LEAST_ONCE_ASYNC works like AT_LEAST_ONCE_PER_RETRY, with one change. + The step returns its result as soon as the SUCCEED checkpoint is queued. + It does not wait for the service to save it. So the step has lower + latency. + + The code after the step can run before the result is saved. If the + invocation ends before the save, the step runs again on replay. + Checkpoints are sent in order, and every invocation sends its queued + checkpoints before it returns. So any later checkpoint that the service + accepts also saves this result. + + On that replay the step can return a different value. Later steps then + run again with the new value, and their earlier side effects used the old + one. So do not use this mode for a step whose result becomes an + idempotency key or a client token for a later step. + + Only the SUCCEED checkpoint is not awaited. A failed attempt waits for + its RETRY or FAIL checkpoint. A plugin receives the step's end hook after + the service saves the result, at the latest when the invocation ends. + """ + AT_MOST_ONCE_PER_RETRY = "AT_MOST_ONCE_PER_RETRY" AT_LEAST_ONCE_PER_RETRY = "AT_LEAST_ONCE_PER_RETRY" + AT_LEAST_ONCE_ASYNC = "AT_LEAST_ONCE_ASYNC" _SUB_TYPE_CHARACTERS = frozenset(string.ascii_letters + string.digits + "-_") @@ -520,6 +544,8 @@ class StepConfig: invocation. AT_MOST_ONCE_PER_RETRY waits for the START checkpoint first, and an interrupted attempt fails with StepInterruptedError and goes to the retry strategy instead of running again. + AT_LEAST_ONCE_ASYNC also does not wait for the SUCCEED + checkpoint; see StepSemantics. serdes: Custom serialization/deserialization for the step result. If None, uses the default JSON serializer. diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py index c5d4e3403..4fd0a2f02 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py @@ -567,6 +567,13 @@ def wait_for_checkpoint() -> None: output = ( DurableExecutionInvocationOutput.create_pending().to_dict() ) + # A batch can fail without the handler seeing it, for + # example the SUCCEED of an AT_LEAST_ONCE_ASYNC step sent + # while the handler returns. That result is not saved. So + # the invocation fails instead of reporting SUCCEEDED, and + # the next invocation runs the step again. + if output.get("Status") == InvocationStatus.SUCCEEDED.value: + execution_state.raise_if_checkpointing_failed() completed = DurableExecutionInvocationOutput.from_dict(output) except BaseException as error: # Every started plugin gets its End hook, including when 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 6fed0d72e..c393d3aae 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 @@ -149,11 +149,9 @@ def check_result_status(self) -> CheckResult[T]: self.retry_handler(StepInterruptedError(msg), checkpointed_result) checkpointed_result.raise_operation_error(StepError) - # Ready to execute if STARTED + AT_LEAST_ONCE - if ( - checkpointed_result.is_started() - and self.config.step_semantics is StepSemantics.AT_LEAST_ONCE_PER_RETRY - ): + # Ready to execute if STARTED + AT_LEAST_ONCE (with or without ASYNC). + # An interrupted AT_MOST_ONCE attempt raised above. + if checkpointed_result.is_started(): return CheckResult.create_is_ready_to_execute(checkpointed_result) # Create START checkpoint if nonexistent or READY @@ -258,10 +256,17 @@ def execute(self, checkpointed_result: CheckpointedResult) -> T: payload=serialized_result, ) - # Checkpoint SUCCEED operation with blocking (is_sync=True, default). - # Must ensure the success state is persisted before returning the result to the caller. - # This guarantees the step result is durable and won't be lost if Lambda terminates. - self.state.create_checkpoint(operation_update=success_operation) + # Checkpoint SUCCEED with blocking (is_sync=True), so the result is + # durable before the step returns. AT_LEAST_ONCE_ASYNC does not wait. + # Checkpoints are sent in queue order, and the batcher sends the + # queued ones before the invocation returns. A failed batch fails + # the invocation, so the step runs again on replay. + self.state.create_checkpoint( + operation_update=success_operation, + is_sync=( + self.config.step_semantics is not StepSemantics.AT_LEAST_ONCE_ASYNC + ), + ) logger.debug( "✅ Successfully completed step for id: %s, name: %s", 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 0cb53471d..944ba565b 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 @@ -746,6 +746,11 @@ 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 raise_if_checkpointing_failed(self) -> None: + """Raise the BackgroundThreadError of a failed checkpoint batch, if any.""" + if self._checkpointing_failed.is_set(): + self._checkpointing_failed.wait() + def pause_execution(self, request: PauseExecutionRequest) -> bool: """Ask the service to pause this durable execution. @@ -1131,14 +1136,16 @@ def checkpoint_batches_forever(self) -> None: Their waiters receive OrphanedChildException on completion, SuspendExecution on revocation, or BackgroundThreadError on failure. - On a plain shutdown signal the queue is not drained: only non-essential - asynchronous checkpoints can remain, since the main thread blocks on - every synchronous one. + On a plain shutdown signal the loop first sends the operations still + queued. These are asynchronous checkpoints, since the main thread + blocks on every synchronous one. One of them can be the SUCCEED of an + AT_LEAST_ONCE_ASYNC step, which must be saved before the invocation + returns. """ # Keep checkpoint token as local variable in the loop current_checkpoint_token: str = self._current_checkpoint_token - while not self._checkpointing_stopped.is_set(): + while not self._is_shut_down(): # Collect operations into a batch batch: list[QueuedOperation] = self._collect_checkpoint_batch() @@ -1387,13 +1394,21 @@ def stop_checkpointing(self) -> None: """Signal background thread to stop checkpointing. This method sets the checkpointing stopped event, which signals the background - thread to exit. Any remaining async checkpoints in the queue are non-essential - (observability only) and will be abandoned. All critical synchronous checkpoints + thread to exit. The thread first sends the async checkpoints still in the queue, + such as the SUCCEED of an AT_LEAST_ONCE_ASYNC step. All synchronous checkpoints will have already completed before this is called. """ logger.debug("Signaling background thread to stop checkpointing") self._checkpointing_stopped.set() + def _is_shut_down(self) -> bool: + """Return True once shutdown is signaled and no queued operation is left.""" + return ( + self._checkpointing_stopped.is_set() + and self._checkpoint_queue.empty() + and self._overflow_queue.empty() + ) + def register_branch_pool(self, pool: ThreadPoolExecutor) -> None: """Register a branch thread pool for joining at invocation end. @@ -1446,7 +1461,7 @@ def _collect_checkpoint_batch(self) -> list[QueuedOperation]: return [] deadline = time.time() + self._batcher_config.max_batch_time_seconds - while not batch.is_full() and not self._checkpointing_stopped.is_set(): + while not batch.is_full() and not self._is_shut_down(): now = time.time() self._add_due_refreshes(batch, now) timeout = self._read_timeout(batch, now, deadline) @@ -1501,7 +1516,7 @@ def _drain_overflow(self, batch: _BatchAccumulator) -> None: def _wait_for_first_operation(self, batch: _BatchAccumulator) -> bool: """Block until the batch has an operation. Returns False at shutdown.""" - while not self._checkpointing_stopped.is_set(): + while not self._is_shut_down(): now = time.time() timeout = _STOP_SIGNAL_POLL_SECONDS until_refresh = self._seconds_until_next_refresh(now) diff --git a/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py b/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py new file mode 100644 index 000000000..a140609d7 --- /dev/null +++ b/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py @@ -0,0 +1,327 @@ +"""Tests for StepSemantics.AT_LEAST_ONCE_ASYNC. + +The handlers run through durable_execution with a fake service client, so the +real checkpoint batcher thread sends every checkpoint. +""" + +from __future__ import annotations + +import threading +import time +from typing import Any +from unittest.mock import Mock + +import pytest + +from aws_durable_execution_sdk_python.config import Duration, StepConfig, StepSemantics +from aws_durable_execution_sdk_python.context import DurableContext +from aws_durable_execution_sdk_python.exceptions import ( + BackgroundThreadError, + StepError, + SuspendExecution, +) +from aws_durable_execution_sdk_python.execution import ( + DurableExecutionInvocationInputWithClient, + InitialExecutionState, + InvocationStatus, + durable_execution, +) +from aws_durable_execution_sdk_python.identifier import OperationIdNamespace +from aws_durable_execution_sdk_python.lambda_service import ( + CheckpointOutput, + CheckpointUpdatedExecutionState, + DurableServiceClient, + ExecutionDetails, + Operation, + OperationAction, + OperationStatus, + OperationSubType, + OperationType, + OperationUpdate, + StepDetails, +) +from aws_durable_execution_sdk_python.plugin import ( + DurableInstrumentationPlugin, + InvocationEndInfo, + OperationEndInfo, +) +from aws_durable_execution_sdk_python.retries import RetryDecision +from tests.test_helpers import plugin_factory + +ASYNC = StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE_ASYNC) + +_STATUS_BY_ACTION = { + OperationAction.START: OperationStatus.STARTED, + OperationAction.SUCCEED: OperationStatus.SUCCEEDED, + OperationAction.FAIL: OperationStatus.FAILED, + OperationAction.RETRY: OperationStatus.PENDING, +} + + +class _SlowClient: + """Answer each checkpoint after a delay, and record what was answered. + + ``delays`` maps an action to the seconds a batch that carries it waits + before the answer. ``fail_on`` names an action whose batch raises instead. + """ + + def __init__( + self, + delays: dict[OperationAction, float] | None = None, + fail_on: OperationAction | None = None, + ) -> None: + self.delays = delays or {} + self.fail_on = fail_on + self.answered: list[OperationAction] = [] + self.lock = threading.Lock() + self.mock = Mock(spec=DurableServiceClient) + self.mock.checkpoint.side_effect = self._checkpoint + + def _checkpoint( + self, + durable_execution_arn: str, + checkpoint_token: str, + updates: list[OperationUpdate], + client_token: str | None = None, + ) -> CheckpointOutput: + actions = [update.action for update in updates] + delay = max((self.delays.get(action, 0.0) for action in actions), default=0) + time.sleep(delay) + if self.fail_on in actions: + msg = "checkpoint failed" + raise RuntimeError(msg) + with self.lock: + self.answered.extend(actions) + return CheckpointOutput( + checkpoint_token=f"{checkpoint_token}-next", + new_execution_state=CheckpointUpdatedExecutionState( + operations=[ + Operation( + operation_id=update.operation_id, + operation_type=update.operation_type, + status=_STATUS_BY_ACTION[update.action], + name=update.name, + step_details=StepDetails(attempt=1, result=update.payload), + ) + for update in updates + if update.operation_type is OperationType.STEP + ] + ), + ) + + def was_answered(self, action: OperationAction) -> bool: + with self.lock: + return action in self.answered + + +def _invoke(handler, client: _SlowClient, operations: list[Operation] | None = None): + execution = Operation( + operation_id="exec1", + operation_type=OperationType.EXECUTION, + status=OperationStatus.STARTED, + execution_details=ExecutionDetails(input_payload="{}"), + ) + invocation_input = DurableExecutionInvocationInputWithClient( + durable_execution_arn="arn:test:execution/exec1", + checkpoint_token="token", # noqa: S106 + initial_execution_state=InitialExecutionState( + operations=[execution, *(operations or [])], next_marker="" + ), + service_client=client.mock, + ) + lambda_context = Mock() + lambda_context.aws_request_id = "request" + lambda_context.client_context = None + lambda_context.identity = None + lambda_context._epoch_deadline_time_in_ms = 1_000_000 # noqa: SLF001 + lambda_context.invoked_function_arn = None + lambda_context.tenant_id = None + return handler(invocation_input, lambda_context) + + +def _no_retry(_error: Exception, _attempt: int) -> RetryDecision: + return RetryDecision.no_retry() + + +def _retry(_error: Exception, _attempt: int) -> RetryDecision: + return RetryDecision.retry(Duration.from_seconds(1)) + + +def _raise(_context: Any) -> None: + msg = "boom" + raise ValueError(msg) + + +def test_async_step_returns_before_succeed_is_answered(): + client = _SlowClient({OperationAction.SUCCEED: 0.3}) + seen: dict[str, bool] = {} + + @durable_execution + def handler(_event: Any, context: DurableContext) -> str: + result = context.step(lambda _: "value", name="s", config=ASYNC) + seen["answered"] = client.was_answered(OperationAction.SUCCEED) + return result + + output = _invoke(handler, client) + + assert seen["answered"] is False + assert output["Status"] == InvocationStatus.SUCCEEDED.value + assert client.was_answered(OperationAction.SUCCEED) + + +@pytest.mark.parametrize( + "config", + [None, StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE_PER_RETRY)], +) +def test_at_least_once_step_still_waits_for_succeed(config): + client = _SlowClient({OperationAction.SUCCEED: 0.1}) + seen: dict[str, bool] = {} + + @durable_execution + def handler(_event: Any, context: DurableContext) -> str: + result = context.step(lambda _: "value", name="s", config=config) + seen["answered"] = client.was_answered(OperationAction.SUCCEED) + return result + + output = _invoke(handler, client) + + assert seen["answered"] is True + assert output["Status"] == InvocationStatus.SUCCEEDED.value + + +def test_async_step_waits_for_fail(): + client = _SlowClient({OperationAction.FAIL: 0.1}) + seen: dict[str, bool] = {} + + @durable_execution + def handler(_event: Any, context: DurableContext) -> None: + config = StepConfig( + retry_strategy=_no_retry, + step_semantics=StepSemantics.AT_LEAST_ONCE_ASYNC, + ) + try: + context.step(_raise, name="s", config=config) + except StepError: + seen["answered"] = client.was_answered(OperationAction.FAIL) + raise + + output = _invoke(handler, client) + + assert seen["answered"] is True + assert output["Status"] == InvocationStatus.FAILED.value + + +def test_async_step_waits_for_retry(): + client = _SlowClient({OperationAction.RETRY: 0.1}) + seen: dict[str, bool] = {} + + @durable_execution + def handler(_event: Any, context: DurableContext) -> None: + config = StepConfig( + retry_strategy=_retry, + step_semantics=StepSemantics.AT_LEAST_ONCE_ASYNC, + ) + try: + context.step(_raise, name="s", config=config) + except SuspendExecution: + seen["answered"] = client.was_answered(OperationAction.RETRY) + raise + + output = _invoke(handler, client) + + assert seen["answered"] is True + assert output["Status"] == InvocationStatus.PENDING.value + + +def test_started_async_step_runs_again_on_replay(): + """An async step whose SUCCEED was not saved runs again, like AT_LEAST_ONCE.""" + client = _SlowClient() + calls: list[int] = [] + + def run(_context: Any) -> str: + calls.append(1) + return "again" + + @durable_execution + def handler(_event: Any, context: DurableContext) -> str: + return context.step(run, name="s", config=ASYNC) + + started = Operation( + operation_id=OperationIdNamespace().create_id_for_step(1), + operation_type=OperationType.STEP, + status=OperationStatus.STARTED, + name="s", + sub_type=OperationSubType.STEP.value, + step_details=StepDetails(attempt=0), + ) + + output = _invoke(handler, client, [started]) + + assert calls == [1] + assert output["Status"] == InvocationStatus.SUCCEEDED.value + assert client.answered == [OperationAction.SUCCEED] + + +def test_succeed_queued_at_handler_end_is_saved_before_succeeded(): + """The batcher sends a SUCCEED that is still queued when the handler returns. + + The START batch is slow, so the SUCCEED is still in the queue when the + handler returns and the batcher is told to stop. + """ + client = _SlowClient({OperationAction.START: 0.3}) + + def slow(_context: Any) -> str: + # Longer than the batcher's empty-queue wait, so START goes alone. + time.sleep(0.15) + return "value" + + @durable_execution + def handler(_event: Any, context: DurableContext) -> str: + return context.step(slow, name="s", config=ASYNC) + + output = _invoke(handler, client) + + assert output["Status"] == InvocationStatus.SUCCEEDED.value + assert client.answered == [OperationAction.START, OperationAction.SUCCEED] + + +def test_failed_succeed_batch_does_not_report_succeeded(): + client = _SlowClient( + {OperationAction.SUCCEED: 0.1}, fail_on=OperationAction.SUCCEED + ) + + @durable_execution + def handler(_event: Any, context: DurableContext) -> str: + return context.step(lambda _: "value", name="s", config=ASYNC) + + with pytest.raises(BackgroundThreadError) as raised: + _invoke(handler, client) + assert str(raised.value.source_exception) == "checkpoint failed" + + +def test_plugin_sees_async_step_end_before_invocation_end(): + class Recorder(DurableInstrumentationPlugin): + def __init__(self) -> None: + self.events: list[Any] = [] + + def on_operation_end(self, info: OperationEndInfo) -> None: + self.events.append(info) + + def on_invocation_end(self, info: InvocationEndInfo) -> None: + self.events.append("invocation_end") + + recorder = Recorder() + client = _SlowClient({OperationAction.SUCCEED: 0.2}) + + @durable_execution(plugins=[plugin_factory(recorder)]) + def handler(_event: Any, context: DurableContext) -> str: + return context.step(lambda _: "value", name="s", config=ASYNC) + + output = _invoke(handler, client) + + assert output["Status"] == InvocationStatus.SUCCEEDED.value + step_end, last = recorder.events + assert isinstance(step_end, OperationEndInfo) + assert step_end.status is OperationStatus.SUCCEEDED + assert step_end.result == '"value"' + assert last == "invocation_end" diff --git a/packages/aws-durable-execution-sdk-python/tests/state_test.py b/packages/aws-durable-execution-sdk-python/tests/state_test.py index d9860a3da..ea0b1ce08 100644 --- a/packages/aws-durable-execution-sdk-python/tests/state_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/state_test.py @@ -2942,9 +2942,9 @@ def test_checkpoint_missing_token_on_empty_only_batch_is_revoked(): def test_collect_checkpoint_batch_shutdown_path(): """Test _collect_checkpoint_batch during shutdown with operations in queue. - With the simplified shutdown logic, once stop_checkpointing() is called, - _collect_checkpoint_batch() returns empty immediately. Any remaining operations - in the queue are non-essential async checkpoints that will be abandoned. + After stop_checkpointing(), _collect_checkpoint_batch() still collects the + queued async checkpoints, such as the SUCCEED of an AT_LEAST_ONCE_ASYNC + step. It returns empty only once the queue is empty. """ mock_lambda_client = Mock(spec=LambdaClient) @@ -2956,7 +2956,7 @@ def test_collect_checkpoint_batch_shutdown_path(): plugin_executor=PluginExecutor(plugins=None), ) - # Add operation to queue (would be a non-essential async checkpoint in practice) + # Add an async checkpoint to the queue. operation_update = OperationUpdate( operation_id="test_op", operation_type=OperationType.STEP, @@ -2967,11 +2967,12 @@ def test_collect_checkpoint_batch_shutdown_path(): # Signal shutdown state.stop_checkpointing() - # Collect batch during shutdown - returns empty immediately + # Collect batch during shutdown - the queued checkpoint is still collected batch = state._collect_checkpoint_batch() + assert [q.operation_update for q in batch] == [operation_update] - # Should return empty batch, abandoning the non-essential async checkpoint - assert len(batch) == 0 + # The queue is now empty, so the next collect returns empty + assert state._collect_checkpoint_batch() == [] def test_collect_checkpoint_batch_shutdown_empty_queue(): @@ -6287,20 +6288,22 @@ def test_stop_settles_every_pending_refresh(): state.schedule_refresh(time.time() + 60) -def test_stop_settles_pending_refresh_and_keeps_queued_items(): - """At shutdown a pending refresh is settled. Any queued operation stays in - the queue.""" - state = _refresh_state(_refresh_client([])) +def test_stop_settles_pending_refresh_and_sends_queued_items(): + """At shutdown a pending refresh is settled. A queued operation is sent + first.""" + calls: list[list] = [] + state = _refresh_state(_refresh_client(calls)) refresh = state.schedule_refresh(time.time() + 60) async_op = QueuedOperation(_step_update(OperationAction.START), None) state._checkpoint_queue.put(async_op) state.stop_checkpointing() - state.checkpoint_batches_forever() # exits at once, then settles + state.checkpoint_batches_forever() # sends the queued op, then settles with pytest.raises(OrphanedChildException): refresh.wait(timeout=1) - assert _queued_operations(state) == [async_op] + assert _queued_operations(state) == [] + assert calls == [[async_op.operation_update]] def test_cancelled_refresh_deferred_then_due_is_dropped(): From 9becaea3c4c97495fc728347b476ce9d475df0f8 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Thu, 26 Nov 2026 23:12:25 +0000 Subject: [PATCH 02/17] feat(sdk): rename the PerRetry step semantics AT_MOST_ONCE and AT_LEAST_ONCE are the new names. They keep the old values, so nothing on the wire changes. AT_MOST_ONCE_PER_RETRY and AT_LEAST_ONCE_PER_RETRY stay as deprecated aliases of the same members. Code, tests, examples and docs use the new names. --- .../src/step/step_semantics_at_most_once.py | 6 +-- .../step/test_step_semantics_at_most_once.py | 3 +- .../README.md | 2 +- .../config.py | 20 ++++++-- .../exceptions.py | 2 +- .../operation/step.py | 10 ++-- .../retries.py | 2 +- .../aws_durable_execution_sdk_python/state.py | 4 +- .../tests/config_test.py | 25 ++++++---- .../tests/e2e/large_step_result_int_test.py | 2 +- .../tests/execution_test.py | 6 +-- .../step_at_least_once_async_test.py | 2 +- .../tests/operation/step_pause_test.py | 2 +- .../tests/operation/step_test.py | 46 +++++++++---------- .../tests/state_test.py | 2 +- 15 files changed, 73 insertions(+), 61 deletions(-) diff --git a/packages/aws-durable-execution-sdk-python-examples/src/step/step_semantics_at_most_once.py b/packages/aws-durable-execution-sdk-python-examples/src/step/step_semantics_at_most_once.py index 1f6f634ee..e074ee578 100644 --- a/packages/aws-durable-execution-sdk-python-examples/src/step/step_semantics_at_most_once.py +++ b/packages/aws-durable-execution-sdk-python-examples/src/step/step_semantics_at_most_once.py @@ -7,11 +7,11 @@ @durable_execution def handler(_event: Any, context: DurableContext) -> str: - # Step with AT_MOST_ONCE_PER_RETRY semantics - config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE_PER_RETRY) + # Step with AT_MOST_ONCE semantics + config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE) result = context.step( - lambda _: "AT_MOST_ONCE_PER_RETRY semantics", + lambda _: "AT_MOST_ONCE semantics", name="at_most_once_step", config=config, ) diff --git a/packages/aws-durable-execution-sdk-python-examples/test/step/test_step_semantics_at_most_once.py b/packages/aws-durable-execution-sdk-python-examples/test/step/test_step_semantics_at_most_once.py index a67892e2a..a5acfc312 100644 --- a/packages/aws-durable-execution-sdk-python-examples/test/step/test_step_semantics_at_most_once.py +++ b/packages/aws-durable-execution-sdk-python-examples/test/step/test_step_semantics_at_most_once.py @@ -20,8 +20,7 @@ def test_step_semantics_at_most_once(durable_runner): assert result.status is InvocationStatus.SUCCEEDED assert ( - deserialize_operation_payload(result.result) - == "Result: AT_MOST_ONCE_PER_RETRY semantics" + deserialize_operation_payload(result.result) == "Result: AT_MOST_ONCE semantics" ) # Verify step operation exists with correct name diff --git a/packages/aws-durable-execution-sdk-python/README.md b/packages/aws-durable-execution-sdk-python/README.md index aee9c2717..51980c1fb 100644 --- a/packages/aws-durable-execution-sdk-python/README.md +++ b/packages/aws-durable-execution-sdk-python/README.md @@ -205,7 +205,7 @@ 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. +- Only an attempt that raised in the current invocation can pause. An `AT_MOST_ONCE` 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. 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 2e33dcd49..88888222d 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 @@ -479,7 +479,7 @@ def __call__(self, *args, **kwargs): class StepSemantics(Enum): """How often one step attempt may run its function. See StepConfig. - AT_LEAST_ONCE_ASYNC works like AT_LEAST_ONCE_PER_RETRY, with one change. + AT_LEAST_ONCE_ASYNC works like AT_LEAST_ONCE, with one change. The step returns its result as soon as the SUCCEED checkpoint is queued. It does not wait for the service to save it. So the step has lower latency. @@ -498,11 +498,21 @@ class StepSemantics(Enum): Only the SUCCEED checkpoint is not awaited. A failed attempt waits for its RETRY or FAIL checkpoint. A plugin receives the step's end hook after the service saves the result, at the latest when the invocation ends. + + AT_MOST_ONCE_PER_RETRY and AT_LEAST_ONCE_PER_RETRY are deprecated aliases + of AT_MOST_ONCE and AT_LEAST_ONCE. Existing code keeps working. """ + AT_MOST_ONCE = "AT_MOST_ONCE_PER_RETRY" + AT_LEAST_ONCE = "AT_LEAST_ONCE_PER_RETRY" + AT_LEAST_ONCE_ASYNC = "AT_LEAST_ONCE_ASYNC" + + # Deprecated: use AT_MOST_ONCE. It is the same member, with the same value + # and behavior. AT_MOST_ONCE_PER_RETRY = "AT_MOST_ONCE_PER_RETRY" + # Deprecated: use AT_LEAST_ONCE. It is the same member, with the same value + # and behavior. AT_LEAST_ONCE_PER_RETRY = "AT_LEAST_ONCE_PER_RETRY" - AT_LEAST_ONCE_ASYNC = "AT_LEAST_ONCE_ASYNC" _SUB_TYPE_CHARACTERS = frozenset(string.ascii_letters + string.digits + "-_") @@ -539,9 +549,9 @@ class StepConfig: If None, the SDK uses its default retry strategy. step_semantics: How often one attempt may run the function. - AT_LEAST_ONCE_PER_RETRY (the default) checkpoints START without + AT_LEAST_ONCE (the default) checkpoints START without waiting, so an interrupted attempt runs again on the next - invocation. AT_MOST_ONCE_PER_RETRY waits for the START checkpoint + invocation. AT_MOST_ONCE waits for the START checkpoint first, and an interrupted attempt fails with StepInterruptedError and goes to the retry strategy instead of running again. AT_LEAST_ONCE_ASYNC also does not wait for the SUCCEED @@ -564,7 +574,7 @@ class StepConfig: """ retry_strategy: Callable[[Exception, int], RetryDecision] | None = None - step_semantics: StepSemantics = StepSemantics.AT_LEAST_ONCE_PER_RETRY + step_semantics: StepSemantics = StepSemantics.AT_LEAST_ONCE serdes: SerDes | None = None sub_type: str | None = field(default=None, kw_only=True) diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/exceptions.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/exceptions.py index ea3f163f2..2c9604627 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/exceptions.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/exceptions.py @@ -445,7 +445,7 @@ class RetryableSerDesError(InvocationError): In a map or parallel branch it escapes the batch rather than becoming a failed item, so the invocation still fails and retries. - A step configured AT_MOST_ONCE_PER_RETRY has already persisted its START + A step configured AT_MOST_ONCE has already persisted its START checkpoint, so the retried invocation treats the step as interrupted and applies the step retry strategy. A strategy that declines or exhausts its retries fails the step and surfaces :class:`StepError` to the caller. 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 c393d3aae..b84edc5b7 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 @@ -142,7 +142,7 @@ def check_result_status(self) -> CheckResult[T]: # ready_to_execute directly, so process() never calls check_result_status() again if ( checkpointed_result.is_started() - and self.config.step_semantics is StepSemantics.AT_MOST_ONCE_PER_RETRY + and self.config.step_semantics is StepSemantics.AT_MOST_ONCE ): # Step was previously interrupted in a prior invocation - handle retry msg: str = f"Step operation_id={self.operation_identifier.operation_id} name={self.operation_identifier.name} was previously interrupted" @@ -160,13 +160,11 @@ def check_result_status(self) -> CheckResult[T]: identifier=self.operation_identifier, ) # Checkpoint START operation with appropriate synchronization: - # - AtMostOncePerRetry: Use blocking checkpoint (is_sync=True) to prevent duplicate execution. + # - AT_MOST_ONCE: Use blocking checkpoint (is_sync=True) to prevent duplicate execution. # The step must not execute until the START checkpoint is persisted, ensuring exactly-once semantics. - # - AtLeastOncePerRetry: Use non-blocking checkpoint (is_sync=False) for performance optimization. + # - AT_LEAST_ONCE: Use non-blocking checkpoint (is_sync=False) for performance optimization. # The step can execute immediately without waiting for checkpoint persistence, allowing at-least-once semantics. - is_sync: bool = ( - self.config.step_semantics is StepSemantics.AT_MOST_ONCE_PER_RETRY - ) + is_sync: bool = self.config.step_semantics is StepSemantics.AT_MOST_ONCE self.state.create_checkpoint( operation_update=start_operation, is_sync=is_sync ) 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 36fc5a850..4aca32756 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 @@ -42,7 +42,7 @@ class RetryDecision: 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 + An AT_MOST_ONCE 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 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 944ba565b..8d370655e 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 @@ -801,7 +801,7 @@ def create_checkpoint( - Use cases: observability checkpoints, fire-and-forget operations When to use synchronous checkpoints (is_sync=True, default): - 1. Step START with AtMostOncePerRetry semantics - prevents duplicate execution + 1. Step START with AT_MOST_ONCE semantics - prevents duplicate execution 2. Operation completion (SUCCEED/FAIL) - ensures state persisted before returning 3. Retry operations - ensures retry state recorded before continuing 4. Callback START - must wait for API to generate callback ID @@ -812,7 +812,7 @@ def create_checkpoint( 9. Most operations - safe default When to use asynchronous checkpoints (is_sync=False, opt-in): - 1. Step START with AtLeastOncePerRetry semantics - performance optimization + 1. Step START with AT_LEAST_ONCE semantics - performance optimization 2. Child context START - fire-and-forget for performance 3. Wait for condition START - observability only, no blocking needed 4. Any checkpoint where immediate confirmation is not required AND performance matters diff --git a/packages/aws-durable-execution-sdk-python/tests/config_test.py b/packages/aws-durable-execution-sdk-python/tests/config_test.py index c2fbc78b2..5bcf20475 100644 --- a/packages/aws-durable-execution-sdk-python/tests/config_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/config_test.py @@ -101,15 +101,24 @@ def wait_strategy(state, attempt): def test_step_semantics_enum(): """Test StepSemantics enum.""" - assert StepSemantics.AT_MOST_ONCE_PER_RETRY.value == "AT_MOST_ONCE_PER_RETRY" - assert StepSemantics.AT_LEAST_ONCE_PER_RETRY.value == "AT_LEAST_ONCE_PER_RETRY" + assert StepSemantics.AT_MOST_ONCE.value == "AT_MOST_ONCE_PER_RETRY" + assert StepSemantics.AT_LEAST_ONCE.value == "AT_LEAST_ONCE_PER_RETRY" + assert StepSemantics.AT_LEAST_ONCE_ASYNC.value == "AT_LEAST_ONCE_ASYNC" + + +def test_deprecated_step_semantics_are_the_new_members(): + """The PerRetry names are aliases, so `is` checks match either name.""" + assert StepSemantics.AT_MOST_ONCE_PER_RETRY is StepSemantics.AT_MOST_ONCE + assert StepSemantics.AT_LEAST_ONCE_PER_RETRY is StepSemantics.AT_LEAST_ONCE + assert StepSemantics("AT_MOST_ONCE_PER_RETRY") is StepSemantics.AT_MOST_ONCE + assert StepSemantics("AT_LEAST_ONCE_PER_RETRY") is StepSemantics.AT_LEAST_ONCE def test_step_config_defaults(): """Test StepConfig default values.""" config = StepConfig() assert config.retry_strategy is None - assert config.step_semantics == StepSemantics.AT_LEAST_ONCE_PER_RETRY + assert config.step_semantics == StepSemantics.AT_LEAST_ONCE assert config.serdes is None @@ -120,12 +129,12 @@ def test_step_config_with_values(): config = StepConfig( retry_strategy=retry_strategy, - step_semantics=StepSemantics.AT_MOST_ONCE_PER_RETRY, + step_semantics=StepSemantics.AT_MOST_ONCE, serdes=serdes, ) assert config.retry_strategy is retry_strategy - assert config.step_semantics == StepSemantics.AT_MOST_ONCE_PER_RETRY + assert config.step_semantics == StepSemantics.AT_MOST_ONCE assert config.serdes is serdes @@ -172,13 +181,11 @@ def test_sub_type_is_keyword_only_so_positional_order_is_unchanged(): ) assert config.retry_strategy is retry assert config.sub_type is None - assert ( - StepConfig(retry, StepSemantics.AT_MOST_ONCE_PER_RETRY, serdes).serdes is serdes - ) + assert StepConfig(retry, StepSemantics.AT_MOST_ONCE, serdes).serdes is serdes # ChildConfig.sub_type keeps its 2.x positional slot; only its type changed. assert ChildConfig(serdes, "OrderSaga").sub_type == "OrderSaga" with pytest.raises(TypeError): - StepConfig(retry, StepSemantics.AT_LEAST_ONCE_PER_RETRY, serdes, "OrderCharge") # type: ignore[misc] + StepConfig(retry, StepSemantics.AT_LEAST_ONCE, serdes, "OrderCharge") # type: ignore[misc] def test_child_config_with_summary_generator(): diff --git a/packages/aws-durable-execution-sdk-python/tests/e2e/large_step_result_int_test.py b/packages/aws-durable-execution-sdk-python/tests/e2e/large_step_result_int_test.py index 0d7eb3ac3..b42e41cac 100644 --- a/packages/aws-durable-execution-sdk-python/tests/e2e/large_step_result_int_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/e2e/large_step_result_int_test.py @@ -2,7 +2,7 @@ The step result is 800 KB. That is above ``max_batch_size_bytes`` (750 KB) and below the service's 1 MB per-operation limit. With the default -``AT_LEAST_ONCE_PER_RETRY`` semantics the START checkpoint is async, so the +``AT_LEAST_ONCE`` semantics the START checkpoint is async, so the batcher still holds it when the sync SUCCEED arrives, and SUCCEED takes the overflow path. Before the fix the SUCCEED operation was never sent and the handler thread blocked forever, so ``run()`` raised ``TimeoutError``. diff --git a/packages/aws-durable-execution-sdk-python/tests/execution_test.py b/packages/aws-durable-execution-sdk-python/tests/execution_test.py index 1dfbae474..d49908da4 100644 --- a/packages/aws-durable-execution-sdk-python/tests/execution_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/execution_test.py @@ -1915,9 +1915,9 @@ def selective_failing_checkpoint( @durable_execution def test_handler(event: Any, context: DurableContext) -> dict: - # First step with AT_MOST_ONCE_PER_RETRY (synchronous START checkpoint) + # First step with AT_MOST_ONCE (synchronous START checkpoint) # This should fail on START checkpoint and prevent execution - step_config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE_PER_RETRY) + step_config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE) context.step(lambda ctx: "first_step_result", config=step_config) # Second step should never be reached if first step's START checkpoint fails @@ -1955,7 +1955,7 @@ def test_handler(event: Any, context: DurableContext) -> dict: test_handler(invocation_input, lambda_context) # Verify that checkpoint was called exactly once with only the START update: - # With AT_MOST_ONCE_PER_RETRY, START checkpoint is synchronous and blocks execution + # With AT_MOST_ONCE, START checkpoint is synchronous and blocks execution assert mock_client.checkpoint.call_count == 1 # Verify the checkpoint call contained only the first step's START update diff --git a/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py b/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py index a140609d7..b47e56fcd 100644 --- a/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py @@ -171,7 +171,7 @@ def handler(_event: Any, context: DurableContext) -> str: @pytest.mark.parametrize( "config", - [None, StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE_PER_RETRY)], + [None, StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE)], ) def test_at_least_once_step_still_waits_for_succeed(config): client = _SlowClient({OperationAction.SUCCEED: 0.1}) 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 384b883aa..cf3a0de68 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 @@ -356,7 +356,7 @@ def test_no_pause_on_interrupted_at_most_once_replay(): state, StepConfig( retry_strategy=strategy, - step_semantics=StepSemantics.AT_MOST_ONCE_PER_RETRY, + step_semantics=StepSemantics.AT_MOST_ONCE, ), ) diff --git a/packages/aws-durable-execution-sdk-python/tests/operation/step_test.py b/packages/aws-durable-execution-sdk-python/tests/operation/step_test.py index 08ffae984..86c5f11d4 100644 --- a/packages/aws-durable-execution-sdk-python/tests/operation/step_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/operation/step_test.py @@ -190,7 +190,7 @@ def test_step_handler_started_at_most_once(): mock_result = CheckpointedResult.create_from_operation(operation) mock_state.get_checkpoint_result.return_value = mock_result - config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE_PER_RETRY) + config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE) mock_callable = Mock() mock_logger = Mock(spec=Logger) @@ -228,7 +228,7 @@ def test_step_handler_started_at_least_once(): mock_result = CheckpointedResult.create_from_operation(operation) mock_state.get_checkpoint_result.return_value = mock_result - config = StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE_PER_RETRY) + config = StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE) mock_callable = Mock(return_value="success_result") mock_state.wrap_user_function.return_value = mock_callable mock_logger = Mock(spec=Logger) @@ -255,7 +255,7 @@ def test_step_handler_success_at_least_once(): mock_state.get_checkpoint_result.return_value = mock_result mock_state.durable_execution_arn = "test_arn" - config = StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE_PER_RETRY) + config = StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE) mock_callable = Mock(return_value="success_result") mock_state.wrap_user_function.return_value = mock_callable mock_logger = Mock(spec=Logger) @@ -342,7 +342,7 @@ def step_func(context: StepContext) -> str: "test_step", operation_type=OperationType.STEP, ), - StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE_PER_RETRY), + StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE), mock_logger, ) @@ -369,7 +369,7 @@ def test_step_handler_success_at_most_once(): started = CheckpointedResult.create_from_operation(started_op) mock_state.get_checkpoint_result.side_effect = [not_found, started] - config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE_PER_RETRY) + config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE) mock_callable = Mock(return_value="success_result") mock_state.wrap_user_function.return_value = mock_callable mock_logger = Mock(spec=Logger) @@ -739,7 +739,7 @@ def test_step_handler_custom_serdes_success(): mock_state.durable_execution_arn = "test_arn" config = StepConfig( - step_semantics=StepSemantics.AT_LEAST_ONCE_PER_RETRY, serdes=CustomDictSerDes() + step_semantics=StepSemantics.AT_LEAST_ONCE, serdes=CustomDictSerDes() ) complex_result = {"key": "value", "number": 42, "list": [1, 2, 3]} mock_callable = Mock(return_value=complex_result) @@ -841,9 +841,7 @@ def deserialize(self, data: str, _: SerDesContext) -> dict[str, Any]: mock_logger = Mock(spec=Logger) mock_logger.with_log_info.return_value = mock_logger - config = StepConfig( - step_semantics=StepSemantics.AT_LEAST_ONCE_PER_RETRY, serdes=serdes - ) + config = StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE, serdes=serdes) first_run_result = step_handler( mock_callable, first_run_state, @@ -926,7 +924,7 @@ def deserialize(self, _data: str, _ctx: SerDesContext) -> Any: mock_logger.with_log_info.return_value = mock_logger config = StepConfig( - step_semantics=StepSemantics.AT_LEAST_ONCE_PER_RETRY, + step_semantics=StepSemantics.AT_LEAST_ONCE, serdes=NonePayloadSerDes(), ) result = step_handler( @@ -959,7 +957,7 @@ def test_step_handler_empty_string_result_first_run(): mock_logger.with_log_info.return_value = mock_logger config = StepConfig( - step_semantics=StepSemantics.AT_LEAST_ONCE_PER_RETRY, + step_semantics=StepSemantics.AT_LEAST_ONCE, serdes=PassThroughSerDes(), ) result = step_handler( @@ -1042,7 +1040,7 @@ def test_step_immediate_response_get_checkpoint_called_twice(): started = CheckpointedResult.create_from_operation(started_op) mock_state.get_checkpoint_result.side_effect = [not_found, started] - config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE_PER_RETRY) + config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE) mock_callable = Mock(return_value="success_result") mock_state.wrap_user_function.return_value = mock_callable mock_logger = Mock(spec=Logger) @@ -1085,7 +1083,7 @@ def test_step_immediate_response_create_checkpoint_sync_at_most_once(): started = CheckpointedResult.create_from_operation(started_op) mock_state.get_checkpoint_result.side_effect = [not_found, started] - config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE_PER_RETRY) + config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE) mock_callable = Mock(return_value="success_result") mock_state.wrap_user_function.return_value = mock_callable mock_logger = Mock(spec=Logger) @@ -1119,7 +1117,7 @@ def test_step_immediate_response_create_checkpoint_async_at_least_once(): not_found = CheckpointedResult.create_not_found() mock_state.get_checkpoint_result.return_value = not_found - config = StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE_PER_RETRY) + config = StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE) mock_callable = Mock(return_value="success_result") mock_state.wrap_user_function.return_value = mock_callable mock_logger = Mock(spec=Logger) @@ -1167,7 +1165,7 @@ def test_step_immediate_response_immediate_success(): started = CheckpointedResult.create_from_operation(started_op) mock_state.get_checkpoint_result.side_effect = [not_found, started] - config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE_PER_RETRY) + config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE) mock_callable = Mock(return_value="immediate_success_result") mock_state.wrap_user_function.return_value = mock_callable mock_logger = Mock(spec=Logger) @@ -1213,7 +1211,7 @@ def test_step_immediate_response_immediate_failure(): started = CheckpointedResult.create_from_operation(started_op) mock_state.get_checkpoint_result.side_effect = [not_found, started] - config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE_PER_RETRY) + config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE) # Make the step function raise an error mock_callable = Mock(side_effect=RuntimeError("Step execution error")) mock_state.wrap_user_function.return_value = mock_callable @@ -1225,7 +1223,7 @@ def test_step_immediate_response_immediate_failure(): return_value=RetryDecision(should_retry=False, delay=Duration.from_seconds(0)) ) config = StepConfig( - step_semantics=StepSemantics.AT_MOST_ONCE_PER_RETRY, + step_semantics=StepSemantics.AT_MOST_ONCE, retry_strategy=mock_retry_strategy, ) @@ -1269,7 +1267,7 @@ def test_step_immediate_response_no_immediate_response(): started = CheckpointedResult.create_from_operation(started_op) mock_state.get_checkpoint_result.side_effect = [not_found, started] - config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE_PER_RETRY) + config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE) mock_callable = Mock(return_value="normal_execution_result") mock_state.wrap_user_function.return_value = mock_callable mock_logger = Mock(spec=Logger) @@ -1313,7 +1311,7 @@ def test_step_immediate_response_already_completed(): succeeded = CheckpointedResult.create_from_operation(succeeded_op) mock_state.get_checkpoint_result.return_value = succeeded - config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE_PER_RETRY) + config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE) mock_callable = Mock(return_value="should_not_call") mock_logger = Mock(spec=Logger) @@ -1367,7 +1365,7 @@ def test_step_executes_function_when_second_check_returns_started(): executor = StepOperationExecutor( func=mock_step_function, - config=StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE_PER_RETRY), + config=StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE), state=mock_state, operation_identifier=OperationIdentifier( "step-1", @@ -1417,7 +1415,7 @@ def test_step_creates_start_checkpoint_when_status_is_ready(): started_result = CheckpointedResult.create_from_operation(started_op) mock_state.get_checkpoint_result.side_effect = [ready_result, started_result] - config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE_PER_RETRY) + config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE) mock_callable = Mock(return_value="ready_step_result") mock_state.wrap_user_function.return_value = mock_callable mock_logger = Mock(spec=Logger) @@ -1483,7 +1481,7 @@ def test_step_handler_permanent_serdes_error_surfaces_without_double_checkpoint( operation_type=OperationType.STEP, ), StepConfig( - step_semantics=StepSemantics.AT_LEAST_ONCE_PER_RETRY, + step_semantics=StepSemantics.AT_LEAST_ONCE, serdes=PermanentDeserializeSerDes(), ), mock_logger, @@ -1525,7 +1523,7 @@ def test_step_handler_permanent_serdes_error_bypasses_retry_strategy(): operation_type=OperationType.STEP, ), StepConfig( - step_semantics=StepSemantics.AT_LEAST_ONCE_PER_RETRY, + step_semantics=StepSemantics.AT_LEAST_ONCE, serdes=PermanentDeserializeSerDes(), retry_strategy=mock_retry_strategy, ), @@ -1571,7 +1569,7 @@ def test_step_handler_transient_serdes_error_reraised(): operation_type=OperationType.STEP, ), StepConfig( - step_semantics=StepSemantics.AT_LEAST_ONCE_PER_RETRY, + step_semantics=StepSemantics.AT_LEAST_ONCE, serdes=RetryableDeserializeSerDes(), ), mock_logger, diff --git a/packages/aws-durable-execution-sdk-python/tests/state_test.py b/packages/aws-durable-execution-sdk-python/tests/state_test.py index ea0b1ce08..46d361d15 100644 --- a/packages/aws-durable-execution-sdk-python/tests/state_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/state_test.py @@ -1468,7 +1468,7 @@ def test_collect_checkpoint_batch_sends_oversized_operation_from_overflow() -> N """An operation above max_batch_size_bytes that reached the overflow queue is still sent, alone, in the next batch (issue #871). - This is the default AT_LEAST_ONCE_PER_RETRY step shape: a small START is + This is the default AT_LEAST_ONCE step shape: a small START is already in the batch when the large SUCCEED arrives, so SUCCEED does not fit and moves to the overflow queue. The next batch must send it rather than return it to the queue forever. From aaef634ab457eec5ee0d0e1f36318f08cf4b4b8e Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Thu, 26 Nov 2026 23:18:59 +0000 Subject: [PATCH 03/17] feat(sdk): add default_step_semantics durable_execution takes default_step_semantics. It sets the semantics of every step whose StepConfig sets none, in every context of the execution. A step's own step_semantics wins. The default stays AT_LEAST_ONCE. StepConfig.step_semantics now defaults to None, which means the execution default. --- .../README.md | 27 +++++++ .../config.py | 6 +- .../context.py | 4 +- .../execution.py | 18 ++++- .../aws_durable_execution_sdk_python/state.py | 6 ++ .../tests/config_test.py | 2 +- .../tests/context_test.py | 35 ++++++++- .../e2e/default_step_semantics_int_test.py | 76 +++++++++++++++++++ .../step_at_least_once_async_test.py | 57 +++++++++++++- 9 files changed, 224 insertions(+), 7 deletions(-) create mode 100644 packages/aws-durable-execution-sdk-python/tests/e2e/default_step_semantics_int_test.py diff --git a/packages/aws-durable-execution-sdk-python/README.md b/packages/aws-durable-execution-sdk-python/README.md index 51980c1fb..437c60c32 100644 --- a/packages/aws-durable-execution-sdk-python/README.md +++ b/packages/aws-durable-execution-sdk-python/README.md @@ -170,6 +170,33 @@ def handler(event: dict, context: DurableContext) -> dict: `RetryPresets` in `aws_durable_execution_sdk_python.retries` holds ready-made strategies. +### Step semantics + +`StepConfig(step_semantics=...)` sets how often one attempt may run the step function: + +- `StepSemantics.AT_LEAST_ONCE` (default): the attempt runs again on replay if it was interrupted before its result was saved. The step waits for its result to be saved before it returns. +- `StepSemantics.AT_MOST_ONCE`: the step saves its start before it runs. An interrupted attempt does not run again. It fails with `StepInterruptedError` and goes to the retry strategy. +- `StepSemantics.AT_LEAST_ONCE_ASYNC`: like `AT_LEAST_ONCE`, but the step returns its result without waiting for the save. So the step has lower latency. Each invocation saves the result before it returns. If the invocation ends before the save, the step runs again on replay. On that replay the step can return a different value, and later steps run again with it. So do not use this mode for a step whose result becomes an idempotency key or a client token for a later step. A failed attempt still waits for its retry or failure to be saved. + +`AT_MOST_ONCE_PER_RETRY` and `AT_LEAST_ONCE_PER_RETRY` are deprecated aliases of `AT_MOST_ONCE` and `AT_LEAST_ONCE`. + +`@durable_execution(default_step_semantics=...)` sets the semantics of every step that does not set its own. It applies in child contexts, `map` items, `parallel` branches, and the steps that SDK extensions create, unless the extension sets its own. A step's own `step_semantics` wins. + +```python +from aws_durable_execution_sdk_python.config import StepConfig, StepSemantics + + +@durable_execution(default_step_semantics=StepSemantics.AT_LEAST_ONCE_ASYNC) +def handler(event: dict, context: DurableContext) -> dict: + # create_order_id and charge are @durable_step functions. + # The order ID becomes an idempotency key, so its step waits for the save. + order_id = context.step( + create_order_id(), + config=StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE), + ) + return context.step(charge(order_id, event["amount"])) +``` + ### 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. 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 88888222d..ff17ba7f4 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 @@ -549,7 +549,9 @@ class StepConfig: If None, the SDK uses its default retry strategy. step_semantics: How often one attempt may run the function. - AT_LEAST_ONCE (the default) checkpoints START without + None (the default) uses the default_step_semantics of + durable_execution, which is AT_LEAST_ONCE unless set. + AT_LEAST_ONCE checkpoints START without waiting, so an interrupted attempt runs again on the next invocation. AT_MOST_ONCE waits for the START checkpoint first, and an interrupted attempt fails with StepInterruptedError @@ -574,7 +576,7 @@ class StepConfig: """ retry_strategy: Callable[[Exception, int], RetryDecision] | None = None - step_semantics: StepSemantics = StepSemantics.AT_LEAST_ONCE + step_semantics: StepSemantics | None = None serdes: SerDes | None = None sub_type: str | None = field(default=None, kw_only=True) diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/context.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/context.py index e1957932e..a86806153 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/context.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/context.py @@ -2,7 +2,7 @@ import logging from contextlib import contextmanager -from dataclasses import dataclass +from dataclasses import dataclass, replace from threading import Lock from typing import ( TYPE_CHECKING, @@ -899,6 +899,8 @@ def step( logger.debug("Step name: %s", step_name) if not config: config = StepConfig() + if config.step_semantics is None: + config = replace(config, step_semantics=self.state.default_step_semantics) sub_type = config.sub_type or OperationSubType.STEP.value with self._operation_replay_aware( sub_type, step_name, operation_type=OperationType.STEP diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py index 4fd0a2f02..2e1b8ccf1 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py @@ -9,6 +9,7 @@ from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, overload +from aws_durable_execution_sdk_python.config import StepSemantics from aws_durable_execution_sdk_python.context import DurableContext from aws_durable_execution_sdk_python.exceptions import ( BackgroundThreadError, @@ -172,6 +173,7 @@ def durable_execution( *, boto3_client: Boto3LambdaClient | None = None, plugins: list[DurableInstrumentationPluginFactory] | None = None, + default_step_semantics: StepSemantics = StepSemantics.AT_LEAST_ONCE, ) -> Callable[[Any, LambdaContext], Any]: ... @@ -181,6 +183,7 @@ def durable_execution( *, boto3_client: Boto3LambdaClient | None = None, plugins: list[DurableInstrumentationPluginFactory] | None = None, + default_step_semantics: StepSemantics = StepSemantics.AT_LEAST_ONCE, ) -> Callable[ [Callable[[Any, DurableContext], Any]], Callable[[Any, LambdaContext], Any], @@ -192,6 +195,7 @@ def durable_execution( *, boto3_client: Boto3LambdaClient | None = None, plugins: list[DurableInstrumentationPluginFactory] | None = None, + default_step_semantics: StepSemantics = StepSemantics.AT_LEAST_ONCE, ) -> ( Callable[[Any, LambdaContext], Any] | Callable[ @@ -209,12 +213,23 @@ def durable_execution( factory's ``create_plugin`` is called once per invocation with that invocation's ``InvocationStartInfo``, and the instance it returns serves only that invocation. + default_step_semantics: The semantics of every step whose StepConfig + sets none. It applies to the steps of every context in the + execution, including child contexts, map items and parallel + branches. It also applies to the steps that SDK extensions create, + unless the extension sets step_semantics itself. A step's own + step_semantics wins. Before you set AT_LEAST_ONCE_ASYNC here, read + StepSemantics: a step whose result becomes an idempotency key for + a later step needs its own AT_LEAST_ONCE. """ # Decorator called with parameters if func is None: logger.debug("Decorator called with parameters") return functools.partial( - durable_execution, boto3_client=boto3_client, plugins=plugins + durable_execution, + boto3_client=boto3_client, + plugins=plugins, + default_step_semantics=default_step_semantics, ) logger.debug("Starting durable execution handler...") @@ -261,6 +276,7 @@ def wrapper(event: Any, context: LambdaContext) -> MutableMapping[str, Any]: service_client=service_client, plugin_executor=plugin_executor, updated_operation_ids=invocation_input.updated_operation_ids, + default_step_semantics=default_step_semantics, ) try: 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 8d370655e..26eae14c4 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 @@ -16,6 +16,7 @@ from threading import Lock from typing import TYPE_CHECKING, Callable, NoReturn +from aws_durable_execution_sdk_python.config import StepSemantics from aws_durable_execution_sdk_python.exceptions import ( BackgroundThreadError, DurableExecutionsError, @@ -372,6 +373,9 @@ class ExecutionState: Internal to the SDK. Not part of the public API. """ + # The semantics of every step whose StepConfig sets none. + default_step_semantics: StepSemantics = StepSemantics.AT_LEAST_ONCE + def __init__( self, durable_execution_arn: str, @@ -381,8 +385,10 @@ def __init__( plugin_executor: PluginExecutor, batcher_config: CheckpointBatcherConfig | None = None, updated_operation_ids: list[str] | None = None, + default_step_semantics: StepSemantics = StepSemantics.AT_LEAST_ONCE, ): self.durable_execution_arn: str = durable_execution_arn + self.default_step_semantics = default_step_semantics self._current_checkpoint_token: str = initial_checkpoint_token self._operations: dict[str, Operation] = dict(operations) self._service_client: DurableServiceClient = service_client diff --git a/packages/aws-durable-execution-sdk-python/tests/config_test.py b/packages/aws-durable-execution-sdk-python/tests/config_test.py index 5bcf20475..04360584e 100644 --- a/packages/aws-durable-execution-sdk-python/tests/config_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/config_test.py @@ -118,7 +118,7 @@ def test_step_config_defaults(): """Test StepConfig default values.""" config = StepConfig() assert config.retry_strategy is None - assert config.step_semantics == StepSemantics.AT_LEAST_ONCE + assert config.step_semantics is None assert config.serdes is None diff --git a/packages/aws-durable-execution-sdk-python/tests/context_test.py b/packages/aws-durable-execution-sdk-python/tests/context_test.py index beb9df4ad..bc792e742 100644 --- a/packages/aws-durable-execution-sdk-python/tests/context_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/context_test.py @@ -20,6 +20,7 @@ ParallelBranch, ParallelConfig, StepConfig, + StepSemantics, ) from aws_durable_execution_sdk_python.context import ( Callback, @@ -519,7 +520,7 @@ def test_step_with_name_and_config(mock_executor_class): del ( mock_callable._original_name # noqa: SLF001 ) # Ensure Mock doesn't have _original_name - config = StepConfig() + config = StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE) context = create_test_context(state=mock_state) [context._create_step_id() for _ in range(5)] # Set counter to 5 # noqa: SLF001 @@ -548,6 +549,38 @@ def test_step_with_name_and_config(mock_executor_class): mock_executor.process.assert_called_once() +@pytest.mark.parametrize( + ("config", "expected"), + [ + (None, StepSemantics.AT_LEAST_ONCE_ASYNC), + (StepConfig(), StepSemantics.AT_LEAST_ONCE_ASYNC), + (StepConfig(sub_type="Custom"), StepSemantics.AT_LEAST_ONCE_ASYNC), + ( + StepConfig(step_semantics=StepSemantics.AT_MOST_ONCE), + StepSemantics.AT_MOST_ONCE, + ), + ( + StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE), + StepSemantics.AT_LEAST_ONCE, + ), + ], +) +@patch("aws_durable_execution_sdk_python.context.StepOperationExecutor") +def test_step_uses_default_semantics_unless_set(mock_executor_class, config, expected): + """A step without step_semantics gets the execution default; its own wins.""" + mock_state = Mock(spec=ExecutionState) + mock_state.durable_execution_arn = "arn:test" + mock_state.default_step_semantics = StepSemantics.AT_LEAST_ONCE_ASYNC + context = create_test_context(state=mock_state) + + context.step(lambda _: None, name="s", config=config) + + passed: StepConfig = mock_executor_class.call_args.kwargs["config"] + assert passed.step_semantics is expected + if config is not None: + assert passed.sub_type == config.sub_type + + @patch("aws_durable_execution_sdk_python.context.StepOperationExecutor") def test_step_with_parent_id(mock_executor_class): """Test step with parent_id.""" diff --git a/packages/aws-durable-execution-sdk-python/tests/e2e/default_step_semantics_int_test.py b/packages/aws-durable-execution-sdk-python/tests/e2e/default_step_semantics_int_test.py new file mode 100644 index 000000000..45bd7b27b --- /dev/null +++ b/packages/aws-durable-execution-sdk-python/tests/e2e/default_step_semantics_int_test.py @@ -0,0 +1,76 @@ +"""default_step_semantics=AT_LEAST_ONCE_ASYNC through the local test runner. + +The steps do not wait for their SUCCEED checkpoints. Each invocation still +sends them before it returns, so the history records every step as SUCCEEDED, +including the steps before a wait that suspends the execution. +""" + +from __future__ import annotations + +import json +from typing import Any + +from aws_durable_execution_sdk_python import DurableContext, durable_execution +from aws_durable_execution_sdk_python.config import Duration, StepSemantics +from aws_durable_execution_sdk_python.execution import InvocationStatus +from aws_durable_execution_sdk_python.lambda_service import ( + OperationStatus, + OperationType, +) +from aws_durable_execution_sdk_python_testing.runner import DurableFunctionTestRunner + +_calls: list[str] = [] + + +def _step(context: DurableContext, name: str) -> str: + def run(_step_context: Any) -> str: + _calls.append(name) + return name + + return context.step(run, name=name) + + +@durable_execution(default_step_semantics=StepSemantics.AT_LEAST_ONCE_ASYNC) +def _handler(_event: Any, context: DurableContext) -> list[str]: + results = [_step(context, "root")] + results.append( + context.run_in_child_context(lambda child: _step(child, "child"), name="group") + ) + results.extend( + context.map( + ["a", "b"], + lambda item_context, item, _index, _items: _step( + item_context, f"item-{item}" + ), + name="items", + ).get_results() + ) + context.wait(Duration.from_seconds(1), name="pause") + results.append(_step(context, "after-wait")) + return results + + +def test_async_default_saves_every_step_before_the_invocation_returns() -> None: + _calls.clear() + with DurableFunctionTestRunner(handler=_handler) as runner: + result = runner.run(input="{}", execution_timeout=30) + + assert result.status is InvocationStatus.SUCCEEDED + assert json.loads(result.result) == [ + "root", + "child", + "item-a", + "item-b", + "after-wait", + ] + # Each step ran once: the replay after the wait read the saved results. + assert sorted(_calls) == sorted(json.loads(result.result)) + steps = { + operation.name: operation.status + for operation in result.get_all_operations() + if operation.operation_type is OperationType.STEP + } + assert steps == dict.fromkeys( + ["root", "child", "item-a", "item-b", "after-wait"], + OperationStatus.SUCCEEDED, + ) diff --git a/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py b/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py index b47e56fcd..07878d4a6 100644 --- a/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py @@ -73,6 +73,7 @@ def __init__( self.delays = delays or {} self.fail_on = fail_on self.answered: list[OperationAction] = [] + self.answered_names: set[tuple[OperationAction, str | None]] = set() self.lock = threading.Lock() self.mock = Mock(spec=DurableServiceClient) self.mock.checkpoint.side_effect = self._checkpoint @@ -92,6 +93,7 @@ def _checkpoint( raise RuntimeError(msg) with self.lock: self.answered.extend(actions) + self.answered_names.update((u.action, u.name) for u in updates) return CheckpointOutput( checkpoint_token=f"{checkpoint_token}-next", new_execution_state=CheckpointUpdatedExecutionState( @@ -109,8 +111,10 @@ def _checkpoint( ), ) - def was_answered(self, action: OperationAction) -> bool: + def was_answered(self, action: OperationAction, name: str | None = None) -> bool: with self.lock: + if name is not None: + return (action, name) in self.answered_names return action in self.answered @@ -325,3 +329,54 @@ def handler(_event: Any, context: DurableContext) -> str: assert step_end.status is OperationStatus.SUCCEEDED assert step_end.result == '"value"' assert last == "invocation_end" + + +def test_default_step_semantics_reaches_every_context(): + """default_step_semantics applies at the root, in child contexts and in map + items. A step's own step_semantics wins.""" + client = _SlowClient({OperationAction.SUCCEED: 0.2}) + saved_at_return: dict[str, bool] = {} + + def run_step(context: DurableContext, name: str, config=None) -> str: + result = context.step(lambda _: name, name=name, config=config) + saved_at_return[name] = client.was_answered(OperationAction.SUCCEED, name) + return result + + @durable_execution(default_step_semantics=StepSemantics.AT_LEAST_ONCE_ASYNC) + def handler(_event: Any, context: DurableContext) -> list[str]: + results = [run_step(context, "root")] + results.append( + context.run_in_child_context( + lambda child: run_step(child, "child"), name="group" + ) + ) + results.extend( + context.map( + ["a", "b"], + lambda item_context, item, _i, _items: run_step( + item_context, f"item-{item}" + ), + name="items", + ).get_results() + ) + results.append( + run_step( + context, + "own", + StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE), + ) + ) + return results + + output = _invoke(handler, client) + + assert output["Status"] == InvocationStatus.SUCCEEDED.value + assert saved_at_return == { + "root": False, + "child": False, + "item-a": False, + "item-b": False, + "own": True, + } + for name in saved_at_return: + assert client.was_answered(OperationAction.SUCCEED, name) From 56b3ec7930b72a34141ed4e9986bf478c448f272 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Thu, 26 Nov 2026 23:25:19 +0000 Subject: [PATCH 04/17] fix(extensions): pin session ID step semantics The microvm and agentcore session ID steps feed a client token or a runtime session to later steps. They now set AT_LEAST_ONCE themselves, so default_step_semantics=AT_LEAST_ONCE_ASYNC cannot make them async. They use the deprecated AT_LEAST_ONCE_PER_RETRY name, so the core requirement stays >=3.0.0. --- .../compute/agentcore/operation.py | 9 +++++- .../compute/microvm/session.py | 9 +++++- .../agentcore/agentcore_session_test.py | 26 ++++++++++++++++- .../tests/compute/microvm/session_test.py | 28 ++++++++++++++++++- 4 files changed, 68 insertions(+), 4 deletions(-) diff --git a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/agentcore/operation.py b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/agentcore/operation.py index 77ba41ee3..a2a09904f 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/agentcore/operation.py +++ b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/agentcore/operation.py @@ -21,6 +21,7 @@ ChildConfig, Duration, StepConfig, + StepSemantics, ) from aws_durable_execution_sdk_python.exceptions import ( CallbackError, @@ -344,7 +345,13 @@ def _create_session_id(child: DurableContext, name: str) -> str: # Plain JSON, so a reader of the execution history finds the # session ID. config=StepConfig( - serdes=JsonSerDes(), sub_type=AgentcoreOperationSubType.SESSION_ID + serdes=JsonSerDes(), + sub_type=AgentcoreOperationSubType.SESSION_ID, + # Later steps use the ID as the runtime session. So it must be + # saved before they run, even when default_step_semantics is + # AT_LEAST_ONCE_ASYNC. The deprecated name keeps the core + # requirement >=3.0.0, which has no AT_LEAST_ONCE. + step_semantics=StepSemantics.AT_LEAST_ONCE_PER_RETRY, ), ) return session_id diff --git a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/microvm/session.py b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/microvm/session.py index 72adf85ba..b4bf860d4 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/microvm/session.py +++ b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/microvm/session.py @@ -11,6 +11,7 @@ from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, TypeVar +from aws_durable_execution_sdk_python.config import StepConfig, StepSemantics from aws_durable_execution_sdk_python.exceptions import ( ChildContextError, ExecutionError, @@ -383,7 +384,13 @@ def run_session( ) -> _T: """Run the session's durable operations in its child context.""" session_id: str = child.step( - lambda _: str(uuid.uuid4()), name=f"{self.name}.session" + lambda _: str(uuid.uuid4()), + name=f"{self.name}.session", + # The launch uses the ID as its client token. So it must be saved + # before the launch runs, even when default_step_semantics is + # AT_LEAST_ONCE_ASYNC. The deprecated name keeps the core + # requirement >=3.0.0, which has no AT_LEAST_ONCE. + config=StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE_PER_RETRY), ) launched = self.launch( child, diff --git a/packages/aws-durable-execution-sdk-python-extensions/tests/compute/agentcore/agentcore_session_test.py b/packages/aws-durable-execution-sdk-python-extensions/tests/compute/agentcore/agentcore_session_test.py index 3ae3108d6..b4b431980 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/tests/compute/agentcore/agentcore_session_test.py +++ b/packages/aws-durable-execution-sdk-python-extensions/tests/compute/agentcore/agentcore_session_test.py @@ -8,9 +8,14 @@ import json from collections.abc import Callable from typing import Any +from unittest.mock import patch import pytest -from aws_durable_execution_sdk_python.config import Duration, StepConfig +from aws_durable_execution_sdk_python.config import ( + Duration, + StepConfig, + StepSemantics, +) from aws_durable_execution_sdk_python.context import DurableContext from aws_durable_execution_sdk_python.exceptions import ( ChildContextError, @@ -771,3 +776,22 @@ def handler(event: Any, context: DurableContext) -> Any: "test", "review.stop", ] + + +def test_session_id_step_waits_for_its_save(fake_agentcore_client: Any) -> None: + """The session ID becomes the runtime session of later steps. So its step + sets AT_LEAST_ONCE itself, and default_step_semantics cannot make it async.""" + client = fake_agentcore_client() + original_step = DurableContext.step + + with patch.object( + DurableContext, "step", autospec=True, side_effect=original_step + ) as step: + outcome(run(session_handler(session_config(client), lambda s, ctx: None))) + + [config] = [ + call.kwargs["config"] + for call in step.call_args_list + if call.kwargs.get("name") == "review.session" + ] + assert config.step_semantics is StepSemantics.AT_LEAST_ONCE diff --git a/packages/aws-durable-execution-sdk-python-extensions/tests/compute/microvm/session_test.py b/packages/aws-durable-execution-sdk-python-extensions/tests/compute/microvm/session_test.py index 7f5d36b60..9a22df8fd 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/tests/compute/microvm/session_test.py +++ b/packages/aws-durable-execution-sdk-python-extensions/tests/compute/microvm/session_test.py @@ -14,10 +14,15 @@ from collections.abc import Callable, Iterator from types import SimpleNamespace from typing import Any +from unittest.mock import patch import boto3 import pytest -from aws_durable_execution_sdk_python.config import Duration, StepConfig +from aws_durable_execution_sdk_python.config import ( + Duration, + StepConfig, + StepSemantics, +) from aws_durable_execution_sdk_python.context import Callback, DurableContext from aws_durable_execution_sdk_python.exceptions import ( ChildContextError, @@ -2453,3 +2458,24 @@ def body(vm: MicrovmSession, ctx: DurableContext, event: Any) -> Any: assert error["error"] == "MicrovmNotRunningError" assert "MicroVM mvm-1 is TERMINATED." in error["message"] assert len(endpoint.requests) == 1 + + +def test_session_id_step_waits_for_its_save( + run: Any, fake_client: Any, fake_endpoint: Any +) -> None: + """The session ID becomes the launch's client token. So its step sets + AT_LEAST_ONCE itself, and default_step_semantics cannot make it async.""" + client = fake_client(endpoint=fake_endpoint().url) + original_step = DurableContext.step + + with patch.object( + DurableContext, "step", autospec=True, side_effect=original_step + ) as step: + outcome(run(session_handler(session_config(client), lambda vm, ctx, e: None))) + + [config] = [ + call.kwargs["config"] + for call in step.call_args_list + if call.kwargs.get("name") == "pipeline.session" + ] + assert config.step_semantics is StepSemantics.AT_LEAST_ONCE From dd755fe780d6682c3e3ae43385648f75992fea76 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Thu, 26 Nov 2026 23:39:14 +0000 Subject: [PATCH 05/17] fix(sdk): retry when a late checkpoint fails An AT_LEAST_ONCE_ASYNC step can return, and the handler can then raise before the step's SUCCEED is sent. If that checkpoint then failed, the invocation answered FAILED for the handler error, so the execution ended without the step's result. After the batcher stops, an invocation-scope checkpoint failure now raises, so Lambda retries the invocation. An execution-scope failure, such as a validation error, still answers FAILED. A handler error keeps its own FAILED answer then. --- .../execution.py | 39 +++++++++--- .../step_at_least_once_async_test.py | 61 +++++++++++++++++-- 2 files changed, 88 insertions(+), 12 deletions(-) diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py index 2e1b8ccf1..ae3b366c0 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py @@ -583,13 +583,7 @@ def wait_for_checkpoint() -> None: output = ( DurableExecutionInvocationOutput.create_pending().to_dict() ) - # A batch can fail without the handler seeing it, for - # example the SUCCEED of an AT_LEAST_ONCE_ASYNC step sent - # while the handler returns. That result is not saved. So - # the invocation fails instead of reporting SUCCEEDED, and - # the next invocation runs the step again. - if output.get("Status") == InvocationStatus.SUCCEEDED.value: - execution_state.raise_if_checkpointing_failed() + output = _apply_late_checkpoint_failure(output, execution_state) completed = DurableExecutionInvocationOutput.from_dict(output) except BaseException as error: # Every started plugin gets its End hook, including when @@ -626,6 +620,37 @@ def wait_for_checkpoint() -> None: return wrapper +def _apply_late_checkpoint_failure( + output: MutableMapping[str, Any], execution_state: ExecutionState +) -> MutableMapping[str, Any]: + """Classify a checkpoint batch that failed without the handler seeing it. + + An example is the SUCCEED of an AT_LEAST_ONCE_ASYNC step, sent after the + handler returned or raised. That result is not saved. An invocation-scope + failure raises, so Lambda retries the invocation and the step runs again. + An execution-scope failure answers FAILED, as it does when the handler + sees it. A handler error keeps its own FAILED answer then. + """ + if output.get("Status") not in { + InvocationStatus.SUCCEEDED.value, + InvocationStatus.FAILED.value, + }: + return output + try: + execution_state.raise_if_checkpointing_failed() + except BackgroundThreadError as bg_error: + source = bg_error.source_exception + if isinstance(source, BotoClientError) and not source.is_retryable(): + if output.get("Status") == InvocationStatus.FAILED.value: + return output + return DurableExecutionInvocationOutput( + status=InvocationStatus.FAILED, + error=ErrorObject.from_exception(source), + ).to_dict() + raise source from bg_error + return output + + def handle_checkpoint_error(error: CheckpointError) -> DurableExecutionInvocationOutput: if error.is_retryable(): raise error from None # Terminate Lambda immediately and have it be retried diff --git a/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py b/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py index 07878d4a6..e5711f819 100644 --- a/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py @@ -16,7 +16,8 @@ from aws_durable_execution_sdk_python.config import Duration, StepConfig, StepSemantics from aws_durable_execution_sdk_python.context import DurableContext from aws_durable_execution_sdk_python.exceptions import ( - BackgroundThreadError, + CheckpointError, + DurableApiErrorCategory, StepError, SuspendExecution, ) @@ -69,9 +70,11 @@ def __init__( self, delays: dict[OperationAction, float] | None = None, fail_on: OperationAction | None = None, + error: Exception | None = None, ) -> None: self.delays = delays or {} self.fail_on = fail_on + self.error = error or RuntimeError("checkpoint failed") self.answered: list[OperationAction] = [] self.answered_names: set[tuple[OperationAction, str | None]] = set() self.lock = threading.Lock() @@ -89,8 +92,7 @@ def _checkpoint( delay = max((self.delays.get(action, 0.0) for action in actions), default=0) time.sleep(delay) if self.fail_on in actions: - msg = "checkpoint failed" - raise RuntimeError(msg) + raise self.error with self.lock: self.answered.extend(actions) self.answered_names.update((u.action, u.name) for u in updates) @@ -298,9 +300,58 @@ def test_failed_succeed_batch_does_not_report_succeeded(): def handler(_event: Any, context: DurableContext) -> str: return context.step(lambda _: "value", name="s", config=ASYNC) - with pytest.raises(BackgroundThreadError) as raised: + with pytest.raises(RuntimeError, match="checkpoint failed"): _invoke(handler, client) - assert str(raised.value.source_exception) == "checkpoint failed" + + +def _failing_succeed(category: DurableApiErrorCategory) -> _SlowClient: + return _SlowClient( + {OperationAction.SUCCEED: 0.1}, + fail_on=OperationAction.SUCCEED, + error=CheckpointError("checkpoint failed", error_category=category), + ) + + +def _step_then_raise(_event: Any, context: DurableContext) -> None: + context.step(lambda _: "value", name="s", config=ASYNC) + msg = "handler failed" + raise ValueError(msg) + + +def test_handler_error_after_unsaved_succeed_retries_the_invocation(): + """The handler raises while the SUCCEED is queued, and the SUCCEED then + fails with an invocation-scope error. The invocation raises, so Lambda + retries it, instead of answering FAILED without the step's result.""" + client = _failing_succeed(DurableApiErrorCategory.INVOCATION) + + with pytest.raises(CheckpointError, match="checkpoint failed"): + _invoke(durable_execution(_step_then_raise), client) + + +def test_handler_error_after_execution_scope_failure_answers_failed(): + """An execution-scope checkpoint failure, such as a validation error, + still answers FAILED with the handler's error.""" + client = _failing_succeed(DurableApiErrorCategory.EXECUTION) + + output = _invoke(durable_execution(_step_then_raise), client) + + assert output["Status"] == InvocationStatus.FAILED.value + assert output["Error"]["ErrorMessage"] == "handler failed" + + +def test_result_after_execution_scope_failure_answers_failed(): + """A handler that returns after an execution-scope SUCCEED failure answers + FAILED with the checkpoint error, as when the handler sees the failure.""" + client = _failing_succeed(DurableApiErrorCategory.EXECUTION) + + @durable_execution + def handler(_event: Any, context: DurableContext) -> str: + return context.step(lambda _: "value", name="s", config=ASYNC) + + output = _invoke(handler, client) + + assert output["Status"] == InvocationStatus.FAILED.value + assert output["Error"]["ErrorMessage"] == "checkpoint failed" def test_plugin_sees_async_step_end_before_invocation_end(): From 860900f44a889345c0ad83b77e379e8300c7b20c Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Thu, 26 Nov 2026 23:41:49 +0000 Subject: [PATCH 06/17] feat(examples): add an async default step example The handler sets default_step_semantics=AT_LEAST_ONCE_ASYNC. The step that makes the idempotency key sets AT_LEAST_ONCE itself. A wait ends the first invocation, so the second invocation replays the saved steps. --- .../examples-catalog.json | 11 ++++ .../src/step/step_semantics_async_default.py | 54 +++++++++++++++++++ .../step/test_step_semantics_async_default.py | 41 ++++++++++++++ 3 files changed, 106 insertions(+) create mode 100644 packages/aws-durable-execution-sdk-python-examples/src/step/step_semantics_async_default.py create mode 100644 packages/aws-durable-execution-sdk-python-examples/test/step/test_step_semantics_async_default.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 fad9712f6..abd046247 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 Semantics Async Default", + "description": "Make every step AT_LEAST_ONCE_ASYNC with default_step_semantics, and keep AT_LEAST_ONCE on the step that makes an idempotency key", + "handler": "step_semantics_async_default.handler", + "integration": true, + "durableConfig": { + "RetentionPeriodInDays": 7, + "ExecutionTimeout": 300 + }, + "path": "./src/step/step_semantics_async_default.py" + }, { "name": "Step with Pause Every", "description": "Experimental: pause the execution after every third failed attempt of a step, until an operator resumes it", diff --git a/packages/aws-durable-execution-sdk-python-examples/src/step/step_semantics_async_default.py b/packages/aws-durable-execution-sdk-python-examples/src/step/step_semantics_async_default.py new file mode 100644 index 000000000..79079a4f4 --- /dev/null +++ b/packages/aws-durable-execution-sdk-python-examples/src/step/step_semantics_async_default.py @@ -0,0 +1,54 @@ +"""Make every step AT_LEAST_ONCE_ASYNC, except the one that makes a key. + +An AT_LEAST_ONCE_ASYNC step returns its result before the result is saved. +Each invocation saves the result before it returns. If an invocation ends +first, the step runs again on replay and can return a different value. + +The order ID becomes the idempotency key of the charge. A new ID on replay +would charge twice. So that step sets AT_LEAST_ONCE itself, and waits for its +result to be saved. The wait ends the first invocation, and the second +invocation replays the saved steps. +""" + +import uuid +from typing import Any + +from aws_durable_execution_sdk_python.config import ( + Duration, + StepConfig, + StepSemantics, +) +from aws_durable_execution_sdk_python.context import ( + DurableContext, + StepContext, + durable_step, +) +from aws_durable_execution_sdk_python.execution import durable_execution + + +@durable_step +def create_order_id(_step_context: StepContext) -> str: + return str(uuid.uuid4()) + + +@durable_step +def charge(_step_context: StepContext, order_id: str, amount: int) -> dict: + # Call the payment service here, with order_id as the idempotency key. + return {"order_id": order_id, "amount": amount, "status": "charged"} + + +@durable_step +def send_receipt(_step_context: StepContext, order_id: str) -> str: + return f"receipt sent for {order_id}" + + +@durable_execution(default_step_semantics=StepSemantics.AT_LEAST_ONCE_ASYNC) +def handler(_event: Any, context: DurableContext) -> dict: + order_id = context.step( + create_order_id(), + config=StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE), + ) + payment = context.step(charge(order_id, 42)) + context.wait(Duration.from_seconds(1), name="settle") + receipt = context.step(send_receipt(order_id)) + return {"payment": payment, "receipt": receipt} diff --git a/packages/aws-durable-execution-sdk-python-examples/test/step/test_step_semantics_async_default.py b/packages/aws-durable-execution-sdk-python-examples/test/step/test_step_semantics_async_default.py new file mode 100644 index 000000000..cb2652747 --- /dev/null +++ b/packages/aws-durable-execution-sdk-python-examples/test/step/test_step_semantics_async_default.py @@ -0,0 +1,41 @@ +"""Tests for the step_semantics_async_default example.""" + +import pytest +from aws_durable_execution_sdk_python.execution import InvocationStatus +from aws_durable_execution_sdk_python.lambda_service import ( + OperationStatus, + OperationType, +) + +from src.step import step_semantics_async_default +from test.conftest import deserialize_operation_payload + + +@pytest.mark.example +@pytest.mark.durable_execution( + handler=step_semantics_async_default.handler, + lambda_function_name="step semantics async default", +) +def test_step_semantics_async_default(durable_runner): + """Every step is saved, and the replay after the wait reuses the order ID.""" + with durable_runner: + result = durable_runner.run(input="test", timeout=30) + + assert result.status is InvocationStatus.SUCCEEDED + output = deserialize_operation_payload(result.result) + order_id = output["payment"]["order_id"] + assert output == { + "payment": {"order_id": order_id, "amount": 42, "status": "charged"}, + "receipt": f"receipt sent for {order_id}", + } + + steps = { + op.name: op + for op in result.operations + if op.operation_type is OperationType.STEP + } + assert set(steps) == {"create_order_id", "charge", "send_receipt"} + assert {op.status for op in steps.values()} == {OperationStatus.SUCCEEDED} + [wait] = [op for op in result.operations if op.operation_type is OperationType.WAIT] + assert wait.name == "settle" + assert wait.status is OperationStatus.SUCCEEDED From da57ab36d09709bda2dab51efa195a1bbf65c9df Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Thu, 26 Nov 2026 23:42:10 +0000 Subject: [PATCH 07/17] docs(sdk): mark AT_LEAST_ONCE_ASYNC experimental The StepSemantics docstring, the StepConfig docstring, the README and the example say AT_LEAST_ONCE_ASYNC is experimental, as the pause option does. default_step_semantics, AT_LEAST_ONCE and AT_MOST_ONCE are not experimental. --- .../examples-catalog.json | 2 +- .../src/step/step_semantics_async_default.py | 3 +++ packages/aws-durable-execution-sdk-python/README.md | 2 +- .../src/aws_durable_execution_sdk_python/config.py | 7 ++++--- 4 files changed, 9 insertions(+), 5 deletions(-) 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 abd046247..83b29b2cd 100644 --- a/packages/aws-durable-execution-sdk-python-examples/examples-catalog.json +++ b/packages/aws-durable-execution-sdk-python-examples/examples-catalog.json @@ -47,7 +47,7 @@ }, { "name": "Step Semantics Async Default", - "description": "Make every step AT_LEAST_ONCE_ASYNC with default_step_semantics, and keep AT_LEAST_ONCE on the step that makes an idempotency key", + "description": "Experimental: make every step AT_LEAST_ONCE_ASYNC with default_step_semantics, and keep AT_LEAST_ONCE on the step that makes an idempotency key", "handler": "step_semantics_async_default.handler", "integration": true, "durableConfig": { diff --git a/packages/aws-durable-execution-sdk-python-examples/src/step/step_semantics_async_default.py b/packages/aws-durable-execution-sdk-python-examples/src/step/step_semantics_async_default.py index 79079a4f4..da6e64365 100644 --- a/packages/aws-durable-execution-sdk-python-examples/src/step/step_semantics_async_default.py +++ b/packages/aws-durable-execution-sdk-python-examples/src/step/step_semantics_async_default.py @@ -1,5 +1,8 @@ """Make every step AT_LEAST_ONCE_ASYNC, except the one that makes a key. +Experimental: StepSemantics.AT_LEAST_ONCE_ASYNC may change or be removed in a +future release. + An AT_LEAST_ONCE_ASYNC step returns its result before the result is saved. Each invocation saves the result before it returns. If an invocation ends first, the step runs again on replay and can return a different value. diff --git a/packages/aws-durable-execution-sdk-python/README.md b/packages/aws-durable-execution-sdk-python/README.md index 437c60c32..20ffd61d3 100644 --- a/packages/aws-durable-execution-sdk-python/README.md +++ b/packages/aws-durable-execution-sdk-python/README.md @@ -176,7 +176,7 @@ def handler(event: dict, context: DurableContext) -> dict: - `StepSemantics.AT_LEAST_ONCE` (default): the attempt runs again on replay if it was interrupted before its result was saved. The step waits for its result to be saved before it returns. - `StepSemantics.AT_MOST_ONCE`: the step saves its start before it runs. An interrupted attempt does not run again. It fails with `StepInterruptedError` and goes to the retry strategy. -- `StepSemantics.AT_LEAST_ONCE_ASYNC`: like `AT_LEAST_ONCE`, but the step returns its result without waiting for the save. So the step has lower latency. Each invocation saves the result before it returns. If the invocation ends before the save, the step runs again on replay. On that replay the step can return a different value, and later steps run again with it. So do not use this mode for a step whose result becomes an idempotency key or a client token for a later step. A failed attempt still waits for its retry or failure to be saved. +- `StepSemantics.AT_LEAST_ONCE_ASYNC` (experimental): like `AT_LEAST_ONCE`, but the step returns its result without waiting for the save. So the step has lower latency. Each invocation saves the result before it returns. If the invocation ends before the save, the step runs again on replay. On that replay the step can return a different value, and later steps run again with it. So do not use this mode for a step whose result becomes an idempotency key or a client token for a later step. A failed attempt still waits for its retry or failure to be saved. This value is experimental. It may change or be removed in a future release. `AT_MOST_ONCE_PER_RETRY` and `AT_LEAST_ONCE_PER_RETRY` are deprecated aliases of `AT_MOST_ONCE` and `AT_LEAST_ONCE`. 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 ff17ba7f4..39a6e7cc7 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 @@ -479,7 +479,8 @@ def __call__(self, *args, **kwargs): class StepSemantics(Enum): """How often one step attempt may run its function. See StepConfig. - AT_LEAST_ONCE_ASYNC works like AT_LEAST_ONCE, with one change. + AT_LEAST_ONCE_ASYNC is experimental; it may change or be removed in a + future release. It works like AT_LEAST_ONCE, with one change. The step returns its result as soon as the SUCCEED checkpoint is queued. It does not wait for the service to save it. So the step has lower latency. @@ -556,8 +557,8 @@ class StepConfig: invocation. AT_MOST_ONCE waits for the START checkpoint first, and an interrupted attempt fails with StepInterruptedError and goes to the retry strategy instead of running again. - AT_LEAST_ONCE_ASYNC also does not wait for the SUCCEED - checkpoint; see StepSemantics. + AT_LEAST_ONCE_ASYNC (experimental) also does not wait for the + SUCCEED checkpoint; see StepSemantics. serdes: Custom serialization/deserialization for the step result. If None, uses the default JSON serializer. From 24552197b5ae79cdb1ca53f82d3e6e3361e308d0 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Fri, 27 Nov 2026 00:31:49 +0000 Subject: [PATCH 08/17] fix(sdk): check late failures on PENDING too A handler can suspend while an AT_LEAST_ONCE_ASYNC SUCCEED is still queued, for example on a replayed wait. close() sends it, and when that call failed the invocation still answered PENDING. A permanent failure then let each later invocation rerun the step, and a retryable one waited for the timer. The late-failure check now covers PENDING too, except when the token was withdrawn. Both cases now match AT_LEAST_ONCE: FAILED, or a raised CheckpointError that Lambda retries. --- .../execution.py | 8 ++++ .../step_at_least_once_async_test.py | 46 +++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py index ae3b366c0..9461134cc 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py @@ -630,12 +630,20 @@ def _apply_late_checkpoint_failure( failure raises, so Lambda retries the invocation and the step runs again. An execution-scope failure answers FAILED, as it does when the handler sees it. A handler error keeps its own FAILED answer then. + + A PENDING answer is checked too: a handler can suspend while the SUCCEED + is still queued, for example on a replayed wait. A withdrawn token is the + exception, because then the service records nothing from this invocation + and PENDING is the only true answer. """ if output.get("Status") not in { InvocationStatus.SUCCEEDED.value, InvocationStatus.FAILED.value, + InvocationStatus.PENDING.value, }: return output + if execution_state.is_checkpoint_token_revoked: + return output try: execution_state.raise_if_checkpointing_failed() except BackgroundThreadError as bg_error: diff --git a/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py b/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py index e5711f819..233b15385 100644 --- a/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py @@ -6,6 +6,7 @@ from __future__ import annotations +import datetime import threading import time from typing import Any @@ -40,6 +41,7 @@ OperationType, OperationUpdate, StepDetails, + WaitDetails, ) from aws_durable_execution_sdk_python.plugin import ( DurableInstrumentationPlugin, @@ -431,3 +433,47 @@ def handler(_event: Any, context: DurableContext) -> list[str]: } for name in saved_at_return: assert client.was_answered(OperationAction.SUCCEED, name) + + +def _pending_wait_operation() -> Operation: + """A wait that started in an earlier invocation and ends in an hour.""" + return Operation( + operation_id=OperationIdNamespace().create_id_for_step(2), + operation_type=OperationType.WAIT, + status=OperationStatus.STARTED, + name="w", + sub_type="Wait", + wait_details=WaitDetails( + scheduled_end_timestamp=datetime.datetime.now(datetime.UTC) + + datetime.timedelta(hours=1) + ), + ) + + +def _step_then_pending_wait(_event: Any, context: DurableContext) -> str: + context.step(lambda _: "v", name="s", config=ASYNC) + context.wait(Duration.from_seconds(3600), name="w") + return "done" + + +def test_suspend_after_execution_scope_failure_answers_failed(): + """The handler suspends while the async SUCCEED is queued, and it fails for good.""" + client = _failing_succeed(DurableApiErrorCategory.EXECUTION) + + out = _invoke( + durable_execution(_step_then_pending_wait), client, [_pending_wait_operation()] + ) + + assert out["Status"] == InvocationStatus.FAILED.value + + +def test_suspend_after_invocation_scope_failure_retries_the_invocation(): + """The handler suspends while the async SUCCEED is queued, and it fails for now.""" + client = _failing_succeed(DurableApiErrorCategory.INVOCATION) + + with pytest.raises(CheckpointError): + _invoke( + durable_execution(_step_then_pending_wait), + client, + [_pending_wait_operation()], + ) From ef4c19b0993b60504c4cfb42cd7fdd1fff70bd57 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Fri, 27 Nov 2026 06:04:45 +0000 Subject: [PATCH 09/17] fix: drop unreachable status check _apply_late_checkpoint_failure only receives SUCCEEDED, FAILED or PENDING output from invoke_handler. So the status filter at its top never returns early, and this change removes it. --- .../src/aws_durable_execution_sdk_python/execution.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py index 9461134cc..f11149711 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py @@ -636,12 +636,6 @@ def _apply_late_checkpoint_failure( exception, because then the service records nothing from this invocation and PENDING is the only true answer. """ - if output.get("Status") not in { - InvocationStatus.SUCCEEDED.value, - InvocationStatus.FAILED.value, - InvocationStatus.PENDING.value, - }: - return output if execution_state.is_checkpoint_token_revoked: return output try: From 2077ba5a6f83760e012bd72925bfa492225974a7 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Fri, 27 Nov 2026 15:29:44 +0000 Subject: [PATCH 10/17] fix(sdk): keep StepConfig.step_semantics default StepConfig.step_semantics keeps its type StepSemantics and its default AT_LEAST_ONCE, as on main. So StepConfig().step_semantics.value works. StepConfig records privately whether the caller set the field. So DurableContext.step applies default_step_semantics only to a step that did not set it, and an explicit AT_LEAST_ONCE wins. The flag is an init field, so dataclasses.replace keeps it. --- .../config.py | 36 ++++++++++++++++--- .../context.py | 2 +- .../tests/config_test.py | 10 +++++- .../tests/context_test.py | 13 +++++++ 4 files changed, 54 insertions(+), 7 deletions(-) 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 39a6e7cc7..e8e65bccb 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 @@ -7,7 +7,7 @@ import string from dataclasses import dataclass, field from enum import Enum, StrEnum -from typing import TYPE_CHECKING, Generic, TypeVar +from typing import TYPE_CHECKING, Generic, TypeVar, cast from aws_durable_execution_sdk_python.exceptions import ValidationError @@ -541,6 +541,11 @@ def _validate_sub_type(sub_type: str | None) -> None: raise ValidationError(msg) +# Default of StepConfig.step_semantics. StepConfig stores AT_LEAST_ONCE in its +# place and records that the caller did not set the field. +_STEP_SEMANTICS_UNSET: StepSemantics = cast("StepSemantics", object()) + + @dataclass(frozen=True) class StepConfig: """Configuration for a step. @@ -550,9 +555,10 @@ class StepConfig: If None, the SDK uses its default retry strategy. step_semantics: How often one attempt may run the function. - None (the default) uses the default_step_semantics of - durable_execution, which is AT_LEAST_ONCE unless set. - AT_LEAST_ONCE checkpoints START without + The default is AT_LEAST_ONCE. A step that does not set this + field uses the default_step_semantics of durable_execution, + which is AT_LEAST_ONCE unless set. A value set here wins, even + AT_LEAST_ONCE. AT_LEAST_ONCE checkpoints START without waiting, so an interrupted attempt runs again on the next invocation. AT_MOST_ONCE waits for the START checkpoint first, and an interrupted attempt fails with StepInterruptedError @@ -577,12 +583,32 @@ class StepConfig: """ retry_strategy: Callable[[Exception, int], RetryDecision] | None = None - step_semantics: StepSemantics | None = None + step_semantics: StepSemantics = _STEP_SEMANTICS_UNSET serdes: SerDes | None = None sub_type: str | None = field(default=None, kw_only=True) + # Private. True when the caller set step_semantics. It is an init field, + # so dataclasses.replace passes it on to the copy. + _step_semantics_set: bool | None = field( + default=None, kw_only=True, repr=False, compare=False + ) def __post_init__(self) -> None: _validate_sub_type(self.sub_type) + if self.step_semantics is _STEP_SEMANTICS_UNSET: + object.__setattr__(self, "step_semantics", StepSemantics.AT_LEAST_ONCE) + is_set = False + elif self._step_semantics_set is None: + is_set = True + else: + # dataclasses.replace copies the stored value and the flag. So a + # replace that changes the value to another member sets the field. + # A replace to AT_LEAST_ONCE on an unset config stays unset, + # because the copy cannot tell it from the stored default. + is_set = ( + self._step_semantics_set + or self.step_semantics is not StepSemantics.AT_LEAST_ONCE + ) + object.__setattr__(self, "_step_semantics_set", is_set) @dataclass(frozen=True) diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/context.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/context.py index a86806153..415d59974 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/context.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/context.py @@ -899,7 +899,7 @@ def step( logger.debug("Step name: %s", step_name) if not config: config = StepConfig() - if config.step_semantics is None: + if not config._step_semantics_set: # noqa: SLF001 config = replace(config, step_semantics=self.state.default_step_semantics) sub_type = config.sub_type or OperationSubType.STEP.value with self._operation_replay_aware( diff --git a/packages/aws-durable-execution-sdk-python/tests/config_test.py b/packages/aws-durable-execution-sdk-python/tests/config_test.py index 04360584e..425244c35 100644 --- a/packages/aws-durable-execution-sdk-python/tests/config_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/config_test.py @@ -118,10 +118,18 @@ def test_step_config_defaults(): """Test StepConfig default values.""" config = StepConfig() assert config.retry_strategy is None - assert config.step_semantics is None + assert config.step_semantics == StepSemantics.AT_LEAST_ONCE + assert config.step_semantics.value == "AT_LEAST_ONCE_PER_RETRY" assert config.serdes is None +def test_step_config_default_semantics_equals_explicit_default(): + """An unset step_semantics compares equal to an explicit AT_LEAST_ONCE.""" + explicit = StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE) + assert StepConfig() == explicit + assert repr(StepConfig()) == repr(explicit) + + def test_step_config_with_values(): """Test StepConfig with custom values.""" retry_strategy = Mock() diff --git a/packages/aws-durable-execution-sdk-python/tests/context_test.py b/packages/aws-durable-execution-sdk-python/tests/context_test.py index bc792e742..78f894c8e 100644 --- a/packages/aws-durable-execution-sdk-python/tests/context_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/context_test.py @@ -5,6 +5,7 @@ import random import threading from concurrent.futures import ThreadPoolExecutor +from dataclasses import replace from itertools import islice from unittest.mock import ANY, MagicMock, Mock, patch @@ -563,6 +564,18 @@ def test_step_with_name_and_config(mock_executor_class): StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE), StepSemantics.AT_LEAST_ONCE, ), + (StepConfig(None, StepSemantics.AT_LEAST_ONCE), StepSemantics.AT_LEAST_ONCE), + (replace(StepConfig(), serdes=None), StepSemantics.AT_LEAST_ONCE_ASYNC), + ( + replace( + StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE), serdes=None + ), + StepSemantics.AT_LEAST_ONCE, + ), + ( + replace(StepConfig(), step_semantics=StepSemantics.AT_MOST_ONCE), + StepSemantics.AT_MOST_ONCE, + ), ], ) @patch("aws_durable_execution_sdk_python.context.StepOperationExecutor") From 266916a929b0addd8cf6a5ae4d2745a54c4e03e5 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Fri, 27 Nov 2026 15:32:12 +0000 Subject: [PATCH 11/17] test(sdk): send overflow checkpoint at stop Add a test for the overflow part of the batcher's stop condition. An async SUCCEED that does not fit next to a START goes to the overflow queue. Stop is signaled while the START is in flight, so only the overflow queue has work. The test runs the real batch loop in a thread and checks that the SUCCEED is sent before the thread stops. --- .../tests/state_test.py | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/packages/aws-durable-execution-sdk-python/tests/state_test.py b/packages/aws-durable-execution-sdk-python/tests/state_test.py index 46d361d15..05badc424 100644 --- a/packages/aws-durable-execution-sdk-python/tests/state_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/state_test.py @@ -6306,6 +6306,58 @@ def test_stop_settles_pending_refresh_and_sends_queued_items(): assert calls == [[async_op.operation_update]] +def test_stop_sends_async_succeed_left_in_overflow_queue(): + """At stop, an operation that is only in the overflow queue is still sent. + + The async SUCCEED does not fit next to the START, so the batcher moves it + to the overflow queue. The stop signal comes while the START is in flight, + so at stop the main queue is empty and only the overflow queue has work. + """ + calls: list[list] = [] + in_flight = threading.Event() + release = threading.Event() + recording_client = _refresh_client(calls) + record = recording_client.checkpoint + + def _checkpoint(**kwargs): + if not calls: + in_flight.set() + assert release.wait(timeout=5) + return record(**kwargs) + + recording_client.checkpoint = _checkpoint + state = ExecutionState( + durable_execution_arn="test_arn", + initial_checkpoint_token="token123", # noqa: S106 + operations={}, + service_client=recording_client, + plugin_executor=PluginExecutor(plugins=None), + batcher_config=CheckpointBatcherConfig(max_batch_size_bytes=200), + ) + start = _step_update(OperationAction.START, "a") + succeed = OperationUpdate( + operation_id="b", + operation_type=OperationType.STEP, + action=OperationAction.SUCCEED, + payload="x" * 300, + ) + state.create_checkpoint(start, is_sync=False) + state.create_checkpoint(succeed, is_sync=False) + + thread = threading.Thread(target=state.checkpoint_batches_forever, daemon=True) + thread.start() + assert in_flight.wait(timeout=5) + assert state._checkpoint_queue.empty() + assert list(state._overflow_queue.queue)[0].operation_update is succeed + + state.stop_checkpointing() + release.set() + thread.join(timeout=5) + + assert not thread.is_alive() + assert calls == [[start], [succeed]] + + def test_cancelled_refresh_deferred_then_due_is_dropped(): """A refresh cancelled while pending is dropped when its time comes, and the batch goes on without it.""" From 528fa96996da9e9379d535d78ab0720e8bb6cd45 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Fri, 27 Nov 2026 16:07:51 +0000 Subject: [PATCH 12/17] docs(sdk): note replace keeps step_semantics unset dataclasses.replace cannot tell an explicit AT_LEAST_ONCE from the default. Tell users to build StepConfig with step_semantics set to pin AT_LEAST_ONCE under an async execution default. --- packages/aws-durable-execution-sdk-python/README.md | 2 +- .../src/aws_durable_execution_sdk_python/config.py | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/aws-durable-execution-sdk-python/README.md b/packages/aws-durable-execution-sdk-python/README.md index 20ffd61d3..79d3136c6 100644 --- a/packages/aws-durable-execution-sdk-python/README.md +++ b/packages/aws-durable-execution-sdk-python/README.md @@ -180,7 +180,7 @@ def handler(event: dict, context: DurableContext) -> dict: `AT_MOST_ONCE_PER_RETRY` and `AT_LEAST_ONCE_PER_RETRY` are deprecated aliases of `AT_MOST_ONCE` and `AT_LEAST_ONCE`. -`@durable_execution(default_step_semantics=...)` sets the semantics of every step that does not set its own. It applies in child contexts, `map` items, `parallel` branches, and the steps that SDK extensions create, unless the extension sets its own. A step's own `step_semantics` wins. +`@durable_execution(default_step_semantics=...)` sets the semantics of every step that does not set its own. It applies in child contexts, `map` items, `parallel` branches, and the steps that SDK extensions create, unless the extension sets its own. A step's own `step_semantics` wins. `dataclasses.replace` cannot tell an explicit `AT_LEAST_ONCE` from the default. So to pin `AT_LEAST_ONCE` under an async default, build the config with `StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE, ...)`. ```python from aws_durable_execution_sdk_python.config import StepConfig, StepSemantics 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 e8e65bccb..692e310b1 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 @@ -565,6 +565,10 @@ class StepConfig: and goes to the retry strategy instead of running again. AT_LEAST_ONCE_ASYNC (experimental) also does not wait for the SUCCEED checkpoint; see StepSemantics. + dataclasses.replace cannot tell an explicit AT_LEAST_ONCE from + the default. So to pin AT_LEAST_ONCE under an async execution + default, build the config with + StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE, ...). serdes: Custom serialization/deserialization for the step result. If None, uses the default JSON serializer. From c72f52bc50c2d2378b3ae5324d8fd6fa8fb0f255 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Fri, 27 Nov 2026 16:09:49 +0000 Subject: [PATCH 13/17] fix(sdk): keep PerRetry names as canonical members Declaring AT_MOST_ONCE and AT_LEAST_ONCE first made them the canonical members. That changed .name of the PerRetry members and the order of list(StepSemantics). Declare the PerRetry members first, as on main, and make the new names aliases with the same values. Add a test for .name, identity, and iteration order. --- .../README.md | 2 +- .../config.py | 24 +++++++++++-------- .../tests/config_test.py | 17 +++++++++++-- 3 files changed, 30 insertions(+), 13 deletions(-) diff --git a/packages/aws-durable-execution-sdk-python/README.md b/packages/aws-durable-execution-sdk-python/README.md index 79d3136c6..65800833c 100644 --- a/packages/aws-durable-execution-sdk-python/README.md +++ b/packages/aws-durable-execution-sdk-python/README.md @@ -178,7 +178,7 @@ def handler(event: dict, context: DurableContext) -> dict: - `StepSemantics.AT_MOST_ONCE`: the step saves its start before it runs. An interrupted attempt does not run again. It fails with `StepInterruptedError` and goes to the retry strategy. - `StepSemantics.AT_LEAST_ONCE_ASYNC` (experimental): like `AT_LEAST_ONCE`, but the step returns its result without waiting for the save. So the step has lower latency. Each invocation saves the result before it returns. If the invocation ends before the save, the step runs again on replay. On that replay the step can return a different value, and later steps run again with it. So do not use this mode for a step whose result becomes an idempotency key or a client token for a later step. A failed attempt still waits for its retry or failure to be saved. This value is experimental. It may change or be removed in a future release. -`AT_MOST_ONCE_PER_RETRY` and `AT_LEAST_ONCE_PER_RETRY` are deprecated aliases of `AT_MOST_ONCE` and `AT_LEAST_ONCE`. +`AT_MOST_ONCE` and `AT_LEAST_ONCE` are aliases of `AT_MOST_ONCE_PER_RETRY` and `AT_LEAST_ONCE_PER_RETRY`, so they are the same members. The `PerRetry` names are deprecated. They stay the canonical members, so `.name` and iteration do not change. `@durable_execution(default_step_semantics=...)` sets the semantics of every step that does not set its own. It applies in child contexts, `map` items, `parallel` branches, and the steps that SDK extensions create, unless the extension sets its own. A step's own `step_semantics` wins. `dataclasses.replace` cannot tell an explicit `AT_LEAST_ONCE` from the default. So to pin `AT_LEAST_ONCE` under an async default, build the config with `StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE, ...)`. 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 692e310b1..cbf29377c 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 @@ -500,20 +500,24 @@ class StepSemantics(Enum): its RETRY or FAIL checkpoint. A plugin receives the step's end hook after the service saves the result, at the latest when the invocation ends. - AT_MOST_ONCE_PER_RETRY and AT_LEAST_ONCE_PER_RETRY are deprecated aliases - of AT_MOST_ONCE and AT_LEAST_ONCE. Existing code keeps working. + AT_MOST_ONCE and AT_LEAST_ONCE are aliases of AT_MOST_ONCE_PER_RETRY and + AT_LEAST_ONCE_PER_RETRY. They are the same members. The PerRetry names + are deprecated, so use AT_MOST_ONCE and AT_LEAST_ONCE in new code. The + PerRetry names stay the canonical members, so ``.name`` and iteration + match earlier releases. """ - AT_MOST_ONCE = "AT_MOST_ONCE_PER_RETRY" - AT_LEAST_ONCE = "AT_LEAST_ONCE_PER_RETRY" - AT_LEAST_ONCE_ASYNC = "AT_LEAST_ONCE_ASYNC" - - # Deprecated: use AT_MOST_ONCE. It is the same member, with the same value - # and behavior. + # Deprecated: use AT_MOST_ONCE. It stays the canonical member, so .name + # and iteration match earlier releases. AT_MOST_ONCE_PER_RETRY = "AT_MOST_ONCE_PER_RETRY" - # Deprecated: use AT_LEAST_ONCE. It is the same member, with the same value - # and behavior. + # Deprecated: use AT_LEAST_ONCE. It stays the canonical member, so .name + # and iteration match earlier releases. AT_LEAST_ONCE_PER_RETRY = "AT_LEAST_ONCE_PER_RETRY" + AT_LEAST_ONCE_ASYNC = "AT_LEAST_ONCE_ASYNC" + + # Aliases of the members above, with the same value and behavior. + AT_MOST_ONCE = "AT_MOST_ONCE_PER_RETRY" + AT_LEAST_ONCE = "AT_LEAST_ONCE_PER_RETRY" _SUB_TYPE_CHARACTERS = frozenset(string.ascii_letters + string.digits + "-_") diff --git a/packages/aws-durable-execution-sdk-python/tests/config_test.py b/packages/aws-durable-execution-sdk-python/tests/config_test.py index 425244c35..36b813d69 100644 --- a/packages/aws-durable-execution-sdk-python/tests/config_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/config_test.py @@ -106,14 +106,27 @@ def test_step_semantics_enum(): assert StepSemantics.AT_LEAST_ONCE_ASYNC.value == "AT_LEAST_ONCE_ASYNC" -def test_deprecated_step_semantics_are_the_new_members(): - """The PerRetry names are aliases, so `is` checks match either name.""" +def test_new_step_semantics_names_are_aliases(): + """The new names are aliases, so `is` checks match either name.""" assert StepSemantics.AT_MOST_ONCE_PER_RETRY is StepSemantics.AT_MOST_ONCE assert StepSemantics.AT_LEAST_ONCE_PER_RETRY is StepSemantics.AT_LEAST_ONCE assert StepSemantics("AT_MOST_ONCE_PER_RETRY") is StepSemantics.AT_MOST_ONCE assert StepSemantics("AT_LEAST_ONCE_PER_RETRY") is StepSemantics.AT_LEAST_ONCE +def test_step_semantics_names_and_order_match_earlier_releases(): + """The PerRetry members stay canonical, and the async member is added last.""" + assert StepSemantics.AT_MOST_ONCE_PER_RETRY.name == "AT_MOST_ONCE_PER_RETRY" + assert StepSemantics.AT_LEAST_ONCE_PER_RETRY.name == "AT_LEAST_ONCE_PER_RETRY" + assert StepSemantics.AT_MOST_ONCE.name == "AT_MOST_ONCE_PER_RETRY" + assert StepSemantics.AT_LEAST_ONCE.name == "AT_LEAST_ONCE_PER_RETRY" + assert list(StepSemantics) == [ + StepSemantics.AT_MOST_ONCE_PER_RETRY, + StepSemantics.AT_LEAST_ONCE_PER_RETRY, + StepSemantics.AT_LEAST_ONCE_ASYNC, + ] + + def test_step_config_defaults(): """Test StepConfig default values.""" config = StepConfig() From 1c473656b3da34d941bd16e43079f5fbf1ed6c86 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Fri, 27 Nov 2026 16:23:56 +0000 Subject: [PATCH 14/17] fix(sdk): drop unreachable revoked-token return The checkpoint thread sets the revoked flag or the failed flag, then leaves its loop. So both are never set, and the early return for a revoked token could not change the answer. --- .../src/aws_durable_execution_sdk_python/execution.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py index f11149711..c1c548de3 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py @@ -632,12 +632,8 @@ def _apply_late_checkpoint_failure( sees it. A handler error keeps its own FAILED answer then. A PENDING answer is checked too: a handler can suspend while the SUCCEED - is still queued, for example on a replayed wait. A withdrawn token is the - exception, because then the service records nothing from this invocation - and PENDING is the only true answer. + is still queued, for example on a replayed wait. """ - if execution_state.is_checkpoint_token_revoked: - return output try: execution_state.raise_if_checkpointing_failed() except BackgroundThreadError as bg_error: From e129e66f3381875b69dcd4437fb2e6527d80bf22 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Fri, 27 Nov 2026 17:59:42 +0000 Subject: [PATCH 15/17] fix(sdk): treat a replaced StepConfig as set dataclasses.replace passes the stored step_semantics to the copy, so an explicit AT_LEAST_ONCE looked unset and an async execution default replaced it. The set flag is no longer an init field: __post_init__ sets it from the value it gets, so every replaced config counts as set. A replaced config can then only lose the execution default, never turn async when the caller pinned AT_LEAST_ONCE. --- .../README.md | 2 +- .../config.py | 31 ++++++------------- .../tests/context_test.py | 7 ++++- 3 files changed, 17 insertions(+), 23 deletions(-) diff --git a/packages/aws-durable-execution-sdk-python/README.md b/packages/aws-durable-execution-sdk-python/README.md index 65800833c..457eaf603 100644 --- a/packages/aws-durable-execution-sdk-python/README.md +++ b/packages/aws-durable-execution-sdk-python/README.md @@ -180,7 +180,7 @@ def handler(event: dict, context: DurableContext) -> dict: `AT_MOST_ONCE` and `AT_LEAST_ONCE` are aliases of `AT_MOST_ONCE_PER_RETRY` and `AT_LEAST_ONCE_PER_RETRY`, so they are the same members. The `PerRetry` names are deprecated. They stay the canonical members, so `.name` and iteration do not change. -`@durable_execution(default_step_semantics=...)` sets the semantics of every step that does not set its own. It applies in child contexts, `map` items, `parallel` branches, and the steps that SDK extensions create, unless the extension sets its own. A step's own `step_semantics` wins. `dataclasses.replace` cannot tell an explicit `AT_LEAST_ONCE` from the default. So to pin `AT_LEAST_ONCE` under an async default, build the config with `StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE, ...)`. +`@durable_execution(default_step_semantics=...)` sets the semantics of every step that does not set its own. It applies in child contexts, `map` items, `parallel` branches, and the steps that SDK extensions create, unless the extension sets its own. A step's own `step_semantics` wins. A config made with `dataclasses.replace` counts `step_semantics` as set, so it keeps its value and does not take the execution default. ```python from aws_durable_execution_sdk_python.config import StepConfig, StepSemantics 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 cbf29377c..0d861c188 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 @@ -569,10 +569,8 @@ class StepConfig: and goes to the retry strategy instead of running again. AT_LEAST_ONCE_ASYNC (experimental) also does not wait for the SUCCEED checkpoint; see StepSemantics. - dataclasses.replace cannot tell an explicit AT_LEAST_ONCE from - the default. So to pin AT_LEAST_ONCE under an async execution - default, build the config with - StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE, ...). + A config made with dataclasses.replace counts the field as set, + so it keeps its value and does not take the execution default. serdes: Custom serialization/deserialization for the step result. If None, uses the default JSON serializer. @@ -594,28 +592,19 @@ class StepConfig: step_semantics: StepSemantics = _STEP_SEMANTICS_UNSET serdes: SerDes | None = None sub_type: str | None = field(default=None, kw_only=True) - # Private. True when the caller set step_semantics. It is an init field, - # so dataclasses.replace passes it on to the copy. - _step_semantics_set: bool | None = field( - default=None, kw_only=True, repr=False, compare=False + # Private. True when the caller set step_semantics. It is not an init + # field, so dataclasses.replace, which passes the stored value, sets it. + # A replaced config can then only lose the execution default, never + # take AT_LEAST_ONCE_ASYNC when the caller pinned AT_LEAST_ONCE. + _step_semantics_set: bool = field( + default=False, init=False, repr=False, compare=False ) def __post_init__(self) -> None: _validate_sub_type(self.sub_type) - if self.step_semantics is _STEP_SEMANTICS_UNSET: + is_set = self.step_semantics is not _STEP_SEMANTICS_UNSET + if not is_set: object.__setattr__(self, "step_semantics", StepSemantics.AT_LEAST_ONCE) - is_set = False - elif self._step_semantics_set is None: - is_set = True - else: - # dataclasses.replace copies the stored value and the flag. So a - # replace that changes the value to another member sets the field. - # A replace to AT_LEAST_ONCE on an unset config stays unset, - # because the copy cannot tell it from the stored default. - is_set = ( - self._step_semantics_set - or self.step_semantics is not StepSemantics.AT_LEAST_ONCE - ) object.__setattr__(self, "_step_semantics_set", is_set) diff --git a/packages/aws-durable-execution-sdk-python/tests/context_test.py b/packages/aws-durable-execution-sdk-python/tests/context_test.py index 78f894c8e..98e7c3aac 100644 --- a/packages/aws-durable-execution-sdk-python/tests/context_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/context_test.py @@ -565,7 +565,12 @@ def test_step_with_name_and_config(mock_executor_class): StepSemantics.AT_LEAST_ONCE, ), (StepConfig(None, StepSemantics.AT_LEAST_ONCE), StepSemantics.AT_LEAST_ONCE), - (replace(StepConfig(), serdes=None), StepSemantics.AT_LEAST_ONCE_ASYNC), + # A replaced config counts the field as set, so it keeps AT_LEAST_ONCE. + (replace(StepConfig(), serdes=None), StepSemantics.AT_LEAST_ONCE), + ( + replace(StepConfig(), step_semantics=StepSemantics.AT_LEAST_ONCE), + StepSemantics.AT_LEAST_ONCE, + ), ( replace( StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE), serdes=None From f36679c392cf4e1ee1180b31ef80faaa69d616a6 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Fri, 27 Nov 2026 21:08:18 +0000 Subject: [PATCH 16/17] test(extensions): check that session ID steps wait The session ID pin tests read StepConfig.step_semantics. StepConfig stores AT_LEAST_ONCE for both a set and an unset field, and the tests ran under the default semantics. So they passed without the pin. The tests now run the session under default_step_semantics set to AT_LEAST_ONCE_ASYNC. They delay the answer to the session ID's SUCCEED checkpoint. The AgentCore test checks that the session handler starts only after the answer. The MicroVM test checks that the launch has not run before the answer. Each test fails when its pin is removed. --- .../agentcore/agentcore_session_test.py | 74 +++++++++++++++---- .../tests/compute/microvm/session_test.py | 62 ++++++++++++---- 2 files changed, 106 insertions(+), 30 deletions(-) diff --git a/packages/aws-durable-execution-sdk-python-extensions/tests/compute/agentcore/agentcore_session_test.py b/packages/aws-durable-execution-sdk-python-extensions/tests/compute/agentcore/agentcore_session_test.py index b4b431980..2f7712f27 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/tests/compute/agentcore/agentcore_session_test.py +++ b/packages/aws-durable-execution-sdk-python-extensions/tests/compute/agentcore/agentcore_session_test.py @@ -6,6 +6,7 @@ from __future__ import annotations import json +import time from collections.abc import Callable from typing import Any from unittest.mock import patch @@ -28,9 +29,14 @@ InvocationStatus, durable_execution, ) -from aws_durable_execution_sdk_python.lambda_service import ErrorObject +from aws_durable_execution_sdk_python.lambda_service import ( + ErrorObject, + OperationAction, + OperationUpdate, +) from aws_durable_execution_sdk_python.retries import RetryDecision from aws_durable_execution_sdk_python.serdes import SerDes +from aws_durable_execution_sdk_python_testing.client import InMemoryServiceClient from aws_durable_execution_sdk_python_testing.runner import ( DurableFunctionTestResult, DurableFunctionTestRunner, @@ -66,11 +72,15 @@ def session_config(client: Any, **fields: Any) -> AgentcoreSessionConfig: return AgentcoreSessionConfig(**values) -def session_handler(config: AgentcoreSessionConfig, body: Body) -> Callable[..., Any]: +def session_handler( + config: AgentcoreSessionConfig, + body: Body, + default_step_semantics: StepSemantics = StepSemantics.AT_LEAST_ONCE, +) -> Callable[..., Any]: """A durable handler that runs ``body`` in a session named ``review``, and returns the message of an error that leaves it.""" - @durable_execution + @durable_execution(default_step_semantics=default_step_semantics) def handler(event: Any, context: DurableContext) -> Any: try: return { @@ -780,18 +790,52 @@ def handler(event: Any, context: DurableContext) -> Any: def test_session_id_step_waits_for_its_save(fake_agentcore_client: Any) -> None: """The session ID becomes the runtime session of later steps. So its step - sets AT_LEAST_ONCE itself, and default_step_semantics cannot make it async.""" + waits for its SUCCEED checkpoint, even when default_step_semantics is + AT_LEAST_ONCE_ASYNC.""" client = fake_agentcore_client() - original_step = DurableContext.step + original_checkpoint = InMemoryServiceClient.checkpoint + events: list[str] = [] + + def checkpoint( + self: InMemoryServiceClient, + durable_execution_arn: str, + checkpoint_token: str, + updates: list[OperationUpdate], + client_token: str | None, + ) -> Any: + saves_id = any( + update.name == "review.session" and update.action is OperationAction.SUCCEED + for update in updates + ) + if saves_id: + # A step that does not wait for this save lets the handler run now. + time.sleep(0.5) + output = original_checkpoint( + self, durable_execution_arn, checkpoint_token, updates, client_token + ) + if saves_id: + events.append("session ID saved") + return output - with patch.object( - DurableContext, "step", autospec=True, side_effect=original_step - ) as step: - outcome(run(session_handler(session_config(client), lambda s, ctx: None))) + def body(session: AgentcoreSession, ctx: DurableContext) -> Any: + events.append("handler started") + return session.invoke(ctx, "build", job_input=1, options=OPTIONS) + + with patch.object(InMemoryServiceClient, "checkpoint", checkpoint): + result = run_jobs( + session_handler( + session_config(client), + body, + default_step_semantics=StepSemantics.AT_LEAST_ONCE_ASYNC, + ), + {"build.callback": b'"built"'}, + ) - [config] = [ - call.kwargs["config"] - for call in step.call_args_list - if call.kwargs.get("name") == "review.session" - ] - assert config.step_semantics is StepSemantics.AT_LEAST_ONCE + assert outcome(result) == {"result": "built"} + # The service answered the save before the handler first started. The + # handler starts again in the replay after the callback. + assert events[:2] == ["session ID saved", "handler started"] + session = result.get_context("review").get_step("review.session") + assert session.result is not None + [request] = client.requests("invoke_agent_runtime") + assert request["runtimeSessionId"] == json.loads(session.result) diff --git a/packages/aws-durable-execution-sdk-python-extensions/tests/compute/microvm/session_test.py b/packages/aws-durable-execution-sdk-python-extensions/tests/compute/microvm/session_test.py index 9a22df8fd..f85fbefab 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/tests/compute/microvm/session_test.py +++ b/packages/aws-durable-execution-sdk-python-extensions/tests/compute/microvm/session_test.py @@ -35,9 +35,14 @@ InvocationStatus, durable_execution, ) -from aws_durable_execution_sdk_python.lambda_service import ErrorObject +from aws_durable_execution_sdk_python.lambda_service import ( + ErrorObject, + OperationAction, + OperationUpdate, +) from aws_durable_execution_sdk_python.retries import RetryDecision from aws_durable_execution_sdk_python.serdes import SerDes +from aws_durable_execution_sdk_python_testing.client import InMemoryServiceClient from aws_durable_execution_sdk_python_testing.runner import ( DurableFunctionTestResult, DurableFunctionTestRunner, @@ -147,11 +152,12 @@ def _run( def session_handler( config: MicrovmSessionConfig, body: Callable[[MicrovmSession, DurableContext, Any], Any], + default_step_semantics: StepSemantics = StepSemantics.AT_LEAST_ONCE, ) -> Callable[..., Any]: """A durable handler that runs ``body`` in a session named ``pipeline``, and returns the class and message of an error that leaves it.""" - @durable_execution + @durable_execution(default_step_semantics=default_step_semantics) def handler(event: Any, context: DurableContext) -> Any: try: return { @@ -2463,19 +2469,45 @@ def body(vm: MicrovmSession, ctx: DurableContext, event: Any) -> Any: def test_session_id_step_waits_for_its_save( run: Any, fake_client: Any, fake_endpoint: Any ) -> None: - """The session ID becomes the launch's client token. So its step sets - AT_LEAST_ONCE itself, and default_step_semantics cannot make it async.""" + """The session ID becomes the launch's client token. So its step waits for + its SUCCEED checkpoint, even when default_step_semantics is + AT_LEAST_ONCE_ASYNC.""" client = fake_client(endpoint=fake_endpoint().url) - original_step = DurableContext.step + original_checkpoint = InMemoryServiceClient.checkpoint + launches_at_save: list[int] = [] + + def checkpoint( + self: InMemoryServiceClient, + durable_execution_arn: str, + checkpoint_token: str, + updates: list[OperationUpdate], + client_token: str | None, + ) -> Any: + saves_id = any( + update.name == "pipeline.session" + and update.action is OperationAction.SUCCEED + for update in updates + ) + if saves_id: + # A step that does not wait for this save lets the launch run now. + time.sleep(0.5) + output = original_checkpoint( + self, durable_execution_arn, checkpoint_token, updates, client_token + ) + if saves_id: + launches_at_save.append(len(client.requests("run_microvm"))) + return output - with patch.object( - DurableContext, "step", autospec=True, side_effect=original_step - ) as step: - outcome(run(session_handler(session_config(client), lambda vm, ctx, e: None))) + with patch.object(InMemoryServiceClient, "checkpoint", checkpoint): + result = run( + session_handler( + session_config(client), + lambda vm, ctx, e: None, + default_step_semantics=StepSemantics.AT_LEAST_ONCE_ASYNC, + ) + ) - [config] = [ - call.kwargs["config"] - for call in step.call_args_list - if call.kwargs.get("name") == "pipeline.session" - ] - assert config.step_semantics is StepSemantics.AT_LEAST_ONCE + assert outcome(result) == {"result": None} + # The service answered the save before the launch step started. + assert launches_at_save == [0] + assert len(client.requests("run_microvm")) == 1 From 3bfac47834350fb29ddf2cc2192749073be672ce Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Fri, 27 Nov 2026 22:40:54 +0000 Subject: [PATCH 17/17] fix(sdk): fail checkpoints when batching fails Sizing an update for a checkpoint batch can raise, for example when PassThroughSerDes leaves bytes in the payload. This ran outside the batcher's failure handling. So the error was not observed, waiters were not woken, and an unsaved AT_LEAST_ONCE_ASYNC SUCCEED could still answer SUCCEEDED. Move the failure handling into _fail_checkpointing and call it for both a failed API call and a failed batch collection. The operation that failed to size is failed with the rest of the batch. --- .../aws_durable_execution_sdk_python/state.py | 90 ++++++++++++------- .../step_at_least_once_async_test.py | 52 +++++++++++ 2 files changed, 111 insertions(+), 31 deletions(-) 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 26eae14c4..c71a3950d 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 @@ -133,6 +133,15 @@ def cancel(self) -> None: self.cancelled.set() +class _BatchCollectionError(Exception): + """Collecting a batch failed after operations were taken off the queues.""" + + def __init__(self, error: Exception, operations: list[QueuedOperation]) -> None: + super().__init__(str(error)) + self.error = error + self.operations = operations + + class _BatchAccumulator: """The operations of one checkpoint request, with the limit accounting. @@ -1153,7 +1162,12 @@ def checkpoint_batches_forever(self) -> None: while not self._is_shut_down(): # Collect operations into a batch - batch: list[QueuedOperation] = self._collect_checkpoint_batch() + try: + batch: list[QueuedOperation] = self._collect_checkpoint_batch() + except _BatchCollectionError as e: + logger.exception("Checkpoint batch collection failed") + self._fail_checkpointing(e.error, e.operations) + break if batch: # Extract OperationUpdates, excluding empty checkpoints from API call @@ -1271,34 +1285,8 @@ def checkpoint_batches_forever(self) -> None: self._settle_after_execution_completed() break except Exception as e: - # Checkpoint failed - wake all blocked threads so they can raise error - # Drain both queues and signal all completion events logger.exception("Checkpoint batch processing failed") - bg_error: BackgroundThreadError = BackgroundThreadError( - "Checkpoint creation failed", e - ) - - # Signal completion events for the failed batch (already dequeued, - # so no producer can race these). - for queued_op in batch: - if queued_op.completion_event is not None: - queued_op.completion_event.set(bg_error) - - # Drain the queues and set the failure flag under the completion - # lock so a concurrent create_checkpoint either observes the - # failure and raises, or has its operation drained here - never - # enqueued after the drain and left blocked. - with self._completion_lock: - for queued_op in self._drain_unsent_operations(): - if queued_op.completion_event is not None: - queued_op.completion_event.set(bg_error) - - for refresh in self._drain_pending_refreshes(): - refresh.completion_event.set(bg_error) - - # Future checkpoint attempts fail immediately. - self._checkpointing_failed.set(bg_error) - + self._fail_checkpointing(e, batch) # Exit the loop - error has been signaled to main thread via completion events break @@ -1317,6 +1305,35 @@ def checkpoint_batches_forever(self) -> None: logger.debug("Background checkpoint processing stopped") + def _fail_checkpointing( + self, error: Exception, batch: list[QueuedOperation] + ) -> None: + """Wake all blocked threads with the error and stop future checkpoints. + + The batch is already dequeued, so no producer can race its events. + """ + bg_error: BackgroundThreadError = BackgroundThreadError( + "Checkpoint creation failed", error + ) + for queued_op in batch: + if queued_op.completion_event is not None: + queued_op.completion_event.set(bg_error) + + # Drain the queues and set the failure flag under the completion + # lock so a concurrent create_checkpoint either observes the + # failure and raises, or has its operation drained here - never + # enqueued after the drain and left blocked. + with self._completion_lock: + for queued_op in self._drain_unsent_operations(): + if queued_op.completion_event is not None: + queued_op.completion_event.set(bg_error) + + for refresh in self._drain_pending_refreshes(): + refresh.completion_event.set(bg_error) + + # Future checkpoint attempts fail immediately. + self._checkpointing_failed.set(bg_error) + def _drain_unsent_operations(self) -> list[QueuedOperation]: """Take queued operations, overflow first. The caller holds _completion_lock.""" unsent: list[QueuedOperation] = [] @@ -1485,7 +1502,7 @@ def _collect_checkpoint_batch(self) -> list[QueuedOperation]: if isinstance(item, _Signal): self._consume_refresh_wake() continue - size = self._calculate_operation_size(item) + size = self._operation_size(item, batch) if not batch.fits(size): self._overflow_queue.put(item) logger.debug( @@ -1512,7 +1529,7 @@ def _drain_overflow(self, batch: _BatchAccumulator) -> None: try: while not batch.is_full(): op = self._overflow_queue.get_nowait() - size = self._calculate_operation_size(op) + size = self._operation_size(op, batch) if not batch.fits(size): self._overflow_queue.put(op) break @@ -1539,7 +1556,7 @@ def _wait_for_first_operation(self, batch: _BatchAccumulator) -> bool: self._consume_refresh_wake() continue # The first operation is never refused for size; see fits(). - batch.add(item, self._calculate_operation_size(item)) + batch.add(item, self._operation_size(item, batch)) return True return False @@ -1554,6 +1571,17 @@ def _read_timeout( timeout = min(timeout, _BLOCKED_CALLER_WAIT_SECONDS) return timeout + def _operation_size(self, item: QueuedOperation, batch: _BatchAccumulator) -> int: + """Size an operation taken off a queue for the batch. + + A sizing error is raised as _BatchCollectionError with the item and the + batch so far. These are already dequeued, so the caller must fail them. + """ + try: + return self._calculate_operation_size(item) + except Exception as e: + raise _BatchCollectionError(e, [*batch.operations, item]) from e + @staticmethod def _calculate_operation_size(queued_op: QueuedOperation) -> int: """Calculate the serialized size of a queued operation for batching limits. diff --git a/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py b/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py index 233b15385..4eebffd66 100644 --- a/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py @@ -49,6 +49,7 @@ OperationEndInfo, ) from aws_durable_execution_sdk_python.retries import RetryDecision +from aws_durable_execution_sdk_python.serdes import PassThroughSerDes from tests.test_helpers import plugin_factory ASYNC = StepConfig(step_semantics=StepSemantics.AT_LEAST_ONCE_ASYNC) @@ -306,6 +307,57 @@ def handler(_event: Any, context: DurableContext) -> str: _invoke(handler, client) +def _bytes_step_config(semantics: StepSemantics) -> StepConfig: + # PassThroughSerDes keeps the bytes in the update, so sizing the update for + # the batch fails in json.dumps. + return StepConfig(serdes=PassThroughSerDes(), step_semantics=semantics) + + +def test_unsizable_async_succeed_does_not_report_succeeded(): + """The batcher cannot size the SUCCEED, so it is never saved. The handler + ignores the step result and returns. The invocation raises the error, so + Lambda retries it, instead of answering SUCCEEDED.""" + client = _SlowClient() + config = _bytes_step_config(StepSemantics.AT_LEAST_ONCE_ASYNC) + + @durable_execution + def handler(_event: Any, context: DurableContext) -> str: + context.step(lambda _: b"value", name="s", config=config) + return "done" + + with pytest.raises(TypeError, match="bytes"): + _invoke(handler, client) + assert not client.was_answered(OperationAction.SUCCEED) + + +def test_unsizable_sync_succeed_raises_instead_of_hanging(): + """A sync SUCCEED that the batcher cannot size wakes its waiter with the + error.""" + client = _SlowClient() + config = _bytes_step_config(StepSemantics.AT_LEAST_ONCE) + + @durable_execution + def handler(_event: Any, context: DurableContext) -> str: + context.step(lambda _: b"value", name="s", config=config) + return "done" + + outcome: dict[str, BaseException] = {} + + def run() -> None: + try: + _invoke(handler, client) + except BaseException as e: # noqa: BLE001 + outcome["error"] = e + + thread = threading.Thread(target=run, daemon=True) + thread.start() + thread.join(timeout=10) + + assert not thread.is_alive(), "sync step waiter hung" + assert isinstance(outcome.get("error"), TypeError) + assert not client.was_answered(OperationAction.SUCCEED) + + def _failing_succeed(category: DurableApiErrorCategory) -> _SlowClient: return _SlowClient( {OperationAction.SUCCEED: 0.1},