diff --git a/packages/aws-durable-execution-sdk-python-compute-worker/docs/worker.md b/packages/aws-durable-execution-sdk-python-compute-worker/docs/worker.md index a1e53cb43..869f8d158 100644 --- a/packages/aws-durable-execution-sdk-python-compute-worker/docs/worker.md +++ b/packages/aws-durable-execution-sdk-python-compute-worker/docs/worker.md @@ -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. @@ -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 diff --git a/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/_user_agent.py b/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/_user_agent.py new file mode 100644 index 000000000..e2f23d6a9 --- /dev/null +++ b/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/_user_agent.py @@ -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}" diff --git a/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/agentcore/worker.py b/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/agentcore/worker.py index 32b007fb6..2c2f75069 100644 --- a/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/agentcore/worker.py +++ b/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/agentcore/worker.py @@ -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 @@ -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 diff --git a/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/microvm/callback_reporter.py b/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/microvm/callback_reporter.py index 1888fbddc..fe3846b39 100644 --- a/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/microvm/callback_reporter.py +++ b/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/microvm/callback_reporter.py @@ -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, @@ -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. @@ -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), ), ) @@ -328,6 +331,7 @@ def create( region: str, *, logger: MicrovmWorkerLogger | None = None, + feature: str = "microvm", ) -> CallbackReporter: """Create a reporter with its own client for ``region``. @@ -335,11 +339,24 @@ def create( 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.""" diff --git a/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/microvm/self_suspend.py b/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/microvm/self_suspend.py index 7a12b4560..f6367ad76 100644 --- a/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/microvm/self_suspend.py +++ b/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/microvm/self_suspend.py @@ -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, @@ -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"), ), ) diff --git a/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/microvm/worker.py b/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/microvm/worker.py index e8c3df934..e568b74b6 100644 --- a/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/microvm/worker.py +++ b/packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/microvm/worker.py @@ -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 diff --git a/packages/aws-durable-execution-sdk-python-compute-worker/tests/agentcore/agentcore_worker_test.py b/packages/aws-durable-execution-sdk-python-compute-worker/tests/agentcore/agentcore_worker_test.py index 699c8c781..9116ad367 100644 --- a/packages/aws-durable-execution-sdk-python-compute-worker/tests/agentcore/agentcore_worker_test.py +++ b/packages/aws-durable-execution-sdk-python-compute-worker/tests/agentcore/agentcore_worker_test.py @@ -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) @@ -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"] diff --git a/packages/aws-durable-execution-sdk-python-compute-worker/tests/microvm/callback_reporter_test.py b/packages/aws-durable-execution-sdk-python-compute-worker/tests/microvm/callback_reporter_test.py index 656287ec7..4ba579021 100644 --- a/packages/aws-durable-execution-sdk-python-compute-worker/tests/microvm/callback_reporter_test.py +++ b/packages/aws-durable-execution-sdk-python-compute-worker/tests/microvm/callback_reporter_test.py @@ -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, @@ -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) @@ -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 @@ -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 diff --git a/packages/aws-durable-execution-sdk-python-compute-worker/tests/microvm/self_suspend_test.py b/packages/aws-durable-execution-sdk-python-compute-worker/tests/microvm/self_suspend_test.py index a7240c073..9d2f8bb7e 100644 --- a/packages/aws-durable-execution-sdk-python-compute-worker/tests/microvm/self_suspend_test.py +++ b/packages/aws-durable-execution-sdk-python-compute-worker/tests/microvm/self_suspend_test.py @@ -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, @@ -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 diff --git a/packages/aws-durable-execution-sdk-python-compute-worker/tests/microvm/worker_test.py b/packages/aws-durable-execution-sdk-python-compute-worker/tests/microvm/worker_test.py index c40ae8bdd..cd04e4af8 100644 --- a/packages/aws-durable-execution-sdk-python-compute-worker/tests/microvm/worker_test.py +++ b/packages/aws-durable-execution-sdk-python-compute-worker/tests/microvm/worker_test.py @@ -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 diff --git a/packages/aws-durable-execution-sdk-python-extensions/docs/ai.md b/packages/aws-durable-execution-sdk-python-extensions/docs/ai.md index 089f1cf62..0869e53d0 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/docs/ai.md +++ b/packages/aws-durable-execution-sdk-python-extensions/docs/ai.md @@ -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. @@ -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 diff --git a/packages/aws-durable-execution-sdk-python-extensions/docs/microvm.md b/packages/aws-durable-execution-sdk-python-extensions/docs/microvm.md index 3e4d8a523..40002d82e 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/docs/microvm.md +++ b/packages/aws-durable-execution-sdk-python-extensions/docs/microvm.md @@ -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. diff --git a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/_user_agent.py b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/_user_agent.py new file mode 100644 index 000000000..96d390bbc --- /dev/null +++ b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/_user_agent.py @@ -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_extensions.__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-extensions/{__version__} md/{feature}" diff --git a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/ai/_shared.py b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/ai/_shared.py index 9d8d9fcd3..432d89d50 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/ai/_shared.py +++ b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/ai/_shared.py @@ -16,7 +16,9 @@ from aws_durable_execution_sdk_python.exceptions import StepError from aws_durable_execution_sdk_python.retries import RetryDecision from aws_durable_execution_sdk_python.serdes import JsonSerDes +from botocore.config import Config +from aws_durable_execution_sdk_python_extensions._user_agent import user_agent_extra from aws_durable_execution_sdk_python_extensions.ai.errors import ( AiError, DeciderInvalidResponseError, @@ -130,5 +132,8 @@ def __init__(self, service: str, client: Any) -> None: def get(self) -> Any: with self._lock: if self._client is None: - self._client = boto3.client(self._service) # type: ignore[call-overload] + self._client = boto3.client( # type: ignore[call-overload] + self._service, + config=Config(user_agent_extra=user_agent_extra("ai")), + ) return self._client diff --git a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/ai/llm.py b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/ai/llm.py index 32f3b686c..18b34c3ca 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/ai/llm.py +++ b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/ai/llm.py @@ -130,7 +130,8 @@ class BedrockConfig: the function's Region and account.""" client: Any = None """A ``bedrock-runtime`` boto3 client. The default client uses the - function's Region and credentials.""" + function's Region and credentials. A client that you pass is used as it + is and keeps its own user agent.""" temperature: float | None = None """The sampling temperature. It is sent only when set, because some newer models, such as Claude Haiku 5.5, reject it.""" diff --git a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/ai/transports.py b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/ai/transports.py index b7957e8cd..4120336e4 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/ai/transports.py +++ b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/ai/transports.py @@ -98,7 +98,8 @@ def agentcore_transport( qualifier: The runtime endpoint name. The default is the runtime's default endpoint. client: A ``bedrock-agentcore`` boto3 client. The default client uses - the function's Region and credentials. + the function's Region and credentials. A client that you pass is + used as it is and keeps its own user agent. """ lazy = LazyClient("bedrock-agentcore", client) @@ -158,7 +159,8 @@ def sagemaker_transport(endpoint_name: str, *, client: Any = None) -> DeciderTra endpoint_name: The name of the SageMaker endpoint that serves the model. client: A ``sagemaker-runtime`` boto3 client. The default client uses - the function's Region and credentials. + the function's Region and credentials. A client that you pass is + used as it is and keeps its own user agent. """ lazy = LazyClient("sagemaker-runtime", client) @@ -235,7 +237,8 @@ def lambda_transport( qualifier: The version or alias to invoke, such as ``live``. The default is ``$LATEST``. client: A ``lambda`` boto3 client. The default client uses the - function's Region and credentials. + function's Region and credentials. A client that you pass is + used as it is and keeps its own user agent. """ lazy = LazyClient("lambda", client) diff --git a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/agentcore/config.py b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/agentcore/config.py index bdc4e7062..73e96e8da 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/agentcore/config.py +++ b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/agentcore/config.py @@ -114,7 +114,8 @@ class AgentcoreConfig: Defaults to one client per Region, created on first use. The Region comes from the agent runtime ARN. The default client has a 5-second connect timeout, a 60-second read timeout, and 3 attempts in botocore's standard - retry mode. A client that you pass keeps its own settings. + retry mode. A client that you pass is used as it is and keeps its own + settings, including its user agent. """ @@ -167,7 +168,8 @@ class AgentcoreSessionConfig: """The boto3 ``bedrock-agentcore`` client. Defaults to one client per Region, created on first use, as in - :attr:`AgentcoreConfig.client`. + :attr:`AgentcoreConfig.client`. A client that you pass is used as it is + and keeps its own settings, including its user agent. """ diff --git a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/agentcore/operation.py b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/agentcore/operation.py index a2a09904f..46694701b 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/agentcore/operation.py +++ b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/agentcore/operation.py @@ -37,6 +37,7 @@ from botocore.config import Config from botocore.exceptions import ClientError +from aws_durable_execution_sdk_python_extensions._user_agent import user_agent_extra from aws_durable_execution_sdk_python_extensions.compute.agentcore.config import ( AgentcoreConfig, AgentcoreSessionConfig, @@ -728,6 +729,7 @@ def get(self, region: str) -> BedrockAgentcoreClient: "mode": "standard", "total_max_attempts": _CLIENT_ATTEMPTS, }, + user_agent_extra=user_agent_extra("agentcore"), ), ) self._clients[region] = client diff --git a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/microvm/config.py b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/microvm/config.py index 023d1b94d..06868c2b5 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/microvm/config.py +++ b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/microvm/config.py @@ -183,9 +183,10 @@ class MicrovmBaseConfig: Defaults to one client per Region, created on first use. The Region comes from the durable execution ARN. The default client has a 5-second connect timeout, a 30-second read timeout, and 3 attempts in botocore's standard - retry mode. A client that you pass keeps its own settings. Keep each call - shorter than the function's timeout, because a call that runs past it - records no outcome for the step attempt. + retry mode. A client that you pass is used as it is and keeps its own + settings, including its user agent. Keep each call shorter than the + function's timeout, because a call that runs past it records no outcome + for the step attempt. """ diff --git a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/microvm/operation.py b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/microvm/operation.py index ea517fef2..458d2e9bc 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/microvm/operation.py +++ b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/microvm/operation.py @@ -34,6 +34,7 @@ from aws_durable_execution_sdk_python.serdes import JsonSerDes from botocore.exceptions import ClientError +from aws_durable_execution_sdk_python_extensions._user_agent import user_agent_extra from aws_durable_execution_sdk_python_extensions.compute.microvm.aws_errors import ( add_request_id, decide_on_original_error, @@ -1108,6 +1109,7 @@ def get(self, region: str) -> LambdaMicrovmsClient: # max_attempts would count only the retries. "total_max_attempts": _CLIENT_ATTEMPTS, }, + user_agent_extra=user_agent_extra("microvm"), ), ) self._clients[region] = client diff --git a/packages/aws-durable-execution-sdk-python-extensions/tests/ai/llm_test.py b/packages/aws-durable-execution-sdk-python-extensions/tests/ai/llm_test.py index c3702b1d3..884cb9389 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/tests/ai/llm_test.py +++ b/packages/aws-durable-execution-sdk-python-extensions/tests/ai/llm_test.py @@ -13,6 +13,7 @@ from aws_durable_execution_sdk_python.retries import RetryDecision from botocore.stub import Stubber +from aws_durable_execution_sdk_python_extensions.__about__ import __version__ from aws_durable_execution_sdk_python_extensions.ai import ( DEFAULT_LLM_MODEL_ID, BedrockConfig, @@ -169,7 +170,7 @@ def test_llm_defaults_to_the_bedrock_transport( client = FakeBedrock(reply("Paris")) created: list[str] = [] - def fake_client(service: str) -> Any: + def fake_client(service: str, **_kwargs: Any) -> Any: created.append(service) return client @@ -286,6 +287,37 @@ def body(context: Any) -> Any: assert len(client.calls) == 1 +def test_default_client_sets_user_agent(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("AWS_DEFAULT_REGION", "us-east-1") + original: Any = boto3.client + created: list[Any] = [] + stubbers: list[Stubber] = [] + + def spy_client(service: str, **kwargs: Any) -> Any: + client = original(service, **kwargs) + stubber = Stubber(client) + stubber.add_response("converse", reply("ok")) + stubber.activate() + created.append(client) + stubbers.append(stubber) + return client + + monkeypatch.setattr(boto3, "client", spy_client) + send = bedrock_transport() + request = LlmRequest(system="s", prompt="Question: Q?", max_tokens=8) + try: + assert send(request) == LlmReply(text="ok", stop_reason="end") + [client] = created + assert client.meta.config.user_agent_extra == ( + f"aws-durable-execution-sdk-python-extensions/{__version__} md/ai" + ) + finally: + for stubber in stubbers: + stubber.deactivate() + for client in created: + client.close() + + class FakeTransport: """Records each request and answers from a list.""" diff --git a/packages/aws-durable-execution-sdk-python-extensions/tests/ai/transports_test.py b/packages/aws-durable-execution-sdk-python-extensions/tests/ai/transports_test.py index e917e4c3e..8159ddaab 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/tests/ai/transports_test.py +++ b/packages/aws-durable-execution-sdk-python-extensions/tests/ai/transports_test.py @@ -15,6 +15,7 @@ from botocore.exceptions import ClientError from botocore.stub import Stubber +from aws_durable_execution_sdk_python_extensions.__about__ import __version__ from aws_durable_execution_sdk_python_extensions.ai import ( DeciderError, DeciderInvalidResponseError, @@ -359,7 +360,7 @@ def test_creates_the_default_client_on_first_use( made: list[str] = [] client = FakeClient("invoke_endpoint", {"Body": stream(json.dumps(REPLY))}) - def fake_client(service: str) -> Any: + def fake_client(service: str, *, config: Any = None) -> Any: made.append(service) return client @@ -370,3 +371,63 @@ def fake_client(service: str) -> Any: send(REQUEST) assert made == ["sagemaker-runtime"] + + +@pytest.mark.parametrize( + ("make_transport", "operation_name", "response"), + [ + ( + lambda client=None: agentcore_transport(ARN, client=client), + "invoke_agent_runtime", + { + "contentType": "application/json", + "statusCode": 200, + "response": stream(json.dumps(REPLY)), + }, + ), + ( + lambda client=None: sagemaker_transport(ENDPOINT, client=client), + "invoke_endpoint", + {"Body": stream(json.dumps(REPLY))}, + ), + ( + lambda client=None: lambda_transport(FUNCTION, client=client), + "invoke", + {"StatusCode": 200, "Payload": stream(json.dumps(REPLY))}, + ), + ], + ids=["agentcore", "sagemaker", "lambda"], +) +def test_default_transport_client_sets_user_agent( + monkeypatch: pytest.MonkeyPatch, + make_transport: Any, + operation_name: str, + response: dict[str, Any], +) -> None: + monkeypatch.setenv("AWS_DEFAULT_REGION", "us-east-1") + original: Any = boto3.client + created: list[Any] = [] + stubbers: list[Stubber] = [] + + def spy_client(service: str, **kwargs: Any) -> Any: + client = original(service, **kwargs) + stubber = Stubber(client) + stubber.add_response(operation_name, response) + stubber.activate() + created.append(client) + stubbers.append(stubber) + return client + + monkeypatch.setattr(boto3, "client", spy_client) + send = make_transport() + try: + assert send(REQUEST) == REPLY + [client] = created + assert client.meta.config.user_agent_extra == ( + f"aws-durable-execution-sdk-python-extensions/{__version__} md/ai" + ) + finally: + for stubber in stubbers: + stubber.deactivate() + for client in created: + client.close() diff --git a/packages/aws-durable-execution-sdk-python-extensions/tests/compute/agentcore/agentcore_operation_test.py b/packages/aws-durable-execution-sdk-python-extensions/tests/compute/agentcore/agentcore_operation_test.py index 39d92f7a7..eafdc12ec 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/tests/compute/agentcore/agentcore_operation_test.py +++ b/packages/aws-durable-execution-sdk-python-extensions/tests/compute/agentcore/agentcore_operation_test.py @@ -36,6 +36,7 @@ from botocore.response import StreamingBody from botocore.stub import ANY, Stubber +from aws_durable_execution_sdk_python_extensions.__about__ import __version__ from aws_durable_execution_sdk_python_extensions.compute.agentcore import ( MAX_JOB_INPUT_BYTES, AgentcoreConfig, @@ -499,6 +500,17 @@ def test_default_clients_creates_one_client_per_region() -> None: assert clients.get("eu-west-1") is not first +def test_default_client_sets_user_agent() -> None: + clients = operation._DefaultClients() # noqa: SLF001 + client: Any = clients.get("us-west-2") + try: + assert client.meta.config.user_agent_extra == ( + f"aws-durable-execution-sdk-python-extensions/{__version__} md/agentcore" + ) + finally: + client.close() + + @pytest.mark.parametrize( ("error", "retried"), [ diff --git a/packages/aws-durable-execution-sdk-python-extensions/tests/compute/microvm/validation_test.py b/packages/aws-durable-execution-sdk-python-extensions/tests/compute/microvm/validation_test.py index 0e3eef6f4..cb97304db 100644 --- a/packages/aws-durable-execution-sdk-python-extensions/tests/compute/microvm/validation_test.py +++ b/packages/aws-durable-execution-sdk-python-extensions/tests/compute/microvm/validation_test.py @@ -12,6 +12,7 @@ from aws_durable_execution_sdk_python.config import Duration from aws_durable_execution_sdk_python.exceptions import ValidationError +from aws_durable_execution_sdk_python_extensions.__about__ import __version__ from aws_durable_execution_sdk_python_extensions.compute.microvm import ( MAX_JOB_INPUT_BYTES, MicrovmConfig, @@ -300,6 +301,17 @@ def client(self, service: str, region_name: str, config: Any) -> object: assert configs[0].retries == {"mode": "standard", "total_max_attempts": 3} +def test_default_client_sets_user_agent() -> None: + clients = operation._DefaultClients() # noqa: SLF001 + client: Any = clients.get("us-east-1") + try: + assert client.meta.config.user_agent_extra == ( + f"aws-durable-execution-sdk-python-extensions/{__version__} md/microvm" + ) + finally: + client.close() + + def test_takes_the_input_and_the_config_by_keyword_only() -> None: with pytest.raises(TypeError, match="positional argument"): microvm(NoOperations(), "build", {}, config()) # type: ignore[arg-type, misc]