From 68094c2935069a51e338e9be9df9fe8a291d6185 Mon Sep 17 00:00:00 2001 From: SRI VILLIAM SAI Date: Wed, 25 Nov 2026 20:58:19 +0530 Subject: [PATCH 1/3] test: assert default client user agent markers Add tests checking user_agent_extra on every default boto3 client in extensions and compute-worker and verifying caller-provided clients keep their own user agent. --- .../tests/microvm/callback_reporter_test.py | 28 +++++ .../tests/microvm/self_suspend_test.py | 11 ++ .../tests/ai/llm_test.py | 53 ++++++++ .../tests/ai/transports_test.py | 119 +++++++++++++++++- .../agentcore/agentcore_operation_test.py | 27 ++++ .../tests/compute/microvm/validation_test.py | 34 +++++ 6 files changed, 271 insertions(+), 1 deletion(-) 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..5bcc87245 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 @@ -12,10 +12,13 @@ import time from typing import Any +import boto3 import pytest +from botocore.config import Config 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, @@ -477,4 +480,29 @@ 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() + + +def test_passed_client_keeps_its_user_agent() -> None: + custom: Any = boto3.session.Session().client( + "lambda", + region_name="us-east-1", + config=Config(user_agent_extra="custom-agent/1.0"), + ) + try: + reporter = CallbackReporter("cb-1", custom) + assert reporter._client is custom # noqa: SLF001 + client_config: Any = custom.meta.config + assert client_config.user_agent_extra == "custom-agent/1.0" + finally: + custom.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-extensions/tests/ai/llm_test.py b/packages/aws-durable-execution-sdk-python-extensions/tests/ai/llm_test.py index a64c023e8..8bdf6aecc 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 @@ -11,8 +11,10 @@ import pytest from aws_durable_execution_sdk_python.config import Duration from aws_durable_execution_sdk_python.retries import RetryDecision +from botocore.config import Config 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, BedrockCallOptions, @@ -245,3 +247,54 @@ def body(context: Any) -> Any: assert value == {"result": "A short summary."} 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) + model = llm() + try: + assert model._converse(model._config, "Question: Q?") == "ok" + [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() + + +def test_passed_client_keeps_its_user_agent(monkeypatch: pytest.MonkeyPatch) -> None: + def fail_boto_client(*args: Any, **kwargs: Any) -> Any: + msg = "boto3.client must not be called when client is passed" + raise AssertionError(msg) + + monkeypatch.setattr(boto3, "client", fail_boto_client) + custom: Any = boto3.session.Session().client( + "bedrock-runtime", + region_name="us-east-1", + config=Config(user_agent_extra="custom-agent/1.0"), + ) + model = llm(BedrockConfig(client=custom)) + try: + with Stubber(custom) as stubber: + stubber.add_response("converse", reply("ok")) + assert model._converse(model._config, "Question: Q?") == "ok" + assert custom.meta.config.user_agent_extra == "custom-agent/1.0" + finally: + custom.close() 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..394a3f69f 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 @@ -12,9 +12,11 @@ import boto3 import pytest from aws_durable_execution_sdk_python.retries import RetryDecision +from botocore.config import Config 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 +361,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 +372,118 @@ 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() + + +@pytest.mark.parametrize( + ("service", "make_transport", "operation_name", "response"), + [ + ( + "bedrock-agentcore", + lambda client: agentcore_transport(ARN, client=client), + "invoke_agent_runtime", + { + "contentType": "application/json", + "statusCode": 200, + "response": stream(json.dumps(REPLY)), + }, + ), + ( + "sagemaker-runtime", + lambda client: sagemaker_transport(ENDPOINT, client=client), + "invoke_endpoint", + {"Body": stream(json.dumps(REPLY))}, + ), + ( + "lambda", + lambda client: lambda_transport(FUNCTION, client=client), + "invoke", + {"StatusCode": 200, "Payload": stream(json.dumps(REPLY))}, + ), + ], + ids=["agentcore", "sagemaker", "lambda"], +) +def test_passed_transport_client_keeps_its_user_agent( + monkeypatch: pytest.MonkeyPatch, + service: str, + make_transport: Any, + operation_name: str, + response: dict[str, Any], +) -> None: + def fail_boto_client(*args: Any, **kwargs: Any) -> Any: + msg = "boto3.client must not be called when client is passed" + raise AssertionError(msg) + + monkeypatch.setattr(boto3, "client", fail_boto_client) + session: Any = boto3.session.Session() + custom: Any = session.client( + service, + region_name="us-east-1", + config=Config(user_agent_extra="custom-agent/1.0"), + ) + try: + with Stubber(custom) as stubber: + stubber.add_response(operation_name, response) + assert make_transport(custom)(REQUEST) == REPLY + assert custom.meta.config.user_agent_extra == "custom-agent/1.0" + finally: + custom.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..b5efa380b 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 @@ -32,10 +32,12 @@ DurableFunctionTestResult, DurableFunctionTestRunner, ) +from botocore.config import Config from botocore.exceptions import ClientError 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 +501,31 @@ 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() + + +def test_passed_client_keeps_its_user_agent() -> None: + custom: Any = boto3.client( + "bedrock-agentcore", + region_name="us-west-2", + config=Config(user_agent_extra="custom-agent/1.0"), + ) + try: + assert operation._client(config_with(custom)) is custom # noqa: SLF001 + client_config: Any = custom.meta.config + assert client_config.user_agent_extra == "custom-agent/1.0" + finally: + custom.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..009d9a241 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 @@ -8,10 +8,13 @@ import math from typing import Any +import boto3 import pytest from aws_durable_execution_sdk_python.config import Duration from aws_durable_execution_sdk_python.exceptions import ValidationError +from botocore.config import Config +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 +303,37 @@ 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_passed_client_keeps_its_user_agent() -> None: + custom: Any = boto3.session.Session().client( + "lambda-microvms", + region_name="us-west-2", + config=Config(user_agent_extra="custom-agent/1.0"), + ) + try: + scope = operation._OperationScope.create( # noqa: SLF001 + context=NoOperations(), # type: ignore[arg-type] + name="build", + job_input={}, + config=config(client=custom), + ) + assert scope._client() is custom # noqa: SLF001 + client_config: Any = custom.meta.config + assert client_config.user_agent_extra == "custom-agent/1.0" + finally: + custom.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] From 3917916473d18d61d5653d86f29e7e67c70d86f6 Mon Sep 17 00:00:00 2001 From: SRI VILLIAM SAI Date: Wed, 25 Nov 2026 21:06:47 +0530 Subject: [PATCH 2/3] feat: mark extension and worker user agents (#985) Set user_agent_extra with package name, version, and feature marker (md/microvm, md/agentcore, or md/ai) on every default boto3 client created by extensions and compute-worker. Document that caller-provided clients are used as they are and keep their own user agent. --- .../docs/worker.md | 4 ++-- .../agentcore/worker.py | 3 ++- .../microvm/callback_reporter.py | 6 +++++- .../microvm/self_suspend.py | 5 +++++ .../microvm/worker.py | 15 ++++++++------- .../docs/ai.md | 4 ++-- .../docs/microvm.md | 1 + .../ai/_shared.py | 12 +++++++++++- .../ai/llm.py | 3 ++- .../ai/transports.py | 9 ++++++--- .../compute/agentcore/config.py | 6 ++++-- .../compute/agentcore/operation.py | 5 +++++ .../compute/microvm/config.py | 7 ++++--- .../compute/microvm/operation.py | 5 +++++ 14 files changed, 62 insertions(+), 23 deletions(-) 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/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..3f19411b9 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 @@ -492,7 +492,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..9efd953ba 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,7 @@ from botocore.config import Config from botocore.exceptions import ClientError, NoCredentialsError - +from aws_durable_execution_sdk_python_compute_worker.__about__ import __version__ from aws_durable_execution_sdk_python_compute_worker.microvm.logger import ( MicrovmWorkerLogger, safe_get, @@ -284,6 +284,10 @@ def _create_client(region: str) -> LambdaClient: read_timeout=COMPLETION_CALL_TIMEOUT_SECONDS, retries={"mode": "standard", "max_attempts": 3}, tcp_keepalive=True, + user_agent_extra=( + "aws-durable-execution-sdk-python-compute-worker/" + f"{__version__} md/microvm" + ), ), ) 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..4b4dd7abb 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,7 @@ from botocore.config import Config from botocore.exceptions import ClientError, NoCredentialsError +from aws_durable_execution_sdk_python_compute_worker.__about__ import __version__ from aws_durable_execution_sdk_python_compute_worker.microvm.callback_reporter import ( TRANSIENT_4XX_CODES, error_code, @@ -143,6 +144,10 @@ def create_microvms_client(region: str) -> LambdaMicrovmsClient: # total_max_attempts counts the first attempt too. "total_max_attempts": _CLIENT_ATTEMPTS, }, + user_agent_extra=( + "aws-durable-execution-sdk-python-compute-worker/" + f"{__version__} md/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-extensions/docs/ai.md b/packages/aws-durable-execution-sdk-python-extensions/docs/ai.md index cc50132ce..0fb5445be 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. @@ -93,7 +93,7 @@ short = model.ask(context, "Summarize.", text, bedrock=BedrockCallOptions(max_to - 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. - `llm()` takes one destination. This release supports `BedrockConfig` only. - `ask` sends a temperature only when you set one, 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. +- `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, and a client that you pass is used as it is and keeps its own user agent. - `bedrock=BedrockCallOptions(...)` changes `model_id`, `temperature`, or `max_tokens` for one call. - `ask` sends the input inside `` tags, and its system prompt says that the input is data, not instructions. An instruction in the input can still change the reply. So do not use a reply alone to authorize an action. 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/ai/_shared.py b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/ai/_shared.py index 9d8d9fcd3..b3fed8a27 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.__about__ import __version__ from aws_durable_execution_sdk_python_extensions.ai.errors import ( AiError, DeciderInvalidResponseError, @@ -130,5 +132,13 @@ 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=( + f"aws-durable-execution-sdk-python-extensions/{__version__} " + "md/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 e92da7c94..c178e9816 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 @@ -82,7 +82,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 77ba41ee3..b806b03fb 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 @@ -36,6 +36,7 @@ from botocore.config import Config from botocore.exceptions import ClientError +from aws_durable_execution_sdk_python_extensions.__about__ import __version__ from aws_durable_execution_sdk_python_extensions.compute.agentcore.config import ( AgentcoreConfig, AgentcoreSessionConfig, @@ -721,6 +722,10 @@ def get(self, region: str) -> BedrockAgentcoreClient: "mode": "standard", "total_max_attempts": _CLIENT_ATTEMPTS, }, + user_agent_extra=( + f"aws-durable-execution-sdk-python-extensions/{__version__} " + "md/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..ced131d08 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.__about__ import __version__ from aws_durable_execution_sdk_python_extensions.compute.microvm.aws_errors import ( add_request_id, decide_on_original_error, @@ -1108,6 +1109,10 @@ def get(self, region: str) -> LambdaMicrovmsClient: # max_attempts would count only the retries. "total_max_attempts": _CLIENT_ATTEMPTS, }, + user_agent_extra=( + f"aws-durable-execution-sdk-python-extensions/{__version__} " + "md/microvm" + ), ), ) self._clients[region] = client From 62b71938a96012803f9568af5f66892eb8af2e3b Mon Sep 17 00:00:00 2001 From: SRI VILLIAM SAI Date: Thu, 3 Dec 2026 10:34:31 +0530 Subject: [PATCH 3/3] fix: address user agent review comments (#985) - Extract _user_agent.user_agent_extra in both packages - Add feature param to CallbackReporter.create for agentcore - Remove redundant caller-client user-agent tests - Update llm_test and agentcore_worker_test assertions --- .../_user_agent.py | 13 +++++ .../agentcore/worker.py | 4 +- .../microvm/callback_reporter.py | 27 ++++++--- .../microvm/self_suspend.py | 9 ++- .../tests/agentcore/agentcore_worker_test.py | 16 ++++-- .../tests/microvm/callback_reporter_test.py | 31 +++++----- .../tests/microvm/worker_test.py | 3 +- .../_user_agent.py | 13 +++++ .../ai/_shared.py | 9 +-- .../compute/agentcore/operation.py | 7 +-- .../compute/microvm/operation.py | 7 +-- .../tests/ai/llm_test.py | 3 +- .../tests/ai/transports_test.py | 56 ------------------- .../agentcore/agentcore_operation_test.py | 15 ----- .../tests/compute/microvm/validation_test.py | 22 -------- 15 files changed, 86 insertions(+), 149 deletions(-) create mode 100644 packages/aws-durable-execution-sdk-python-compute-worker/src/aws_durable_execution_sdk_python_compute_worker/_user_agent.py create mode 100644 packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/_user_agent.py 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 3f19411b9..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 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 9efd953ba..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.__about__ import __version__ +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,10 +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=( - "aws-durable-execution-sdk-python-compute-worker/" - f"{__version__} md/microvm" - ), + user_agent_extra=user_agent_extra(feature), ), ) @@ -332,6 +331,7 @@ def create( region: str, *, logger: MicrovmWorkerLogger | None = None, + feature: str = "microvm", ) -> CallbackReporter: """Create a reporter with its own client for ``region``. @@ -339,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 4b4dd7abb..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,7 +24,9 @@ from botocore.config import Config from botocore.exceptions import ClientError, NoCredentialsError -from aws_durable_execution_sdk_python_compute_worker.__about__ import __version__ +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, @@ -144,10 +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=( - "aws-durable-execution-sdk-python-compute-worker/" - f"{__version__} md/microvm" - ), + user_agent_extra=user_agent_extra("microvm"), ), ) 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 5bcc87245..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 @@ -12,9 +12,7 @@ import time from typing import Any -import boto3 import pytest -from botocore.config import Config from botocore.exceptions import BotoCoreError, NoCredentialsError from botocore.stub import Stubber @@ -417,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) @@ -433,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 @@ -489,20 +487,17 @@ def test_default_client_sets_user_agent() -> None: finally: client.close() - -def test_passed_client_keeps_its_user_agent() -> None: - custom: Any = boto3.session.Session().client( - "lambda", - region_name="us-east-1", - config=Config(user_agent_extra="custom-agent/1.0"), + agentcore_reporter = CallbackReporter.create( + "cb-1", "us-east-1", feature="agentcore" ) try: - reporter = CallbackReporter("cb-1", custom) - assert reporter._client is custom # noqa: SLF001 - client_config: Any = custom.meta.config - assert client_config.user_agent_extra == "custom-agent/1.0" + 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: - custom.close() + agentcore_reporter.close() # endregion client 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/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 b3fed8a27..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 @@ -18,7 +18,7 @@ from aws_durable_execution_sdk_python.serdes import JsonSerDes from botocore.config import Config -from aws_durable_execution_sdk_python_extensions.__about__ import __version__ +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, @@ -134,11 +134,6 @@ def get(self) -> Any: if self._client is None: self._client = boto3.client( # type: ignore[call-overload] self._service, - config=Config( - user_agent_extra=( - f"aws-durable-execution-sdk-python-extensions/{__version__} " - "md/ai" - ) - ), + 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/compute/agentcore/operation.py b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/agentcore/operation.py index 5d4e52a09..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,7 +37,7 @@ from botocore.config import Config from botocore.exceptions import ClientError -from aws_durable_execution_sdk_python_extensions.__about__ import __version__ +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, @@ -729,10 +729,7 @@ def get(self, region: str) -> BedrockAgentcoreClient: "mode": "standard", "total_max_attempts": _CLIENT_ATTEMPTS, }, - user_agent_extra=( - f"aws-durable-execution-sdk-python-extensions/{__version__} " - "md/agentcore" - ), + 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/operation.py b/packages/aws-durable-execution-sdk-python-extensions/src/aws_durable_execution_sdk_python_extensions/compute/microvm/operation.py index ced131d08..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,7 +34,7 @@ from aws_durable_execution_sdk_python.serdes import JsonSerDes from botocore.exceptions import ClientError -from aws_durable_execution_sdk_python_extensions.__about__ import __version__ +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, @@ -1109,10 +1109,7 @@ def get(self, region: str) -> LambdaMicrovmsClient: # max_attempts would count only the retries. "total_max_attempts": _CLIENT_ATTEMPTS, }, - user_agent_extra=( - f"aws-durable-execution-sdk-python-extensions/{__version__} " - "md/microvm" - ), + 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 1b57c3f2f..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 @@ -170,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 @@ -430,4 +430,3 @@ def test_only_end_is_complete_from_a_transport(run_ai: Any) -> None: assert value["error"] == "LlmStoppedError" assert value["stop_reason"] == "end_turn" ->>>>>>> upstream/main 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 394a3f69f..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 @@ -12,7 +12,6 @@ import boto3 import pytest from aws_durable_execution_sdk_python.retries import RetryDecision -from botocore.config import Config from botocore.exceptions import ClientError from botocore.stub import Stubber @@ -432,58 +431,3 @@ def spy_client(service: str, **kwargs: Any) -> Any: stubber.deactivate() for client in created: client.close() - - -@pytest.mark.parametrize( - ("service", "make_transport", "operation_name", "response"), - [ - ( - "bedrock-agentcore", - lambda client: agentcore_transport(ARN, client=client), - "invoke_agent_runtime", - { - "contentType": "application/json", - "statusCode": 200, - "response": stream(json.dumps(REPLY)), - }, - ), - ( - "sagemaker-runtime", - lambda client: sagemaker_transport(ENDPOINT, client=client), - "invoke_endpoint", - {"Body": stream(json.dumps(REPLY))}, - ), - ( - "lambda", - lambda client: lambda_transport(FUNCTION, client=client), - "invoke", - {"StatusCode": 200, "Payload": stream(json.dumps(REPLY))}, - ), - ], - ids=["agentcore", "sagemaker", "lambda"], -) -def test_passed_transport_client_keeps_its_user_agent( - monkeypatch: pytest.MonkeyPatch, - service: str, - make_transport: Any, - operation_name: str, - response: dict[str, Any], -) -> None: - def fail_boto_client(*args: Any, **kwargs: Any) -> Any: - msg = "boto3.client must not be called when client is passed" - raise AssertionError(msg) - - monkeypatch.setattr(boto3, "client", fail_boto_client) - session: Any = boto3.session.Session() - custom: Any = session.client( - service, - region_name="us-east-1", - config=Config(user_agent_extra="custom-agent/1.0"), - ) - try: - with Stubber(custom) as stubber: - stubber.add_response(operation_name, response) - assert make_transport(custom)(REQUEST) == REPLY - assert custom.meta.config.user_agent_extra == "custom-agent/1.0" - finally: - custom.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 b5efa380b..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 @@ -32,7 +32,6 @@ DurableFunctionTestResult, DurableFunctionTestRunner, ) -from botocore.config import Config from botocore.exceptions import ClientError from botocore.response import StreamingBody from botocore.stub import ANY, Stubber @@ -512,20 +511,6 @@ def test_default_client_sets_user_agent() -> None: client.close() -def test_passed_client_keeps_its_user_agent() -> None: - custom: Any = boto3.client( - "bedrock-agentcore", - region_name="us-west-2", - config=Config(user_agent_extra="custom-agent/1.0"), - ) - try: - assert operation._client(config_with(custom)) is custom # noqa: SLF001 - client_config: Any = custom.meta.config - assert client_config.user_agent_extra == "custom-agent/1.0" - finally: - custom.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 009d9a241..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 @@ -8,11 +8,9 @@ import math from typing import Any -import boto3 import pytest from aws_durable_execution_sdk_python.config import Duration from aws_durable_execution_sdk_python.exceptions import ValidationError -from botocore.config import Config from aws_durable_execution_sdk_python_extensions.__about__ import __version__ from aws_durable_execution_sdk_python_extensions.compute.microvm import ( @@ -314,26 +312,6 @@ def test_default_client_sets_user_agent() -> None: client.close() -def test_passed_client_keeps_its_user_agent() -> None: - custom: Any = boto3.session.Session().client( - "lambda-microvms", - region_name="us-west-2", - config=Config(user_agent_extra="custom-agent/1.0"), - ) - try: - scope = operation._OperationScope.create( # noqa: SLF001 - context=NoOperations(), # type: ignore[arg-type] - name="build", - job_input={}, - config=config(client=custom), - ) - assert scope._client() is custom # noqa: SLF001 - client_config: Any = custom.meta.config - assert client_config.user_agent_extra == "custom-agent/1.0" - finally: - custom.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]