Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
@@ -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}
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
ChildConfig,
Duration,
StepConfig,
StepSemantics,
)
from aws_durable_execution_sdk_python.exceptions import (
CallbackError,
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Loading