From 83bc5a4c46802f64801429cf719c32ef5644ea46 Mon Sep 17 00:00:00 2001 From: Mahdi-Hasan <43575088+Mahdi-Hasan@users.noreply.github.com> Date: Mon, 2 Nov 2026 17:17:50 +0600 Subject: [PATCH 1/2] Python: Prefer boto3 session and injected client region over BEDROCK_REGION BedrockChatClient and BedrockEmbeddingClient resolved BEDROCK_REGION before the region of a caller-supplied boto3 session, so a session configured for another region was silently redirected. An injected runtime client also reported the ambient region instead of its own. Region now resolves as: injected client's region, explicit `region=`, boto3 session region, BEDROCK_REGION, then us-east-1. Fixes #9962 Co-Authored-By: Claude Opus 5.5 --- .../agent_framework_bedrock/_chat_client.py | 12 ++++++---- .../_embedding_client.py | 23 +++++++++++-------- .../bedrock/test_bedrock_embedding_client.py | 23 +++++++++++++++---- .../bedrock/tests/test_bedrock_client.py | 21 +++++++++++++---- 4 files changed, 57 insertions(+), 22 deletions(-) diff --git a/python/packages/bedrock/agent_framework_bedrock/_chat_client.py b/python/packages/bedrock/agent_framework_bedrock/_chat_client.py index d03137e2eba..2c3b9fd5650 100644 --- a/python/packages/bedrock/agent_framework_bedrock/_chat_client.py +++ b/python/packages/bedrock/agent_framework_bedrock/_chat_client.py @@ -277,8 +277,8 @@ def __init__( """Create a Bedrock chat client and load AWS credentials. Args: - region: Region to send Bedrock requests to; falls back to BEDROCK_REGION, then to the region - of ``boto3_session``, then to us-east-1. + region: Region to send Bedrock requests to; falls back to the region of ``boto3_session``, + then to BEDROCK_REGION, then to us-east-1. A supplied ``client`` keeps its own region. model: Default model identifier; falls back to BEDROCK_CHAT_MODEL. access_key: Optional AWS access key for manual credential injection. secret_key: Optional AWS secret key paired with ``access_key``. @@ -322,8 +322,12 @@ class MyOptions(BedrockChatOptions, total=False): env_file_path=env_file_path, env_file_encoding=env_file_encoding, ) - session_region = boto3_session.region_name if boto3_session and not client else None - region = settings.get("region") or session_region or DEFAULT_REGION + if client is not None: + client_region = getattr(getattr(client, "meta", None), "region_name", None) + region = client_region if isinstance(client_region, str) else (settings.get("region") or DEFAULT_REGION) + else: + session_region = boto3_session.region_name if boto3_session else None + region = region or session_region or settings.get("region") or DEFAULT_REGION chat_model = settings.get("chat_model") self._owns_client = client is None diff --git a/python/packages/bedrock/agent_framework_bedrock/_embedding_client.py b/python/packages/bedrock/agent_framework_bedrock/_embedding_client.py index 562b4229f5a..8c08042def1 100644 --- a/python/packages/bedrock/agent_framework_bedrock/_embedding_client.py +++ b/python/packages/bedrock/agent_framework_bedrock/_embedding_client.py @@ -84,10 +84,10 @@ class RawBedrockEmbeddingClient( Keyword Args: model: The Bedrock embedding model ID (e.g. "amazon.titan-embed-text-v2:0"). Can also be set via environment variable BEDROCK_EMBEDDING_MODEL. - region: AWS region. Will try to load from BEDROCK_REGION env var, - if not set, the region of ``boto3_session`` is used, or without a session - the regular Boto3 configuration/loading applies (which may include other - env vars, config files, or instance metadata). Falls back to us-east-1. + region: AWS region. If not set, the region of ``boto3_session`` is used, then the + BEDROCK_REGION env var. Without a session the regular Boto3 configuration/loading + applies (which may include other env vars, config files, or instance metadata). + Falls back to us-east-1. A supplied ``client`` keeps its own region. access_key: AWS access key for manual credential injection. secret_key: AWS secret key paired with access_key. session_token: AWS session token for temporary credentials. @@ -128,18 +128,21 @@ def __init__( if client: self._bedrock_client = client + client_region = getattr(getattr(client, "meta", None), "region_name", None) + if isinstance(client_region, str): + resolved_region = client_region else: if not boto3_session: session_kwargs: dict[str, Any] = {} - if region := settings.get("region"): - session_kwargs["region_name"] = region + if settings_region := settings.get("region"): + session_kwargs["region_name"] = settings_region if (access_key := settings.get("access_key")) and (secret_key := settings.get("secret_key")): session_kwargs["aws_access_key_id"] = access_key.get_secret_value() session_kwargs["aws_secret_access_key"] = secret_key.get_secret_value() if session_token := settings.get("session_token"): session_kwargs["aws_session_token"] = session_token.get_secret_value() boto3_session = Boto3Session(**session_kwargs) - resolved_region = settings.get("region") or boto3_session.region_name or DEFAULT_REGION + resolved_region = region or boto3_session.region_name or settings.get("region") or DEFAULT_REGION self._bedrock_client = boto3_session.client( "bedrock-runtime", region_name=resolved_region, @@ -240,9 +243,9 @@ class BedrockEmbeddingClient( Keyword Args: model: The Bedrock embedding model ID (e.g. "amazon.titan-embed-text-v2:0"). Can also be set via environment variable BEDROCK_EMBEDDING_MODEL. - region: AWS region. Can also be set via environment variable BEDROCK_REGION. - If not set, the region of ``boto3_session`` is used, or without a session - the regular Boto3 configuration. Defaults to "us-east-1". + region: AWS region. If not set, the region of ``boto3_session`` is used, then the + environment variable BEDROCK_REGION, or without a session the regular Boto3 + configuration. Defaults to "us-east-1". A supplied ``client`` keeps its own region. access_key: AWS access key for manual credential injection. secret_key: AWS secret key paired with access_key. session_token: AWS session token for temporary credentials. diff --git a/python/packages/bedrock/tests/bedrock/test_bedrock_embedding_client.py b/python/packages/bedrock/tests/bedrock/test_bedrock_embedding_client.py index e7ec102509a..2ffe1d52053 100644 --- a/python/packages/bedrock/tests/bedrock/test_bedrock_embedding_client.py +++ b/python/packages/bedrock/tests/bedrock/test_bedrock_embedding_client.py @@ -158,11 +158,12 @@ def client(self, service_name: str, *, region_name: str, config: Any) -> _StubBe ("region", "env_region", "session_region", "expected_region"), [ (None, None, "eu-west-1", "eu-west-1"), - ("us-west-2", None, "eu-west-1", "us-west-2"), - (None, "ap-south-1", "eu-west-1", "ap-south-1"), + ("us-west-2", "ap-south-1", "eu-west-1", "us-west-2"), + (None, "ap-south-1", "eu-west-1", "eu-west-1"), + (None, "ap-south-1", None, "ap-south-1"), (None, None, None, "us-east-1"), ], - ids=["session-region", "region-argument-wins", "env-region-wins", "default-region"], + ids=["session-region", "region-argument-wins", "session-region-beats-env", "env-region", "default-region"], ) async def test_bedrock_embedding_resolves_region_with_boto3_session( monkeypatch: pytest.MonkeyPatch, @@ -171,7 +172,7 @@ async def test_bedrock_embedding_resolves_region_with_boto3_session( session_region: str | None, expected_region: str, ) -> None: - """A configured region wins, then the provided session's region, then the default region.""" + """The region argument wins, then the provided session's region, then BEDROCK_REGION, then the default.""" if env_region: monkeypatch.setenv("BEDROCK_REGION", env_region) else: @@ -214,6 +215,20 @@ async def test_bedrock_embedding_ignores_boto3_session_when_runtime_client_suppl assert client.region == "us-east-1" +async def test_bedrock_embedding_reports_region_of_supplied_runtime_client(monkeypatch: pytest.MonkeyPatch) -> None: + """A preconfigured runtime client defines the region, so BEDROCK_REGION should not change it.""" + monkeypatch.setenv("BEDROCK_REGION", "ap-south-1") + runtime = _StubBedrockEmbeddingRuntime() + runtime.meta.region_name = "eu-west-1" + + client = BedrockEmbeddingClient( + model="amazon.titan-embed-text-v2:0", + client=runtime, # pyrefly: ignore[bad-argument-type] # ty: ignore[invalid-argument-type] # pyright: ignore[reportArgumentType] + ) + + assert client.region == "eu-west-1" + + # region: Integration Tests skip_if_bedrock_embedding_integration_tests_disabled = pytest.mark.skipif( diff --git a/python/packages/bedrock/tests/test_bedrock_client.py b/python/packages/bedrock/tests/test_bedrock_client.py index 9f753e8835d..18d1765c853 100644 --- a/python/packages/bedrock/tests/test_bedrock_client.py +++ b/python/packages/bedrock/tests/test_bedrock_client.py @@ -668,11 +668,12 @@ def test_init_uses_boto3_session_when_runtime_client_not_supplied() -> None: ("region", "env_region", "session_region", "expected_region"), [ (None, None, "eu-west-1", "eu-west-1"), - ("us-west-2", None, "eu-west-1", "us-west-2"), - (None, "ap-south-1", "eu-west-1", "ap-south-1"), + ("us-west-2", "ap-south-1", "eu-west-1", "us-west-2"), + (None, "ap-south-1", "eu-west-1", "eu-west-1"), + (None, "ap-south-1", None, "ap-south-1"), (None, None, None, "us-east-1"), ], - ids=["session-region", "region-argument-wins", "env-region-wins", "default-region"], + ids=["session-region", "region-argument-wins", "session-region-beats-env", "env-region", "default-region"], ) def test_init_resolves_region_with_boto3_session( monkeypatch: pytest.MonkeyPatch, @@ -681,7 +682,7 @@ def test_init_resolves_region_with_boto3_session( session_region: str | None, expected_region: str, ) -> None: - """A configured region wins, then the provided session's region, then the default region.""" + """The region argument wins, then the provided session's region, then BEDROCK_REGION, then the default.""" if env_region: monkeypatch.setenv("BEDROCK_REGION", env_region) else: @@ -711,6 +712,18 @@ def test_init_ignores_boto3_session_region_when_runtime_client_supplied(monkeypa assert client.service_url() == "https://bedrock-runtime.us-east-1.amazonaws.com" +def test_init_reports_region_of_supplied_runtime_client(monkeypatch: pytest.MonkeyPatch) -> None: + """A preconfigured runtime client defines the region, so BEDROCK_REGION should not change it.""" + monkeypatch.setenv("BEDROCK_REGION", "ap-south-1") + runtime = _StubBedrockRuntime() + runtime.meta = MagicMock(region_name="eu-west-1") # type: ignore[attr-defined] + + client = BedrockChatClient(model="amazon.titan-text", client=cast(BaseClient, runtime)) + + assert client.region == "eu-west-1" + assert client.service_url() == "https://bedrock-runtime.eu-west-1.amazonaws.com" + + @pytest.mark.parametrize("secret_type", [str, SecretString], ids=["str", "secret"]) @pytest.mark.parametrize( ("client_type", "module"), From b9e4833584dddca0c58f1f0405e7ab086fcfa4a0 Mon Sep 17 00:00:00 2001 From: Mahdi-Hasan <43575088+Mahdi-Hasan@users.noreply.github.com> Date: Wed, 4 Nov 2026 12:42:29 +0600 Subject: [PATCH 2/2] Python: Avoid a type-checker error on the stub runtime's meta attribute --- python/packages/bedrock/tests/test_bedrock_client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/packages/bedrock/tests/test_bedrock_client.py b/python/packages/bedrock/tests/test_bedrock_client.py index 18d1765c853..a5026ef348d 100644 --- a/python/packages/bedrock/tests/test_bedrock_client.py +++ b/python/packages/bedrock/tests/test_bedrock_client.py @@ -716,7 +716,7 @@ def test_init_reports_region_of_supplied_runtime_client(monkeypatch: pytest.Monk """A preconfigured runtime client defines the region, so BEDROCK_REGION should not change it.""" monkeypatch.setenv("BEDROCK_REGION", "ap-south-1") runtime = _StubBedrockRuntime() - runtime.meta = MagicMock(region_name="eu-west-1") # type: ignore[attr-defined] + setattr(runtime, "meta", MagicMock(region_name="eu-west-1")) # noqa: B010 client = BedrockChatClient(model="amazon.titan-text", client=cast(BaseClient, runtime))