@@ -357,6 +357,50 @@ def should_trigger_compaction(context: dict[str, Any]) -> bool:
357357
358358 mock_client .responses .compact .assert_awaited_once ()
359359
360+ @pytest .mark .asyncio
361+ async def test_deferred_compaction_persists_across_tool_turns (self ) -> None :
362+ underlying = SimpleListSession ()
363+ compacted = SimpleNamespace (
364+ output = [{"type" : "compaction" , "summary" : "compacted" }],
365+ )
366+ mock_client = MagicMock ()
367+ mock_client .responses .compact = AsyncMock (return_value = compacted )
368+
369+ should_compact_calls = {"count" : 0 }
370+
371+ def should_trigger_compaction (context : dict [str , Any ]) -> bool :
372+ should_compact_calls ["count" ] += 1
373+ return should_compact_calls ["count" ] == 1
374+
375+ session = OpenAIResponsesCompactionSession (
376+ session_id = "demo" ,
377+ underlying_session = underlying ,
378+ client = mock_client ,
379+ should_trigger_compaction = should_trigger_compaction ,
380+ )
381+
382+ tool = get_function_tool (name = "do_thing" , return_value = "done" )
383+ model = FakeModel ()
384+ model .add_multiple_turn_outputs (
385+ [
386+ [get_function_tool_call ("do_thing" )],
387+ [get_function_tool_call ("do_thing" )],
388+ [get_text_message ("ok" )],
389+ ]
390+ )
391+ agent = Agent (
392+ name = "assistant" ,
393+ model = model ,
394+ tools = [tool ],
395+ tool_use_behavior = "stop_on_first_tool" ,
396+ )
397+
398+ await Runner .run (agent , "hello" , session = session )
399+ await Runner .run (agent , "again" , session = session )
400+ await Runner .run (agent , "final" , session = session )
401+
402+ mock_client .responses .compact .assert_awaited_once ()
403+
360404
361405class TestTypeGuard :
362406 def test_is_compaction_aware_session_true (self ) -> None :
0 commit comments