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..83b29b2cd 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": "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": { + "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..da6e64365 --- /dev/null +++ b/packages/aws-durable-execution-sdk-python-examples/src/step/step_semantics_async_default.py @@ -0,0 +1,57 @@ +"""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. + +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/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_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 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-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..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,11 +6,17 @@ from __future__ import annotations import json +import time 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, @@ -23,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, @@ -61,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 { @@ -771,3 +786,56 @@ 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 + waits for its SUCCEED checkpoint, even when default_step_semantics is + AT_LEAST_ONCE_ASYNC.""" + client = fake_agentcore_client() + 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 + + 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"'}, + ) + + 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 7f5d36b60..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 @@ -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, @@ -30,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, @@ -142,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 { @@ -2453,3 +2464,50 @@ 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 waits for + its SUCCEED checkpoint, even when default_step_semantics is + AT_LEAST_ONCE_ASYNC.""" + client = fake_client(endpoint=fake_endpoint().url) + 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(InMemoryServiceClient, "checkpoint", checkpoint): + result = run( + session_handler( + session_config(client), + lambda vm, ctx, e: None, + default_step_semantics=StepSemantics.AT_LEAST_ONCE_ASYNC, + ) + ) + + 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 diff --git a/packages/aws-durable-execution-sdk-python/README.md b/packages/aws-durable-execution-sdk-python/README.md index aee9c2717..457eaf603 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` (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` 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. 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 + + +@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. @@ -205,7 +232,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 199d4e89f..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 @@ -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 @@ -477,8 +477,47 @@ def __call__(self, *args, **kwargs): class StepSemantics(Enum): + """How often one step attempt may run its function. See StepConfig. + + 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. + + 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 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. + """ + + # 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 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 + "-_") @@ -506,6 +545,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. @@ -515,11 +559,18 @@ 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 + 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_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 (experimental) also does not wait for the + SUCCEED checkpoint; see StepSemantics. + 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. @@ -538,12 +589,23 @@ class StepConfig: """ retry_strategy: Callable[[Exception, int], RetryDecision] | None = None - step_semantics: StepSemantics = StepSemantics.AT_LEAST_ONCE_PER_RETRY + 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 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) + is_set = self.step_semantics is not _STEP_SEMANTICS_UNSET + if not is_set: + object.__setattr__(self, "step_semantics", 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 e1957932e..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 @@ -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 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( sub_type, step_name, operation_type=OperationType.STEP 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/execution.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/execution.py index c5d4e3403..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 @@ -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: @@ -567,6 +583,7 @@ def wait_for_checkpoint() -> None: output = ( DurableExecutionInvocationOutput.create_pending().to_dict() ) + 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 @@ -603,6 +620,35 @@ 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. + + A PENDING answer is checked too: a handler can suspend while the SUCCEED + is still queued, for example on a replayed wait. + """ + 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/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..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,18 +142,16 @@ 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" 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 @@ -162,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 ) @@ -258,10 +254,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/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 0cb53471d..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 @@ -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, @@ -132,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. @@ -372,6 +382,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 +394,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 @@ -746,6 +761,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. @@ -796,7 +816,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 @@ -807,7 +827,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 @@ -1131,16 +1151,23 @@ 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() + 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 @@ -1258,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 @@ -1304,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] = [] @@ -1387,13 +1417,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 +1484,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) @@ -1464,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( @@ -1491,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 @@ -1501,7 +1539,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) @@ -1518,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 @@ -1533,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/config_test.py b/packages/aws-durable-execution-sdk-python/tests/config_test.py index c2fbc78b2..36b813d69 100644 --- a/packages/aws-durable-execution-sdk-python/tests/config_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/config_test.py @@ -101,18 +101,48 @@ 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_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() 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.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() @@ -120,12 +150,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 +202,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/context_test.py b/packages/aws-durable-execution-sdk-python/tests/context_test.py index beb9df4ad..98e7c3aac 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 @@ -20,6 +21,7 @@ ParallelBranch, ParallelConfig, StepConfig, + StepSemantics, ) from aws_durable_execution_sdk_python.context import ( Callback, @@ -519,7 +521,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 +550,55 @@ 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, + ), + (StepConfig(None, StepSemantics.AT_LEAST_ONCE), StepSemantics.AT_LEAST_ONCE), + # 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 + ), + StepSemantics.AT_LEAST_ONCE, + ), + ( + replace(StepConfig(), step_semantics=StepSemantics.AT_MOST_ONCE), + StepSemantics.AT_MOST_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/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 new file mode 100644 index 000000000..4eebffd66 --- /dev/null +++ b/packages/aws-durable-execution-sdk-python/tests/operation/step_at_least_once_async_test.py @@ -0,0 +1,531 @@ +"""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 datetime +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 ( + CheckpointError, + DurableApiErrorCategory, + 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, + WaitDetails, +) +from aws_durable_execution_sdk_python.plugin import ( + DurableInstrumentationPlugin, + InvocationEndInfo, + 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) + +_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, + 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() + 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: + raise self.error + 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( + 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, 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 + + +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)], +) +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(RuntimeError, match="checkpoint failed"): + _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}, + 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(): + 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" + + +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) + + +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()], + ) 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 d9860a3da..05badc424 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. @@ -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,74 @@ 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_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():