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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ A second delivery of a job is answered like the first and ignored, while the job
2. A second delivery of a known job gets HTTP 202 after the `terminate` hook. That hook fails a running job's callback. So the durable function learns the outcome from the callback.
3. A second delivery of a running job gets HTTP 503 during a suspend refusal, as a new job does. The running job can freeze with the MicroVM. A 202 would end the delivery, and nothing would resume the MicroVM. The job would then wait for its heartbeat timeout or its timeout. The 503 makes the durable function deliver the job again. The service resumes the MicroVM on that request. That delivery gets HTTP 202, and the job completes once.

The worker creates a Lambda client for each job, after the job arrives, not at image build. A client created before the snapshot would carry build-time state into every MicroVM. A client kept across jobs would keep connections that a suspend of the MicroVM can leave dead. The worker closes each job's default client when the job ends. It never closes a client from `create_client`.
The worker creates a Lambda client for each job, after the job arrives, not at image build. A client created before the snapshot would carry build-time state into every MicroVM. A client kept across jobs would keep connections that a suspend of the MicroVM can leave dead. The worker closes each job's default client when the job ends. It never closes a client from `create_client`, and uses it as it is with its own user agent.

A document that does not match the contract gets HTTP 400 with the validation message. If the document named a callback, the worker also fails that callback, so the durable function fails at once instead of at its timeout. A request whose body cannot be read gets HTTP 400 with a generic message, and the error is logged. The worker accepts a `run` hook body of at most 64 KiB and a job request body of at most 6 MiB, with a `Content-Length` or with chunked transfer encoding. In a chunked body, the chunk-size lines, their extensions, and the trailers have a limit of their own, of the same size. A larger body gets HTTP 400. The worker sends it without reading the body, and then closes the connection. The unread bytes make the kernel send a TCP reset in place of a normal close. So a client that is still sending can get the reset before it reads the 400. A request with `Expect: 100-continue` first gets `100 Continue`, as `http.server` sends it. The client then sends the body, and gets the 400 or the reset in the same way. The MicroVM operations of the JS package (`@aws/durable-execution-sdk-js-extras`) and the Python package (`aws-durable-execution-sdk-python-extensions`) reject a job input that does not fit before they send the job. So only another sender can get the reset. Other lifecycle hooks get HTTP 200. Other paths get HTTP 404.

Expand All @@ -90,7 +90,7 @@ A session's run hook payload can set `autoSuspendIdleSeconds`. The session sets

The worker counts only jobs. It cannot see background threads or processes, or inbound traffic that is not a job. A session with such work leaves `auto_suspend_on_idle` off, and the payload then has no `autoSuspendIdleSeconds`.

The worker creates a `lambda-microvms` client for each suspend, and closes it after the call. Pass `create_microvms_client` to provide the client. The worker never closes a client that it returns. Give the client one attempt, as the default client has. The worker starts no attempt after a `resume` hook. A retry that starts before the `resume` hook arrives can still suspend the MicroVM after it resumed. A client that retries must report its retries in `ResponseMetadata.RetryAttempts` of the error that it raises, as botocore does. The worker otherwise counts a retried call as a first attempt. An earlier attempt of that call may have suspended the MicroVM. So a retried throttle would count as refused for now, and the worker would accept a job that then freezes with the MicroVM.
The worker creates a `lambda-microvms` client for each suspend, and closes it after the call. Pass `create_microvms_client` to provide the client. The worker never closes a client that it returns, and uses it as it is with its own user agent. Give the client one attempt, as the default client has. The worker starts no attempt after a `resume` hook. A retry that starts before the `resume` hook arrives can still suspend the MicroVM after it resumed. A client that retries must report its retries in `ResponseMetadata.RetryAttempts` of the error that it raises, as botocore does. The worker otherwise counts a retried call as a first attempt. An earlier attempt of that call may have suspended the MicroVM. So a retried throttle would count as refused for now, and the worker would accept a job that then freezes with the MicroVM.

## Suspending after a job

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# SPDX-FileCopyrightText: 2026-present Amazon.com, Inc. or its affiliates.
#
# SPDX-License-Identifier: Apache-2.0
"""User-agent marker for default boto3 clients in this package."""

from __future__ import annotations

from aws_durable_execution_sdk_python_compute_worker.__about__ import __version__


