From 041d7068a2251ce379d86321a2186d1f332a9269 Mon Sep 17 00:00:00 2001 From: hyeonsang010716 Date: Thu, 19 Nov 2026 14:19:39 +0900 Subject: [PATCH 1/2] fix(event_handler): clear Bedrock Agent function context when a tool raises BedrockAgentFunctionResolver only cleared the context after a tool returned. When the tool raised, the error response was built without clearing it, so data added with append_context carried over to the next invocation on the same warm container. An event missing a required field had the same problem. Clear the context in a finally block in resolve(), as ApiGatewayResolver and AppSyncResolver already do. --- .../event_handler/bedrock_agent_function.py | 4 +- .../test_bedrock_agent_functions.py | 44 +++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/aws_lambda_powertools/event_handler/bedrock_agent_function.py b/aws_lambda_powertools/event_handler/bedrock_agent_function.py index 7f51f2b9b1b..527da44b2b2 100644 --- a/aws_lambda_powertools/event_handler/bedrock_agent_function.py +++ b/aws_lambda_powertools/event_handler/bedrock_agent_function.py @@ -192,6 +192,8 @@ def resolve(self, event: dict[str, Any], context: Any) -> dict[str, Any]: return self._resolve() except KeyError as e: raise ValueError(f"Missing required field: {str(e)}") from e + finally: + self.clear_context() def _resolve(self) -> dict[str, Any]: """Internal resolution logic""" @@ -235,8 +237,6 @@ def _resolve(self) -> dict[str, Any]: # Call the function with the filtered parameters result = func(**valid_params) - self.clear_context() - # Build and return the response return BedrockFunctionsResponseBuilder(result).build(self.current_event, serializer=self.serializer) except Exception as error: diff --git a/tests/functional/event_handler/required_dependencies/test_bedrock_agent_functions.py b/tests/functional/event_handler/required_dependencies/test_bedrock_agent_functions.py index 4719f8df110..76de1acab89 100644 --- a/tests/functional/event_handler/required_dependencies/test_bedrock_agent_functions.py +++ b/tests/functional/event_handler/required_dependencies/test_bedrock_agent_functions.py @@ -350,6 +350,50 @@ def second_function(): assert not hasattr(app.context, "new_key") +def test_bedrock_agent_function_clears_context_when_tool_raises(): + # GIVEN a Bedrock Agent Function resolver with a tool that appends context and then raises + app = BedrockAgentFunctionResolver() + + @app.tool() + def failing_function(): + app.append_context(user_id="12345") + raise ValueError("Something went wrong") + + @app.tool() + def context_function(): + return dict(app.context) + + # WHEN the failing tool is invoked + raw_event = load_event("bedrockAgentFunctionEvent.json") + raw_event["function"] = "failing_function" + failed_result = app.resolve(raw_event, LambdaContext()) + + # THEN the error is returned to the agent and the context is cleared + failed_body = failed_result["response"]["functionResponse"]["responseBody"]["TEXT"]["body"] + assert failed_body == json.dumps("Error: ValueError: Something went wrong") + assert app.context == {} + + # WHEN the next invocation runs in the same execution environment + raw_event["function"] = "context_function" + next_result = app.resolve(raw_event, LambdaContext()) + + # THEN it does not see the context from the failed invocation + assert next_result["response"]["functionResponse"]["responseBody"]["TEXT"]["body"] == json.dumps({}) + + +def test_bedrock_agent_function_clears_context_when_event_is_invalid(): + # GIVEN a Bedrock Agent Function resolver with context appended before resolving + app = BedrockAgentFunctionResolver() + app.append_context(user_id="12345") + + # WHEN resolving an event without the required fields + with pytest.raises(ValueError, match="Missing required field"): + app.resolve({}, LambdaContext()) + + # THEN the context is cleared + assert app.context == {} + + def test_resolve_with_no_current_event(): """Test that _resolve() raises ValueError when current_event is None""" # GIVEN a Bedrock Agent Function resolver with no current event From 84a5271878a0bc3b952ea918af3df4d0b7343e9d Mon Sep 17 00:00:00 2001 From: hyeonsang010716 Date: Thu, 19 Nov 2026 14:27:02 +0900 Subject: [PATCH 2/2] test(event_handler): pass a plain dict as context in the invalid event test --- .../required_dependencies/test_bedrock_agent_functions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/functional/event_handler/required_dependencies/test_bedrock_agent_functions.py b/tests/functional/event_handler/required_dependencies/test_bedrock_agent_functions.py index 76de1acab89..ed24df843b6 100644 --- a/tests/functional/event_handler/required_dependencies/test_bedrock_agent_functions.py +++ b/tests/functional/event_handler/required_dependencies/test_bedrock_agent_functions.py @@ -388,7 +388,7 @@ def test_bedrock_agent_function_clears_context_when_event_is_invalid(): # WHEN resolving an event without the required fields with pytest.raises(ValueError, match="Missing required field"): - app.resolve({}, LambdaContext()) + app.resolve({}, {}) # THEN the context is cleared assert app.context == {}