Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

feat(lambda): adding support for new durable lambda (#728)

Nahuel Nucera528c10715500
diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml
index 8e3b00d5..c0e5e9ca 100644
--- a/.github/workflows/docker-publish.yml
+++ b/.github/workflows/docker-publish.yml
@@ -8,10 +8,21 @@ on:
env:
DOCKERHUB_IMAGE: nahuelnucera/ministack
DOCKERHUB_IMAGE_ORG: ministackorg/ministack
+ # Free-to-pull mirror on the GitHub Container Registry. Repo-scoped under
+ # the same org as Docker Hub so `ghcr.io/ministackorg/ministack:<tag>` is a
+ # drop-in pull. Anonymous pulls are free; rate limits are per-IP and much
+ # higher than Docker Hub's, which is the reason this mirror exists.
+ GHCR_IMAGE: ghcr.io/ministackorg/ministack
jobs:
publish:
runs-on: ubuntu-latest
+ # `packages: write` lets GITHUB_TOKEN push to ghcr.io for this repo's
+ # org-scoped package; `contents: read` is the standard default kept
+ # explicit since we now set permissions at the job level.
+ permissions:
+ contents: read
+ packages: write
steps:
- uses: actions/checkout@v4
@@ -28,6 +39,13 @@ jobs:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
# ── Regular (Alpine) image — :latest, :{version}, :{major}.{minor} ──
- name: Extract metadata (regular)
id: meta
@@ -36,6 +54,7 @@ jobs:
images: |
${{ env.DOCKERHUB_IMAGE }}
${{ env.DOCKERHUB_IMAGE_ORG }}
+ ${{ env.GHCR_IMAGE }}
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
@@ -67,6 +86,7 @@ jobs:
images: |
${{ env.DOCKERHUB_IMAGE }}
${{ env.DOCKERHUB_IMAGE_ORG }}
+ ${{ env.GHCR_IMAGE }}
flavor: |
latest=false
tags: |
diff --git a/ministack/app.py b/ministack/app.py
index e58613a3..9b080f37 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -347,6 +347,7 @@ _state_map = {
"cloudtrail": "cloudtrail", "iot": "iot",
"inspector2": "inspector2",
"s3tables": "s3tables",
+ "lambda_durable": "lambda_durable",
}
SERVICE_NAME_ALIASES = {
@@ -1820,6 +1821,16 @@ def _load_persisted_state():
_get_module("rds")
logger.info("RDS: eager-loaded module to respawn persisted containers at boot")
+ # `lambda_durable` is reached only via `lambda_svc.handle_request`, never
+ # directly through the lazy router (no SERVICE_REGISTRY entry — it has no
+ # AWS endpoint of its own). Without an eager import at boot, persisted
+ # durable executions silently disappear until something happens to invoke
+ # a durable endpoint. Same conditional-import pattern as RDS — only pay
+ # the cold-start cost when state actually exists.
+ if load_state("lambda_durable"):
+ _get_module("lambda_durable")
+ logger.info("Lambda Durable: eager-loaded module to restore persisted executions")
+
async def _wait_for_port(port, timeout=30):
"""Wait until the server is accepting TCP connections."""
diff --git a/ministack/core/router.py b/ministack/core/router.py
index 3dc8c510..cb0d8b01 100644
--- a/ministack/core/router.py
+++ b/ministack/core/router.py
@@ -20,7 +20,9 @@ logger = logging.getLogger("ministack")
# and routes via credential scope, but raw HTTP/curl/runtime API don't).
_LAMBDA_PATH_RE = re.compile(
r"^/\d{4}-\d{2}-\d{2}/(?:functions|layers|event-source-mappings|"
- r"account-settings|runtime|tags|code-signing-configs)(?:/|$)"
+ r"account-settings|runtime|tags|code-signing-configs|"
+ # Durable Functions (preview, Dec 2025).
+ r"durable-executions|durable-execution-callbacks)(?:/|$)"
)
# ECS Task Metadata V4 paths: /v4/<token>[/task|/stats|...]. Token is
@@ -60,7 +62,13 @@ SERVICE_PATTERNS = {
"host_patterns": [r"dynamodb\."],
},
"lambda": {
- "path_patterns": [r"^/2015-03-31/", r"^/2018-10-31/layers"],
+ "path_patterns": [
+ r"^/2015-03-31/",
+ r"^/2018-10-31/layers",
+ # Durable Functions (preview, Dec 2025) — surface lives on the
+ # Lambda endpoint under a fresh API-version prefix.
+ r"^/2025-12-01/(durable-executions|durable-execution-callbacks|functions)",
+ ],
"host_patterns": [r"lambda\."],
},
"iam": {
diff --git a/ministack/services/cloudformation/provisioners.py b/ministack/services/cloudformation/provisioners.py
index 8fd7f229..f7e05a74 100644
--- a/ministack/services/cloudformation/provisioners.py
+++ b/ministack/services/cloudformation/provisioners.py
@@ -18,6 +18,7 @@ import ministack.services.acm as _acm
import ministack.services.alb as _alb
import ministack.services.apigateway as _apigw_v2
import ministack.services.apigateway_v1 as _apigw_v1
+import ministack.services.appconfig as _appconfig
import ministack.services.appsync as _appsync
import ministack.services.autoscaling as _asg
import ministack.services.backup as _backup
@@ -741,6 +742,30 @@ def _ssm_delete(physical_id, props):
_ssm._parameters.pop(physical_id, None)
+# --- AppConfig Application ---
+
+def _appconfig_application_create(logical_id, props, stack_name):
+ name = props.get("Name") or _physical_name(stack_name, logical_id)
+ app_id = _appconfig._gen_id()
+ _appconfig._applications[app_id] = {
+ "Id": app_id,
+ "Name": name,
+ "Description": props.get("Description", ""),
+ }
+ cfn_tags = props.get("Tags") or []
+ if cfn_tags:
+ _appconfig._apply_tags(
+ _appconfig._app_arn(app_id),
+ {t["Key"]: t["Value"] for t in cfn_tags if "Key" in t},
+ )
+ return app_id, {"ApplicationId": app_id}
+
+
+def _appconfig_application_delete(physical_id, props):
+ _appconfig._applications.pop(physical_id, None)
+ _appconfig._tags.pop(_appconfig._app_arn(physical_id), None)
+
+
# --- CloudWatch Logs LogGroup ---
def _cwlogs_create(logical_id, props, stack_name):
@@ -3867,6 +3892,10 @@ _RESOURCE_HANDLERS = {
"AWS::IAM::Policy": {"create": _iam_policy_create, "delete": _iam_policy_delete},
"AWS::IAM::InstanceProfile": {"create": _iam_ip_create, "delete": _iam_ip_delete},
"AWS::SSM::Parameter": {"create": _ssm_create, "delete": _ssm_delete},
+ "AWS::AppConfig::Application": {
+ "create": _appconfig_application_create,
+ "delete": _appconfig_application_delete,
+ },
"AWS::Logs::LogGroup": {"create": _cwlogs_create, "delete": _cwlogs_delete},
"AWS::Events::Rule": {"create": _eb_rule_create, "delete": _eb_rule_delete},
"AWS::Events::EventBus": {"create": _eb_event_bus_create, "delete": _eb_event_bus_delete},
diff --git a/ministack/services/lambda_durable.py b/ministack/services/lambda_durable.py
new file mode 100644
index 00000000..8fbc1a5e
--- /dev/null
+++ b/ministack/services/lambda_durable.py
@@ -0,0 +1,1281 @@
+"""AWS Lambda Durable Functions / Durable Execution emulator.
+
+Implements the seven management-plane operations of the Lambda Durable Execution
+API (preview, Dec 2025) plus the function-level DurableConfig field on
+CreateFunction / GetFunction. The shapes here are derived from the canonical
+AWS public docs:
+
+ - https://docs.aws.amazon.com/lambda/latest/api/API_CheckpointDurableExecution.html
+ - https://docs.aws.amazon.com/lambda/latest/api/API_GetDurableExecutionState.html
+ - https://docs.aws.amazon.com/lambda/latest/api/API_GetDurableExecution.html
+ - https://docs.aws.amazon.com/lambda/latest/api/API_GetDurableExecutionHistory.html
+ - https://docs.aws.amazon.com/lambda/latest/api/API_ListDurableExecutionsByFunction.html
+ - https://docs.aws.amazon.com/lambda/latest/api/API_StopDurableExecution.html
+
+DurableExecution ARN format per the docs' Pattern field:
+
+ arn:aws:lambda:<region>:<account>:function:<NAME>:<VERSION>/durable-execution/<token>/<id>
+"""
+from __future__ import annotations
+
+import base64
+import copy
+import json
+import secrets
+import time
+import uuid
+from urllib.parse import unquote
+
+from ministack.core.responses import (
+ AccountScopedDict,
+ error_response_json,
+ get_account_id,
+ get_region,
+ json_response,
+)
+from ministack.core.persistence import load_state
+
+
+# ---------------------------------------------------------------------------
+# State
+# ---------------------------------------------------------------------------
+
+# DurableExecutionArn -> execution record:
+# {
+# "DurableExecutionArn": str,
+# "DurableExecutionName": str,
+# "FunctionArn": str,
+# "Version": str,
+# "InputPayload": str,
+# "Status": "RUNNING"|"SUCCEEDED"|"FAILED"|"TIMED_OUT"|"STOPPED",
+# "StartTimestamp": float (epoch seconds),
+# "EndTimestamp": float | None,
+# "Result": str | None,
+# "Error": dict | None,
+# "TraceHeader": dict | None,
+# "CheckpointToken": str, # current valid token
+# "Operations": list[dict], # the operation log (mutated by Checkpoint)
+# "History": list[dict], # append-only event log
+# "NextEventId": int,
+# }
+_executions = AccountScopedDict()
+
+# Resume scheduler — heapq of (resume_at_epoch, durable_arn, account_id).
+# When a durable invocation returns Status=PENDING with WAIT operations still
+# scheduled, ministack schedules a re-invocation at the earliest WAIT expiry.
+import heapq
+import threading as _threading
+
+_resume_queue: list[tuple[float, str, str]] = []
+_resume_lock = _threading.Lock()
+_resume_event = _threading.Event()
+_resume_thread_started = False
+
+# Maps CallbackId → (DurableExecutionArn, OperationId) so external
+# SendCallback{Success,Failure,Heartbeat} can find their target without
+# scanning every execution. Defined HERE (above restore_state) because
+# restore_state rebuilds this index from persisted executions at module
+# import time — if the name were defined later, restore_state would
+# NameError on cold start.
+_callback_index: dict[str, tuple[str, str]] = {}
+
+# Function-level DurableConfig is stored on the function config in lambda_svc;
+# we expose helpers here for serialization parity.
+
+
+# ---------------------------------------------------------------------------
+# Persistence hooks
+# ---------------------------------------------------------------------------
+
+def get_state():
+ return {"executions": copy.deepcopy(_executions)}
+
+
+def restore_state(data):
+ if not data:
+ return
+ _executions.update(data.get("executions", {}))
+ # AWS contract: callbacks and timers survive process restarts. The live
+ # in-memory `_callback_index` and resume heap are NOT persisted (the
+ # heap entries are wall-clock-relative, the index is derivable), so
+ # rebuild both from the restored execution records.
+ # `_executions` is an AccountScopedDict; iterating yields composite
+ # (account, arn) keys, so always read the bare arn off the record itself.
+ for _key, rec in _executions.items():
+ if not isinstance(rec, dict):
+ continue
+ arn = rec.get("DurableExecutionArn")
+ if not arn:
+ continue
+ for op in rec.get("Operations", []):
+ if op.get("Type") == "CALLBACK" and op.get("Status") == "STARTED":
+ op_id = op.get("Id")
+ if op_id:
+ _callback_index[op_id] = (arn, op_id)
+ # Re-arm WAIT and CALLBACK timers for executions that were still
+ # RUNNING when the process went down. Without this, restored
+ # executions stall forever — timers never fire.
+ if rec.get("Status") == "RUNNING":
+ try:
+ schedule_resume(arn)
+ except Exception:
+ import logging
+ logging.getLogger(__name__).exception(
+ "Failed to re-arm timer on restore for %s", arn,
+ )
+
+
+try:
+ _restored = load_state("lambda_durable")
+ if _restored:
+ restore_state(_restored)
+except Exception:
+ import logging
+ logging.getLogger(__name__).exception("Failed to restore lambda_durable state")
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+# AWS uses the function's qualifier (version / "$LATEST") embedded in the ARN.
+# Token + ID follow the "/durable-execution/{token}/{id}" suffix per the docs.
+_VALID_STATUS = {"RUNNING", "SUCCEEDED", "FAILED", "TIMED_OUT", "STOPPED"}
+
+
+def new_checkpoint_token() -> str:
+ # AWS pattern: [A-Za-z0-9+/]+={0,2} — base64. 32 random bytes -> 44 chars.
+ return base64.b64encode(secrets.token_bytes(32)).decode("ascii")
+
+
+def build_durable_execution_arn(function_arn: str, version: str = "$LATEST",
+ name: str | None = None) -> tuple[str, str, str]:
+ """Build a fully-qualified DurableExecutionArn from a function ARN.
+
+ Returns (arn, name, token-uuid) where the suffix `/durable-execution/<token>/<id>`
+ embeds two opaque UUIDs that the SDK echoes back unchanged.
+ """
+ token_id = uuid.uuid4().hex[:24]
+ inner_id = uuid.uuid4().hex[:24]
+ # Strip any pre-existing qualifier from the function ARN.
+ base = function_arn
+ if base.count(":") >= 7:
+ base = ":".join(base.split(":")[:7])
+ qualifier = version or "$LATEST"
+ arn = f"{base}:{qualifier}/durable-execution/{token_id}/{inner_id}"
+ return arn, (name or token_id), token_id
+
+
+import re as _re
+
+# AWS spec Pattern for DurableExecutionArn (verified against
+# https://docs.aws.amazon.com/lambda/latest/api/API_GetDurableExecution.html
+# and the AWS SDK for Java v2 2.44.13 model).
+_DURABLE_EXEC_ARN_RE = _re.compile(
+ r"^arn:([a-zA-Z0-9-]+):lambda:([a-zA-Z0-9-]+):(\d{12})"
+ r":function:([a-zA-Z0-9_-]+):(\$LATEST(?:\.PUBLISHED)?|[0-9]+)"
+ r"/durable-execution/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$"
+)
+
+# CallbackId pattern from API_SendDurableExecutionCallback* (base64).
+_CALLBACK_ID_RE = _re.compile(r"^[A-Za-z0-9+/]+={0,2}$")
+
+
+def _parse_execution_arn(path_arn: str) -> str:
+ """Decode + normalize the URL-embedded ARN (boto3 may URL-encode colons)."""
+ return unquote(path_arn)
+
+
+def _validate_execution_arn(arn: str) -> tuple | None:
+ """AWS returns InvalidParameterValueException 400 for a structurally
+ malformed DurableExecutionArn (separate from ResourceNotFound 404 for a
+ well-formed but unknown one)."""
+ if not isinstance(arn, str) or not _DURABLE_EXEC_ARN_RE.match(arn):
+ return error_response_json(
+ "InvalidParameterValueException",
+ f"Invalid DurableExecutionArn: {arn}",
+ 400,
+ )
+ return None
+
+
+def _require_execution(arn: str):
+ arn = _parse_execution_arn(arn)
+ err = _validate_execution_arn(arn)
+ if err:
+ return None, err
+ rec = _executions.get(arn)
+ if not rec:
+ return None, error_response_json(
+ "ResourceNotFoundException",
+ f"Durable execution not found: {arn}",
+ 404,
+ )
+ return rec, None
+
+
+def _now() -> float:
+ return time.time()
+
+
+_TIMESTAMP_FIELDS_ON_OP = ("StartTimestamp", "EndTimestamp")
+_TIMESTAMP_FIELDS_NESTED = {
+ "StepDetails": ("NextAttemptTimestamp",),
+ "WaitDetails": ("ScheduledEndTimestamp",),
+}
+
+
+def _to_unix_millis(v) -> int | None:
+ """Float-seconds → int Unix-millis. Used on the EVENT path only
+ (InitialExecutionState.Operations) because the durable SDK reads that path
+ via `Operation.from_json_dict` which calls `TimestampConverter.from_unix_millis`.
+ The boto3 API-response path uses `_to_unix_seconds` instead."""
+ if v is None:
+ return None
+ try:
+ return int(float(v) * 1000)
+ except (TypeError, ValueError):
+ return None
+
+
+def _to_unix_seconds(v) -> int | None:
+ """Float-seconds → int Unix-seconds. Used on every boto3 API-RESPONSE
+ timestamp because botocore's `parse_timestamp` interprets numeric values
+ as seconds via `datetime.fromtimestamp(value, tzinfo())`. Ministack-wide
+ JSON convention is int (not float) so the strict-deserializing Java SDK v2
+ and Go SDK v2 don't reject it — see feedback_timestamps_int_epoch."""
+ if v is None:
+ return None
+ try:
+ return int(float(v))
+ except (TypeError, ValueError):
+ return None
+
+
+def _serialize_operations(operations: list[dict], *, for_event: bool = False) -> list[dict]:
+ """Return the wire-shape list of Operation objects.
+
+ Two paths, two timestamp units (the wire shape really is different):
+ - `for_event=True` → InitialExecutionState.Operations on the Lambda
+ event payload. The durable SDK reads this via `Operation.from_json_dict`
+ which expects int Unix-millis.
+ - `for_event=False` → Checkpoint / GetState API response bodies. boto3
+ parses these via `botocore.utils.parse_timestamp` which expects
+ Unix-seconds (the protocol-default for restJson1 timestamps).
+ """
+ convert = _to_unix_millis if for_event else _to_unix_seconds
+ out = []
+ for op in (operations or []):
+ clone = copy.deepcopy(op)
+ for f in _TIMESTAMP_FIELDS_ON_OP:
+ if f in clone:
+ c = convert(clone[f])
+ if c is not None:
+ clone[f] = c
+ for sub_key, fields in _TIMESTAMP_FIELDS_NESTED.items():
+ sub = clone.get(sub_key)
+ if isinstance(sub, dict):
+ for f in fields:
+ if f in sub:
+ c = convert(sub[f])
+ if c is not None:
+ sub[f] = c
+ out.append(clone)
+ return out
+
+
+def _execution_summary(rec: dict) -> dict:
+ out = {
+ "DurableExecutionArn": rec["DurableExecutionArn"],
+ "DurableExecutionName": rec["DurableExecutionName"],
+ "FunctionArn": rec["FunctionArn"],
+ "StartTimestamp": _to_unix_seconds(rec["StartTimestamp"]),
+ "Status": rec["Status"],
+ }
+ if rec.get("EndTimestamp") is not None:
+ out["EndTimestamp"] = _to_unix_seconds(rec["EndTimestamp"])
+ return out
+
+
+def _emit_history_event(rec: dict, event_type: str, details_key: str, details: dict,
+ name: str | None = None, parent_id: str | None = None,
+ sub_type: str | None = None, event_id: str | None = None) -> None:
+ """Append an event to the execution's history log."""
+ rec["NextEventId"] = int(rec.get("NextEventId", 0)) + 1
+ ev = {
+ "EventId": rec["NextEventId"],
+ "EventTimestamp": _now(),
+ "EventType": event_type,
+ details_key: details,
+ }
+ if event_id is not None:
+ ev["Id"] = event_id
+ if name is not None:
+ ev["Name"] = name
+ if parent_id is not None:
+ ev["ParentId"] = parent_id
+ if sub_type is not None:
+ ev["SubType"] = sub_type
+ rec["History"].append(ev)
+
+
+# ---------------------------------------------------------------------------
+# Cross-module: invoked by lambda_svc on Invoke when DurableConfig.Enabled.
+# ---------------------------------------------------------------------------
+
+def create_execution_for_invoke(function_arn: str, version: str,
+ input_payload: str,
+ name: str | None = None,
+ trace_id: str | None = None) -> dict:
+ """Spin up a new durable execution and return its record. The Lambda
+ runtime is expected to read the ARN from the AWS_DURABLE_EXECUTION_ARN
+ env var and call Checkpoint/GetState through the regular Lambda endpoint."""
+ arn, exec_name, _ = build_durable_execution_arn(function_arn, version, name)
+ # AWS seeds a synthetic EXECUTION-type operation into the operations log
+ # so the SDK can read the original user input via
+ # execution_state.get_input_payload() on every invocation (including
+ # replays). The SDK looks this operation up by `arn.split("/")[-1]`
+ # (state.py:get_execution_operation), so its Id must match the trailing
+ # ARN segment exactly.
+ invocation_id = arn.split("/")[-1]
+ execution_op = {
+ "Id": invocation_id,
+ "Type": "EXECUTION",
+ "Status": "STARTED",
+ "StartTimestamp": _now(),
+ "ExecutionDetails": {"InputPayload": input_payload or ""},
+ }
+ rec = {
+ "DurableExecutionArn": arn,
+ "DurableExecutionName": exec_name,
+ "FunctionArn": function_arn,
+ "Version": version or "$LATEST",
+ "InputPayload": input_payload or "",
+ "Status": "RUNNING",
+ "StartTimestamp": _now(),
+ "EndTimestamp": None,
+ "Result": None,
+ "Error": None,
+ "TraceHeader": {"XAmznTraceId": trace_id} if trace_id else None,
+ "CheckpointToken": new_checkpoint_token(),
+ "Operations": [execution_op],
+ "History": [],
+ "NextEventId": 0,
+ }
+ _executions[arn] = rec
+ _emit_history_event(rec, "ExecutionStarted", "ExecutionStartedDetails", {
+ "Input": {"Payload": input_payload or "", "Truncated": False},
+ })
+ return rec
+
+
+def mark_execution_completed(arn: str, result_payload: str | None,
+ error: dict | None) -> None:
+ rec = _executions.get(arn)
+ if not rec:
+ return
+ rec["EndTimestamp"] = _now()
+ if error:
+ rec["Status"] = "FAILED"
+ rec["Error"] = error
+ _emit_history_event(rec, "ExecutionFailed", "ExecutionFailedDetails", {
+ "Error": {"Payload": error, "Truncated": False},
+ })
+ else:
+ rec["Status"] = "SUCCEEDED"
+ rec["Result"] = result_payload
+ _emit_history_event(rec, "ExecutionSucceeded", "ExecutionSucceededDetails", {
+ "Result": {"Payload": result_payload or "", "Truncated": False},
+ })
+
+
+# ---------------------------------------------------------------------------
+# Handlers — wired in from lambda_svc.handle_request based on path matching.
+# ---------------------------------------------------------------------------
+
+def _fire_chained_invoke(parent_rec: dict, op_id: str, ci_opts: dict,
+ payload: str | None) -> None:
+ """Asynchronously invoke a child durable function as part of a chain.
+ The child runs via the existing lambda_svc executor; ministack records
+ its result back onto the parent's ChainedInvoke operation when the child
+ completes."""
+ import threading
+ from ministack.services import lambda_svc
+
+ target = ci_opts.get("FunctionName")
+ tenant_id = ci_opts.get("TenantId")
+
+ def _run():
+ try:
+ event_str = payload or "{}"
+ try:
+ event = json.loads(event_str) if isinstance(event_str, str) else event_str
+ except (TypeError, ValueError):
+ event = {}
+ func_record = lambda_svc._functions.get(lambda_svc._resolve_name(target))
+ if not func_record:
+ # Surface failure back onto the parent's operation log.
+ _append_chained_result(parent_rec, op_id, success=False, result=None,
+ err={"ErrorType": "ResourceNotFoundException",
+ "ErrorMessage": f"Function not found: {target}",
+ "StackTrace": []})
+ return
+ # Run via the existing executor. The child runs synchronously here
+ # but in a worker thread so we don't block ministack's ASGI loop.
+ result = lambda_svc._execute_function(func_record, event)
+ if result.get("error"):
+ _append_chained_result(parent_rec, op_id, success=False, result=None,
+ err={"ErrorType": str(result.get("function_error") or "Unhandled"),
+ "ErrorMessage": str(result.get("body") or ""),
+ "StackTrace": []})
+ else:
+ _append_chained_result(parent_rec, op_id, success=True,
+ result=json.dumps(result.get("body"))
+ if not isinstance(result.get("body"), str)
+ else result.get("body"), err=None)
+ except Exception as exc:
+ _append_chained_result(parent_rec, op_id, success=False, result=None,
+ err={"ErrorType": type(exc).__name__,
+ "ErrorMessage": str(exc),
+ "StackTrace": []})
+
+ threading.Thread(target=_run, daemon=True, name=f"chained-invoke-{op_id}").start()
+
+
+def _append_chained_result(parent_rec: dict, op_id: str, success: bool,
+ result: str | None, err: dict | None) -> None:
+ """Apply the child invocation's outcome onto the parent ChainedInvoke
+ operation in the operation log + emit a history event."""
+ for op in parent_rec["Operations"]:
+ if op.get("Id") == op_id and op.get("Type") == "CHAINED_INVOKE":
+ op["Status"] = "SUCCEEDED" if success else "FAILED"
+ op["EndTimestamp"] = _now()
+ details = op.setdefault("ChainedInvokeDetails", {})
+ if success and result is not None:
+ details["Result"] = result
+ if err:
+ details["Error"] = err
+ break
+ if success:
+ _emit_history_event(parent_rec, "ChainedInvokeSucceeded",
+ "ChainedInvokeSucceededDetails",
+ {"Result": {"Payload": result or "", "Truncated": False}},
+ event_id=op_id)
+ else:
+ _emit_history_event(parent_rec, "ChainedInvokeFailed",
+ "ChainedInvokeFailedDetails",
+ {"Error": {"Payload": err or {}, "Truncated": False}},
+ event_id=op_id)
+
+
+def handle_checkpoint(arn_path: str, body: bytes) -> tuple:
+ rec, err = _require_execution(arn_path)
+ if err:
+ return err
+ try:
+ data = json.loads(body) if body else {}
+ except json.JSONDecodeError:
+ return error_response_json("InvalidParameterValueException",
+ "Request body is not valid JSON", 400)
+ checkpoint_token = data.get("CheckpointToken")
+ if not checkpoint_token:
+ return error_response_json("InvalidParameterValueException",
+ "CheckpointToken is required", 400)
+ if checkpoint_token != rec["CheckpointToken"]:
+ return error_response_json("InvalidParameterValueException",
+ "CheckpointToken does not match the current state of the execution", 400)
+ updates = data.get("Updates") or []
+ if rec["Status"] != "RUNNING":
+ return error_response_json("InvalidParameterValueException",
+ f"Cannot checkpoint a durable execution in status {rec['Status']}", 400)
+
+ for upd in updates:
+ try:
+ _apply_update(rec, upd)
+ except _InvalidUpdate as e:
+ return error_response_json("InvalidParameterValueException",
+ str(e), 400)
+
+ new_token = new_checkpoint_token()
+ rec["CheckpointToken"] = new_token
+ return json_response({
+ "CheckpointToken": new_token,
+ "NewExecutionState": {
+ "NextMarker": "",
+ "Operations": _serialize_operations(rec["Operations"]),
+ },
+ })
+
+
+_VALID_OP_TYPES = frozenset({
+ "EXECUTION", "CONTEXT", "STEP", "WAIT", "CALLBACK", "CHAINED_INVOKE",
+})
+_VALID_OP_ACTIONS = frozenset({
+ "START", "SUCCEED", "FAIL", "CANCEL", "RETRY",
+})
+
+
+class _InvalidUpdate(ValueError):
+ """Signal to handle_checkpoint that an OperationUpdate failed validation
+ and the whole Checkpoint should be rejected with InvalidParameterValueException."""
+
+
+def _apply_update(rec: dict, upd: dict) -> None:
+ """Translate one OperationUpdate into both an Operation log entry and a
+ matching history event. The mapping mirrors the AWS docs Event types.
+
+ Raises _InvalidUpdate when the update is structurally invalid (missing
+ Id/Type/Action, unknown Type or Action) so the caller surfaces a 400
+ rather than silently storing a garbage op."""
+ op_id = upd.get("Id")
+ op_type = upd.get("Type")
+ action = upd.get("Action")
+ if not op_id or not isinstance(op_id, str):
+ raise _InvalidUpdate("OperationUpdate.Id is required and must be a string")
+ if op_type not in _VALID_OP_TYPES:
+ raise _InvalidUpdate(f"OperationUpdate.Type must be one of {sorted(_VALID_OP_TYPES)}, got {op_type!r}")
+ if action not in _VALID_OP_ACTIONS:
+ raise _InvalidUpdate(f"OperationUpdate.Action must be one of {sorted(_VALID_OP_ACTIONS)}, got {action!r}")
+ sub_type = upd.get("SubType")
+ name = upd.get("Name")
+ parent_id = upd.get("ParentId")
+ payload = upd.get("Payload")
+ err = upd.get("Error")
+ now = _now()
+
+ existing = next((o for o in rec["Operations"] if o.get("Id") == op_id), None)
+ if existing is None:
+ op = {
+ "Id": op_id,
+ "Type": op_type,
+ "ParentId": parent_id,
+ "Name": name,
+ "StartTimestamp": now,
+ "Status": "STARTED",
+ }
+ if sub_type:
+ op["SubType"] = sub_type
+ rec["Operations"].append(op)
+ existing = op
+
+ if action == "START":
+ existing["Status"] = "STARTED"
+ elif action == "SUCCEED":
+ existing["Status"] = "SUCCEEDED"
+ existing["EndTimestamp"] = now
+ elif action == "FAIL":
+ existing["Status"] = "FAILED"
+ existing["EndTimestamp"] = now
+ elif action == "CANCEL":
+ existing["Status"] = "CANCELLED"
+ existing["EndTimestamp"] = now
+ elif action == "RETRY":
+ existing["Status"] = "STARTED"
+
+ # Attach type-specific details onto the Operation.
+ if op_type == "STEP":
+ details = existing.setdefault("StepDetails", {})
+ if payload is not None and action == "SUCCEED":
+ details["Result"] = payload
+ if err is not None:
+ details["Error"] = err
+ if upd.get("StepOptions", {}).get("NextAttemptDelaySeconds") is not None:
+ details["NextAttemptTimestamp"] = now + upd["StepOptions"]["NextAttemptDelaySeconds"]
+ details["Attempt"] = details.get("Attempt", 0) + (1 if action in ("SUCCEED", "FAIL") else 0)
+ elif op_type == "WAIT":
+ details = existing.setdefault("WaitDetails", {})
+ wait_secs = upd.get("WaitOptions", {}).get("WaitSeconds")
+ if wait_secs is not None:
+ details["ScheduledEndTimestamp"] = now + wait_secs
+ elif op_type == "CALLBACK":
+ details = existing.setdefault("CallbackDetails", {})
+ if payload is not None and action == "SUCCEED":
+ details["Result"] = payload
+ if err is not None:
+ details["Error"] = err
+ # AWS-spec CallbackOptions per API_CheckpointDurableExecution:
+ # TimeoutSeconds (overall expiry) + HeartbeatTimeoutSeconds (heartbeat
+ # interval cap). Real AWS fires "Callback.Timeout" when either elapses
+ # without resolution. Store both as absolute epoch deadlines so the
+ # resume scheduler can poll them alongside WAIT expiries.
+ cb_opts = upd.get("CallbackOptions") or {}
+ if action == "START":
+ details["CallbackId"] = op_id # SDK uses Operation.Id as CallbackId
+ timeout_s = cb_opts.get("TimeoutSeconds")
+ if timeout_s is not None:
+ details["TimeoutDeadline"] = now + float(timeout_s)
+ hb_s = cb_opts.get("HeartbeatTimeoutSeconds")
+ if hb_s is not None:
+ details["HeartbeatTimeoutSeconds"] = float(hb_s)
+ details["HeartbeatDeadline"] = now + float(hb_s)
+ # Index so Send*Callback handlers can look us up by the bare id.
+ _callback_index[op_id] = (rec["DurableExecutionArn"], op_id)
+ elif action in ("SUCCEED", "FAIL", "CANCEL"):
+ # Callback resolved internally — drop from the live index.
+ _callback_index.pop(op_id, None)
+ elif op_type == "CONTEXT":
+ details = existing.setdefault("ContextDetails", {})
+ if payload is not None and action == "SUCCEED":
+ details["Result"] = payload
+ if err is not None:
+ details["Error"] = err
+ if upd.get("ContextOptions", {}).get("ReplayChildren") is not None:
+ details["ReplayChildren"] = upd["ContextOptions"]["ReplayChildren"]
+ elif op_type == "CHAINED_INVOKE":
+ details = existing.setdefault("ChainedInvokeDetails", {})
+ if payload is not None and action == "SUCCEED":
+ details["Result"] = payload
+ if err is not None:
+ details["Error"] = err
+ # On START, kick off the child function invocation asynchronously so
+ # downstream durable workflows actually run (item #3 in the parity gap).
+ ci_opts = upd.get("ChainedInvokeOptions") or {}
+ if action == "START" and ci_opts.get("FunctionName"):
+ _fire_chained_invoke(rec, op_id, ci_opts, payload)
+ elif op_type == "EXECUTION":
+ details = existing.setdefault("ExecutionDetails", {})
+ if rec.get("InputPayload"):
+ details["InputPayload"] = rec["InputPayload"]
+
+ # History event mirror.
+ event_type_map = {
+ ("STEP", "START"): ("StepStarted", "StepStartedDetails", {}),
+ ("STEP", "SUCCEED"): ("StepSucceeded", "StepSucceededDetails",
+ {"Result": {"Payload": payload or "", "Truncated": False}}),
+ ("STEP", "FAIL"): ("StepFailed", "StepFailedDetails",
+ {"Error": {"Payload": err or {}, "Truncated": False}}),
+ ("WAIT", "START"): ("WaitStarted", "WaitStartedDetails",
+ {"Duration": upd.get("WaitOptions", {}).get("WaitSeconds", 0)}),
+ ("WAIT", "SUCCEED"): ("WaitSucceeded", "WaitSucceededDetails",
+ {"Duration": upd.get("WaitOptions", {}).get("WaitSeconds", 0)}),
+ ("WAIT", "CANCEL"): ("WaitCancelled", "WaitCancelledDetails",
+ {"Error": {"Payload": err or {}, "Truncated": False}}),
+ ("CALLBACK", "START"): ("CallbackStarted", "CallbackStartedDetails",
+ {"CallbackId": op_id or ""}),
+ ("CALLBACK", "SUCCEED"): ("CallbackSucceeded", "CallbackSucceededDetails",
+ {"Result": {"Payload": payload or "", "Truncated": False}}),
+ ("CALLBACK", "FAIL"): ("CallbackFailed", "CallbackFailedDetails",
+ {"Error": {"Payload": err or {}, "Truncated": False}}),
+ ("CONTEXT", "START"): ("ContextStarted", "ContextStartedDetails", {}),
+ ("CONTEXT", "SUCCEED"): ("ContextSucceeded", "ContextSucceededDetails",
+ {"Result": {"Payload": payload or "", "Truncated": False}}),
+ ("CONTEXT", "FAIL"): ("ContextFailed", "ContextFailedDetails",
+ {"Error": {"Payload": err or {}, "Truncated": False}}),
+ }
+ key = (op_type, action)
+ if key in event_type_map:
+ ev_type, details_key, details = event_type_map[key]
+ _emit_history_event(rec, ev_type, details_key, details,
+ name=name, parent_id=parent_id, sub_type=sub_type,
+ event_id=op_id)
+
+
+def handle_get_state(arn_path: str, query_params: dict) -> tuple:
+ rec, err = _require_execution(arn_path)
+ if err:
+ return err
+ checkpoint_token = _qp_first(query_params, "CheckpointToken")
+ if not checkpoint_token:
+ return error_response_json("InvalidParameterValueException",
+ "CheckpointToken is required", 400)
+ if checkpoint_token != rec["CheckpointToken"]:
+ return error_response_json("InvalidParameterValueException",
+ "CheckpointToken does not match the current state of the execution", 400)
+ marker = _qp_first(query_params, "Marker", "")
+ max_items_raw = _qp_first(query_params, "MaxItems", "100")
+ try:
+ max_items = int(max_items_raw)
+ except ValueError:
+ return error_response_json("InvalidParameterValueException",
+ f"MaxItems must be an integer, got {max_items_raw!r}", 400)
+ # AWS docs: "Valid Range: Minimum value of 0. Maximum value of 1000."
+ if max_items < 0 or max_items > 1000:
+ return error_response_json("InvalidParameterValueException",
+ "MaxItems must be between 0 and 1000", 400)
+ if max_items == 0:
+ max_items = 100
+
+ ops = list(rec["Operations"])
+ start = 0
+ if marker:
+ try:
+ start = int(marker)
+ except ValueError:
+ start = 0
+ page = ops[start:start + max_items]
+ resp = {"Operations": _serialize_operations(page)}
+ if start + max_items < len(ops):
+ resp["NextMarker"] = str(start + max_items)
+ return json_response(resp)
+
+
+def handle_get_execution(arn_path: str) -> tuple:
+ rec, err = _require_execution(arn_path)
+ if err:
+ return err
+ out = {
+ "DurableExecutionArn": rec["DurableExecutionArn"],
+ "DurableExecutionName": rec["DurableExecutionName"],
+ "FunctionArn": rec["FunctionArn"],
+ "Version": rec["Version"],
+ "InputPayload": rec["InputPayload"],
+ "Status": rec["Status"],
+ "StartTimestamp": _to_unix_seconds(rec["StartTimestamp"]),
+ }
+ if rec.get("EndTimestamp") is not None:
+ out["EndTimestamp"] = _to_unix_seconds(rec["EndTimestamp"])
+ if rec.get("Result") is not None:
+ out["Result"] = rec["Result"]
+ if rec.get("Error") is not None:
+ out["Error"] = rec["Error"]
+ if rec.get("TraceHeader") is not None:
+ out["TraceHeader"] = rec["TraceHeader"]
+ return json_response(out)
+
+
+def handle_get_history(arn_path: str, query_params: dict) -> tuple:
+ rec, err = _require_execution(arn_path)
+ if err:
+ return err
+ marker = _qp_first(query_params, "Marker", "")
+ reverse = _qp_first(query_params, "ReverseOrder", "false").lower() == "true"
+ max_items_raw = _qp_first(query_params, "MaxItems", "100")
+ try:
+ max_items = int(max_items_raw)
+ except ValueError:
+ return error_response_json("InvalidParameterValueException",
+ f"MaxItems must be an integer, got {max_items_raw!r}", 400)
+ if max_items < 0 or max_items > 1000:
+ return error_response_json("InvalidParameterValueException",
+ "MaxItems must be between 0 and 1000", 400)
+ if max_items == 0:
+ max_items = 100
+
+ events = list(rec["History"])
+ if reverse:
+ events = list(reversed(events))
+ start = 0
+ if marker:
+ try:
+ start = int(marker)
+ except ValueError:
+ start = 0
+ page = events[start:start + max_items]
+ # Convert EventTimestamp from float-seconds to int-seconds for boto3.
+ serialized = []
+ for ev in page:
+ clone = copy.deepcopy(ev)
+ if "EventTimestamp" in clone:
+ clone["EventTimestamp"] = _to_unix_seconds(clone["EventTimestamp"])
+ serialized.append(clone)
+ resp = {"Events": serialized}
+ if start + max_items < len(events):
+ resp["NextMarker"] = str(start + max_items)
+ return json_response(resp)
+
+
+def handle_list_by_function(function_name: str, query_params: dict,
+ function_arn_lookup) -> tuple:
+ """`function_arn_lookup` is a callable from lambda_svc that resolves a
+ name-or-ARN to the canonical function ARN, returning None if unknown."""
+ fn_arn = function_arn_lookup(function_name)
+ if not fn_arn:
+ return error_response_json("ResourceNotFoundException",
+ f"Function not found: {function_name}", 404)
+ qualifier = _qp_first(query_params, "Qualifier", "$LATEST")
+ status_filter = query_params.get("Statuses") or query_params.get("Status")
+ if isinstance(status_filter, list):
+ status_filter = status_filter[0] if status_filter else None
+ name_filter = _qp_first(query_params, "DurableExecutionName")
+ started_after = _qp_first(query_params, "StartedAfter")
+ started_before = _qp_first(query_params, "StartedBefore")
+ reverse = _qp_first(query_params, "ReverseOrder", "false").lower() == "true"
+ marker = _qp_first(query_params, "Marker", "")
+ max_items_raw = _qp_first(query_params, "MaxItems", "100")
+ try:
+ max_items = int(max_items_raw)
+ except ValueError:
+ return error_response_json("InvalidParameterValueException",
+ f"MaxItems must be an integer, got {max_items_raw!r}", 400)
+ # AWS docs: "Valid Range: Minimum value of 0. Maximum value of 1000."
+ if max_items < 0 or max_items > 1000:
+ return error_response_json("InvalidParameterValueException",
+ "MaxItems must be between 0 and 1000", 400)
+ if max_items == 0:
+ max_items = 100
+
+ summaries = []
+ for rec in _executions.values():
+ if rec["FunctionArn"] != fn_arn:
+ continue
+ if rec["Version"] != qualifier:
+ continue
+ if status_filter and rec["Status"] != status_filter:
+ continue
+ if name_filter and rec["DurableExecutionName"] != name_filter:
+ continue
+ if started_after:
+ try:
+ if rec["StartTimestamp"] < float(started_after):
+ continue
+ except ValueError:
+ pass
+ if started_before:
+ try:
+ if rec["StartTimestamp"] > float(started_before):
+ continue
+ except ValueError:
+ pass
+ summaries.append(_execution_summary(rec))
+ summaries.sort(key=lambda s: s["StartTimestamp"], reverse=not reverse)
+ start = 0
+ if marker:
+ try:
+ start = int(marker)
+ except ValueError:
+ start = 0
+ page = summaries[start:start + max_items]
+ resp = {"DurableExecutions": page}
+ if start + max_items < len(summaries):
+ resp["NextMarker"] = str(start + max_items)
+ return json_response(resp)
+
+
+def handle_stop(arn_path: str, body: bytes) -> tuple:
+ rec, err = _require_execution(arn_path)
+ if err:
+ return err
+ try:
+ data = json.loads(body) if body else {}
+ except json.JSONDecodeError:
+ data = {}
+ if rec["Status"] != "RUNNING":
+ return error_response_json("InvalidParameterValueException",
+ f"Cannot stop a durable execution in status {rec['Status']}", 400)
+ rec["Status"] = "STOPPED"
+ rec["EndTimestamp"] = _now()
+ rec["Error"] = {
+ "ErrorType": data.get("ErrorType") or "DurableExecutionStopped",
+ "ErrorMessage": data.get("ErrorMessage") or "Stopped by caller",
+ "ErrorData": data.get("ErrorData") or "",
+ "StackTrace": data.get("StackTrace") or [],
+ }
+ _emit_history_event(rec, "ExecutionStopped", "ExecutionStoppedDetails", {
+ "Error": {"Payload": rec["Error"], "Truncated": False},
+ })
+ return json_response({"StopTimestamp": _to_unix_seconds(rec["EndTimestamp"])})
+
+
+# ---------------------------------------------------------------------------
+# Internal util — mirror of lambda_svc._qp_first to avoid a circular import.
+# ---------------------------------------------------------------------------
+
+def _qp_first(query_params: dict, key: str, default: str = "") -> str:
+ v = query_params.get(key, default)
+ if isinstance(v, list):
+ return v[0] if v else default
+ return v
+
+
+# ---------------------------------------------------------------------------
+# Send*Callback handlers — POST /2025-12-01/durable-execution-callbacks/{id}/{action}
+# Sources verified against:
+# API_SendDurableExecutionCallbackSuccess.html
+# API_SendDurableExecutionCallbackFailure.html
+# API_SendDurableExecutionCallbackHeartbeat.html
+# Each returns HTTP 200 with empty body on success.
+# ---------------------------------------------------------------------------
+
+def _resolve_callback(callback_id: str):
+ """Look up a callback by its id. Returns (rec, callback_op, err)."""
+ if not isinstance(callback_id, str) or not _CALLBACK_ID_RE.match(callback_id):
+ return None, None, error_response_json(
+ "InvalidParameterValueException",
+ f"Invalid CallbackId: {callback_id}",
+ 400,
+ )
+ entry = _callback_index.get(callback_id)
+ if not entry:
+ return None, None, error_response_json(
+ "ResourceNotFoundException",
+ f"Callback not found: {callback_id}",
+ 404,
+ )
+ arn, op_id = entry
+ rec = _executions.get(arn)
+ if not rec:
+ return None, None, error_response_json(
+ "ResourceNotFoundException",
+ f"Durable execution not found for callback: {callback_id}",
+ 404,
+ )
+ op = next((o for o in rec["Operations"] if o.get("Id") == op_id and o.get("Type") == "CALLBACK"), None)
+ if not op or op.get("Status") != "STARTED":
+ # AWS docs: "callback associated with the token has already been closed"
+ return None, None, error_response_json(
+ "CallbackTimeoutException",
+ "The callback ID token has either expired or the callback associated with the token has already been closed.",
+ 400,
+ )
+ return rec, op, None
+
+
+def handle_callback_success(callback_id: str, body: bytes) -> tuple:
+ rec, op, err = _resolve_callback(callback_id)
+ if err:
+ return err
+ # AWS: body is the raw Result blob (max 256 KB). Surface as a UTF-8 string
+ # for the operation details; the SDK reads it back via the operation log.
+ result_payload = ""
+ if body:
+ if len(body) > 262144:
+ return error_response_json("InvalidParameterValueException",
+ "Result exceeds the 256 KB maximum size", 400)
+ try:
+ result_payload = body.decode("utf-8")
+ except UnicodeDecodeError:
+ import base64 as _b64
+ result_payload = _b64.b64encode(body).decode("ascii")
+ op["Status"] = "SUCCEEDED"
+ op["EndTimestamp"] = _now()
+ details = op.setdefault("CallbackDetails", {})
+ details["Result"] = result_payload
+ _emit_history_event(rec, "CallbackSucceeded", "CallbackSucceededDetails",
+ {"Result": {"Payload": result_payload, "Truncated": False}},
+ event_id=op.get("Id"), name=op.get("Name"))
+ # Leave the entry in _callback_index — a subsequent call against the same
+ # id must hit _resolve_callback's "not STARTED" branch and return
+ # CallbackTimeoutException (400), matching the AWS contract.
+ # Wake the execution so it can resume the SDK handler.
+ schedule_resume(rec["DurableExecutionArn"])
+ return 200, {"Content-Type": "application/json"}, b""
+
+
+def handle_callback_failure(callback_id: str, body: bytes) -> tuple:
+ rec, op, err = _resolve_callback(callback_id)
+ if err:
+ return err
+ try:
+ data = json.loads(body) if body else {}
+ except json.JSONDecodeError:
+ data = {}
+ error_obj = {
+ "ErrorType": data.get("ErrorType") or "CallbackFailure",
+ "ErrorMessage": data.get("ErrorMessage") or "Callback failed",
+ "ErrorData": data.get("ErrorData") or "",
+ "StackTrace": data.get("StackTrace") or [],
+ }
+ op["Status"] = "FAILED"
+ op["EndTimestamp"] = _now()
+ details = op.setdefault("CallbackDetails", {})
+ details["Error"] = error_obj
+ _emit_history_event(rec, "CallbackFailed", "CallbackFailedDetails",
+ {"Error": {"Payload": error_obj, "Truncated": False}},
+ event_id=op.get("Id"), name=op.get("Name"))
+ # Index entry retained — see handle_callback_success for the rationale.
+ schedule_resume(rec["DurableExecutionArn"])
+ return 200, {"Content-Type": "application/json"}, b""
+
+
+def handle_callback_heartbeat(callback_id: str, body: bytes) -> tuple:
+ """Heartbeat resets the heartbeat deadline so a long-running external
+ operation doesn't trip its HeartbeatTimeoutSeconds. Overall TimeoutSeconds
+ is unaffected."""
+ rec, op, err = _resolve_callback(callback_id)
+ if err:
+ return err
+ details = op.setdefault("CallbackDetails", {})
+ hb_s = details.get("HeartbeatTimeoutSeconds")
+ if hb_s is not None:
+ details["HeartbeatDeadline"] = _now() + float(hb_s)
+ # The previously-queued resume entry still points at the OLD
+ # deadline. We do NOT push a fresh entry here — heartbeats can fire
+ # frequently and each extra entry would trigger a spurious re-invoke
+ # when it pops. Instead, _resume_execution re-arms the heap from
+ # current deadlines when nothing has actually elapsed (see the
+ # `nothing_elapsed` path below).
+ return 200, {"Content-Type": "application/json"}, b""
+
+
+# ---------------------------------------------------------------------------
+# Path-matching entry point — exposed for lambda_svc.handle_request.
+# ---------------------------------------------------------------------------
+
+# AWS API version date prefix for the durable-execution surface per the spec.
+_DURABLE_API_VERSION = "2025-12-01"
+
+
+def try_route(method: str, path: str, body: bytes, query_params: dict,
+ function_arn_lookup) -> tuple | None:
+ """Returns a `(status, headers, body)` triple if the path is a durable-
+ execution route, or None when the caller should fall through to the
+ normal Lambda router."""
+ path = unquote(path)
+ parts = path.lstrip("/").split("/")
+ if len(parts) < 3 or parts[0] != _DURABLE_API_VERSION:
+ return None
+
+ # /2025-12-01/functions/{name}/durable-executions
+ if parts[1] == "functions" and len(parts) >= 4 and parts[3] == "durable-executions":
+ if method != "GET":
+ return None
+ function_name = parts[2]
+ return handle_list_by_function(function_name, query_params, function_arn_lookup)
+
+ # /2025-12-01/durable-execution-callbacks/{CallbackId}/{succeed|fail|heartbeat}
+ if parts[1] == "durable-execution-callbacks" and len(parts) >= 4 and method == "POST":
+ callback_id = unquote(parts[2])
+ action = parts[3]
+ if action == "succeed":
+ return handle_callback_success(callback_id, body)
+ if action == "fail":
+ return handle_callback_failure(callback_id, body)
+ if action == "heartbeat":
+ return handle_callback_heartbeat(callback_id, body)
+ return None
+
+ if parts[1] != "durable-executions" or len(parts) < 3:
+ return None
+
+ # The DurableExecutionArn embeds slashes ("/durable-execution/<token>/<id>").
+ # Reconstruct it from the path segments — the suffix after the ARN
+ # contains exactly the trailing action keyword (state, history, stop,
+ # checkpoint) OR nothing (GetDurableExecution).
+ tail_keywords = {"state", "history", "stop", "checkpoint"}
+ if parts[-1] in tail_keywords:
+ action = parts[-1]
+ arn = "/".join(parts[2:-1])
+ else:
+ action = None
+ arn = "/".join(parts[2:])
+
+ if action == "checkpoint" and method == "POST":
+ return handle_checkpoint(arn, body)
+ if action == "state" and method == "GET":
+ return handle_get_state(arn, query_params)
+ if action == "history" and method == "GET":
+ return handle_get_history(arn, query_params)
+ if action == "stop" and method == "POST":
+ return handle_stop(arn, body)
+ if action is None and method == "GET":
+ return handle_get_execution(arn)
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Reset hook for ministack's /_ministack/reset.
+# ---------------------------------------------------------------------------
+
+def reset() -> None:
+ _executions.clear()
+ with _resume_lock:
+ _resume_queue.clear()
+
+
+# ---------------------------------------------------------------------------
+# Resume scheduler — fires re-invocations when WAIT operations expire so
+# paused durable executions actually resume the way they do on real AWS.
+# ---------------------------------------------------------------------------
+
+def _next_expiry(rec: dict) -> float | None:
+ """Return the earliest scheduled expiry across all STARTED WAIT and
+ CALLBACK ops, or None when nothing is pending. Callback ops contribute
+ BOTH their HeartbeatDeadline (resets on incoming heartbeats) and their
+ overall TimeoutDeadline; whichever fires first cancels the callback as
+ `Callback.Timeout` per AWS docs."""
+ soonest = None
+ for op in rec.get("Operations", []):
+ if op.get("Status") != "STARTED":
+ continue
+ if op.get("Type") == "WAIT":
+ ts = (op.get("WaitDetails") or {}).get("ScheduledEndTimestamp")
+ if ts is None:
+ continue
+ if soonest is None or ts < soonest:
+ soonest = ts
+ elif op.get("Type") == "CALLBACK":
+ details = op.get("CallbackDetails") or {}
+ for ts in (details.get("HeartbeatDeadline"), details.get("TimeoutDeadline")):
+ if ts is None:
+ continue
+ if soonest is None or ts < soonest:
+ soonest = ts
+ elif op.get("Type") == "STEP":
+ # SDK's RETRY checkpoint records NextAttemptTimestamp = now+delay
+ # and returns PENDING expecting a re-invoke once the delay elapses.
+ # See aws_durable_execution_sdk_python/operation/step.py:336 (the
+ # create_step_retry path) — without scanning STEP ops here, retries
+ # would never fire and the execution would hang at STARTED.
+ ts = (op.get("StepDetails") or {}).get("NextAttemptTimestamp")
+ if ts is None:
+ continue
+ if soonest is None or ts < soonest:
+ soonest = ts
+ return soonest
+
+
+def schedule_resume(arn: str, account_id: str | None = None) -> bool:
+ """Inspect the execution's operations log; if any WAIT or CALLBACK op
+ has a pending expiry, enqueue a re-invocation at the earliest one. Also
+ fires immediately when a callback has already been resolved externally
+ (Send*Callback handlers call us). Returns True when scheduled."""
+ rec = _executions.get(arn)
+ if not rec or rec.get("Status") != "RUNNING":
+ return False
+ expiry = _next_expiry(rec)
+ # When called from a Send*Callback handler we want to wake the execution
+ # immediately so the SDK observes the resolution on its next replay.
+ has_resolved_callback = any(
+ op.get("Type") == "CALLBACK" and op.get("Status") in ("SUCCEEDED", "FAILED")
+ and not (op.get("CallbackDetails") or {}).get("_replayed")
+ for op in rec.get("Operations", [])
+ )
+ if expiry is None and not has_resolved_callback:
+ return False
+ when = _now() if expiry is None else expiry
+ if has_resolved_callback:
+ when = min(when, _now())
+ with _resume_lock:
+ heapq.heappush(_resume_queue, (when, arn, account_id or "000000000000"))
+ _resume_event.set()
+ _ensure_resume_thread()
+ return True
+
+
+def _ensure_resume_thread() -> None:
+ global _resume_thread_started
+ if _resume_thread_started:
+ return
+ _resume_thread_started = True
+ t = _threading.Thread(target=_resume_loop, daemon=True, name="durable-resume")
+ t.start()
+
+
+def _resume_loop() -> None:
+ """Forever: pop the earliest entry from the resume queue, sleep until
+ its expiry, then ask lambda_svc to re-invoke the function with the
+ accumulated operations log so the SDK can replay completed steps."""
+ while True:
+ with _resume_lock:
+ head = _resume_queue[0] if _resume_queue else None
+ if head is None:
+ _resume_event.wait(timeout=1.0)
+ _resume_event.clear()
+ continue
+ wait_for = max(0.0, head[0] - time.time())
+ if wait_for > 0:
+ if _resume_event.wait(timeout=wait_for):
+ _resume_event.clear()
+ continue
+ # Time elapsed — pop and resume.
+ with _resume_lock:
+ if not _resume_queue or _resume_queue[0] != head:
+ continue
+ _, arn, account_id = heapq.heappop(_resume_queue)
+ try:
+ _resume_execution(arn)
+ except Exception:
+ import logging
+ logging.getLogger(__name__).exception(
+ "Failed to resume durable execution %s", arn,
+ )
+
+
+def _resume_execution(arn: str) -> None:
+ """Settle elapsed timers (WAIT expiries, CALLBACK heartbeat/timeout
+ deadlines) then re-invoke the function so the SDK picks up where it
+ left off. When called with a stale heap entry (heartbeat pushed the
+ deadline forward after the entry was queued) we detect that nothing
+ elapsed and simply re-enqueue at the current earliest deadline rather
+ than triggering a spurious re-invoke."""
+ rec = _executions.get(arn)
+ if not rec or rec.get("Status") != "RUNNING":
+ return
+ now = _now()
+ anything_elapsed = False
+ has_resolved_callback = any(
+ op.get("Type") == "CALLBACK" and op.get("Status") in ("SUCCEEDED", "FAILED")
+ and not (op.get("CallbackDetails") or {}).get("_replayed")
+ for op in rec.get("Operations", [])
+ )
+ for op in rec.get("Operations", []):
+ if op.get("Status") != "STARTED":
+ continue
+ if op.get("Type") == "WAIT":
+ ts = (op.get("WaitDetails") or {}).get("ScheduledEndTimestamp")
+ if ts is not None and ts <= now:
+ op["Status"] = "SUCCEEDED"
+ op["EndTimestamp"] = now
+ anything_elapsed = True
+ _emit_history_event(rec, "WaitSucceeded", "WaitSucceededDetails", {
+ "Duration": (op.get("WaitDetails") or {}).get("Duration", 0),
+ }, event_id=op.get("Id"), name=op.get("Name"))
+ elif op.get("Type") == "STEP":
+ # STEP RETRY: the SDK will re-execute the step body on replay; we
+ # just need to wake the function once the recorded delay elapses.
+ # The STEP stays Status=STARTED across attempts (the SDK uses
+ # StepDetails.Attempt for counting), so this branch only marks
+ # "something elapsed" so _resume_execution invokes rather than
+ # taking the stale-entry no-op path.
+ ts = (op.get("StepDetails") or {}).get("NextAttemptTimestamp")
+ if ts is not None and ts <= now:
+ anything_elapsed = True
+ elif op.get("Type") == "CALLBACK":
+ details = op.get("CallbackDetails") or {}
+ t_overall = details.get("TimeoutDeadline")
+ t_heartbeat = details.get("HeartbeatDeadline")
+ fired = None
+ if t_overall is not None and t_overall <= now:
+ fired = "Callback.Timeout"
+ elif t_heartbeat is not None and t_heartbeat <= now:
+ fired = "Callback.Heartbeat"
+ if fired is not None:
+ op["Status"] = "TIMED_OUT"
+ op["EndTimestamp"] = now
+ anything_elapsed = True
+ err_obj = {
+ "ErrorType": fired,
+ "ErrorMessage": f"Callback timed out: {fired}",
+ "ErrorData": "",
+ "StackTrace": [],
+ }
+ details["Error"] = err_obj
+ _emit_history_event(rec, "CallbackTimedOut", "CallbackTimedOutDetails",
+ {"Error": {"Payload": err_obj, "Truncated": False}},
+ event_id=op.get("Id"), name=op.get("Name"))
+ # Index entry stays so a late Send*Callback returns 400
+ # CallbackTimeoutException rather than 404.
+ # Stale heap entry (e.g. heartbeat extended the deadline after we were
+ # queued, or schedule_resume queued an immediate wake that lost a race
+ # with a checkpoint): nothing to settle and no external resolution to
+ # replay. Re-arm at the current earliest deadline and skip the invoke.
+ if not anything_elapsed and not has_resolved_callback:
+ expiry = _next_expiry(rec)
+ if expiry is not None:
+ with _resume_lock:
+ heapq.heappush(_resume_queue, (expiry, arn, "000000000000"))
+ _resume_event.set()
+ return
+ # Mark externally-resolved callbacks as replayed so the next schedule_resume
+ # doesn't loop.
+ for op in rec.get("Operations", []):
+ if op.get("Type") == "CALLBACK" and op.get("Status") in ("SUCCEEDED", "FAILED"):
+ details = op.setdefault("CallbackDetails", {})
+ details["_replayed"] = True
+ # Rotate token so the resumed invocation gets a fresh one.
+ rec["CheckpointToken"] = new_checkpoint_token()
+ # Trigger a fresh invocation through lambda_svc with the populated
+ # operations log — the SDK's `InitialExecutionState` will replay the
+ # completed steps and continue from the WAIT.
+ from ministack.services import lambda_svc
+ function_name = rec["FunctionArn"].rsplit(":", 1)[-1]
+ try:
+ try:
+ event = json.loads(rec.get("InputPayload") or "{}")
+ except (TypeError, ValueError):
+ event = {}
+ lambda_svc.invoke_durable_resume(function_name, arn, event)
+ except Exception:
+ import logging
+ logging.getLogger(__name__).exception("Resume invocation for %s failed", arn)
+
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 20cac43e..9f1bc128 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -526,6 +526,100 @@ def _validate_unzipped_size(zip_data: bytes | None):
return None
+import contextvars
+
+# Per-invocation durable-execution context, set by `_invoke` and read by the
+# executor functions to inject env vars into the Lambda container. Keeps
+# the data flow explicit and concurrency-safe (each request has its own
+# context — ASGI + asyncio.to_thread both propagate ContextVars).
+_durable_ctx: contextvars.ContextVar[dict | None] = contextvars.ContextVar(
+ "lambda_durable_ctx", default=None,
+)
+
+
+def _durable_env_overlay() -> dict[str, str]:
+ """Return env vars to layer onto the Lambda container when the current
+ invocation belongs to a durable execution. Empty dict otherwise."""
+ ctx = _durable_ctx.get()
+ if not ctx:
+ return {}
+ return {
+ "AWS_LAMBDA_DURABLE_EXECUTION_ARN": ctx.get("arn", ""),
+ "AWS_LAMBDA_DURABLE_CHECKPOINT_TOKEN": ctx.get("token", ""),
+ "AWS_LAMBDA_DURABLE_EXECUTION_NAME": ctx.get("name", ""),
+ }
+
+
+def invoke_durable_resume(function_name: str, durable_arn: str, original_event: dict) -> None:
+ """Re-invoke a paused durable function with the existing execution ARN
+ and the now-populated operations log. Called by the resume scheduler
+ when a WAIT expires."""
+ from ministack.services import lambda_durable
+ rec = lambda_durable._executions.get(durable_arn)
+ if not rec:
+ return
+ canonical = _resolve_name(function_name)
+ func = _functions.get(canonical)
+ if not func:
+ return
+ config = func.get("config") or func
+ # Set the durable context to the SAME ARN/token so the SDK reads the
+ # accumulated operations as InitialExecutionState (replay path).
+ _durable_ctx.set({
+ "arn": durable_arn,
+ "token": rec["CheckpointToken"],
+ "name": rec["DurableExecutionName"],
+ })
+ resume_event = {
+ "DurableExecutionArn": durable_arn,
+ "CheckpointToken": rec["CheckpointToken"],
+ "InitialExecutionState": {
+ "Operations": lambda_durable._serialize_operations(rec["Operations"], for_event=True),
+ "NextMarker": "",
+ },
+ }
+ try:
+ result = _execute_function(func, resume_event)
+ # If the resume still returns PENDING, schedule the next wakeup.
+ try:
+ payload = result.get("body")
+ if isinstance(payload, (bytes, bytearray)):
+ payload = payload.decode("utf-8", errors="replace")
+ if isinstance(payload, str):
+ payload = json.loads(payload)
+ if isinstance(payload, dict) and payload.get("Status") == "PENDING":
+ lambda_durable.schedule_resume(durable_arn)
+ elif isinstance(payload, dict) and payload.get("Status") == "SUCCEEDED":
+ lambda_durable.mark_execution_completed(
+ durable_arn,
+ result_payload=payload.get("Result"),
+ error=None,
+ )
+ elif isinstance(payload, dict) and payload.get("Status") == "FAILED":
+ lambda_durable.mark_execution_completed(
+ durable_arn,
+ result_payload=None,
+ error=payload.get("Error"),
+ )
+ except (TypeError, ValueError, json.JSONDecodeError):
+ pass
+ finally:
+ _durable_ctx.set(None)
+
+
+def _durable_arn_lookup(name_or_arn: str) -> str | None:
+ """Resolve a function name or ARN to the canonical function ARN, or None
+ if the function doesn't exist. Used by lambda_durable.handle_list_by_function."""
+ try:
+ canonical = _resolve_name(name_or_arn)
+ except Exception:
+ return None
+ func = _functions.get(canonical)
+ if not func:
+ return None
+ return func.get("FunctionArn") or _func_arn(canonical)
+
+
def _build_config(name: str, data: dict, code_zip: bytes | None = None) -> dict:
code_size = len(code_zip) if code_zip else 0
code_sha = base64.b64encode(hashlib.sha256(code_zip).digest()).decode() if code_zip else ""
@@ -664,6 +758,15 @@ async def handle_request(method: str, path: str, headers: dict, body: bytes, que
path = unquote(path)
parts = path.rstrip("/").split("/")
+ # --- Durable Execution surface (preview, API version 2025-12-01) ---
+ # Routed first because some paths embed the function ARN as a path segment
+ # which can otherwise be misclassified.
+ from ministack.services import lambda_durable
+ durable_resp = lambda_durable.try_route(method, path, body, query_params,
+ function_arn_lookup=_durable_arn_lookup)
+ if durable_resp is not None:
+ return durable_resp
+
try:
data = json.loads(body) if body else {}
except json.JSONDecodeError:
@@ -1428,6 +1531,47 @@ async def _invoke(name: str, event: dict, headers: dict, path_qualifier: str | N
if invocation_type == "DryRun":
return 204, {"X-Amz-Executed-Version": executed_version}, b""
+ # If the function has DurableConfig.Enabled, spin up a durable execution
+ # record so the SDK calls (Checkpoint / GetState) inside the function
+ # have a target. The ARN is surfaced back via the X-Amz-Durable-Execution-
+ # Arn response header so callers can wire it to follow-up management ops.
+ durable_arn = None
+ if (func.get("config", {}) or {}).get("DurableConfig", {}).get("Enabled"):
+ from ministack.services import lambda_durable
+ try:
+ event_payload = json.dumps(event) if not isinstance(event, str) else event
+ except (TypeError, ValueError):
+ event_payload = ""
+ rec = lambda_durable.create_execution_for_invoke(
+ function_arn=_func_arn(name),
+ version=executed_version,
+ input_payload=event_payload,
+ )
+ durable_arn = rec["DurableExecutionArn"]
+ _durable_ctx.set({
+ "arn": durable_arn,
+ "token": rec["CheckpointToken"],
+ "name": rec["DurableExecutionName"],
+ })
+ # AWS sends a durable Lambda an event containing ONLY the durable
+ # context fields the SDK reads via `from_json_dict`: DurableExecutionArn,
+ # CheckpointToken, InitialExecutionState. The user's actual payload
+ # lives inside the InitialExecutionState as a synthetic EXECUTION-type
+ # operation (see lambda_durable.create_execution_for_invoke); the SDK
+ # reads it via execution_state.get_input_payload().
+ # We pass back the operations list (with the seeded EXECUTION op) so
+ # the SDK has the input on every invocation, including replays.
+ # Operations are serialized via lambda_durable._serialize_operations.
+ from ministack.services import lambda_durable as _ld
+ event = {
+ "DurableExecutionArn": durable_arn,
+ "CheckpointToken": rec["CheckpointToken"],
+ "InitialExecutionState": {
+ "Operations": _ld._serialize_operations(rec["Operations"], for_event=True),
+ "NextMarker": "",
+ },
+ }
+
if invocation_type == "Event":
# AWS async invocation: retry + DLQ routing handled by the shared
# helper so event-source fan-out (S3, EventBridge, SNS → Lambda, etc.)
@@ -1452,6 +1596,40 @@ async def _invoke(name: str, event: dict, headers: dict, path_qualifier: str | N
"Content-Type": "application/json",
"X-Amz-Executed-Version": executed_version,
}
+ if durable_arn:
+ resp_headers["X-Amz-Durable-Execution-Arn"] = durable_arn
+ # Real AWS hands the initial CheckpointToken to the runtime via Lambda
+ # context; ministack surfaces it on the response header so test clients
+ # and SDK-less callers can drive the management ops directly.
+ _de_rec = lambda_durable._executions.get(durable_arn)
+ if _de_rec:
+ resp_headers["X-Amz-Durable-Checkpoint-Token"] = _de_rec["CheckpointToken"]
+ # Inspect the SDK's return value: PENDING → schedule the next wakeup
+ # from the latest WAIT timestamp; SUCCEEDED/FAILED → mark terminal.
+ try:
+ payload_obj = result.get("body")
+ if isinstance(payload_obj, (bytes, bytearray)):
+ payload_obj = payload_obj.decode("utf-8", errors="replace")
+ if isinstance(payload_obj, str):
+ payload_obj = json.loads(payload_obj)
+ if isinstance(payload_obj, dict):
+ status = payload_obj.get("Status")
+ if status == "PENDING":
+ lambda_durable.schedule_resume(durable_arn)
+ elif status == "SUCCEEDED":
+ lambda_durable.mark_execution_completed(
+ durable_arn,
+ result_payload=payload_obj.get("Result"),
+ error=None,
+ )
+ elif status == "FAILED":
+ lambda_durable.mark_execution_completed(
+ durable_arn,
+ result_payload=None,
+ error=payload_obj.get("Error"),
+ )
+ except (TypeError, ValueError, json.JSONDecodeError):
+ pass
log_output = result.get("log", "")
if log_output:
@@ -2253,6 +2431,9 @@ def _spawn_lambda_container(config: dict, code_zip: bytes | None):
f"/opt/layer_{i}" for i in range(len(layers_dirs))
)
container_env.update(env_vars)
+ # Per-invocation durable-execution overlay (no-op when the call isn't
+ # inside a durable function).
+ container_env.update(_durable_env_overlay())
# AWS_ENDPOINT_URL set *after* function env so it always points at ministack.
# Replace localhost/127.0.0.1 with host.docker.internal so the container
# can reach the host where ministack is running.
@@ -2621,10 +2802,21 @@ def _execute_function(func: dict, event: dict) -> dict:
runtime = config.get("Runtime", "python3.12")
if runtime.startswith("provided"):
result = _execute_function_provided(func, event)
- elif runtime.startswith("python") or runtime.startswith("nodejs"):
+ elif (runtime.startswith("python") or runtime.startswith("nodejs")) \
+ and not _durable_ctx.get():
+ # Warm pool reuses worker subprocesses whose env was fixed at
+ # spawn time. Durable invocations need per-call env (the
+ # DurableExecutionArn + CheckpointToken change every invoke),
+ # so route them through the per-call local executor.
result = _execute_function_warm(func, event)
- else:
+ elif runtime.startswith(("python", "nodejs")):
+ # Durable python/nodejs falls through to local subprocess (per
+ # the elif above we already filtered durable out of warm).
result = _execute_function_local(func, event)
+ else:
+ # java*/dotnet*/ruby* need the real RIE image — there's no
+ # in-process executor that can run JVM bytecode or .NET IL.
+ result = _execute_function_docker(func, event)
duration_ms = int((time.time() - started) * 1000)
_emit_lambda_logs(
@@ -2923,6 +3115,7 @@ def _execute_function_provided(func: dict, event: dict) -> dict:
"_HANDLER": config.get("Handler", "bootstrap"),
})
proc_env.update(env_vars)
+ proc_env.update(_durable_env_overlay())
# Override AWS_ENDPOINT_URL *after* function env vars so
# Lambda binaries always call back to this MiniStack
# instance. Function-level env vars may carry the
@@ -3074,9 +3267,15 @@ def _execute_function_local(func: dict, event: dict) -> dict:
endpoint = _normalize_endpoint_url(env_vars.get("AWS_ENDPOINT_URL", ""))
if not endpoint:
endpoint = _normalize_endpoint_url(env_vars.get("LOCALSTACK_HOSTNAME", ""))
+ if not endpoint:
+ # Subprocess runs on the same host as ministack — point it at
+ # ourselves so boto3 calls land back here, not at real AWS.
+ gateway_port = os.environ.get("GATEWAY_PORT", "4566")
+ endpoint = f"http://localhost:{gateway_port}"
if endpoint:
env["AWS_ENDPOINT_URL"] = endpoint
env.update(env_vars)
+ env.update(_durable_env_overlay())
cmd = ["node", wrapper_path] if is_node else ["python3", wrapper_path]
proc = subprocess.run(
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index b6f959bd..21c1ecab 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -605,7 +605,7 @@ def _dispatch(
if "uploadId" in query_params:
return _list_parts(bucket, key, query_params)
if "tagging" in query_params:
- return _get_object_tagging(bucket, key)
+ return _get_object_tagging(bucket, key, query_params)
if "retention" in query_params:
return _get_object_retention(bucket, key)
if "legal-hold" in query_params:
@@ -620,7 +620,7 @@ def _dispatch(
return _upload_part_copy(bucket, key, query_params, headers)
return _upload_part(bucket, key, body, query_params, headers)
if "tagging" in query_params:
- return _put_object_tagging(bucket, key, body)
+ return _put_object_tagging(bucket, key, body, query_params)
if "retention" in query_params:
return _put_object_retention(bucket, key, body, headers)
if "legal-hold" in query_params:
@@ -649,7 +649,7 @@ def _dispatch(
if "uploadId" in query_params:
return _abort_multipart_upload(bucket, key, query_params)
if "tagging" in query_params:
- return _delete_object_tagging(bucket, key)
+ return _delete_object_tagging(bucket, key, query_params)
return _delete_object(bucket, key, headers)
return _error(
@@ -1870,12 +1870,14 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):
_apply_object_lock_from_headers(bucket_name, key, headers)
# --- x-amz-tagging header on PutObject ---
+ # Parse + validate up front so the count error returns before persist/event,
+ # but defer the dict write until version_id is assigned (tags are per-version).
+ pending_tags = None
tagging_header = headers.get("x-amz-tagging", "")
if tagging_header:
- tags = {k: v[0] for k, v in _parse_qs(tagging_header).items()}
- if len(tags) > 10:
+ pending_tags = {k: v[0] for k, v in _parse_qs(tagging_header).items()}
+ if len(pending_tags) > 10:
return _error("BadRequest", "Object tags cannot be greater than 10", 400)
- _object_tags[(bucket_name, key)] = tags
if S3_PERSIST:
_persist_object(bucket_name, key, obj)
@@ -1904,6 +1906,9 @@ def _put_object(bucket_name: str, key: str, body: bytes, headers: dict):
# Mark all previous versions as not latest
for v in _object_versions[vkey][:-1]:
v["is_latest"] = False
+
+ if pending_tags is not None:
+ _object_tags[(bucket_name, key, obj.get("version_id"))] = pending_tags
return 200, resp_headers, b""
@@ -2061,11 +2066,13 @@ def _post_object(bucket_name: str, body: bytes, headers: dict):
bucket["objects"][key] = obj
_apply_object_lock_from_headers(bucket_name, key, synth)
+ # Defer tag write until version_id is assigned (tags are per-version).
+ pending_tags = None
tagging_header = synth.get("x-amz-tagging", "")
if tagging_header:
- tags = {k: v[0] for k, v in _parse_qs(tagging_header).items()}
- if len(tags) <= 10:
- _object_tags[(bucket_name, key)] = tags
+ parsed = {k: v[0] for k, v in _parse_qs(tagging_header).items()}
+ if len(parsed) <= 10:
+ pending_tags = parsed
if S3_PERSIST:
_persist_object(bucket_name, key, obj)
@@ -2093,6 +2100,9 @@ def _post_object(bucket_name: str, body: bytes, headers: dict):
for v in _object_versions[vkey][:-1]:
v["is_latest"] = False
+ if pending_tags is not None:
+ _object_tags[(bucket_name, key, version_id)] = pending_tags
+
location = f"http://{bucket_name}.s3.amazonaws.com/{url_quote(key, safe='/')}"
base_resp = {"ETag": etag, "Location": location}
if version_id:
@@ -2285,7 +2295,7 @@ def _delete_object(bucket_name: str, key: str, headers: dict | None = None):
existed = key in bucket["objects"]
bucket["objects"].pop(key, None)
- _object_tags.pop((bucket_name, key), None)
+ _object_tags.pop((bucket_name, key, None), None)
_object_retention.pop((bucket_name, key), None)
_object_legal_hold.pop((bucket_name, key), None)
_object_acl.pop((bucket_name, key), None)
@@ -2413,22 +2423,22 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):
}
dest_bucket["objects"][dest_key] = dest_obj
- # --- Preserve / replace tags ---
+ # --- Resolve tag payload now; commit after dest version_id is assigned
+ # (object tags are per-version per AWS).
tagging_directive = headers.get("x-amz-tagging-directive", "COPY").upper()
+ pending_dest_tags: dict | None = None
if tagging_directive == "REPLACE":
tagging_header = headers.get("x-amz-tagging", "")
if tagging_header:
- _object_tags[(bucket_name, dest_key)] = {
+ pending_dest_tags = {
k: v[0] for k, v in _parse_qs(tagging_header).items()
}
- else:
- _object_tags.pop((bucket_name, dest_key), None)
else:
- src_tags = _object_tags.get((src_bucket_name, src_key))
+ src_tags = _object_tags.get(
+ (src_bucket_name, src_key, src_obj.get("version_id"))
+ )
if src_tags:
- _object_tags[(bucket_name, dest_key)] = dict(src_tags)
- else:
- _object_tags.pop((bucket_name, dest_key), None)
+ pending_dest_tags = dict(src_tags)
# --- Preserve lock / retention ---
src_retention = _object_retention.get((src_bucket_name, src_key))
@@ -2476,6 +2486,12 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):
for v in _object_versions[vkey][:-1]:
v["is_latest"] = False
+ dest_version_id = dest_obj.get("version_id")
+ if pending_dest_tags is not None:
+ _object_tags[(bucket_name, dest_key, dest_version_id)] = pending_dest_tags
+ else:
+ _object_tags.pop((bucket_name, dest_key, dest_version_id), None)
+
root = Element("CopyObjectResult", xmlns=S3_NS)
SubElement(root, "LastModified").text = last_modified
SubElement(root, "ETag").text = new_etag
@@ -2487,7 +2503,21 @@ def _copy_object(bucket_name: str, dest_key: str, headers: dict):
# ---------------------------------------------------------------------------
-def _get_object_tagging(bucket_name: str, key: str):
+def _resolve_tagging_version(query_params: dict, bucket: dict, key: str):
+ """Resolve the (key, version_id) pair an Object Tagging op should act on.
+
+ Per AWS, object tags are per-version: when ``?versionId=`` is present the
+ op targets that specific version; otherwise it targets the current object.
+ The literal ``versionId=null`` means the pre-versioning object (stored as
+ ``None`` in our key tuple)."""
+ vid = _qp(query_params or {}, "versionId", "")
+ if vid:
+ return None if vid == "null" else vid
+ obj = bucket["objects"].get(key)
+ return obj.get("version_id") if obj else None
+
+
+def _get_object_tagging(bucket_name: str, key: str, query_params: dict | None = None):
bucket = _ensure_bucket(bucket_name)
if bucket is None:
return _no_such_bucket(bucket_name)
@@ -2499,17 +2529,23 @@ def _get_object_tagging(bucket_name: str, key: str):
f"/{bucket_name}/{key}",
)
- tags = _object_tags.get((bucket_name, key), {})
+ version_id = _resolve_tagging_version(query_params, bucket, key)
+ tags = _object_tags.get((bucket_name, key, version_id), {})
root = Element("Tagging", xmlns=S3_NS)
tag_set = SubElement(root, "TagSet")
for k, v in tags.items():
tag = SubElement(tag_set, "Tag")
SubElement(tag, "Key").text = k
SubElement(tag, "Value").text = v
- return 200, {"Content-Type": "application/xml"}, _xml_body(root)
+ resp_headers = {"Content-Type": "application/xml"}
+ if version_id:
+ resp_headers["x-amz-version-id"] = version_id
+ return 200, resp_headers, _xml_body(root)
-def _put_object_tagging(bucket_name: str, key: str, body: bytes):
+def _put_object_tagging(
+ bucket_name: str, key: str, body: bytes, query_params: dict | None = None
+):
bucket = _ensure_bucket(bucket_name)
if bucket is None:
return _no_such_bucket(bucket_name)
@@ -2526,11 +2562,17 @@ def _put_object_tagging(bucket_name: str, key: str, body: bytes):
return _error("MalformedXML", "The XML you provided was not well-formed", 400)
if len(tags) > 10:
return _error("BadRequest", "Object tags cannot be greater than 10", 400)
- _object_tags[(bucket_name, key)] = tags
- return 200, {"Content-Type": "application/xml"}, b""
+ version_id = _resolve_tagging_version(query_params, bucket, key)
+ _object_tags[(bucket_name, key, version_id)] = tags
+ resp_headers = {"Content-Type": "application/xml"}
+ if version_id:
+ resp_headers["x-amz-version-id"] = version_id
+ return 200, resp_headers, b""
-def _delete_object_tagging(bucket_name: str, key: str):
+def _delete_object_tagging(
+ bucket_name: str, key: str, query_params: dict | None = None
+):
bucket = _ensure_bucket(bucket_name)
if bucket is None:
return _no_such_bucket(bucket_name)
@@ -2541,8 +2583,12 @@ def _delete_object_tagging(bucket_name: str, key: str):
404,
f"/{bucket_name}/{key}",
)
- _object_tags.pop((bucket_name, key), None)
- return 204, {}, b""
+ version_id = _resolve_tagging_version(query_params, bucket, key)
+ _object_tags.pop((bucket_name, key, version_id), None)
+ resp_headers = {}
+ if version_id:
+ resp_headers["x-amz-version-id"] = version_id
+ return 204, resp_headers, b""
# ---------------------------------------------------------------------------
@@ -3262,7 +3308,7 @@ def _delete_objects(bucket_name: str, body: bytes, headers: dict = None):
)
continue
bucket["objects"].pop(k, None)
- _object_tags.pop((bucket_name, k), None)
+ _object_tags.pop((bucket_name, k, None), None)
_object_retention.pop((bucket_name, k), None)
_object_legal_hold.pop((bucket_name, k), None)
_object_acl.pop((bucket_name, k), None)
diff --git a/tests/test_cfn.py b/tests/test_cfn.py
index d8047b7f..8e95f457 100644
--- a/tests/test_cfn.py
+++ b/tests/test_cfn.py
@@ -1402,6 +1402,52 @@ def test_cfn_ssm_parameter_timestamp_is_epoch(cfn, ssm):
_wait_stack(cfn, "cfn-ssm-epoch")
+def test_cfn_appconfig_application(cfn, appconfig_client):
+ """AWS::AppConfig::Application provisions via CFN and is reachable via the
+ AppConfig API. Mirrors the CDK template from the reporter."""
+ template = json.dumps({
+ "Resources": {
+ "AppConfig1FDF3617": {
+ "Type": "AWS::AppConfig::Application",
+ "Properties": {
+ "Name": "digital-cdk-template-test-master-AppConfig",
+ "Tags": [
+ {"Key": "application-id", "Value": "digital-cdk-template"},
+ ],
+ },
+ },
+ },
+ })
+ cfn.create_stack(StackName="cfn-appconfig-app", TemplateBody=template)
+ _wait_stack(cfn, "cfn-appconfig-app")
+
+ try:
+ apps = appconfig_client.list_applications()["Items"]
+ match = [
+ a for a in apps
+ if a["Name"] == "digital-cdk-template-test-master-AppConfig"
+ ]
+ assert len(match) == 1
+ app_id = match[0]["Id"]
+
+ resources = cfn.describe_stack_resources(StackName="cfn-appconfig-app")
+ cfn_res = [
+ r for r in resources["StackResources"]
+ if r["LogicalResourceId"] == "AppConfig1FDF3617"
+ ]
+ assert len(cfn_res) == 1
+ assert cfn_res[0]["PhysicalResourceId"] == app_id
+ finally:
+ cfn.delete_stack(StackName="cfn-appconfig-app")
+ _wait_stack(cfn, "cfn-appconfig-app")
+
+ apps_after = appconfig_client.list_applications()["Items"]
+ assert not any(
+ a["Name"] == "digital-cdk-template-test-master-AppConfig"
+ for a in apps_after
+ )
+
+
def test_cfn_lambda_nodejs_inline_zip(cfn, lam):
"""CFN inline ZipFile with Node.js runtime should write index.js, not index.py."""
template = json.dumps({
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index fe8612be..cf22645a 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -556,7 +556,7 @@ def test_lambda_warm_start(lam, apigw):
import urllib.request as _urlreq
import uuid as _uuid
- fname = f"intg-warm-{_uuid.uuid4().hex[:8]}"
+ fname = f"intg-warm-{_uuid_mod.uuid4().hex[:8]}"
code = (
b"import time\n"
b"_boot_time = time.time()\n"
@@ -1916,7 +1916,7 @@ def test_apigwv2_nodejs_lambda_proxy(lam, apigw):
from botocore.exceptions import ClientError
- fname = f"apigwv2-node-{_uuid.uuid4().hex[:8]}"
+ fname = f"apigwv2-node-{_uuid_mod.uuid4().hex[:8]}"
api_id = None
code = (
"exports.handler = async (event) => ({"
@@ -3753,9 +3753,9 @@ def test_nodejs_worker_aws_sdk_v3_stub_wire_roundtrip(lam, ssm):
if not shutil.which("node"):
pytest.skip("node not found on PATH")
- fname = f"sdk-roundtrip-{_uuid.uuid4().hex[:8]}"
- param_name = f"/ministack-test/{_uuid.uuid4().hex[:8]}"
- param_value = f"value-{_uuid.uuid4().hex[:8]}"
+ fname = f"sdk-roundtrip-{_uuid_mod.uuid4().hex[:8]}"
+ param_name = f"/ministack-test/{_uuid_mod.uuid4().hex[:8]}"
+ param_value = f"value-{_uuid_mod.uuid4().hex[:8]}"
code = (
"const { SSMClient, PutParameterCommand } = require('@aws-sdk/client-ssm');\n"
"exports.handler = async (event) => {\n"
@@ -3805,3 +3805,900 @@ def test_lambda_ruby_4_0_runtime_maps_to_official_image():
from ministack.services.lambda_svc import _RUNTIME_IMAGE_MAP
assert _RUNTIME_IMAGE_MAP.get("ruby4.0") == "public.ecr.aws/lambda/ruby:4.0"
+
+
+# ---------------------------------------------------------------------------
+# Lambda Durable Functions (Durable Execution).
+# Shapes verified against:
+# https://docs.aws.amazon.com/lambda/latest/api/API_CheckpointDurableExecution.html
+# https://docs.aws.amazon.com/lambda/latest/api/API_GetDurableExecutionState.html
+# https://docs.aws.amazon.com/lambda/latest/api/API_GetDurableExecution.html
+# https://docs.aws.amazon.com/lambda/latest/api/API_ListDurableExecutionsByFunction.html
+# https://docs.aws.amazon.com/lambda/latest/api/API_GetDurableExecutionHistory.html
+# https://docs.aws.amazon.com/lambda/latest/api/API_StopDurableExecution.html
+# ---------------------------------------------------------------------------
+
+import urllib.request
+import urllib.error
+
+
+def _ms_endpoint():
+ return os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+
+
+def _raw_durable(method: str, path: str, body: dict | None = None,
+ query: dict | None = None):
+ """Hit ministack with a raw HTTP call for the durable-execution surface.
+ Boto3 doesn't carry the preview shapes yet, so use urllib."""
+ import json as _json
+ from urllib.parse import urlencode
+ qstr = ("?" + urlencode(query)) if query else ""
+ req = urllib.request.Request(
+ f"{_ms_endpoint()}{path}{qstr}",
+ method=method,
+ data=(_json.dumps(body).encode("utf-8") if body is not None else None),
+ headers={"Content-Type": "application/json"},
+ )
+ try:
+ with urllib.request.urlopen(req) as r:
+ payload = r.read()
+ return r.getcode(), _json.loads(payload) if payload else {}
+ except urllib.error.HTTPError as e:
+ body_bytes = e.read()
+ try:
+ return e.code, _json.loads(body_bytes) if body_bytes else {}
+ except Exception:
+ return e.code, {"raw": body_bytes.decode("utf-8", "replace")}
+
+
+def _create_durable_execution_directly(lam):
+ """Create a function with DurableConfig.Enabled, invoke it, and read
+ the resulting DurableExecutionArn from the X-Amz-Durable-Execution-Arn
+ response header. Returns (function_name, function_arn, dict with
+ DurableExecutionArn + CheckpointToken)."""
+ import base64 as _b64
+ import json as _json
+ fname = f"durable-fn-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ lam.delete_function(FunctionName=fname)
+ except Exception:
+ pass
+ zip_b64 = _b64.b64encode(_make_zip("def handler(e,c): return e")).decode()
+ code, body = _raw_durable("POST", "/2015-03-31/functions", body={
+ "FunctionName": fname,
+ "Runtime": "python3.12",
+ "Role": _LAMBDA_ROLE,
+ "Handler": "index.handler",
+ "Code": {"ZipFile": zip_b64},
+ "DurableConfig": {"Enabled": True},
+ })
+ fn_arn = body["FunctionArn"]
+ # Invoke to create a durable execution.
+ invoke_req = urllib.request.Request(
+ f"{_ms_endpoint()}/2015-03-31/functions/{fname}/invocations",
+ method="POST",
+ data=b'{"hello":"world"}',
+ headers={"Content-Type": "application/json"},
+ )
+ with urllib.request.urlopen(invoke_req) as r:
+ arn = r.headers.get("X-Amz-Durable-Execution-Arn")
+ token = r.headers.get("X-Amz-Durable-Checkpoint-Token")
+ r.read()
+ assert arn, "expected X-Amz-Durable-Execution-Arn header on invoke response"
+ assert token, "expected X-Amz-Durable-Checkpoint-Token header on invoke response"
+ return fname, fn_arn, {"DurableExecutionArn": arn, "CheckpointToken": token}
+
+
+def test_lambda_durable_function_config_round_trip(lam):
+ """CreateFunction accepts DurableConfig via raw HTTP (boto3 client-side
+ rejects unknown params until its model is updated) and GetFunction
+ echoes it back."""
+ fname = f"durable-cfg-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ lam.delete_function(FunctionName=fname)
+ except Exception:
+ pass
+ import json as _json
+ import base64 as _b64
+ zip_b64 = _b64.b64encode(_make_zip("def handler(e,c): return e")).decode()
+ code, body = _raw_durable("POST", "/2015-03-31/functions", body={
+ "FunctionName": fname,
+ "Runtime": "python3.12",
+ "Role": _LAMBDA_ROLE,
+ "Handler": "index.handler",
+ "Code": {"ZipFile": zip_b64},
+ "DurableConfig": {"Enabled": True},
+ })
+ try:
+ assert code in (200, 201), body
+ assert body.get("DurableConfig") == {"Enabled": True}
+ # Boto3 strips unknown fields, so verify the round-trip via raw HTTP.
+ code, gf = _raw_durable("GET", f"/2015-03-31/functions/{fname}")
+ assert code == 200
+ assert gf["Configuration"].get("DurableConfig") == {"Enabled": True}
+ finally:
+ try:
+ lam.delete_function(FunctionName=fname)
+ except Exception:
+ pass
+
+
+def test_lambda_durable_get_execution(lam):
+ fname, fn_arn, rec = _create_durable_execution_directly(lam)
+ try:
+ from urllib.parse import quote
+ path = f"/2025-12-01/durable-executions/{quote(rec['DurableExecutionArn'], safe='/:$')}"
+ code, body = _raw_durable("GET", path)
+ assert code == 200
+ assert body["DurableExecutionArn"] == rec["DurableExecutionArn"]
+ assert body["Status"] == "RUNNING"
+ assert json.loads(body["InputPayload"]) == {"hello": "world"}
+ assert body["FunctionArn"] == fn_arn
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_durable_get_state_requires_token(lam):
+ fname, _, rec = _create_durable_execution_directly(lam)
+ try:
+ from urllib.parse import quote
+ arn = quote(rec["DurableExecutionArn"], safe="/:$")
+ # Wrong token rejected.
+ code, body = _raw_durable("GET", f"/2025-12-01/durable-executions/{arn}/state",
+ query={"CheckpointToken": "wrong"})
+ assert code == 400
+ # Correct token succeeds. AWS seeds an EXECUTION-type operation on
+ # invoke so the SDK can read the input payload via
+ # state.get_execution_operation; expect exactly that op here.
+ code, body = _raw_durable("GET", f"/2025-12-01/durable-executions/{arn}/state",
+ query={"CheckpointToken": rec["CheckpointToken"]})
+ assert code == 200
+ assert len(body["Operations"]) == 1
+ assert body["Operations"][0]["Type"] == "EXECUTION"
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_durable_checkpoint_rotates_token_and_records_operations(lam):
+ fname, _, rec = _create_durable_execution_directly(lam)
+ try:
+ from urllib.parse import quote
+ arn = quote(rec["DurableExecutionArn"], safe="/:$")
+ original_token = rec["CheckpointToken"]
+ # Checkpoint a single Step succeed.
+ code, body = _raw_durable("POST", f"/2025-12-01/durable-executions/{arn}/checkpoint", body={
+ "CheckpointToken": original_token,
+ "Updates": [{
+ "Id": "step-1",
+ "Type": "STEP",
+ "Action": "SUCCEED",
+ "Name": "first-step",
+ "Payload": '{"value":42}',
+ }],
+ })
+ assert code == 200
+ assert body["CheckpointToken"] != original_token
+ ops = body["NewExecutionState"]["Operations"]
+ assert any(op["Id"] == "step-1" and op["Status"] == "SUCCEEDED" for op in ops)
+ # Replaying with the OLD token must fail.
+ code, _ = _raw_durable("POST", f"/2025-12-01/durable-executions/{arn}/checkpoint", body={
+ "CheckpointToken": original_token,
+ "Updates": [],
+ })
+ assert code == 400
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_durable_get_history(lam):
+ fname, _, rec = _create_durable_execution_directly(lam)
+ try:
+ from urllib.parse import quote
+ arn = quote(rec["DurableExecutionArn"], safe="/:$")
+ # Run a checkpoint so we have a non-trivial history.
+ _raw_durable("POST", f"/2025-12-01/durable-executions/{arn}/checkpoint", body={
+ "CheckpointToken": rec["CheckpointToken"],
+ "Updates": [{"Id": "s", "Type": "STEP", "Action": "SUCCEED",
+ "Name": "n", "Payload": "1"}],
+ })
+ code, body = _raw_durable("GET", f"/2025-12-01/durable-executions/{arn}/history")
+ assert code == 200
+ events = body["Events"]
+ assert any(e["EventType"] == "ExecutionStarted" for e in events)
+ assert any(e["EventType"] == "StepSucceeded" for e in events)
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_durable_stop(lam):
+ fname, _, rec = _create_durable_execution_directly(lam)
+ try:
+ from urllib.parse import quote
+ arn = quote(rec["DurableExecutionArn"], safe="/:$")
+ code, body = _raw_durable("POST", f"/2025-12-01/durable-executions/{arn}/stop", body={
+ "ErrorMessage": "stop-test",
+ })
+ assert code == 200
+ assert "StopTimestamp" in body
+ # GetDurableExecution reflects the STOPPED status + error.
+ code, body = _raw_durable("GET", f"/2025-12-01/durable-executions/{arn}")
+ assert body["Status"] == "STOPPED"
+ assert body["Error"]["ErrorMessage"] == "stop-test"
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_durable_list_by_function(lam):
+ fname, fn_arn, rec = _create_durable_execution_directly(lam)
+ try:
+ from urllib.parse import quote
+ code, body = _raw_durable("GET", f"/2025-12-01/functions/{fname}/durable-executions")
+ assert code == 200
+ arns = [s["DurableExecutionArn"] for s in body["DurableExecutions"]]
+ assert rec["DurableExecutionArn"] in arns
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_durable_unknown_execution_404(lam):
+ code, body = _raw_durable(
+ "GET",
+ "/2025-12-01/durable-executions/arn:aws:lambda:us-east-1:000000000000:function:nofn:$LATEST/durable-execution/aaa/bbb",
+ )
+ assert code == 404
+ assert "ResourceNotFoundException" in body.get("__type", "")
+
+
+# ---------------------------------------------------------------------------
+# Durable Lambda — runtime env injection + chained invoke + persistence.
+# ---------------------------------------------------------------------------
+
+def test_lambda_durable_runtime_env_vars_present(lam):
+ """A function with DurableConfig.Enabled gets the durable ARN + initial
+ CheckpointToken injected as env vars in its execution environment."""
+ import base64 as _b64
+ import json as _json
+ fname = f"durable-env-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ lam.delete_function(FunctionName=fname)
+ except Exception:
+ pass
+ # Handler echoes the durable env vars back so the test can verify them.
+ code = """
+import os, json
+def handler(event, context):
+ return {
+ "arn": os.environ.get("AWS_LAMBDA_DURABLE_EXECUTION_ARN"),
+ "token": os.environ.get("AWS_LAMBDA_DURABLE_CHECKPOINT_TOKEN"),
+ "name": os.environ.get("AWS_LAMBDA_DURABLE_EXECUTION_NAME"),
+ }
+"""
+ zip_b64 = _b64.b64encode(_make_zip(code)).decode()
+ _raw_durable("POST", "/2015-03-31/functions", body={
+ "FunctionName": fname,
+ "Runtime": "python3.12",
+ "Role": _LAMBDA_ROLE,
+ "Handler": "index.handler",
+ "Code": {"ZipFile": zip_b64},
+ "DurableConfig": {"Enabled": True},
+ })
+ try:
+ resp = lam.invoke(FunctionName=fname, Payload=b"{}")
+ body = _json.loads(resp["Payload"].read())
+ assert body["arn"] and body["arn"].startswith("arn:aws:lambda:")
+ assert "/durable-execution/" in body["arn"]
+ assert body["token"]
+ assert body["name"]
+ finally:
+ try:
+ lam.delete_function(FunctionName=fname)
+ except Exception:
+ pass
+
+
+def test_lambda_durable_chained_invoke_runs_child(lam):
+ """A CHAINED_INVOKE checkpoint update with Action=START actually spawns
+ the child function and records the result back into the parent's
+ operation log."""
+ import base64 as _b64
+ import json as _json
+ parent = f"durable-parent-{_uuid_mod.uuid4().hex[:8]}"
+ child = f"durable-child-{_uuid_mod.uuid4().hex[:8]}"
+ for n in (parent, child):
+ try:
+ lam.delete_function(FunctionName=n)
+ except Exception:
+ pass
+ # Child handler returns a deterministic marker.
+ child_code = "def handler(e,c): return {'child_marker': 'CHILD_OK'}"
+ _raw_durable("POST", "/2015-03-31/functions", body={
+ "FunctionName": child,
+ "Runtime": "python3.12",
+ "Role": _LAMBDA_ROLE,
+ "Handler": "index.handler",
+ "Code": {"ZipFile": _b64.b64encode(_make_zip(child_code)).decode()},
+ })
+ parent_code = "def handler(e,c): return {}"
+ _raw_durable("POST", "/2015-03-31/functions", body={
+ "FunctionName": parent,
+ "Runtime": "python3.12",
+ "Role": _LAMBDA_ROLE,
+ "Handler": "index.handler",
+ "Code": {"ZipFile": _b64.b64encode(_make_zip(parent_code)).decode()},
+ "DurableConfig": {"Enabled": True},
+ })
+ try:
+ # Invoke parent to spin up its durable execution.
+ invoke_req = urllib.request.Request(
+ f"{_ms_endpoint()}/2015-03-31/functions/{parent}/invocations",
+ method="POST", data=b"{}", headers={"Content-Type": "application/json"},
+ )
+ with urllib.request.urlopen(invoke_req) as r:
+ arn = r.headers.get("X-Amz-Durable-Execution-Arn")
+ token = r.headers.get("X-Amz-Durable-Checkpoint-Token")
+ r.read()
+ from urllib.parse import quote
+ arn_enc = quote(arn, safe="/:$")
+ # Post a CHAINED_INVOKE START targeting the child.
+ code, body = _raw_durable("POST",
+ f"/2025-12-01/durable-executions/{arn_enc}/checkpoint", body={
+ "CheckpointToken": token,
+ "Updates": [{
+ "Id": "chain-1",
+ "Type": "CHAINED_INVOKE",
+ "Action": "START",
+ "Name": "call-child",
+ "ChainedInvokeOptions": {"FunctionName": child},
+ }],
+ })
+ assert code == 200
+ # The child runs in a daemon thread; give it a moment.
+ import time as _time
+ for _ in range(30):
+ _time.sleep(0.1)
+ code, history = _raw_durable("GET",
+ f"/2025-12-01/durable-executions/{arn_enc}/history")
+ if any(e["EventType"] == "ChainedInvokeSucceeded" for e in history.get("Events", [])):
+ break
+ events = history["Events"]
+ assert any(e["EventType"] == "ChainedInvokeSucceeded" for e in events), \
+ f"expected ChainedInvokeSucceeded, got {[e['EventType'] for e in events]}"
+ # Confirm the child's marker is in the result payload.
+ for e in events:
+ if e["EventType"] == "ChainedInvokeSucceeded":
+ payload = e["ChainedInvokeSucceededDetails"]["Result"]["Payload"]
+ assert "CHILD_OK" in payload
+ break
+ finally:
+ for n in (parent, child):
+ try:
+ lam.delete_function(FunctionName=n)
+ except Exception:
+ pass
+
+
+def test_lambda_durable_persistence_round_trip():
+ """get_state / restore_state round-trip preserves the executions map."""
+ from ministack.services import lambda_durable
+ # Snapshot original state.
+ original = lambda_durable.get_state()
+ try:
+ # Create a synthetic execution.
+ lambda_durable._executions.clear()
+ rec = lambda_durable.create_execution_for_invoke(
+ function_arn="arn:aws:lambda:us-east-1:000000000000:function:persist-test",
+ version="$LATEST",
+ input_payload='{"k":"v"}',
+ )
+ snap = lambda_durable.get_state()
+ # Wipe and restore.
+ lambda_durable._executions.clear()
+ assert not lambda_durable._executions
+ lambda_durable.restore_state(snap)
+ assert rec["DurableExecutionArn"] in lambda_durable._executions
+ restored = lambda_durable._executions[rec["DurableExecutionArn"]]
+ assert restored["Status"] == "RUNNING"
+ assert restored["InputPayload"] == '{"k":"v"}'
+ finally:
+ lambda_durable._executions.clear()
+ lambda_durable.restore_state(original)
+
+
+def test_lambda_durable_event_wrapped_with_sdk_fields(lam):
+ """A durable invocation's event payload is wrapped with the fields the
+ aws-durable-execution-sdk-python SDK reads from the Lambda event:
+ DurableExecutionArn, CheckpointToken, InitialExecutionState.
+ Without this wrapping the SDK's `@durable_execution` decorator raises
+ ExecutionError on the first line of its wrapper."""
+ import base64 as _b64
+ import json as _json
+ fname = f"durable-wrap-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ lam.delete_function(FunctionName=fname)
+ except Exception:
+ pass
+ # Handler echoes the keys it received.
+ code = """
+def handler(event, context):
+ return {"keys": sorted(list(event.keys())), "event": event}
+"""
+ _raw_durable("POST", "/2015-03-31/functions", body={
+ "FunctionName": fname,
+ "Runtime": "python3.12",
+ "Role": _LAMBDA_ROLE,
+ "Handler": "index.handler",
+ "Code": {"ZipFile": _b64.b64encode(_make_zip(code)).decode()},
+ "DurableConfig": {"Enabled": True},
+ })
+ try:
+ resp = lam.invoke(FunctionName=fname, Payload=b'{"user":"data"}')
+ body = _json.loads(resp["Payload"].read())
+ # SDK requires these three top-level keys.
+ for key in ("DurableExecutionArn", "CheckpointToken", "InitialExecutionState"):
+ assert key in body["keys"], f"missing {key} in {body['keys']}"
+ ops = body["event"]["InitialExecutionState"]["Operations"]
+ # AWS seeds the synthetic EXECUTION-type op with the input payload.
+ assert len(ops) == 1 and ops[0]["Type"] == "EXECUTION"
+ finally:
+ try:
+ lam.delete_function(FunctionName=fname)
+ except Exception:
+ pass
+
+
+# ---------------------------------------------------------------------------
+# Durable execution — external callbacks (SendCallback{Success,Failure,Heartbeat}).
+# Spec: callbacks suspend the SDK; external systems resolve them via REST.
+# https://docs.aws.amazon.com/lambda/latest/api/API_SendDurableExecutionCallbackSuccess.html
+# https://docs.aws.amazon.com/lambda/latest/api/API_SendDurableExecutionCallbackFailure.html
+# https://docs.aws.amazon.com/lambda/latest/api/API_SendDurableExecutionCallbackHeartbeat.html
+# ---------------------------------------------------------------------------
+
+def _start_callback(lam):
+ """Create a durable execution and checkpoint a CALLBACK START so a callback
+ is registered and resolvable externally. Returns (fname, arn, callback_id,
+ new_checkpoint_token)."""
+ fname, _, rec = _create_durable_execution_directly(lam)
+ from urllib.parse import quote
+ arn_q = quote(rec["DurableExecutionArn"], safe="/:$")
+ code, body = _raw_durable("POST", f"/2025-12-01/durable-executions/{arn_q}/checkpoint", body={
+ "CheckpointToken": rec["CheckpointToken"],
+ "Updates": [{
+ "Id": "cbop1aaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "Type": "CALLBACK",
+ "Action": "START",
+ "Name": "ext-cb",
+ "CallbackOptions": {"TimeoutSeconds": 120, "HeartbeatTimeoutSeconds": 30},
+ }],
+ })
+ assert code == 200, body
+ ops = body["NewExecutionState"]["Operations"]
+ op = next(o for o in ops if o["Id"] == "cbop1aaaaaaaaaaaaaaaaaaaaaaaaaa")
+ cb_id = (op.get("CallbackDetails") or {}).get("CallbackId")
+ assert cb_id, f"no CallbackId in {op}"
+ return fname, rec["DurableExecutionArn"], cb_id, body["CheckpointToken"]
+
+
+def test_lambda_durable_send_callback_success_then_already_closed(lam):
+ """First succeed returns 200; second call against the same closed callback
+ must return CallbackTimeoutException (400) per the spec."""
+ import urllib.request, urllib.error
+ from urllib.parse import quote
+ fname, arn, cb_id, _ = _start_callback(lam)
+ try:
+ url = f"{_ms_endpoint()}/2025-12-01/durable-execution-callbacks/{quote(cb_id, safe='')}/succeed"
+ req = urllib.request.Request(url, method="POST", data=b'"first"',
+ headers={"Content-Type": "application/json"})
+ with urllib.request.urlopen(req) as r:
+ assert r.status == 200
+ # Re-fire: already-closed callback → 400.
+ req2 = urllib.request.Request(url, method="POST", data=b'"second"',
+ headers={"Content-Type": "application/json"})
+ try:
+ urllib.request.urlopen(req2)
+ assert False, "expected 400 on already-closed callback"
+ except urllib.error.HTTPError as e:
+ assert e.code == 400
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_durable_send_callback_success_records_result(lam):
+ fname, arn, cb_id, _ = _start_callback(lam)
+ try:
+ import urllib.request
+ from urllib.parse import quote
+ req = urllib.request.Request(
+ f"{_ms_endpoint()}/2025-12-01/durable-execution-callbacks/{quote(cb_id, safe='')}/succeed",
+ method="POST", data=b'"forty-two"',
+ headers={"Content-Type": "application/json"},
+ )
+ with urllib.request.urlopen(req) as r:
+ assert r.status == 200
+ # History should include CallbackSucceeded with the Result payload.
+ code, hist = _raw_durable("GET",
+ f"/2025-12-01/durable-executions/{quote(arn, safe='/:$')}/history")
+ assert code == 200
+ types = [e["EventType"] for e in hist["Events"]]
+ assert "CallbackSucceeded" in types
+ ev = next(e for e in hist["Events"] if e["EventType"] == "CallbackSucceeded")
+ assert ev["CallbackSucceededDetails"]["Result"]["Payload"] == '"forty-two"'
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_durable_send_callback_failure(lam):
+ fname, arn, cb_id, _ = _start_callback(lam)
+ try:
+ import urllib.request, json as _json
+ from urllib.parse import quote
+ req = urllib.request.Request(
+ f"{_ms_endpoint()}/2025-12-01/durable-execution-callbacks/{quote(cb_id, safe='')}/fail",
+ method="POST",
+ data=_json.dumps({
+ "ErrorType": "ExternalTimeout",
+ "ErrorMessage": "third-party timed out",
+ "ErrorData": "extra-context",
+ }).encode(),
+ headers={"Content-Type": "application/json"},
+ )
+ with urllib.request.urlopen(req) as r:
+ assert r.status == 200
+ code, hist = _raw_durable("GET",
+ f"/2025-12-01/durable-executions/{quote(arn, safe='/:$')}/history")
+ assert code == 200
+ ev = next(e for e in hist["Events"] if e["EventType"] == "CallbackFailed")
+ err = ev["CallbackFailedDetails"]["Error"]["Payload"]
+ assert err["ErrorType"] == "ExternalTimeout"
+ assert err["ErrorMessage"] == "third-party timed out"
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_durable_send_callback_heartbeat(lam):
+ """Heartbeat must return 200 and must NOT close the callback — a
+ subsequent succeed on the same id must still work."""
+ import urllib.request
+ from urllib.parse import quote
+ fname, arn, cb_id, _ = _start_callback(lam)
+ try:
+ hb_url = f"{_ms_endpoint()}/2025-12-01/durable-execution-callbacks/{quote(cb_id, safe='')}/heartbeat"
+ for _ in range(3):
+ req = urllib.request.Request(hb_url, method="POST", data=b"",
+ headers={"Content-Type": "application/json"})
+ with urllib.request.urlopen(req) as r:
+ assert r.status == 200
+ # Callback should still be live → succeed returns 200.
+ ok_url = f"{_ms_endpoint()}/2025-12-01/durable-execution-callbacks/{quote(cb_id, safe='')}/succeed"
+ req = urllib.request.Request(ok_url, method="POST", data=b'"done"',
+ headers={"Content-Type": "application/json"})
+ with urllib.request.urlopen(req) as r:
+ assert r.status == 200
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_durable_send_callback_unknown_id_400(lam):
+ """Unknown CallbackId returns InvalidParameterValueException, not 500."""
+ import urllib.request, urllib.error
+ req = urllib.request.Request(
+ f"{_ms_endpoint()}/2025-12-01/durable-execution-callbacks/does-not-exist/succeed",
+ method="POST", data=b'"x"',
+ headers={"Content-Type": "application/json"},
+ )
+ try:
+ urllib.request.urlopen(req)
+ assert False, "expected 400"
+ except urllib.error.HTTPError as e:
+ assert e.code == 400
+
+
+def test_lambda_durable_get_execution_rejects_malformed_arn(lam):
+ """Malformed DurableExecutionArn → 400 InvalidParameterValueException."""
+ code, body = _raw_durable("GET", "/2025-12-01/durable-executions/not-a-real-arn")
+ assert code == 400
+ assert body.get("__type") == "InvalidParameterValueException"
+
+
+# ---------------------------------------------------------------------------
+# Resume scheduler — fires WAIT/CALLBACK expiries and survives restart.
+# These exercise lambda_durable._resume_execution and restore_state directly
+# (they're internal but they ARE the AWS-parity contract for in-flight
+# durable executions: timers keep ticking, callbacks stay resolvable across
+# restarts).
+# ---------------------------------------------------------------------------
+
+def test_lambda_durable_heartbeat_extends_callback_timeout():
+ """Pushing the HeartbeatDeadline forward must actually delay the
+ CallbackTimedOut firing. Stale heap entries must be no-ops."""
+ from ministack.services import lambda_durable as _ld
+ arn = "arn:aws:lambda:us-east-1:000000000000:function:hb-test:$LATEST/durable-execution/" \
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
+ now = _ld._now()
+ op_id = "hbop1aaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ rec = {
+ "DurableExecutionArn": arn,
+ "FunctionArn": "arn:aws:lambda:us-east-1:000000000000:function:hb-test",
+ "Status": "RUNNING",
+ "Operations": [{
+ "Id": op_id, "Type": "CALLBACK", "Status": "STARTED",
+ "CallbackDetails": {
+ "CallbackId": op_id,
+ "HeartbeatTimeoutSeconds": 30.0,
+ "HeartbeatDeadline": now - 5, # already past
+ "TimeoutDeadline": now + 600,
+ },
+ }],
+ "History": [], "NextEventId": 1, "CheckpointToken": "tok",
+ "InputPayload": "{}",
+ }
+ _ld._executions[arn] = rec
+ _ld._callback_index[op_id] = (arn, op_id)
+ try:
+ # Heartbeat now → pushes HeartbeatDeadline to now+30s.
+ status, _, _ = _ld.handle_callback_heartbeat(op_id, b"")
+ assert status == 200
+ new_deadline = rec["Operations"][0]["CallbackDetails"]["HeartbeatDeadline"]
+ assert new_deadline > _ld._now() + 25
+ # Simulate the stale heap entry firing now — must be a no-op
+ # (callback not timed out, status still STARTED).
+ _ld._resume_execution(arn)
+ assert rec["Operations"][0]["Status"] == "STARTED"
+ assert (rec["Operations"][0].get("CallbackDetails") or {}).get("Error") is None
+ finally:
+ _ld._executions.pop(arn, None)
+ _ld._callback_index.pop(op_id, None)
+
+
+def test_lambda_durable_restore_rebuilds_callback_index_and_rearms_timers():
+ """After restore_state, in-flight callbacks must be resolvable and
+ pending timers must be back on the heap."""
+ from ministack.services import lambda_durable as _ld
+ arn = "arn:aws:lambda:us-east-1:000000000000:function:restore-test:$LATEST/durable-execution/" \
+ "cccccccccccccccccccccccccccccccc/dddddddddddddddddddddddddddddddd"
+ cb_op_id = "rstcbaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ wait_op_id = "rstwaitaaaaaaaaaaaaaaaaaaaaaaaaa"
+ now = _ld._now()
+ rec = {
+ "DurableExecutionArn": arn,
+ "FunctionArn": "arn:aws:lambda:us-east-1:000000000000:function:restore-test",
+ "Status": "RUNNING",
+ "Operations": [
+ {"Id": cb_op_id, "Type": "CALLBACK", "Status": "STARTED",
+ "CallbackDetails": {"CallbackId": cb_op_id,
+ "TimeoutDeadline": now + 300}},
+ {"Id": wait_op_id, "Type": "WAIT", "Status": "STARTED",
+ "WaitDetails": {"ScheduledEndTimestamp": now + 60, "Duration": 60}},
+ ],
+ "History": [], "NextEventId": 1, "CheckpointToken": "tok",
+ "InputPayload": "{}",
+ }
+ # Wipe live state so the test is hermetic.
+ pre_index = dict(_ld._callback_index)
+ pre_execs = dict(_ld._executions)
+ pre_queue = list(_ld._resume_queue)
+ _ld._executions.clear()
+ _ld._callback_index.clear()
+ with _ld._resume_lock:
+ _ld._resume_queue.clear()
+ try:
+ # Pretend ministack just booted and read this rec from disk.
+ _ld.restore_state({"executions": {arn: rec}})
+ # Index must contain the STARTED callback.
+ assert cb_op_id in _ld._callback_index
+ assert _ld._callback_index[cb_op_id] == (arn, cb_op_id)
+ # Heap must have at least one entry for this arn at or before the
+ # earliest deadline (the WAIT at now+60).
+ with _ld._resume_lock:
+ entries = [(t, a) for (t, a, _acct) in _ld._resume_queue if a == arn]
+ assert entries, "no resume entry queued after restore"
+ assert min(t for t, _ in entries) <= now + 60 + 1
+ # And Send*Callback resolves the restored callback (no 404).
+ target, op, err = _ld._resolve_callback(cb_op_id)
+ assert err is None and target is rec and op["Id"] == cb_op_id
+ finally:
+ _ld._executions.clear()
+ _ld._executions.update(pre_execs)
+ _ld._callback_index.clear()
+ _ld._callback_index.update(pre_index)
+ with _ld._resume_lock:
+ _ld._resume_queue.clear()
+ for e in pre_queue:
+ _ld._resume_queue.append(e)
+
+
+def test_lambda_durable_restore_skips_non_running_executions():
+ """SUCCEEDED/FAILED/STOPPED executions must NOT be re-armed (they would
+ pin a function arn that may not exist anymore) and their callbacks must
+ NOT be re-indexed."""
+ from ministack.services import lambda_durable as _ld
+ arn_done = "arn:aws:lambda:us-east-1:000000000000:function:done-fn:$LATEST/durable-execution/" \
+ "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee/ffffffffffffffffffffffffffffffff"
+ cb_op_id = "donecbaaaaaaaaaaaaaaaaaaaaaaaaaa"
+ rec = {
+ "DurableExecutionArn": arn_done,
+ "FunctionArn": "arn:aws:lambda:us-east-1:000000000000:function:done-fn",
+ "Status": "SUCCEEDED",
+ "Operations": [
+ {"Id": cb_op_id, "Type": "CALLBACK", "Status": "SUCCEEDED",
+ "CallbackDetails": {"CallbackId": cb_op_id, "Result": "x"}},
+ ],
+ "History": [], "NextEventId": 1, "CheckpointToken": "tok",
+ "InputPayload": "{}",
+ }
+ pre_index = dict(_ld._callback_index)
+ pre_execs = dict(_ld._executions)
+ _ld._executions.clear()
+ _ld._callback_index.clear()
+ try:
+ _ld.restore_state({"executions": {arn_done: rec}})
+ # SUCCEEDED callback must NOT be indexed (only STARTED ones).
+ assert cb_op_id not in _ld._callback_index
+ finally:
+ _ld._executions.clear()
+ _ld._executions.update(pre_execs)
+ _ld._callback_index.clear()
+ _ld._callback_index.update(pre_index)
+
+
+# ---------------------------------------------------------------------------
+# Edge-case coverage for the 7 ops in issue #670 — written so we can close
+# the ticket with confidence rather than just on happy-path verification.
+# ---------------------------------------------------------------------------
+
+def test_lambda_durable_stop_on_terminal_returns_invalid_parameter(lam):
+ """Per AWS docs ('Stops a running durable execution'), Stop on a
+ non-running execution must return 400 InvalidParameterValueException —
+ the only 4xx-class error the API documents for input failures."""
+ from urllib.parse import quote
+ fname, _, rec = _create_durable_execution_directly(lam)
+ try:
+ arn_q = quote(rec["DurableExecutionArn"], safe="/:$")
+ code1, _ = _raw_durable("POST", f"/2025-12-01/durable-executions/{arn_q}/stop", body={})
+ assert code1 == 200
+ code2, body2 = _raw_durable("POST", f"/2025-12-01/durable-executions/{arn_q}/stop", body={})
+ assert code2 == 400, f"expected 400, got {code2}: {body2}"
+ assert body2.get("__type") == "InvalidParameterValueException", body2
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_durable_checkpoint_malformed_updates_rejected(lam):
+ """A Checkpoint with garbage Updates (missing required fields, unknown
+ Type) must 400, not 500 or silent accept."""
+ from urllib.parse import quote
+ fname, _, rec = _create_durable_execution_directly(lam)
+ try:
+ arn_q = quote(rec["DurableExecutionArn"], safe="/:$")
+ # Missing Id, Type, Action.
+ code, body = _raw_durable("POST",
+ f"/2025-12-01/durable-executions/{arn_q}/checkpoint",
+ body={"CheckpointToken": rec["CheckpointToken"],
+ "Updates": [{"banana": "split"}]})
+ assert code == 400 or (code == 200 and body.get("NewExecutionState", {}).get("Operations") == []), \
+ f"malformed update accepted as valid update: code={code} body={body}"
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_durable_checkpoint_unknown_op_type_rejected(lam):
+ """Unknown Type (not in EXECUTION/CONTEXT/STEP/WAIT/CALLBACK/CHAINED_INVOKE)
+ must not silently create an Op with that bogus Type."""
+ from urllib.parse import quote
+ fname, _, rec = _create_durable_execution_directly(lam)
+ try:
+ arn_q = quote(rec["DurableExecutionArn"], safe="/:$")
+ code, body = _raw_durable("POST",
+ f"/2025-12-01/durable-executions/{arn_q}/checkpoint",
+ body={"CheckpointToken": rec["CheckpointToken"],
+ "Updates": [{"Id": "x" * 32, "Type": "NOT_A_REAL_TYPE",
+ "Action": "START"}]})
+ # Either 400-reject, or the bogus type must not create a recognised op.
+ if code == 200:
+ ops = body["NewExecutionState"]["Operations"]
+ bogus = [o for o in ops if o.get("Type") == "NOT_A_REAL_TYPE"]
+ assert not bogus, "ministack silently created an Op with an invalid Type"
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_durable_list_pagination_max_items(lam):
+ """Per AWS docs, ListDurableExecutionsByFunction uses MaxItems (not
+ MaxResults) with 'Valid Range: Minimum 0, Maximum 1000'. Out-of-range
+ must 400 with InvalidParameterValueException."""
+ fname, _, _ = _create_durable_execution_directly(lam)
+ try:
+ # Out-of-range → 400 InvalidParameterValueException.
+ code, body = _raw_durable("GET",
+ f"/2025-12-01/functions/{fname}/durable-executions",
+ query={"MaxItems": "9999999"})
+ assert code == 400, f"expected 400, got {code}: {body}"
+ assert body.get("__type") == "InvalidParameterValueException", body
+ # MaxItems=1 with a single execution → still returns it.
+ code, body = _raw_durable("GET",
+ f"/2025-12-01/functions/{fname}/durable-executions",
+ query={"MaxItems": "1"})
+ assert code == 200, f"got {code}: {body}"
+ assert len(body.get("DurableExecutions", [])) >= 1
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_durable_get_history_pagination_marker(lam):
+ """Per AWS docs, the Lambda pagination contract uses Marker (not
+ NextToken) and MaxItems (not MaxResults). MaxItems > 1000 must 400."""
+ from urllib.parse import quote
+ fname, _, rec = _create_durable_execution_directly(lam)
+ try:
+ arn_q = quote(rec["DurableExecutionArn"], safe="/:$")
+ code, body = _raw_durable("GET",
+ f"/2025-12-01/durable-executions/{arn_q}/history",
+ query={"MaxItems": "1"})
+ assert code == 200, body
+ assert "Events" in body
+ code, body = _raw_durable("GET",
+ f"/2025-12-01/durable-executions/{arn_q}/history",
+ query={"MaxItems": "9999999"})
+ assert code == 400, body
+ assert body.get("__type") == "InvalidParameterValueException", body
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_durable_get_execution_state_old_token_rejected(lam):
+ """GetDurableExecutionState with a stale CheckpointToken must 400 —
+ SDKs rely on this to detect they've been preempted."""
+ from urllib.parse import quote
+ fname, _, rec = _create_durable_execution_directly(lam)
+ try:
+ arn_q = quote(rec["DurableExecutionArn"], safe="/:$")
+ original_token = rec["CheckpointToken"]
+ # Rotate the token via a Checkpoint.
+ code, body = _raw_durable("POST",
+ f"/2025-12-01/durable-executions/{arn_q}/checkpoint",
+ body={"CheckpointToken": original_token, "Updates": []})
+ assert code == 200
+ # Old token must now be rejected on GetState.
+ code, body = _raw_durable("GET",
+ f"/2025-12-01/durable-executions/{arn_q}/state",
+ query={"CheckpointToken": original_token})
+ assert code == 400, f"stale token accepted: code={code} body={body}"
+ finally:
+ lam.delete_function(FunctionName=fname)
+
+
+def test_lambda_durable_get_unknown_arn_404(lam):
+ """GetDurableExecution with a syntactically-valid but unknown ARN must
+ return 404 (ResourceNotFoundException), not 500."""
+ fake = ("arn:aws:lambda:us-east-1:000000000000:function:does-not-exist:"
+ "$LATEST/durable-execution/" + ("a" * 32) + "/" + ("b" * 32))
+ from urllib.parse import quote
+ code, body = _raw_durable("GET", f"/2025-12-01/durable-executions/{quote(fake, safe='/:$')}")
+ assert code == 404, f"expected 404, got {code}: {body}"
+
+
+def test_lambda_durable_create_function_durable_config_round_trip_with_update(lam):
+ """DurableConfig must survive UpdateFunctionConfiguration that touches
+ unrelated fields (timeout, memory)."""
+ import base64 as _b64, json as _json
+ fname = f"dur-upd-{_uuid_mod.uuid4().hex[:8]}"
+ try:
+ lam.delete_function(FunctionName=fname)
+ except Exception:
+ pass
+ zip_b64 = _b64.b64encode(_make_zip("def handler(e,c): return e")).decode()
+ code, _ = _raw_durable("POST", "/2015-03-31/functions", body={
+ "FunctionName": fname, "Runtime": "python3.12", "Role": _LAMBDA_ROLE,
+ "Handler": "index.handler", "Code": {"ZipFile": zip_b64},
+ "DurableConfig": {"Enabled": True},
+ })
+ assert code == 201
+ try:
+ # Touch unrelated config.
+ lam.update_function_configuration(FunctionName=fname, Timeout=60, MemorySize=256)
+ code, body = _raw_durable("GET", f"/2015-03-31/functions/{fname}")
+ assert body["Configuration"].get("DurableConfig") == {"Enabled": True}, \
+ f"DurableConfig lost after Update: {body['Configuration'].get('DurableConfig')}"
+ finally:
+ try: lam.delete_function(FunctionName=fname)
+ except Exception: pass
diff --git a/tests/test_s3.py b/tests/test_s3.py
index d868cf0f..28a0f05d 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -808,6 +808,52 @@ def test_s3_object_tagging(s3):
assert tags["status"] == "active"
assert tags["priority"] == "high"
+
+def test_s3_object_tagging_per_version(s3):
+ """Tags must be stored per object version, not collapsed onto the key.
+
+ Repro for #N: in a versioned bucket, tagging two versions of the same
+ object resulted in only the last-written tag set being returned for
+ either version.
+ """
+ bkt = "intg-s3-objtags-versioned"
+ s3.create_bucket(Bucket=bkt)
+ s3.put_bucket_versioning(
+ Bucket=bkt, VersioningConfiguration={"Status": "Enabled"}
+ )
+
+ v1 = s3.put_object(Bucket=bkt, Key="k", Body=b"one")["VersionId"]
+ v2 = s3.put_object(Bucket=bkt, Key="k", Body=b"two")["VersionId"]
+ assert v1 and v2 and v1 != v2
+
+ s3.put_object_tagging(
+ Bucket=bkt, Key="k", VersionId=v1,
+ Tagging={"TagSet": [{"Key": "ver", "Value": "1"}]},
+ )
+ s3.put_object_tagging(
+ Bucket=bkt, Key="k", VersionId=v2,
+ Tagging={"TagSet": [{"Key": "ver", "Value": "2"}]},
+ )
+
+ g1 = s3.get_object_tagging(Bucket=bkt, Key="k", VersionId=v1)
+ g2 = s3.get_object_tagging(Bucket=bkt, Key="k", VersionId=v2)
+ assert {t["Key"]: t["Value"] for t in g1["TagSet"]} == {"ver": "1"}
+ assert {t["Key"]: t["Value"] for t in g2["TagSet"]} == {"ver": "2"}
+ assert g1["VersionId"] == v1
+ assert g2["VersionId"] == v2
+
+ # GetObjectTagging without VersionId targets the current version (v2).
+ g_current = s3.get_object_tagging(Bucket=bkt, Key="k")
+ assert {t["Key"]: t["Value"] for t in g_current["TagSet"]} == {"ver": "2"}
+
+ # DeleteObjectTagging on v1 must not touch v2's tag set.
+ s3.delete_object_tagging(Bucket=bkt, Key="k", VersionId=v1)
+ g1_after = s3.get_object_tagging(Bucket=bkt, Key="k", VersionId=v1)
+ g2_after = s3.get_object_tagging(Bucket=bkt, Key="k", VersionId=v2)
+ assert g1_after["TagSet"] == []
+ assert {t["Key"]: t["Value"] for t in g2_after["TagSet"]} == {"ver": "2"}
+
+
def test_s3_public_access_block(s3):
bkt = "intg-s3-pab"
s3.create_bucket(Bucket=bkt)