2222from typing import Optional
2323from unittest import mock
2424
25+ from google .adk .agents .llm_agent import Agent
26+ from google .adk .apps .app import App
2527from google .adk .integrations .model_armor import ModelArmorConfig
2628from google .adk .integrations .model_armor import ModelArmorPlugin
2729from google .adk .integrations .model_armor ._config import _DEFAULT_TOOL_OUTPUT_BLOCKED_MESSAGE
3133from google .adk .integrations .model_armor ._plugin import _TOOL_OUTPUT_CHUNK_OVERLAP_CHARS
3234from google .adk .models .llm_request import LlmRequest
3335from google .adk .models .llm_response import LlmResponse
36+ from google .adk .runners import Runner
37+ from google .adk .sessions .in_memory_session_service import InMemorySessionService
3438from google .adk .utils import _mtls_utils
3539from google .auth .credentials import AnonymousCredentials
3640from google .cloud import modelarmor_v1
3741from google .genai import types
3842import pytest
3943
44+ from tests .unittests .testing_utils import MockModel
45+
4046_PROMPT_TEMPLATE_PATH = (
4147 'projects/test-project/locations/us-central1/templates/test-prompt'
4248)
@@ -725,7 +731,7 @@ async def test_sanitize_model_response_returns_the_sanitization_result():
725731
726732
727733@pytest .mark .asyncio
728- async def test_close_only_closes_own_client () :
734+ async def test_close_leaves_supplied_client_untouched () -> None :
729735 """A supplied SDK client belongs to its caller, so close() must leave it."""
730736 supplied = mock .Mock ()
731737 supplied .transport .close = mock .AsyncMock ()
@@ -734,18 +740,8 @@ async def test_close_only_closes_own_client():
734740
735741 supplied .transport .close .assert_not_awaited ()
736742
737- plugin = ModelArmorPlugin (
738- config = _config (), credentials = AnonymousCredentials ()
739- )
740- built_client = plugin .client # Opens the channel the plugin owns.
741- built_client .transport .close = mock .AsyncMock ()
742743
743- await plugin .close ()
744-
745- built_client .transport .close .assert_awaited_once ()
746-
747-
748- def test_each_event_loop_gets_its_own_client ():
744+ def test_each_event_loop_gets_its_own_client () -> None :
749745 """Each sync Runner.run call runs a new loop, which needs its own channel."""
750746 plugin = ModelArmorPlugin (
751747 config = _config (), credentials = AnonymousCredentials ()
@@ -764,8 +760,8 @@ async def read_client():
764760
765761
766762@pytest .mark .asyncio
767- async def test_close_releases_the_running_loops_client () :
768- """After close() the next read on the same loop builds a fresh client ."""
763+ async def test_close_does_not_close_shared_client () -> None :
764+ """Runner close must not tear down the shared client on the running loop ."""
769765 plugin = ModelArmorPlugin (
770766 config = _config (), credentials = AnonymousCredentials ()
771767 )
@@ -774,9 +770,107 @@ async def test_close_releases_the_running_loops_client():
774770
775771 await plugin .close ()
776772
777- client .transport .close .assert_awaited_once ()
778- assert plugin .client is not client
779- await plugin .close ()
773+ client .transport .close .assert_not_awaited ()
774+ assert plugin .client is client
775+
776+
777+ def test_closing_one_runner_keeps_sibling_runners_screening (
778+ monkeypatch : pytest .MonkeyPatch ,
779+ ) -> None :
780+ """Closing one runner must not cancel a sibling runner's screening."""
781+
782+ class _ClosableClient :
783+ instances : list [_ClosableClient ] = []
784+ parse_template_path = staticmethod (
785+ modelarmor_v1 .ModelArmorAsyncClient .parse_template_path
786+ )
787+
788+ def __init__ (self , * args : Any , ** kwargs : Any ) -> None :
789+ _ClosableClient .instances .append (self )
790+ self .closed = False
791+ self .in_flight = asyncio .Event ()
792+ self .release = asyncio .Event ()
793+ self .transport = mock .AsyncMock ()
794+
795+ async def _close () -> None :
796+ self .closed = True
797+
798+ self .transport .close .side_effect = _close
799+
800+ async def sanitize_user_prompt (
801+ self , request : Any
802+ ) -> modelarmor_v1 .SanitizeUserPromptResponse :
803+ self .in_flight .set ()
804+ await self .release .wait ()
805+ if self .closed :
806+ raise asyncio .CancelledError ('Channel closed' )
807+ return modelarmor_v1 .SanitizeUserPromptResponse (
808+ sanitization_result = _sanitization_result ()
809+ )
810+
811+ async def sanitize_model_response (
812+ self , request : Any
813+ ) -> modelarmor_v1 .SanitizeModelResponseResponse :
814+ return modelarmor_v1 .SanitizeModelResponseResponse (
815+ sanitization_result = _sanitization_result ()
816+ )
817+
818+ monkeypatch .setattr (modelarmor_v1 , 'ModelArmorAsyncClient' , _ClosableClient )
819+
820+ plugin = ModelArmorPlugin (
821+ config = _config (), credentials = AnonymousCredentials ()
822+ )
823+ agent = Agent (
824+ name = 'test_agent' , model = MockModel .create (['Hello from sibling runner!' ])
825+ )
826+ app = App (name = 'test_app' , root_agent = agent , plugins = [plugin ])
827+ session_service = InMemorySessionService ()
828+
829+ async def scenario () -> tuple [list [Any ], _ClosableClient ]:
830+ runner_closing = Runner (app = app , session_service = session_service )
831+ runner_busy = Runner (app = app , session_service = session_service )
832+
833+ await session_service .create_session (
834+ app_name = 'test_app' , user_id = 'u' , session_id = 's'
835+ )
836+
837+ async def turn () -> list [Any ]:
838+ events = []
839+ async for event in runner_busy .run_async (
840+ user_id = 'u' ,
841+ session_id = 's' ,
842+ new_message = types .Content (
843+ role = 'user' , parts = [types .Part (text = 'hello' )]
844+ ),
845+ ):
846+ events .append (event )
847+ return events
848+
849+ task = asyncio .create_task (turn ())
850+
851+ async def _get_client () -> _ClosableClient :
852+ while not _ClosableClient .instances :
853+ await asyncio .sleep (0 )
854+ return _ClosableClient .instances [0 ]
855+
856+ client = await asyncio .wait_for (_get_client (), timeout = 10.0 )
857+ await asyncio .wait_for (client .in_flight .wait (), timeout = 10.0 )
858+
859+ await runner_closing .close ()
860+ client .release .set ()
861+
862+ events = await task
863+ return events , client
864+
865+ events , client = asyncio .run (scenario ())
866+ texts = [
867+ event .content .parts [0 ].text
868+ for event in events
869+ if event .content and event .content .parts and event .content .parts [0 ].text
870+ ]
871+ assert texts == ['Hello from sibling runner!' ]
872+ assert not client .closed
873+ client .transport .close .assert_not_awaited ()
780874
781875
782876# --- Tool output screening --------------------------------------------------
0 commit comments