From 4d3c39ab45750e6b8ad40cc3326c373b92564b78 Mon Sep 17 00:00:00 2001 From: adaines Date: Fri, 4 Dec 2026 14:21:15 -0500 Subject: [PATCH] Back off with jitter on throttles and the Lex build quota in the integration tests The IAM and DynamoDB integration clients now use a retry strategy from tests/retries.py that marks the unmodeled 400 throttles as retry safe, so the SDK's throttle backoff applies: full jitter, 1 s base, 20 s cap. The released smithy-python treats an unmodeled error as a throttle only on a 429. IAM matches code Throttling (10 attempts). DynamoDB matches any unmodeled 400 on the five control plane operations that these tests call, since the error keeps no code (6 attempts). Other errors keep today's attempt counts and backoff when max_attempts and retry_mode are unset in the environment (AWS_MAX_ATTEMPTS, AWS_RETRY_MODE) and the profile; these test clients still read and validate those settings but no longer apply them to retries. The retry quota rises from 500 to 10,000 tokens. The Lex fixture waits out the bot-locale-builds-per-account quota with a jittered loop and a 900 s deadline, and deletes its bot when the build fails. Remove the strategy when the pins move to a release with smithy-python#955. --- .../tests/functional/test_throttle_retries.py | 235 ++++++++++ .../tests/integration/__init__.py | 9 +- .../aws-sdk-iam/tests/functional/__init__.py | 2 + .../tests/functional/test_throttle_retries.py | 225 ++++++++++ .../aws-sdk-iam/tests/integration/__init__.py | 7 +- .../tests/functional/test_quota_retries.py | 414 ++++++++++++++++++ .../tests/integration/__init__.py | 188 ++++++++ .../tests/integration/conftest.py | 139 +----- tests/retries.py | 233 ++++++++++ 9 files changed, 1314 insertions(+), 138 deletions(-) create mode 100644 clients/aws-sdk-dynamodb/tests/functional/test_throttle_retries.py create mode 100644 clients/aws-sdk-iam/tests/functional/__init__.py create mode 100644 clients/aws-sdk-iam/tests/functional/test_throttle_retries.py create mode 100644 clients/aws-sdk-lex-runtime-v2/tests/functional/test_quota_retries.py create mode 100644 tests/retries.py diff --git a/clients/aws-sdk-dynamodb/tests/functional/test_throttle_retries.py b/clients/aws-sdk-dynamodb/tests/functional/test_throttle_retries.py new file mode 100644 index 000000000..2405ddd1b --- /dev/null +++ b/clients/aws-sdk-dynamodb/tests/functional/test_throttle_retries.py @@ -0,0 +1,235 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The integration tests' retry strategy, against DynamoDB wire responses.""" + +import logging +from typing import Any + +import pytest +from aws_sdk_dynamodb.aio.client import AsyncDynamoDBClient +from aws_sdk_dynamodb.aio.config import AsyncDynamoDBConfig +from aws_sdk_dynamodb.client import DynamoDBClient +from aws_sdk_dynamodb.config import DynamoDBConfig +from aws_sdk_dynamodb.models import ( + AttributeValueS, + DeleteTableInput, + DescribeTableInput, + GetItemInput, + ListTablesInput, + ResourceInUseException, +) +from retries import ( + ThrottleRetryStrategy, + dynamodb_retry_strategy, + is_dynamodb_control_plane_throttle, +) +from smithy_core.aio.client import AsyncRequestPipeline +from smithy_core.client import RequestPipeline +from smithy_core.exceptions import CallError +from smithy_test import mock +from smithy_test.aio import mock_async + +from ..integration import create_async_client, create_sync_client + +JSON_HEADERS = {"content-type": "application/x-amz-json-1.0"} +OK = "{}" +THROTTLE = ( + '{"__type": "com.amazon.coral.availability#ThrottlingException",' + ' "message": "The rate of control plane requests made by this account is too high"}' +) +VALIDATION = ( + '{"__type": "com.amazon.coral.validate#ValidationException", "message": "bad key"}' +) +IN_USE = ( + '{"__type": "com.amazonaws.dynamodb#ResourceInUseException", "message": "busy"}' +) +TIMEOUT = '{"__type": "com.amazonaws.dynamodb#RequestTimeout", "message": "slow"}' + + +@pytest.fixture +def sleeps(monkeypatch: pytest.MonkeyPatch) -> list[float]: + """Records the pipeline's waits instead of waiting, in both modes.""" + recorded: list[float] = [] + + def sleep(self: RequestPipeline[Any, Any], delay: float) -> None: + recorded.append(delay) + + async def sleep_async(self: AsyncRequestPipeline[Any, Any], delay: float) -> None: + recorded.append(delay) + + monkeypatch.setattr(RequestPipeline, "_sleep", sleep) + monkeypatch.setattr(AsyncRequestPipeline, "_sleep", sleep_async) + return recorded + + +def _client() -> DynamoDBClient: + # The random value is fixed, so each wait is the top of its jitter range. + strategy = dynamodb_retry_strategy(random=lambda: 1.0) + return DynamoDBClient( + DynamoDBConfig.resolve(region="us-west-2", retry_strategy=strategy) + ) + + +def test_retries_a_control_plane_throttle_with_the_throttle_backoff( + sleeps: list[float], +) -> None: + """Two ThrottlingException 400s on DeleteTable and then a success make 3 requests.""" + client = _client() + controller = mock(client) + controller.expect_request().respond_with(400, JSON_HEADERS, THROTTLE).respond_with( + 400, JSON_HEADERS, THROTTLE + ).respond_with(200, JSON_HEADERS, OK) + + client.delete_table(DeleteTableInput(table_name="t")) + + assert len(controller.requests) == 3 + assert sleeps == [1.0, 2.0] + + +async def test_retries_a_control_plane_throttle_with_the_async_client( + sleeps: list[float], +) -> None: + """The async client, which the session table fixture uses, retries the same way.""" + strategy = dynamodb_retry_strategy(random=lambda: 1.0) + client = AsyncDynamoDBClient( + await AsyncDynamoDBConfig.resolve(region="us-west-2", retry_strategy=strategy) + ) + controller = await mock_async(client) + controller.expect_request().respond_with(400, JSON_HEADERS, THROTTLE).respond_with( + 400, JSON_HEADERS, THROTTLE + ).respond_with(200, JSON_HEADERS, OK) + + await client.describe_table(DescribeTableInput(table_name="t")) + + assert len(controller.requests) == 3 + assert sleeps == [1.0, 2.0] + + +def test_gives_up_after_6_attempts_with_a_note(sleeps: list[float]) -> None: + """A throttle that never ends raises the original error after 6 attempts, 31 s of waits.""" + client = _client() + controller = mock(client) + controller.expect_request().respond_with(400, JSON_HEADERS, THROTTLE) + + with pytest.raises(CallError) as caught: + client.delete_table(DeleteTableInput(table_name="t")) + + assert "#DeleteTable - status: 400" in caught.value.message + assert "gave up after 6 attempts" in "".join(caught.value.__notes__) + assert len(controller.requests) == 6 + assert sleeps == [1.0, 2.0, 4.0, 8.0, 16.0] + + +def test_makes_one_request_and_no_wait_without_a_throttle( + sleeps: list[float], caplog: pytest.LogCaptureFixture +) -> None: + """A call that succeeds makes 1 request, waits for nothing and logs nothing.""" + client = _client() + controller = mock(client) + controller.expect_request().respond_with(200, JSON_HEADERS, OK) + + with caplog.at_level(logging.WARNING, logger="retries"): + client.delete_table(DeleteTableInput(table_name="t")) + + assert len(controller.requests) == 1 + assert sleeps == [] + assert [r for r in caplog.records if r.name == "retries"] == [] + + +def test_does_not_retry_an_unmodeled_400_on_a_data_plane_operation( + sleeps: list[float], +) -> None: + """An unmodeled 400 on GetItem, which is not a control plane operation, gets 1 request.""" + client = _client() + controller = mock(client) + controller.expect_request().respond_with(400, JSON_HEADERS, VALIDATION) + + with pytest.raises(CallError, match="#GetItem - status: 400"): + client.get_item(GetItemInput(table_name="t", key={"pk": AttributeValueS("x")})) + + assert len(controller.requests) == 1 + assert sleeps == [] + + +def test_does_not_retry_a_modeled_error_on_a_control_plane_operation( + sleeps: list[float], +) -> None: + """A modeled ResourceInUseException 400 on DeleteTable gets 1 request.""" + client = _client() + controller = mock(client) + controller.expect_request().respond_with(400, JSON_HEADERS, IN_USE) + + with pytest.raises(ResourceInUseException): + client.delete_table(DeleteTableInput(table_name="t")) + + assert len(controller.requests) == 1 + assert sleeps == [] + + +def test_keeps_4_attempts_and_25ms_base_for_other_retryable_errors( + sleeps: list[float], caplog: pytest.LogCaptureFixture +) -> None: + """A timeout keeps DynamoDB's defaults: 4 attempts and a 25 ms backoff base, unlogged.""" + client = _client() + controller = mock(client) + controller.expect_request().respond_with(408, JSON_HEADERS, TIMEOUT) + + with caplog.at_level(logging.WARNING, logger="retries"): + with pytest.raises(CallError): + client.list_tables(ListTablesInput()) + + assert len(controller.requests) == 4 + assert sleeps == [0.025, 0.05, 0.1] + assert [r for r in caplog.records if r.name == "retries"] == [] + + +@pytest.mark.parametrize( + "message", + [ + # The message of the failed builds of 4 December 2026, which carries a reason. + "Unknown error for operation com.amazonaws.dynamodb#DeleteTable - status: 400 - reason: Bad Request", + "Unknown error for operation com.amazonaws.dynamodb#CreateTable - status: 400", + # The tag calls of the integration tests are control plane calls too. + "Unknown error for operation com.amazonaws.dynamodb#TagResource - status: 400", + "Unknown error for operation com.amazonaws.dynamodb#ListTagsOfResource - status: 400", + ], +) +def test_matches_the_logged_throttle_messages(message: str) -> None: + """The matcher accepts the throttle message with and without an HTTP reason.""" + assert is_dynamodb_control_plane_throttle(CallError(message)) + + +@pytest.mark.parametrize( + "message", + [ + "Unknown error for operation com.amazonaws.dynamodb#DeleteTable - status: 400 - id: com.amazonaws.dynamodb#Other", + "Unknown error for operation com.amazonaws.dynamodb#DeleteTable - status: 500", + "Unknown error for operation com.amazonaws.dynamodb#PutItem - status: 400", + "Unknown error for operation com.amazonaws.dynamodb#deletetable - status: 400", + ], +) +def test_rejects_other_messages(message: str) -> None: + """The matcher rejects an identified error, another status and a data plane operation.""" + assert not is_dynamodb_control_plane_throttle(CallError(message)) + + +def test_each_integration_client_gets_its_own_strategy() -> None: + """The integration tests' clients use the strategy, one instance per client.""" + first = create_sync_client()._config.retry_strategy + second = create_sync_client()._config.retry_strategy + + assert isinstance(first, ThrottleRetryStrategy) + assert isinstance(second, ThrottleRetryStrategy) + assert first is not second + + +async def test_each_async_integration_client_gets_its_own_strategy() -> None: + """The async factory, which the session table fixture uses, also gives each its own.""" + async with ( + await create_async_client() as first, + await create_async_client() as second, + ): + assert isinstance(first._config.retry_strategy, ThrottleRetryStrategy) + assert isinstance(second._config.retry_strategy, ThrottleRetryStrategy) + assert first._config.retry_strategy is not second._config.retry_strategy diff --git a/clients/aws-sdk-dynamodb/tests/integration/__init__.py b/clients/aws-sdk-dynamodb/tests/integration/__init__.py index cde65b6a4..526af2d73 100644 --- a/clients/aws-sdk-dynamodb/tests/integration/__init__.py +++ b/clients/aws-sdk-dynamodb/tests/integration/__init__.py @@ -22,6 +22,7 @@ TableStatus, Tag, ) +from retries import dynamodb_retry_strategy from waiters import wait_until, wait_until_gone REGION = "us-west-2" @@ -61,12 +62,16 @@ def table_input(name: str) -> CreateTableInput: async def create_async_client() -> AsyncDynamoDBClient: - config = await AsyncDynamoDBConfig.resolve(region=REGION) + config = await AsyncDynamoDBConfig.resolve( + region=REGION, retry_strategy=dynamodb_retry_strategy() + ) return AsyncDynamoDBClient(config=config) def create_sync_client() -> DynamoDBClient: - config = DynamoDBConfig.resolve(region=REGION) + config = DynamoDBConfig.resolve( + region=REGION, retry_strategy=dynamodb_retry_strategy() + ) return DynamoDBClient(config=config) diff --git a/clients/aws-sdk-iam/tests/functional/__init__.py b/clients/aws-sdk-iam/tests/functional/__init__.py new file mode 100644 index 000000000..04f8b7b76 --- /dev/null +++ b/clients/aws-sdk-iam/tests/functional/__init__.py @@ -0,0 +1,2 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 diff --git a/clients/aws-sdk-iam/tests/functional/test_throttle_retries.py b/clients/aws-sdk-iam/tests/functional/test_throttle_retries.py new file mode 100644 index 000000000..7bea1333c --- /dev/null +++ b/clients/aws-sdk-iam/tests/functional/test_throttle_retries.py @@ -0,0 +1,225 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The integration tests' retry strategy, against IAM wire responses.""" + +import logging +from typing import Any + +import pytest +from aws_sdk_iam.aio.client import AsyncIAMClient +from aws_sdk_iam.aio.config import AsyncIAMConfig +from aws_sdk_iam.client import IAMClient +from aws_sdk_iam.config import IAMConfig +from aws_sdk_iam.models import DeleteUserInput, NoSuchEntityException +from retries import ThrottleRetryStrategy, iam_retry_strategy, is_iam_throttle +from smithy_core.aio.client import AsyncRequestPipeline +from smithy_core.client import RequestPipeline +from smithy_core.exceptions import CallError +from smithy_test import mock +from smithy_test.aio import mock_async + +from ..integration import create_async_client, create_sync_client + +XML_HEADERS = {"content-type": "text/xml"} +OK = ( + '' + "req" + "" +) + + +def _error(code: str) -> str: + return ( + '' + f"Sender{code}x" + "req" + ) + + +THROTTLE = _error("Throttling") + + +@pytest.fixture +def sleeps(monkeypatch: pytest.MonkeyPatch) -> list[float]: + """Records the pipeline's waits instead of waiting, in both modes.""" + recorded: list[float] = [] + + def sleep(self: RequestPipeline[Any, Any], delay: float) -> None: + recorded.append(delay) + + async def sleep_async(self: AsyncRequestPipeline[Any, Any], delay: float) -> None: + recorded.append(delay) + + monkeypatch.setattr(RequestPipeline, "_sleep", sleep) + monkeypatch.setattr(AsyncRequestPipeline, "_sleep", sleep_async) + return recorded + + +def _client() -> IAMClient: + # The random value is fixed, so each wait is the top of its jitter range. + strategy = iam_retry_strategy(random=lambda: 1.0) + return IAMClient(IAMConfig.resolve(region="us-east-1", retry_strategy=strategy)) + + +def test_retries_a_throttle_with_the_throttle_backoff( + sleeps: list[float], caplog: pytest.LogCaptureFixture +) -> None: + """Two Throttling 400s and then a success make 3 requests, waiting 1 s and 2 s.""" + client = _client() + controller = mock(client) + controller.expect_request().respond_with(400, XML_HEADERS, THROTTLE).respond_with( + 400, XML_HEADERS, THROTTLE + ).respond_with(200, XML_HEADERS, OK) + + with caplog.at_level(logging.WARNING, logger="retries"): + client.delete_user(DeleteUserInput(user_name="u")) + + assert len(controller.requests) == 3 + assert sleeps == [1.0, 2.0] + assert len([r for r in caplog.records if r.name == "retries"]) == 2 + + +async def test_retries_a_throttle_with_the_async_client(sleeps: list[float]) -> None: + """The async client retries a Throttling 400 the same way.""" + strategy = iam_retry_strategy(random=lambda: 1.0) + client = AsyncIAMClient( + await AsyncIAMConfig.resolve(region="us-east-1", retry_strategy=strategy) + ) + controller = await mock_async(client) + controller.expect_request().respond_with(400, XML_HEADERS, THROTTLE).respond_with( + 400, XML_HEADERS, THROTTLE + ).respond_with(200, XML_HEADERS, OK) + + await client.delete_user(DeleteUserInput(user_name="u")) + + assert len(controller.requests) == 3 + assert sleeps == [1.0, 2.0] + + +def test_gives_up_after_10_attempts_with_a_note(sleeps: list[float]) -> None: + """A throttle that never ends raises the original error after 10 attempts.""" + client = _client() + controller = mock(client) + controller.expect_request().respond_with(400, XML_HEADERS, THROTTLE) + + with pytest.raises(CallError) as caught: + client.delete_user(DeleteUserInput(user_name="u")) + + assert caught.value.message.endswith("#DeleteUser - status: 400, code: Throttling") + assert "gave up after 10 attempts" in "".join(caught.value.__notes__) + assert len(controller.requests) == 10 + assert sleeps == [1.0, 2.0, 4.0, 8.0, 16.0, 20.0, 20.0, 20.0, 20.0] + + +def test_makes_one_request_and_no_wait_without_a_throttle( + sleeps: list[float], caplog: pytest.LogCaptureFixture +) -> None: + """A call that succeeds makes 1 request, waits for nothing and logs nothing.""" + client = _client() + controller = mock(client) + controller.expect_request().respond_with(200, XML_HEADERS, OK) + + with caplog.at_level(logging.WARNING, logger="retries"): + client.delete_user(DeleteUserInput(user_name="u")) + + assert len(controller.requests) == 1 + assert sleeps == [] + assert [r for r in caplog.records if r.name == "retries"] == [] + + +def test_does_not_retry_an_unmodeled_validation_error(sleeps: list[float]) -> None: + """An unmodeled 400 with another code is raised after 1 request.""" + client = _client() + controller = mock(client) + controller.expect_request().respond_with( + 400, XML_HEADERS, _error("ValidationError") + ) + + with pytest.raises(CallError, match="code: ValidationError$"): + client.delete_user(DeleteUserInput(user_name="u")) + + assert len(controller.requests) == 1 + assert sleeps == [] + + +def test_does_not_retry_a_modeled_error(sleeps: list[float]) -> None: + """A modeled NoSuchEntity 404 is raised after 1 request.""" + client = _client() + controller = mock(client) + controller.expect_request().respond_with(404, XML_HEADERS, _error("NoSuchEntity")) + + with pytest.raises(NoSuchEntityException): + client.delete_user(DeleteUserInput(user_name="u")) + + assert len(controller.requests) == 1 + + +def test_keeps_3_attempts_for_other_retryable_errors( + sleeps: list[float], caplog: pytest.LogCaptureFixture +) -> None: + """A timeout, which the SDK retries, keeps the default of 3 attempts, unlogged.""" + client = _client() + controller = mock(client) + controller.expect_request().respond_with(408, XML_HEADERS, _error("RequestTimeout")) + + with caplog.at_level(logging.WARNING, logger="retries"): + with pytest.raises(CallError): + client.delete_user(DeleteUserInput(user_name="u")) + + assert len(controller.requests) == 3 + assert sleeps == [0.05, 0.1] + assert [r for r in caplog.records if r.name == "retries"] == [] + + +def test_keeps_retrying_throttles_over_many_calls() -> None: + """The retry quota does not run out before the attempt cap on a throttled client.""" + strategy = iam_retry_strategy(random=lambda: 0.0) + throttle = CallError( + "Unknown error for operation com.amazonaws.iam#DeleteUser" + " - status: 400, code: Throttling" + ) + + # With the default quota of 500 tokens, call 13 would stop after 5 attempts. + for _ in range(50): + token = strategy.acquire_initial_retry_token() + for _ in range(9): + token = strategy.refresh_retry_token_for_retry( + token_to_renew=token, error=throttle + ) + strategy.record_success(token=token) + + +@pytest.mark.parametrize( + "message", + [ + "Unknown error for operation com.amazonaws.iam#DeleteUser - status: 400, code: ThrottlingException", + "Unknown error for operation com.amazonaws.iam#DeleteUser - status: 400, code: ValidationError", + "Unknown error for operation com.amazonaws.iam#DeleteUser - status: 500, code: Throttling", + "Unknown error for operation com.amazonaws.iam#DeleteUser - status: 400, code: throttling", + ], +) +def test_rejects_other_messages(message: str) -> None: + """The matcher takes the whole message, so another code or status is not a throttle.""" + assert not is_iam_throttle(CallError(message)) + + +def test_each_integration_client_gets_its_own_strategy() -> None: + """The integration tests' clients use the strategy, one instance per client.""" + first = create_sync_client()._config.retry_strategy + second = create_sync_client()._config.retry_strategy + + assert isinstance(first, ThrottleRetryStrategy) + assert isinstance(second, ThrottleRetryStrategy) + assert first is not second + + +async def test_each_async_integration_client_gets_its_own_strategy() -> None: + """The async factory, which the [async] tests use, also gives each client its own.""" + async with ( + await create_async_client() as first, + await create_async_client() as second, + ): + assert isinstance(first._config.retry_strategy, ThrottleRetryStrategy) + assert isinstance(second._config.retry_strategy, ThrottleRetryStrategy) + assert first._config.retry_strategy is not second._config.retry_strategy diff --git a/clients/aws-sdk-iam/tests/integration/__init__.py b/clients/aws-sdk-iam/tests/integration/__init__.py index a0080ad7b..f112c4092 100644 --- a/clients/aws-sdk-iam/tests/integration/__init__.py +++ b/clients/aws-sdk-iam/tests/integration/__init__.py @@ -10,6 +10,7 @@ from aws_sdk_iam.client import IAMClient from aws_sdk_iam.config import IAMConfig from aws_sdk_iam.models import Tag +from retries import iam_retry_strategy REGION = "us-west-2" @@ -24,10 +25,12 @@ def unique_name(infix: str = "") -> str: async def create_async_client() -> AsyncIAMClient: - config = await AsyncIAMConfig.resolve(region=REGION) + config = await AsyncIAMConfig.resolve( + region=REGION, retry_strategy=iam_retry_strategy() + ) return AsyncIAMClient(config=config) def create_sync_client() -> IAMClient: - config = IAMConfig.resolve(region=REGION) + config = IAMConfig.resolve(region=REGION, retry_strategy=iam_retry_strategy()) return IAMClient(config=config) diff --git a/clients/aws-sdk-lex-runtime-v2/tests/functional/test_quota_retries.py b/clients/aws-sdk-lex-runtime-v2/tests/functional/test_quota_retries.py new file mode 100644 index 000000000..db0d674fc --- /dev/null +++ b/clients/aws-sdk-lex-runtime-v2/tests/functional/test_quota_retries.py @@ -0,0 +1,414 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The integration tests' wait on the Lex locale build quota, with stubbed boto3 clients.""" + +import logging +from collections.abc import Iterator +from dataclasses import dataclass +from datetime import datetime +from typing import TYPE_CHECKING, Any + +import boto3 +import pytest +from botocore.stub import ANY, Stubber +from retries import retry_on_quota + +from ..integration import _lex_bot + +if TYPE_CHECKING: + from types_boto3_iam import IAMClient + from types_boto3_lexv2_models import LexModelsV2Client + from types_boto3_sts import STSClient + +BOT_ID = "BOTID12345" +QUOTA_MESSAGE = ( + "Validation failed for quota bot-locale-builds-per-account. The maximum is 5," + " but account 123456789012 requested 6." +) + + +class Quota(Exception): + pass + + +class FakeClock: + """A clock that moves only when ``sleep`` is called.""" + + def __init__(self) -> None: + self.now = 0.0 + self.sleeps: list[float] = [] + + def __call__(self) -> float: + return self.now + + def sleep(self, delay: float) -> None: + self.sleeps.append(delay) + self.now += delay + + +class Outcomes: + """A call that raises or returns each outcome in turn, then repeats the last one.""" + + def __init__(self, *outcomes: Exception | str) -> None: + self._outcomes = outcomes + self.count = 0 + + def __call__(self) -> str: + outcome = self._outcomes[min(self.count, len(self._outcomes) - 1)] + self.count += 1 + if isinstance(outcome, Exception): + raise outcome + return outcome + + +def _is_quota(error: Exception) -> bool: + return isinstance(error, Quota) + + +def test_retries_the_quota_with_jittered_waits() -> None: + """Two quota errors and then a success make 3 calls, waiting 15 s and 30 s.""" + clock = FakeClock() + call = Outcomes(Quota(), Quota(), "built") + + result = retry_on_quota( + call, _is_quota, sleep=clock.sleep, clock=clock, rand=lambda: 1.0 + ) + + assert result == "built" + assert call.count == 3 + assert clock.sleeps == [15.0, 30.0] + + +def test_logs_each_quota_wait(caplog: pytest.LogCaptureFixture) -> None: + """Each wait is visible as a warning on the ``retries`` logger.""" + clock = FakeClock() + call = Outcomes(Quota(), "built") + + with caplog.at_level(logging.WARNING, logger="retries"): + retry_on_quota( + call, _is_quota, sleep=clock.sleep, clock=clock, rand=lambda: 1.0 + ) + + assert len([r for r in caplog.records if r.name == "retries"]) == 1 + + +def test_makes_one_call_and_no_wait_without_the_quota( + caplog: pytest.LogCaptureFixture, +) -> None: + """A call that succeeds is made once and logs nothing.""" + clock = FakeClock() + call = Outcomes("built") + + with caplog.at_level(logging.WARNING, logger="retries"): + retry_on_quota(call, _is_quota, sleep=clock.sleep, clock=clock) + + assert call.count == 1 + assert clock.sleeps == [] + assert [r for r in caplog.records if r.name == "retries"] == [] + + +def test_raises_another_error_at_once() -> None: + """An error that is not the quota is raised after 1 call.""" + clock = FakeClock() + call = Outcomes(ValueError("other")) + + with pytest.raises(ValueError, match="other"): + retry_on_quota(call, _is_quota, sleep=clock.sleep, clock=clock) + + assert call.count == 1 + assert clock.sleeps == [] + + +def test_clamps_the_last_wait_and_raises_at_the_deadline() -> None: + """A quota that never frees ends at the deadline exactly, with a note.""" + clock = FakeClock() + call = Outcomes(Quota()) + + with pytest.raises(Quota) as caught: + retry_on_quota( + call, + _is_quota, + deadline=900, + sleep=clock.sleep, + clock=clock, + rand=lambda: 1.0, + ) + + # 15 + 30 + 14 * 60 = 885, so the last wait is clamped to the 15 s left. + assert clock.sleeps == [15.0, 30.0, *[60.0] * 14, 15.0] + assert clock.now == 900 + assert call.count == 18 + assert "18 attempts" in "".join(caught.value.__notes__) + + +@dataclass +class Stubbed: + """Stubbed boto3 clients for the bot fixture, and their stubbers.""" + + iam: Any + lex: Any + sts: Any + iam_stub: Stubber + lex_stub: Stubber + + def add_quota_error(self) -> None: + self.lex_stub.add_client_error( + "build_bot_locale", + service_error_code="ServiceQuotaExceededException", + service_message=QUOTA_MESSAGE, + http_status_code=402, + ) + + def expect_teardown(self) -> None: + self.lex_stub.add_response( + "delete_bot", + {"botId": BOT_ID, "botStatus": "Deleting"}, + {"botId": BOT_ID, "skipResourceInUseCheck": True}, + ) + self.iam_stub.add_response("delete_role", {}, {"RoleName": ANY}) + + +@pytest.fixture +def stubbed(monkeypatch: pytest.MonkeyPatch) -> Iterator[Stubbed]: + """Clients that answer from stubs and never reach a network, set up to create a bot.""" + monkeypatch.setenv("AWS_CONFIG_FILE", "/nonexistent") + monkeypatch.setenv("AWS_SHARED_CREDENTIALS_FILE", "/nonexistent") + monkeypatch.delenv("AWS_PROFILE", raising=False) + session = boto3.Session( + aws_access_key_id="x", aws_secret_access_key="x", region_name="us-east-1" + ) + iam: IAMClient = session.client("iam") + lex: LexModelsV2Client = session.client("lexv2-models") + sts: STSClient = session.client("sts") + with Stubber(iam) as iam_stub, Stubber(lex) as lex_stub, Stubber(sts) as sts_stub: + sts_stub.add_response( + "get_caller_identity", + { + "Account": "123456789012", + "UserId": "AIDAEXAMPLE", + "Arn": "arn:aws:iam::123456789012:user/x", + }, + ) + iam_stub.add_response( + "create_role", + { + "Role": { + "Path": "/", + "RoleName": "role", + "RoleId": "AROAEXAMPLEEXAMPLE1", + "Arn": "arn:aws:iam::123456789012:role/role", + "CreateDate": datetime(2026, 12, 4), + } + }, + ) + lex_stub.add_response("create_bot", {"botId": BOT_ID}) + lex_stub.add_response("describe_bot", {"botStatus": "Available"}) + lex_stub.add_response("create_bot_locale", {}) + lex_stub.add_response("describe_bot_locale", {"botLocaleStatus": "NotBuilt"}) + lex_stub.add_response("create_intent", {}) + yield Stubbed(iam, lex, sts, iam_stub, lex_stub) + iam_stub.assert_no_pending_responses() + lex_stub.assert_no_pending_responses() + sts_stub.assert_no_pending_responses() + + +def test_bot_build_waits_out_the_quota(stubbed: Stubbed) -> None: + """Two 402 quota errors at BuildBotLocale are waited out, and the bot is deleted after.""" + stubbed.add_quota_error() + stubbed.add_quota_error() + stubbed.lex_stub.add_response("build_bot_locale", {}) + stubbed.lex_stub.add_response("describe_bot_locale", {"botLocaleStatus": "Built"}) + stubbed.expect_teardown() + clock = FakeClock() + + with _lex_bot( + stubbed.iam, + stubbed.lex, + stubbed.sts, + "suffix", + sleep=clock.sleep, + clock=clock, + rand=lambda: 1.0, + ) as bot_id: + assert bot_id == BOT_ID + + assert clock.sleeps == [15.0, 30.0] + + +def test_failed_build_still_deletes_the_bot(stubbed: Stubbed) -> None: + """A build that fails on another error raises it at once and still deletes the bot.""" + stubbed.lex_stub.add_client_error( + "build_bot_locale", + service_error_code="ValidationException", + service_message="bad locale", + http_status_code=400, + ) + stubbed.expect_teardown() + clock = FakeClock() + + with pytest.raises(stubbed.lex.exceptions.ValidationException): + with _lex_bot( + stubbed.iam, + stubbed.lex, + stubbed.sts, + "suffix", + sleep=clock.sleep, + clock=clock, + ): + pass + + # DeleteBot and DeleteRole were called. + stubbed.lex_stub.assert_no_pending_responses() + stubbed.iam_stub.assert_no_pending_responses() + assert clock.sleeps == [] + + +@pytest.mark.parametrize( + "message", + [ + # Shares the prefix bot-locale-builds with the build quota. + "Validation failed for quota bot-locale-builds-per-bot. The maximum is 5.", + # The build quota's name in another letter case. + "Validation failed for quota BOT-LOCALE-BUILDS-PER-ACCOUNT. The maximum is 5.", + ], +) +def test_another_quota_is_raised_at_once(stubbed: Stubbed, message: str) -> None: + """A ServiceQuotaExceededException for another quota is not waited out.""" + stubbed.lex_stub.add_client_error( + "build_bot_locale", + service_error_code="ServiceQuotaExceededException", + service_message=message, + http_status_code=402, + ) + stubbed.expect_teardown() + clock = FakeClock() + + with pytest.raises(stubbed.lex.exceptions.ServiceQuotaExceededException): + with _lex_bot( + stubbed.iam, + stubbed.lex, + stubbed.sts, + "suffix", + sleep=clock.sleep, + clock=clock, + ): + pass + + stubbed.lex_stub.assert_no_pending_responses() + stubbed.iam_stub.assert_no_pending_responses() + assert clock.sleeps == [] + + +def test_failed_bot_deletion_still_deletes_the_role(stubbed: Stubbed) -> None: + """When DeleteBot fails after a failed build, DeleteRole is still called.""" + stubbed.lex_stub.add_client_error( + "build_bot_locale", + service_error_code="ValidationException", + service_message="bad locale", + http_status_code=400, + ) + stubbed.lex_stub.add_client_error( + "delete_bot", + service_error_code="PreconditionFailedException", + service_message="busy", + http_status_code=412, + ) + stubbed.iam_stub.add_response("delete_role", {}, {"RoleName": ANY}) + clock = FakeClock() + + with pytest.raises(stubbed.lex.exceptions.PreconditionFailedException) as caught: + with _lex_bot( + stubbed.iam, + stubbed.lex, + stubbed.sts, + "suffix", + sleep=clock.sleep, + clock=clock, + ): + pass + + # The build error stays in the chain, and the role was deleted. + assert isinstance( + caught.value.__context__, stubbed.lex.exceptions.ValidationException + ) + stubbed.lex_stub.assert_no_pending_responses() + stubbed.iam_stub.assert_no_pending_responses() + assert clock.sleeps == [] + + +def test_build_that_never_gets_the_quota_still_deletes_the_bot( + stubbed: Stubbed, +) -> None: + """A quota that lasts past the deadline raises the quota error and deletes the bot.""" + for _ in range(18): + stubbed.add_quota_error() + stubbed.expect_teardown() + clock = FakeClock() + + with pytest.raises(stubbed.lex.exceptions.ServiceQuotaExceededException): + with _lex_bot( + stubbed.iam, + stubbed.lex, + stubbed.sts, + "suffix", + sleep=clock.sleep, + clock=clock, + rand=lambda: 1.0, + ): + pass + + stubbed.lex_stub.assert_no_pending_responses() + stubbed.iam_stub.assert_no_pending_responses() + assert clock.now == 900 + + +def test_failed_bot_creation_still_deletes_the_role( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """When CreateBot fails after the role exists, DeleteRole is called and DeleteBot is not.""" + monkeypatch.setenv("AWS_CONFIG_FILE", "/nonexistent") + monkeypatch.setenv("AWS_SHARED_CREDENTIALS_FILE", "/nonexistent") + monkeypatch.delenv("AWS_PROFILE", raising=False) + session = boto3.Session( + aws_access_key_id="x", aws_secret_access_key="x", region_name="us-east-1" + ) + iam: IAMClient = session.client("iam") + lex: LexModelsV2Client = session.client("lexv2-models") + sts: STSClient = session.client("sts") + with Stubber(iam) as iam_stub, Stubber(lex) as lex_stub, Stubber(sts) as sts_stub: + sts_stub.add_response( + "get_caller_identity", + { + "Account": "123456789012", + "UserId": "AIDAEXAMPLE", + "Arn": "arn:aws:iam::123456789012:user/x", + }, + ) + iam_stub.add_response( + "create_role", + { + "Role": { + "Path": "/", + "RoleName": "role", + "RoleId": "AROAEXAMPLEEXAMPLE1", + "Arn": "arn:aws:iam::123456789012:role/role", + "CreateDate": datetime(2026, 12, 4), + } + }, + ) + lex_stub.add_client_error( + "create_bot", + service_error_code="ValidationException", + service_message="bad bot", + http_status_code=400, + ) + iam_stub.add_response("delete_role", {}, {"RoleName": ANY}) + + with pytest.raises(lex.exceptions.ValidationException): + with _lex_bot(iam, lex, sts, "suffix"): + pass + + # No DeleteBot was queued, so a call to it would fail the stubber. + iam_stub.assert_no_pending_responses() + lex_stub.assert_no_pending_responses() diff --git a/clients/aws-sdk-lex-runtime-v2/tests/integration/__init__.py b/clients/aws-sdk-lex-runtime-v2/tests/integration/__init__.py index 01a616f7a..b21b8dfe9 100644 --- a/clients/aws-sdk-lex-runtime-v2/tests/integration/__init__.py +++ b/clients/aws-sdk-lex-runtime-v2/tests/integration/__init__.py @@ -1,10 +1,18 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 +import json +import random +import time +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from typing import Any + from aws_sdk_lex_runtime_v2.aio.client import AsyncLexRuntimeV2Client from aws_sdk_lex_runtime_v2.aio.config import AsyncLexRuntimeV2Config from smithy_aws_core.aio.config import AsyncAwsConfigOverrides from smithy_http.aio.interfaces import AsyncHTTPClient +from retries import retry_on_quota BOT_ALIAS_ID = "TSTALIASID" LOCALE_ID = "en_US" @@ -23,3 +31,183 @@ async def create_lex_client( return AsyncLexRuntimeV2Client( config=await AsyncLexRuntimeV2Config.resolve(**overrides) ) + + +# Tags applied to all resources so orphaned resources from interrupted +# test runs can be discovered and cleaned up. +_TAGS = [{"Key": "Purpose", "Value": "IntegTest"}] + + +def _create_lex_bot( + iam_client: Any, lex_client: Any, sts_client: Any, role_name: str, bot_name: str +) -> str: + """Create a Lex V2 bot and its IAM role, before any locale is added. + + Args: + iam_client: A boto3 IAM client. + lex_client: A boto3 lexv2-models client. + sts_client: A boto3 STS client. + role_name: The name of the IAM role to create for the bot. + bot_name: The name of the Lex bot to create. + + Returns: + The bot ID. + """ + account_id = sts_client.get_caller_identity()["Account"] + role_arn = f"arn:aws:iam::{account_id}:role/{role_name}" + + # Create IAM role for the bot + trust_policy = { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Principal": {"Service": "lexv2.amazonaws.com"}, + "Action": "sts:AssumeRole", + } + ], + } + iam_client.create_role( + RoleName=role_name, + AssumeRolePolicyDocument=json.dumps(trust_policy), + Tags=_TAGS, + ) + + # Create bot + response = lex_client.create_bot( + botName=bot_name, + roleArn=role_arn, + dataPrivacy={"childDirected": False}, + # 5-minute idle timeout is sufficient for integration tests. + idleSessionTTLInSeconds=300, + botTags={t["Key"]: t["Value"] for t in _TAGS}, + ) + return response["botId"] + + +def _build_lex_bot( + lex_client: Any, + bot_id: str, + *, + sleep: Callable[[float], None] = time.sleep, + clock: Callable[[], float] = time.monotonic, + rand: Callable[[], float] = random.random, +) -> None: + """Add a locale with a Greeting intent to the bot and build it. + + Args: + lex_client: A boto3 lexv2-models client. + bot_id: The bot ID. + sleep: Waits between builds that hit the account's build quota. + clock: Measures the time spent waiting for the quota. + rand: Jitters the waits. + """ + lex_client.get_waiter("bot_available").wait(botId=bot_id) + + # Create locale + lex_client.create_bot_locale( + botId=bot_id, + botVersion="DRAFT", + localeId=LOCALE_ID, + # Required field. Confidence threshold (0-1) that determines when Lex + # inserts AMAZON.FallbackIntent into the interpretations list. + # 0.40 is a reasonable value for a simple test bot. + nluIntentConfidenceThreshold=0.40, + ) + lex_client.get_waiter("bot_locale_created").wait( + botId=bot_id, botVersion="DRAFT", localeId=LOCALE_ID + ) + + # Create intent + lex_client.create_intent( + intentName="Greeting", + botId=bot_id, + botVersion="DRAFT", + localeId=LOCALE_ID, + sampleUtterances=[ + {"utterance": "Hello"}, + {"utterance": "Hi"}, + {"utterance": "Hey"}, + ], + intentClosingSetting={ + "closingResponse": { + "messageGroups": [ + { + "message": { + "plainTextMessage": {"value": "Hello! How can I help you?"} + } + } + ] + }, + "active": True, + }, + ) + + # Build locale. The account allows 5 locale builds at a time, and runs that start + # together share it. A build and its wait take about 30 s. + def is_build_quota(error: Exception) -> bool: + return isinstance( + error, lex_client.exceptions.ServiceQuotaExceededException + ) and "bot-locale-builds-per-account" in str(error) + + retry_on_quota( + lambda: lex_client.build_bot_locale( + botId=bot_id, botVersion="DRAFT", localeId=LOCALE_ID + ), + is_build_quota, + sleep=sleep, + clock=clock, + rand=rand, + ) + lex_client.get_waiter("bot_locale_built").wait( + botId=bot_id, botVersion="DRAFT", localeId=LOCALE_ID + ) + + +def _delete_lex_bot( + iam_client: Any, lex_client: Any, role_name: str, bot_id: str | None +) -> None: + """Delete a Lex V2 bot and its associated IAM role. + + Args: + iam_client: A boto3 IAM client. + lex_client: A boto3 lexv2-models client. + role_name: The name of the IAM role to delete. + bot_id: The bot ID to delete, or None if creation failed. + """ + try: + if bot_id: + lex_client.delete_bot(botId=bot_id, skipResourceInUseCheck=True) + finally: + # Deleted even when DeleteBot fails, so the role does not leak. + try: + iam_client.delete_role(RoleName=role_name) + except iam_client.exceptions.NoSuchEntityException: + pass + + +@contextmanager +def _lex_bot( + iam_client: Any, + lex_client: Any, + sts_client: Any, + unique_suffix: str, + *, + sleep: Callable[[float], None] = time.sleep, + clock: Callable[[], float] = time.monotonic, + rand: Callable[[], float] = random.random, +) -> Iterator[str]: + """Yield the ID of a built bot, and delete the bot and its role on exit.""" + role_name = f"integ-test-lex-runtime-v2-role-{unique_suffix}" + bot_name = f"integ-test-lex-runtime-v2-bot-{unique_suffix}" + + bot_id = None + try: + # Recorded before the build, so a failed build still deletes the bot. + bot_id = _create_lex_bot( + iam_client, lex_client, sts_client, role_name, bot_name + ) + _build_lex_bot(lex_client, bot_id, sleep=sleep, clock=clock, rand=rand) + yield bot_id + finally: + _delete_lex_bot(iam_client, lex_client, role_name, bot_id) diff --git a/clients/aws-sdk-lex-runtime-v2/tests/integration/conftest.py b/clients/aws-sdk-lex-runtime-v2/tests/integration/conftest.py index 7475cefa3..c83ad2458 100644 --- a/clients/aws-sdk-lex-runtime-v2/tests/integration/conftest.py +++ b/clients/aws-sdk-lex-runtime-v2/tests/integration/conftest.py @@ -8,9 +8,9 @@ ``lex_bot`` fixture. """ -import json import uuid -from typing import TYPE_CHECKING, Any +from collections.abc import Iterator +from typing import TYPE_CHECKING import boto3 import pytest @@ -22,144 +22,15 @@ from types_boto3_lexv2_models import LexModelsV2Client from types_boto3_sts import STSClient -from . import LOCALE_ID, REGION - -# Tags applied to all resources so orphaned resources from interrupted -# test runs can be discovered and cleaned up. -_TAGS = [{"Key": "Purpose", "Value": "IntegTest"}] - - -def _create_lex_bot( - iam_client: Any, lex_client: Any, sts_client: Any, role_name: str, bot_name: str -) -> str: - """Create a Lex V2 bot with a Greeting intent. - - Args: - iam_client: A boto3 IAM client. - lex_client: A boto3 lexv2-models client. - sts_client: A boto3 STS client. - role_name: The name of the IAM role to create for the bot. - bot_name: The name of the Lex bot to create. - - Returns: - The bot ID. - """ - account_id = sts_client.get_caller_identity()["Account"] - role_arn = f"arn:aws:iam::{account_id}:role/{role_name}" - - # Create IAM role for the bot - trust_policy = { - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Principal": {"Service": "lexv2.amazonaws.com"}, - "Action": "sts:AssumeRole", - } - ], - } - iam_client.create_role( - RoleName=role_name, - AssumeRolePolicyDocument=json.dumps(trust_policy), - Tags=_TAGS, - ) - - # Create bot - response = lex_client.create_bot( - botName=bot_name, - roleArn=role_arn, - dataPrivacy={"childDirected": False}, - # 5-minute idle timeout is sufficient for integration tests. - idleSessionTTLInSeconds=300, - botTags={t["Key"]: t["Value"] for t in _TAGS}, - ) - bot_id = response["botId"] - lex_client.get_waiter("bot_available").wait(botId=bot_id) - - # Create locale - lex_client.create_bot_locale( - botId=bot_id, - botVersion="DRAFT", - localeId=LOCALE_ID, - # Required field. Confidence threshold (0-1) that determines when Lex - # inserts AMAZON.FallbackIntent into the interpretations list. - # 0.40 is a reasonable value for a simple test bot. - nluIntentConfidenceThreshold=0.40, - ) - lex_client.get_waiter("bot_locale_created").wait( - botId=bot_id, botVersion="DRAFT", localeId=LOCALE_ID - ) - - # Create intent - lex_client.create_intent( - intentName="Greeting", - botId=bot_id, - botVersion="DRAFT", - localeId=LOCALE_ID, - sampleUtterances=[ - {"utterance": "Hello"}, - {"utterance": "Hi"}, - {"utterance": "Hey"}, - ], - intentClosingSetting={ - "closingResponse": { - "messageGroups": [ - { - "message": { - "plainTextMessage": {"value": "Hello! How can I help you?"} - } - } - ] - }, - "active": True, - }, - ) - - # Build locale - lex_client.build_bot_locale(botId=bot_id, botVersion="DRAFT", localeId=LOCALE_ID) - lex_client.get_waiter("bot_locale_built").wait( - botId=bot_id, botVersion="DRAFT", localeId=LOCALE_ID - ) - - return bot_id - - -def _delete_lex_bot( - iam_client: Any, lex_client: Any, role_name: str, bot_id: str | None -) -> None: - """Delete a Lex V2 bot and its associated IAM role. - - Args: - iam_client: A boto3 IAM client. - lex_client: A boto3 lexv2-models client. - role_name: The name of the IAM role to delete. - bot_id: The bot ID to delete, or None if creation failed. - """ - if bot_id: - lex_client.delete_bot(botId=bot_id, skipResourceInUseCheck=True) - - try: - iam_client.delete_role(RoleName=role_name) - except iam_client.exceptions.NoSuchEntityException: - pass +from . import REGION, _lex_bot @pytest.fixture(scope="session") -def lex_bot(): +def lex_bot() -> Iterator[str]: """Create a Lex bot for the test session and delete it after.""" - unique_suffix = uuid.uuid4().hex[:16] - role_name = f"integ-test-lex-runtime-v2-role-{unique_suffix}" - bot_name = f"integ-test-lex-runtime-v2-bot-{unique_suffix}" - iam_client: IAMClient = boto3.client("iam") lex_client: LexModelsV2Client = boto3.client("lexv2-models", region_name=REGION) sts_client: STSClient = boto3.client("sts") - bot_id = None - try: - bot_id = _create_lex_bot( - iam_client, lex_client, sts_client, role_name, bot_name - ) + with _lex_bot(iam_client, lex_client, sts_client, uuid.uuid4().hex[:16]) as bot_id: yield bot_id - finally: - _delete_lex_bot(iam_client, lex_client, role_name, bot_id) diff --git a/tests/retries.py b/tests/retries.py new file mode 100644 index 000000000..45f7546c7 --- /dev/null +++ b/tests/retries.py @@ -0,0 +1,233 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 +# pyright: strict + +"""Backoff with jitter on the shared test account's limits, for live tests. + +TODO: remove the retry strategies when the pins move to a smithy-python release with +smithy-lang/smithy-python#955. Until then an unmodeled HTTP 400 throttle reaches the +client as a plain CallError that is not retry safe, so the standard strategy never +retries it, whatever max_attempts is. +""" + +import logging +import random +import re +import time +from collections.abc import Callable + +from smithy_core.exceptions import CallError, RetryError +from smithy_core.interfaces.retries import RetryBackoffStrategy, RetryToken +from smithy_core.retries import ( + ExponentialBackoffJitterType, + ExponentialRetryBackoffStrategy, + StandardRetryQuota, + StandardRetryStrategy, + StandardRetryToken, +) + +_logger = logging.getLogger(__name__) + +# The released pipeline attaches response_metadata only after the retry loop, so the +# status reads None when the strategy decides, and the error keeps no body or code. +# The message is the only signal. +_IAM_THROTTLE = re.compile( + r"Unknown error for operation com\.amazonaws\.iam#\w+ - status: 400, code: Throttling" +) + +# DynamoDB models ThrottlingException only on data plane operations. A control plane +# throttle names a ThrottlingException in its body, and the released client drops a +# body type the operation does not model, so an unmodeled 400 on these operations with +# no x-amzn-errortype header matches, a real validation error too (up to 6 attempts). +_DYNAMODB_CONTROL_PLANE_THROTTLE = re.compile( + r"Unknown error for operation com\.amazonaws\.dynamodb#" + r"(?:CreateTable|DeleteTable|DescribeTable|ListTagsOfResource|TagResource)" + r" - status: 400(?: - reason: .*)?" +) + +# The standard strategy's backoff for throttles: full jitter, 1 s base, 20 s cap. +_THROTTLE_BACKOFF_SCALE = 1.0 +_MAX_BACKOFF = 20.0 + +# Test only. A throttle retry takes 5 of the default quota's 500 tokens, and a call that +# gives up returns none of them, so a client that is throttled on many calls would stop +# retrying long before its attempt cap. +_RETRY_QUOTA_CAPACITY = 10_000 + + +class ThrottleRetryStrategy(StandardRetryStrategy): + """Retries the throttles that ``is_throttle`` names with the SDK's throttle backoff. + + A matched error is marked retry safe and as a throttle, and gets up to + ``throttle_max_attempts`` attempts. Every other error keeps ``max_attempts``, the + count the client uses today with max_attempts and retry_mode unset, in the + environment (AWS_MAX_ATTEMPTS, AWS_RETRY_MODE) and in the profile. A client with + this strategy still reads and validates those settings but no longer applies + them to retries. + """ + + def __init__( + self, + *, + is_throttle: Callable[[CallError], bool], + max_attempts: int, + throttle_max_attempts: int, + backoff_strategy: RetryBackoffStrategy | None = None, + random: Callable[[], float] = random.random, + ) -> None: + super().__init__( + backoff_strategy=backoff_strategy, + throttling_backoff_strategy=ExponentialRetryBackoffStrategy( + backoff_scale_value=_THROTTLE_BACKOFF_SCALE, + max_backoff=_MAX_BACKOFF, + jitter_type=ExponentialBackoffJitterType.FULL, + random=random, + ), + max_attempts=throttle_max_attempts, + retry_quota=StandardRetryQuota(initial_capacity=_RETRY_QUOTA_CAPACITY), + ) + self._is_throttle = is_throttle + self._default_max_attempts = max_attempts + + def refresh_retry_token_for_retry( + self, *, token_to_renew: RetryToken, error: Exception + ) -> StandardRetryToken: + attempts = token_to_renew.retry_count + 1 + if not (isinstance(error, CallError) and self._is_throttle(error)): + if attempts >= self._default_max_attempts: + raise RetryError( + f"Reached maximum number of allowed attempts: {self._default_max_attempts}" + ) from error + return super().refresh_retry_token_for_retry( + token_to_renew=token_to_renew, error=error + ) + + error.is_retry_safe = True + error.is_throttling_error = True + try: + token = super().refresh_retry_token_for_retry( + token_to_renew=token_to_renew, error=error + ) + except RetryError as retry_error: + error.add_note( + f"tests/retries.py retried this as a possible throttle and gave up " + f"after {attempts} attempts: {retry_error}. An unmodeled error with the " + f"same message is retried the same way (smithy-python#955)" + ) + raise + _logger.warning( + "Retrying attempt %d as a throttle in %.1f s: %s", + attempts, + token.retry_delay, + error.message, + ) + return token + + +def is_iam_throttle(error: CallError) -> bool: + """Whether the error is IAM's unmodeled ``Throttling`` HTTP 400.""" + return type(error) is CallError and bool(_IAM_THROTTLE.fullmatch(error.message)) + + +def is_dynamodb_control_plane_throttle(error: CallError) -> bool: + """Whether the error is an unmodeled HTTP 400 on one of the five DynamoDB control + plane operations that the integration tests call. + """ + return type(error) is CallError and bool( + _DYNAMODB_CONTROL_PLANE_THROTTLE.fullmatch(error.message) + ) + + +def iam_retry_strategy( + *, random: Callable[[], float] = random.random +) -> ThrottleRetryStrategy: + """A new strategy for one IAM client: 10 attempts on a throttle. + + With no x-amz-retry-after in the responses, the throttle waits add up to at most + 111 s; that header can add up to 5 s to each wait. + + Other errors keep the standard defaults of 3 attempts and a 50 ms backoff base, the + counts of a client with max_attempts and retry_mode unset in the environment + (AWS_MAX_ATTEMPTS, AWS_RETRY_MODE) and in the profile. A client with this strategy + still reads and validates those settings but no longer applies them to retries. + """ + return ThrottleRetryStrategy( + is_throttle=is_iam_throttle, + max_attempts=3, + throttle_max_attempts=10, + backoff_strategy=ExponentialRetryBackoffStrategy( + backoff_scale_value=0.05, + max_backoff=_MAX_BACKOFF, + jitter_type=ExponentialBackoffJitterType.FULL, + random=random, + ), + random=random, + ) + + +def dynamodb_retry_strategy( + *, random: Callable[[], float] = random.random +) -> ThrottleRetryStrategy: + """A new strategy for one DynamoDB client: 6 attempts on a throttle. + + With no x-amz-retry-after in the responses, the throttle waits add up to at most + 31 s; that header can add up to 5 s to each wait. + + Other errors keep DynamoDB's defaults of 4 attempts and a 25 ms backoff base, the + counts of a client with max_attempts and retry_mode unset in the environment + (AWS_MAX_ATTEMPTS, AWS_RETRY_MODE) and in the profile. A client with this strategy + still reads and validates those settings but no longer applies them to retries. + """ + return ThrottleRetryStrategy( + is_throttle=is_dynamodb_control_plane_throttle, + max_attempts=4, + throttle_max_attempts=6, + backoff_strategy=ExponentialRetryBackoffStrategy( + backoff_scale_value=0.025, + max_backoff=_MAX_BACKOFF, + jitter_type=ExponentialBackoffJitterType.FULL, + random=random, + ), + random=random, + ) + + +def retry_on_quota[T]( + call: Callable[[], T], + is_quota: Callable[[Exception], bool], + *, + base: float = 15.0, + cap: float = 60.0, + deadline: float = 900.0, + sleep: Callable[[float], None] = time.sleep, + clock: Callable[[], float] = time.monotonic, + rand: Callable[[], float] = random.random, +) -> T: + """Repeats ``call`` while it raises an error that ``is_quota`` accepts. + + Each wait is ``rand() * min(base * 2 ** (n - 1), cap)``, clamped to the time left + before ``deadline`` seconds. At the deadline the last error is raised. Any other + error is raised at once. + """ + start = clock() + attempts = 0 + while True: + attempts += 1 + try: + return call() + except Exception as e: + if not is_quota(e): + raise + elapsed = clock() - start + remaining = deadline - elapsed + if remaining <= 0: + e.add_note( + f"tests/retries.py waited {elapsed:.0f} s over {attempts} attempts " + f"for the quota, up to its deadline of {deadline:.0f} s" + ) + raise + wait = min(rand() * min(base * 2 ** (attempts - 1), cap), remaining) + _logger.warning( + "Quota reached at attempt %d, retrying in %.1f s: %s", attempts, wait, e + ) + sleep(wait)