|
| 1 | +""" |
| 2 | +Unit tests for connection cleanup in BaseGatewayComponent._handle_agent_event. |
| 3 | +
|
| 4 | +Verifies that _close_external_connections is called in error paths before |
| 5 | +remove_context, preventing SSE connection leaks. |
| 6 | +""" |
| 7 | + |
| 8 | +import pytest |
| 9 | +from unittest.mock import AsyncMock, Mock |
| 10 | + |
| 11 | +from a2a.types import ( |
| 12 | + JSONRPCResponse, |
| 13 | + JSONRPCError, |
| 14 | + Task, |
| 15 | + TaskState, |
| 16 | + TaskStatus, |
| 17 | + TaskStatusUpdateEvent, |
| 18 | +) |
| 19 | + |
| 20 | +from solace_agent_mesh.gateway.base.component import BaseGatewayComponent |
| 21 | +from solace_agent_mesh.gateway.base.task_context import TaskContextManager |
| 22 | + |
| 23 | + |
| 24 | +TASK_ID = "test-task-123" |
| 25 | +RPC_ID = "rpc-001" |
| 26 | + |
| 27 | + |
| 28 | +def _build_component(): |
| 29 | + """Build a mock BaseGatewayComponent with real TaskContextManager.""" |
| 30 | + component = Mock(spec=BaseGatewayComponent) |
| 31 | + component.log_identifier = "[TestGateway]" |
| 32 | + component.task_context_manager = TaskContextManager() |
| 33 | + component._send_error_to_external = AsyncMock() |
| 34 | + component._close_external_connections = AsyncMock() |
| 35 | + component._process_parsed_a2a_event = AsyncMock() |
| 36 | + component._handle_agent_event = ( |
| 37 | + BaseGatewayComponent._handle_agent_event.__get__(component) |
| 38 | + ) |
| 39 | + return component |
| 40 | + |
| 41 | + |
| 42 | +def _store_context(component, task_id=TASK_ID): |
| 43 | + """Store a minimal external request context for the given task.""" |
| 44 | + ctx = {"sse_task_id": task_id, "connection": "mock-sse-conn"} |
| 45 | + component.task_context_manager.store_context(task_id, ctx) |
| 46 | + return ctx |
| 47 | + |
| 48 | + |
| 49 | +def _valid_rpc_response_payload(task_id=TASK_ID, rpc_id=RPC_ID): |
| 50 | + """Build a valid JSONRPCResponse payload with a TaskStatusUpdateEvent result.""" |
| 51 | + event = TaskStatusUpdateEvent( |
| 52 | + task_id=task_id, |
| 53 | + context_id=task_id, |
| 54 | + final=False, |
| 55 | + status=TaskStatus(state=TaskState.working), |
| 56 | + ) |
| 57 | + return JSONRPCResponse(id=rpc_id, result=event).model_dump(mode="json") |
| 58 | + |
| 59 | + |
| 60 | +def _rpc_response_with_null_result(rpc_id=RPC_ID): |
| 61 | + """Build a JSONRPCResponse where both result and error are None.""" |
| 62 | + return {"jsonrpc": "2.0", "id": rpc_id, "result": None} |
| 63 | + |
| 64 | + |
| 65 | +def _rpc_response_with_error(rpc_id=RPC_ID): |
| 66 | + """Build a JSONRPCResponse carrying an error.""" |
| 67 | + error = JSONRPCError(code=-32000, message="Agent exploded") |
| 68 | + return JSONRPCResponse(id=rpc_id, error=error).model_dump(mode="json") |
| 69 | + |
| 70 | + |
| 71 | +def _rpc_response_with_task_id_mismatch(rpc_id=RPC_ID): |
| 72 | + """Build a JSONRPCResponse whose inner task_id mismatches the topic task_id.""" |
| 73 | + event = TaskStatusUpdateEvent( |
| 74 | + task_id="wrong-task-id", |
| 75 | + context_id="wrong-task-id", |
| 76 | + final=False, |
| 77 | + status=TaskStatus(state=TaskState.working), |
| 78 | + ) |
| 79 | + return JSONRPCResponse(id=rpc_id, result=event).model_dump(mode="json") |
| 80 | + |
| 81 | + |
| 82 | +class TestHandleAgentEventConnectionCleanup: |
| 83 | + """Verify _close_external_connections is called in all error paths.""" |
| 84 | + |
| 85 | + @pytest.mark.asyncio |
| 86 | + async def test_null_result_closes_connections_before_removing_context(self): |
| 87 | + """Error path 1: result is None — connections must close before context removal.""" |
| 88 | + component = _build_component() |
| 89 | + _store_context(component) |
| 90 | + |
| 91 | + result = await component._handle_agent_event( |
| 92 | + "topic/response", _rpc_response_with_null_result(), TASK_ID |
| 93 | + ) |
| 94 | + |
| 95 | + assert result is False |
| 96 | + component._send_error_to_external.assert_called_once() |
| 97 | + component._close_external_connections.assert_called_once() |
| 98 | + assert component.task_context_manager.get_context(TASK_ID) is None |
| 99 | + |
| 100 | + @pytest.mark.asyncio |
| 101 | + async def test_task_id_mismatch_closes_connections_before_removing_context(self): |
| 102 | + """Error path 1 variant: task_id mismatch nullifies parsed event.""" |
| 103 | + component = _build_component() |
| 104 | + _store_context(component) |
| 105 | + |
| 106 | + result = await component._handle_agent_event( |
| 107 | + "topic/response", _rpc_response_with_task_id_mismatch(), TASK_ID |
| 108 | + ) |
| 109 | + |
| 110 | + assert result is False |
| 111 | + component._send_error_to_external.assert_called_once() |
| 112 | + component._close_external_connections.assert_called_once() |
| 113 | + assert component.task_context_manager.get_context(TASK_ID) is None |
| 114 | + |
| 115 | + @pytest.mark.asyncio |
| 116 | + async def test_process_event_exception_closes_connections_before_removing_context(self): |
| 117 | + """Error path 2: _process_parsed_a2a_event raises — connections must close.""" |
| 118 | + component = _build_component() |
| 119 | + _store_context(component) |
| 120 | + component._process_parsed_a2a_event.side_effect = RuntimeError("boom") |
| 121 | + |
| 122 | + result = await component._handle_agent_event( |
| 123 | + "topic/response", _valid_rpc_response_payload(), TASK_ID |
| 124 | + ) |
| 125 | + |
| 126 | + assert result is False |
| 127 | + component._send_error_to_external.assert_called_once() |
| 128 | + component._close_external_connections.assert_called_once() |
| 129 | + assert component.task_context_manager.get_context(TASK_ID) is None |
| 130 | + |
| 131 | + @pytest.mark.asyncio |
| 132 | + async def test_close_called_after_send_error_and_before_context_gone(self): |
| 133 | + """Verify ordering: send_error → close_connections → context removed.""" |
| 134 | + component = _build_component() |
| 135 | + _store_context(component) |
| 136 | + |
| 137 | + call_order = [] |
| 138 | + component._send_error_to_external.side_effect = ( |
| 139 | + lambda *a, **kw: call_order.append("send_error") |
| 140 | + ) |
| 141 | + |
| 142 | + original_close = component._close_external_connections |
| 143 | + |
| 144 | + async def track_close(*a, **kw): |
| 145 | + assert component.task_context_manager.get_context(TASK_ID) is not None, ( |
| 146 | + "Context was removed before _close_external_connections" |
| 147 | + ) |
| 148 | + call_order.append("close_connections") |
| 149 | + return await original_close(*a, **kw) |
| 150 | + |
| 151 | + component._close_external_connections = track_close |
| 152 | + |
| 153 | + await component._handle_agent_event( |
| 154 | + "topic/response", _rpc_response_with_null_result(), TASK_ID |
| 155 | + ) |
| 156 | + |
| 157 | + assert call_order == ["send_error", "close_connections"] |
| 158 | + assert component.task_context_manager.get_context(TASK_ID) is None |
| 159 | + |
| 160 | + |
| 161 | +class TestHandleAgentEventConnectionCleanupOnProcessException: |
| 162 | + """Same ordering guarantees for the _process_parsed_a2a_event exception path.""" |
| 163 | + |
| 164 | + @pytest.mark.asyncio |
| 165 | + async def test_close_called_after_send_error_and_before_context_gone(self): |
| 166 | + """Verify ordering in exception path: send_error → close → context removed.""" |
| 167 | + component = _build_component() |
| 168 | + _store_context(component) |
| 169 | + component._process_parsed_a2a_event.side_effect = ValueError("bad data") |
| 170 | + |
| 171 | + call_order = [] |
| 172 | + component._send_error_to_external.side_effect = ( |
| 173 | + lambda *a, **kw: call_order.append("send_error") |
| 174 | + ) |
| 175 | + |
| 176 | + original_close = component._close_external_connections |
| 177 | + |
| 178 | + async def track_close(*a, **kw): |
| 179 | + assert component.task_context_manager.get_context(TASK_ID) is not None, ( |
| 180 | + "Context was removed before _close_external_connections" |
| 181 | + ) |
| 182 | + call_order.append("close_connections") |
| 183 | + return await original_close(*a, **kw) |
| 184 | + |
| 185 | + component._close_external_connections = track_close |
| 186 | + |
| 187 | + await component._handle_agent_event( |
| 188 | + "topic/response", _valid_rpc_response_payload(), TASK_ID |
| 189 | + ) |
| 190 | + |
| 191 | + assert call_order == ["send_error", "close_connections"] |
| 192 | + assert component.task_context_manager.get_context(TASK_ID) is None |
| 193 | + |
| 194 | + @pytest.mark.asyncio |
| 195 | + async def test_stream_buffer_context_also_removed(self): |
| 196 | + """Both task context and stream buffer context should be cleaned up.""" |
| 197 | + component = _build_component() |
| 198 | + _store_context(component) |
| 199 | + component.task_context_manager.store_context( |
| 200 | + f"{TASK_ID}_stream_buffer", {"buffer": []} |
| 201 | + ) |
| 202 | + component._process_parsed_a2a_event.side_effect = RuntimeError("boom") |
| 203 | + |
| 204 | + await component._handle_agent_event( |
| 205 | + "topic/response", _valid_rpc_response_payload(), TASK_ID |
| 206 | + ) |
| 207 | + |
| 208 | + assert component.task_context_manager.get_context(TASK_ID) is None |
| 209 | + assert ( |
| 210 | + component.task_context_manager.get_context(f"{TASK_ID}_stream_buffer") |
| 211 | + is None |
| 212 | + ) |
| 213 | + |
| 214 | + |
| 215 | +class TestHandleAgentEventHappyPath: |
| 216 | + """Verify _close_external_connections is NOT called by _handle_agent_event |
| 217 | + in the happy path (it's the responsibility of _process_parsed_a2a_event).""" |
| 218 | + |
| 219 | + @pytest.mark.asyncio |
| 220 | + async def test_successful_event_does_not_close_connections(self): |
| 221 | + """Happy path delegates to _process_parsed_a2a_event without closing.""" |
| 222 | + component = _build_component() |
| 223 | + _store_context(component) |
| 224 | + |
| 225 | + result = await component._handle_agent_event( |
| 226 | + "topic/response", _valid_rpc_response_payload(), TASK_ID |
| 227 | + ) |
| 228 | + |
| 229 | + assert result is True |
| 230 | + component._close_external_connections.assert_not_called() |
| 231 | + component._send_error_to_external.assert_not_called() |
| 232 | + |
| 233 | + |
| 234 | +class TestHandleAgentEventNoContext: |
| 235 | + """Edge case: no context stored for the task_id.""" |
| 236 | + |
| 237 | + @pytest.mark.asyncio |
| 238 | + async def test_missing_context_returns_true_without_closing(self): |
| 239 | + """When no context exists, the method returns early without closing.""" |
| 240 | + component = _build_component() |
| 241 | + |
| 242 | + result = await component._handle_agent_event( |
| 243 | + "topic/response", _valid_rpc_response_payload(), TASK_ID |
| 244 | + ) |
| 245 | + |
| 246 | + assert result is True |
| 247 | + component._close_external_connections.assert_not_called() |
| 248 | + component._send_error_to_external.assert_not_called() |
| 249 | + |
| 250 | + @pytest.mark.asyncio |
| 251 | + async def test_invalid_payload_returns_false_without_closing(self): |
| 252 | + """Completely invalid payload fails before reaching cleanup paths.""" |
| 253 | + component = _build_component() |
| 254 | + |
| 255 | + result = await component._handle_agent_event( |
| 256 | + "topic/response", {"garbage": True}, TASK_ID |
| 257 | + ) |
| 258 | + |
| 259 | + assert result is False |
| 260 | + component._close_external_connections.assert_not_called() |
| 261 | + component._send_error_to_external.assert_not_called() |
| 262 | + |
| 263 | + |
| 264 | +class TestHandleAgentEventWithRPCError: |
| 265 | + """When the RPC response carries an error, it goes through _process_parsed_a2a_event.""" |
| 266 | + |
| 267 | + @pytest.mark.asyncio |
| 268 | + async def test_rpc_error_delegates_to_process_parsed_event(self): |
| 269 | + """An error in the RPC response is parsed and delegated, not handled locally.""" |
| 270 | + component = _build_component() |
| 271 | + _store_context(component) |
| 272 | + |
| 273 | + result = await component._handle_agent_event( |
| 274 | + "topic/response", _rpc_response_with_error(), TASK_ID |
| 275 | + ) |
| 276 | + |
| 277 | + assert result is True |
| 278 | + component._process_parsed_a2a_event.assert_called_once() |
| 279 | + component._close_external_connections.assert_not_called() |
0 commit comments