def user_agent_extra(feature: str) -> str:
"""Return the ``user_agent_extra`` string for ``feature``."""
return f"aws-durable-execution-sdk-python-compute-worker/{__version__} md/{feature}"
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,9 @@ def _run_job_and_report(
fields: dict[str, object],
) -> None:
reporter = (
CallbackReporter.create(job.callback_id, region, logger=self._logger)
CallbackReporter.create(
job.callback_id, region, logger=self._logger, feature="agentcore"
)
if self._create_client is None
else CallbackReporter(
job.callback_id, self._create_client(region), logger=self._logger
Expand Down Expand Up @@ -492,7 +494,8 @@ def start_agentcore_worker(
create_client: Creates the Lambda client for the callback calls of
one job, from the durable function's Region. Defaults to a boto3
client with the default credential chain, which resolves the
agent runtime's execution role.
agent runtime's execution role. A client that this function
returns is used as it is and keeps its own user agent.
heartbeat_interval_seconds: An explicit heartbeat interval. It is cut
to a third of the job's heartbeat timeout.
host: The address to listen on. ``None`` picks ``0.0.0.0``, which
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
from botocore.config import Config
from botocore.exceptions import ClientError, NoCredentialsError


from aws_durable_execution_sdk_python_compute_worker._user_agent import (
user_agent_extra,
)
from aws_durable_execution_sdk_python_compute_worker.microvm.logger import (
MicrovmWorkerLogger,
safe_get,
Expand Down Expand Up @@ -272,7 +274,7 @@ def _is_uncertain_outcome(error: BaseException) -> bool:
return status is None or status >= 500


def _create_client(region: str) -> LambdaClient:
def _create_client(region: str, *, feature: str = "microvm") -> LambdaClient:
# Each reporter gets its own session. boto3's default session is not safe
# to use from several threads at once, and the worker runs one thread per
# job.
Expand All @@ -284,6 +286,7 @@ def _create_client(region: str) -> LambdaClient:
read_timeout=COMPLETION_CALL_TIMEOUT_SECONDS,
retries={"mode": "standard", "max_attempts": 3},
tcp_keepalive=True,
user_agent_extra=user_agent_extra(feature),
),
)

Expand Down Expand Up @@ -328,18 +331,32 @@ def create(
region: str,
*,
logger: MicrovmWorkerLogger | None = None,
feature: str = "microvm",
) -> CallbackReporter:
"""Create a reporter with its own client for ``region``.

The client uses the default credential chain. Inside a MicroVM, that
chain resolves the MicroVM's execution role. :meth:`close` closes the
client.

Args:
callback_id: The callback ID from the job document.
region: The Region of the durable function.
logger: Receives warnings and errors. Defaults to the package's
standard library logger.
feature: Feature marker in the default client's user agent,
for example ``"microvm"`` or ``"agentcore"``.

Raises:
botocore.exceptions.BotoCoreError: When boto3 cannot create the
client, for example for an unknown ``AWS_PROFILE``.
"""
return cls(callback_id, _create_client(region), owns_client=True, logger=logger)
return cls(
callback_id,
_create_client(region, feature=feature),
owns_client=True,
logger=logger,
)

def close(self) -> None:
"""Release the connections of a client that the reporter created."""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
from botocore.config import Config
from botocore.exceptions import ClientError, NoCredentialsError

from aws_durable_execution_sdk_python_compute_worker._user_agent import (
user_agent_extra,
)
from aws_durable_execution_sdk_python_compute_worker.microvm.callback_reporter import (
TRANSIENT_4XX_CODES,
error_code,
Expand Down Expand Up @@ -143,6 +146,7 @@ def create_microvms_client(region: str) -> LambdaMicrovmsClient:
# total_max_attempts counts the first attempt too.
"total_max_attempts": _CLIENT_ATTEMPTS,
},
user_agent_extra=user_agent_extra("microvm"),
),
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -554,17 +554,18 @@ def create(
create_client: Creates the Lambda client for a Region. The
listener calls it for each job, after the job arrives, and to
fail the callback of an invalid request. It never closes a
client that this function returns. Defaults to a client of
its own per job, from the default credential chain. The
listener closes that client when the job ends.
client that this function returns, and uses it as it is with
its own user agent. Defaults to a client of its own per job,
from the default credential chain. The listener closes that
client when the job ends.
create_microvms_client: Creates the ``lambda-microvms`` client
that suspends this MicroVM. The listener calls it only when
a session asks the worker to suspend when idle, once per
suspend. It never closes a client that this function
returns. Defaults to a client of
its own per suspend, from the default credential chain. The
listener closes that client after the call. The listener
stops the client's attempts once a ``resume`` hook arrived.
returns, and uses it as it is with its own user agent.
Defaults to a client of its own per suspend, from the default
credential chain. The listener closes that client after the
call. The listener stops the client's attempts once a ``resume`` hook arrived.
Give the client one attempt, as the default client has. A
retry that starts before the ``resume`` hook arrives can
still suspend the MicroVM after it resumed. A client that
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -632,10 +632,16 @@ def test_creates_its_own_reporter_without_create_client(
fake_client: Any, logger: Any, monkeypatch: pytest.MonkeyPatch
) -> None:
client = fake_client()
regions: list[str] = []

def create(callback_id: str, region: str, *, logger: Any = None) -> Any:
regions.append(region)
calls: list[tuple[str, str]] = []

def create(
callback_id: str,
region: str,
*,
logger: Any = None,
feature: str = "microvm",
) -> Any:
calls.append((region, feature))
return CallbackReporter(callback_id, client, logger=logger)

monkeypatch.setattr(worker_module.CallbackReporter, "create", create)
Expand All @@ -651,7 +657,7 @@ def create(callback_id: str, region: str, *, logger: Any = None) -> Any:
finally:
worker.close()

assert regions == ["us-west-2"]
assert calls == [("us-west-2", "agentcore")]
assert client.names() == ["success"]


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from botocore.exceptions import BotoCoreError, NoCredentialsError
from botocore.stub import Stubber

from aws_durable_execution_sdk_python_compute_worker.__about__ import __version__
from aws_durable_execution_sdk_python_compute_worker.microvm import callback_reporter
from aws_durable_execution_sdk_python_compute_worker.microvm.callback_reporter import (
CLOSED_CALLBACK_CODE,
Expand Down Expand Up @@ -414,7 +415,7 @@ def send_durable_execution_callback_heartbeat(self, **_kwargs: Any) -> dict:
def test_the_given_client_is_used_and_no_client_is_created(monkeypatch):
"""__init__ only assigns. A falsy test double is used as given."""

def fail_create(_region: str) -> Any:
def fail_create(_region: str, *, feature: str = "microvm") -> Any:
msg = "the reporter created its own client"
raise AssertionError(msg)

Expand All @@ -430,16 +431,16 @@ def test_reporter_closes_only_its_own_client(fake_client, monkeypatch):
assert passed.closed is False

created = fake_client()
regions: list[str] = []
calls: list[tuple[str, str]] = []

def create(region: str) -> Any:
regions.append(region)
def create(region: str, *, feature: str = "microvm") -> Any:
calls.append((region, feature))
return created

monkeypatch.setattr(callback_reporter, "_create_client", create)
owned = CallbackReporter.create("cb-1", "eu-west-1")
owned.close()
assert regions == ["eu-west-1"]
assert calls == [("eu-west-1", "microvm")]
assert created.closed is True


Expand Down Expand Up @@ -477,4 +478,26 @@ def test_requests_match_the_lambda_api_model():
client.close()


def test_default_client_sets_user_agent() -> None:
client: Any = callback_reporter._create_client("us-east-1") # noqa: SLF001
try:
assert client.meta.config.user_agent_extra == (
f"aws-durable-execution-sdk-python-compute-worker/{__version__} md/microvm"
)
finally:
client.close()

agentcore_reporter = CallbackReporter.create(
"cb-1", "us-east-1", feature="agentcore"
)
try:
agentcore_client: Any = agentcore_reporter._client # noqa: SLF001
assert agentcore_client.meta.config.user_agent_extra == (
f"aws-durable-execution-sdk-python-compute-worker/{__version__}"
" md/agentcore"
)
finally:
agentcore_reporter.close()


# endregion client
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
)
from botocore.retries.standard import ExponentialBackoff

from aws_durable_execution_sdk_python_compute_worker.__about__ import __version__
from aws_durable_execution_sdk_python_compute_worker.microvm.self_suspend import (
SUSPEND_CALL_TIMEOUT_SECONDS,
SuspendDeadlineError,
Expand Down Expand Up @@ -184,6 +185,16 @@ def test_the_default_client_ends_a_read_at_the_call_timeout() -> None:
client.close()


def test_default_client_sets_user_agent() -> None:
client: Any = create_microvms_client("us-west-2")
try:
assert client.meta.config.user_agent_extra == (
f"aws-durable-execution-sdk-python-compute-worker/{__version__} md/microvm"
)
finally:
client.close()


class _Body:
def __init__(self, data: bytes) -> None:
self._data = data
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -571,7 +571,8 @@ def test_creates_a_default_client_per_job_and_closes_it(
) -> None:
created: list[Any] = []

def create_client(region: str) -> Any:
def create_client(region: str, *, feature: str = "microvm") -> Any:
assert feature == "microvm"
client = fake_client()
created.append(client)
return client
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ on_a_server = decider(
```

- A `transport` takes precedence. When it is set, `endpoint` and `headers` are not used. Without either, `decider()` uses the `STRANDS_DECIDER_ENDPOINT` environment variable. It raises `TypeError` when that is not set, because it then has nowhere to send the request.
- The AWS transports use boto3, which this package already depends on. They sign the call with the function's credentials. Each one takes `client=` to replace the default boto3 client, for example to set a Region.
- The AWS transports use boto3, which this package already depends on. They sign the call with the function's credentials. Each one takes `client=` to replace the default boto3 client, for example to set a Region. A client that you pass is used as it is and keeps its own user agent.
- A transport is any callable that takes a `DeciderRequest` dict and returns the JSON reply. An exception it raises goes to the step retry strategy. The step calls it directly, so a transport that can hang needs its own timeout.
- On SageMaker and AgentCore Runtime, the call reaches the server's `POST /invocations` route. The Strands Decider server answers that route like `/v1/systemone`. The 0.2.0 release on PyPI has no `/invocations` route, so deploy a later version.
- On SageMaker, an HTTP error from the server becomes a `DeciderError` with the server's status.
Expand Down Expand Up @@ -103,7 +103,7 @@ short = model.ask(context, "Summarize.", text, max_tokens=100)

- The default model is Claude Haiku 5.5 (`global.anthropic.claude-haiku-5-5`, exported as `DEFAULT_LLM_MODEL_ID`). Bedrock has no alias that follows the newest model of a family. So the default is pinned, and a later release moves it to a newer model. Set `model_id` to keep one model.
- It sends a temperature only when you set `temperature`, because some newer models, such as Claude Haiku 5.5, reject it.
- `system` adds your own instructions after the built-in system prompt. `guardrail=BedrockGuardrail(identifier=..., version=...)` applies a Bedrock guardrail. `client` replaces the default `bedrock-runtime` client, for example to set a Region.
- `system` adds your own instructions after the built-in system prompt. `guardrail=BedrockGuardrail(identifier=..., version=...)` applies a Bedrock guardrail. `client` replaces the default `bedrock-runtime` client, for example to set a Region. A client that you pass is used as it is and keeps its own user agent.
- Converse's `end_turn` and `stop_sequence` become `"end"`. Other stop reasons pass through, and a reply with none has `stop_reason=None`.

### A model that is not on Bedrock
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,7 @@ The MicroVM operations handle the network, the service, and the worker lifecycle
### Custom clients and tests

1. A `client` that you pass must behave as a boto3 `lambda-microvms` client.
- It is used as it is and keeps its own user agent.
- It returns outputs in the boto3 shape, with `ResponseMetadata`. A `RunMicrovm` output without `microvmId`, or without `endpoint` for HTTP delivery, fails the launch with `MicrovmLaunchError`. An output without `ResponseMetadata.RequestId` gives error messages without a request ID.
- It raises botocore `ClientError` with a `response` that holds `Error.Code` and `ResponseMetadata.HTTPStatusCode`. The default strategy reads both. It fails the step at once for an error of any other class, unless the error is a timeout or a connection failure.
- It sets connect and read timeouts, such as the 5 and 30 seconds of the default client. botocore's own defaults are 60 seconds each. A `RunMicrovm` or `TerminateMicrovm` call that runs past the function timeout records no outcome for its step attempt. So the step runs again. A `CreateMicrovmAuthToken` or `GetMicrovm` call that reaches the invocation reserve fails its attempt. Its thread keeps running until the call returns. So the call can still reach the service after the step stopped waiting for it.
Expand Down
Loading
Loading