openai-agents-python/tests/memory/test_openai_responses_compaction_session.py
Kazuhiro Sera 1fc77bbc8a
fix: use gpt-6-luna for session compaction by default (#5646)
* fix: use gpt-6-luna for session compaction by default

* fix: preserve the released compaction model contract
2026-11-09 07:06:14 +00:00

2728 lines
106 KiB
Python

from __future__ import annotations
import asyncio
import json
import logging
import sqlite3
import threading
import warnings as warnings_module
from collections.abc import Awaitable, Callable
from pathlib import Path
from types import SimpleNamespace
from typing import Any, cast
from unittest.mock import AsyncMock, MagicMock, patch
import httpx2
import pytest
from openai import AsyncOpenAI
from openai.types.responses.response_usage import (
InputTokensDetails,
OutputTokensDetails,
ResponseUsage,
)
import agents._debug as _debug
from agents import Agent, OpenAIResponsesModel, RunConfig, Runner
from agents.items import MessageOutputItem, TResponseInputItem
from agents.memory import (
OpenAIResponsesCompactionSession,
Session,
SessionSettings,
SQLiteSession,
is_openai_responses_compaction_aware_session,
)
from agents.memory.openai_responses_compaction_session import (
DEFAULT_COMPACTION_THRESHOLD,
_strip_orphaned_assistant_ids,
is_openai_model_name,
select_compaction_candidate_items,
)
from agents.run_context import RunContextWrapper
from agents.run_internal.items import (
TOOL_CALL_SESSION_DESCRIPTION_KEY,
TOOL_CALL_SESSION_TITLE_KEY,
)
from agents.run_internal.session_persistence import (
prepare_input_with_session,
save_result_to_session,
)
from agents.run_state import RunState
from agents.testing import ModelStep, ScriptedModel
from tests.model_test_helpers import get_response_obj
from tests.test_responses import get_function_tool, get_function_tool_call, get_text_message
from tests.utils.simple_session import SimpleListSession
@pytest.mark.asyncio
@pytest.mark.allow_call_model_methods
@pytest.mark.parametrize("history_source", ["automatic", "manual", "stored"])
async def test_compaction_replay_strips_created_by(history_source: str) -> None:
compacted_item = {
"id": "cmp_synthetic",
"type": "compaction",
"encrypted_content": "synthetic-encrypted-content",
"created_by": "server",
}
request_inputs: list[list[dict[str, Any]]] = []
async def handler(request: httpx2.Request) -> httpx2.Response:
request_inputs.append(json.loads(request.content)["input"])
if request.url.path.endswith("/compact"):
return httpx2.Response(
200,
json={
"id": "cmp_response",
"object": "response.compaction",
"created_at": 1,
"output": [compacted_item],
},
)
assert request.url.path.endswith("/responses")
return httpx2.Response(
200, content=get_response_obj([get_text_message("42")]).model_dump_json()
)
underlying = SQLiteSession("created-by-replay")
try:
async with AsyncOpenAI(
api_key="synthetic-key",
http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(handler)),
) as client:
session = OpenAIResponsesCompactionSession(
session_id="created-by-replay",
underlying_session=underlying,
client=client,
model="gpt-5",
compaction_mode="input",
should_trigger_compaction=lambda ctx: bool(ctx["compaction_candidate_items"]),
)
agent = Agent(name="test", model=OpenAIResponsesModel("gpt-5", openai_client=client))
config = RunConfig(tracing_disabled=True)
if history_source == "stored":
# History saved before the fix must also remain usable.
await underlying.add_items([cast(TResponseInputItem, compacted_item)])
elif history_source == "manual":
await session.add_items([{"role": "user", "content": "How many?"}])
await session.run_compaction({"force": True})
else:
await Runner.run(agent, "How many?", session=session, run_config=config)
stored_items = await underlying.get_items()
assert stored_items == [compacted_item]
if history_source == "manual":
# Repeated manual compaction reuses cached output without a history reload.
await session.add_items([{"role": "user", "content": "More context"}])
await session.run_compaction({"force": True})
result = await Runner.run(agent, "And urgent?", session=session, run_config=config)
assert result.final_output == "42"
# Inspect encoded inputs to both Responses and the next compact request.
replayed_items = [
item
for items in request_inputs
for item in items
if item.get("type") == "compaction"
]
assert replayed_items == [
{
"id": "cmp_synthetic",
"type": "compaction",
"encrypted_content": "synthetic-encrypted-content",
}
] * (3 if history_source == "manual" else 2)
assert stored_items[0] == compacted_item
assert (await underlying.get_items())[0] == compacted_item
finally:
underlying.close()
class TestIsOpenAIModelName:
def test_gpt_models(self) -> None:
assert is_openai_model_name("gpt-4o") is True
assert is_openai_model_name("gpt-4o-mini") is True
assert is_openai_model_name("gpt-3.5-turbo") is True
assert is_openai_model_name("gpt-4.1") is True
assert is_openai_model_name("gpt-5") is True
assert is_openai_model_name("gpt-5.2") is True
assert is_openai_model_name("gpt-5-mini") is True
assert is_openai_model_name("gpt-5-nano") is True
def test_o_models(self) -> None:
assert is_openai_model_name("o1") is True
assert is_openai_model_name("o1-preview") is True
assert is_openai_model_name("o3") is True
def test_fine_tuned_models(self) -> None:
assert is_openai_model_name("ft:gpt-4o-mini:org:proj:suffix") is True
assert is_openai_model_name("ft:gpt-4.1:my-org::id") is True
def test_invalid_models(self) -> None:
assert is_openai_model_name("") is False
assert is_openai_model_name("not-openai") is False
class TestSelectCompactionCandidateItems:
def test_excludes_user_messages(self) -> None:
items: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "message", "role": "user", "content": "hello"}),
cast(TResponseInputItem, {"type": "message", "role": "assistant", "content": "hi"}),
]
result = select_compaction_candidate_items(items)
assert len(result) == 1
assert result[0].get("role") == "assistant"
def test_excludes_compaction_items(self) -> None:
items: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "compaction", "summary": "..."}),
cast(TResponseInputItem, {"type": "message", "role": "assistant", "content": "hi"}),
]
result = select_compaction_candidate_items(items)
assert len(result) == 1
assert result[0].get("type") == "message"
def test_excludes_easy_user_messages_without_type(self) -> None:
items: list[TResponseInputItem] = [
cast(TResponseInputItem, {"content": "hi", "role": "user"}),
cast(TResponseInputItem, {"type": "message", "role": "assistant", "content": "hello"}),
]
result = select_compaction_candidate_items(items)
assert len(result) == 1
assert result[0].get("role") == "assistant"
class TestOpenAIResponsesCompactionSession:
@pytest.mark.asyncio
@pytest.mark.parametrize("budget", [None, 2])
@pytest.mark.parametrize("failure_stage", ["clear", "add"])
async def test_rollback_does_not_revive_items_expired_during_compaction(
self,
budget: int | None,
failure_stage: str,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
pytest.importorskip("cryptography")
from agents.extensions.memory.encrypt_session import EncryptedSession
clock = [1000]
monkeypatch.setattr("cryptography.fernet.time.time", lambda: clock[0])
backend = SQLiteSession("ttl-rollback", tmp_path / "history.db")
encrypted = EncryptedSession("ttl-rollback", backend, "synthetic-key", ttl=10)
live_item: TResponseInputItem = {"role": "user", "content": "still live"}
await encrypted.add_items([{"role": "user", "content": "expires during request"}])
clock[0] = 1005
await encrypted.add_items([live_item])
async def compact(**kwargs: Any) -> SimpleNamespace:
clock[0] = 1011
return SimpleNamespace(output=[{"role": "assistant", "content": "summary"}])
client = MagicMock()
client.responses.compact = AsyncMock(side_effect=compact)
session = OpenAIResponsesCompactionSession(
"ttl-rollback", encrypted, client=client, max_rollback_items=budget
)
operation = encrypted.clear_session if failure_stage == "clear" else encrypted.add_items
calls = 0
async def fail_once(*args: Any) -> None:
nonlocal calls
calls += 1
await operation(*args)
if calls == 1:
raise RuntimeError("replacement failed")
try:
with patch.object(
encrypted,
"clear_session" if failure_stage == "clear" else "add_items",
side_effect=fail_once,
):
with pytest.raises(RuntimeError, match="replacement failed"):
await session.run_compaction({"force": True})
client.responses.compact.assert_awaited_once()
assert await encrypted.get_items() == [live_item]
finally:
backend.close()
@pytest.mark.parametrize("budget", [0, -1])
def test_rejects_nonpositive_rollback_budget(self, budget: int) -> None:
with pytest.raises(ValueError, match="max_rollback_items must be positive"):
OpenAIResponsesCompactionSession("test", SimpleListSession(), max_rollback_items=budget)
@pytest.mark.asyncio
@pytest.mark.parametrize("retrieval_limit", [None, 1])
async def test_manual_rollback_budget_rejects_before_api_or_writes(
self, retrieval_limit: int | None, tmp_path: Path
) -> None:
backend = SQLiteSession(
"test", tmp_path / "budget.db", session_settings=SessionSettings(limit=retrieval_limit)
)
history: list[TResponseInputItem] = [
{"role": "user", "content": f"{index}:" + "x" * 4096} for index in range(64)
]
await backend.add_items(history)
client = MagicMock()
client.responses.compact = AsyncMock()
session = OpenAIResponsesCompactionSession(
"test", backend, client=client, max_rollback_items=3
)
try:
with (
patch.object(backend, "get_items", wraps=backend.get_items) as reads,
patch.object(backend, "clear_session", wraps=backend.clear_session) as clear,
patch.object(backend, "add_items", wraps=backend.add_items) as writes,
pytest.raises(ValueError, match="exceeds max_rollback_items"),
):
await session.run_compaction({"force": True})
reads.assert_awaited_once_with(limit=4)
client.responses.compact.assert_not_awaited()
clear.assert_not_awaited()
writes.assert_not_awaited()
assert await backend.get_items(limit=100) == history
finally:
backend.close()
@pytest.mark.asyncio
@pytest.mark.parametrize("clear_mutates", [False, True])
async def test_rollback_budget_bounds_failed_clear_inspection(
self, clear_mutates: bool
) -> None:
history: list[TResponseInputItem] = [
{"role": "user", "content": "old"},
{"role": "assistant", "content": "new"},
]
class FailingClearSession(SimpleListSession):
async def clear_session(self) -> None:
if clear_mutates:
await super().clear_session()
raise RuntimeError("clear failed")
backend = FailingClearSession(history=history)
client = MagicMock()
client.responses.compact = AsyncMock(return_value=SimpleNamespace(output=[]))
session = OpenAIResponsesCompactionSession(
"test", backend, client=client, max_rollback_items=2
)
with patch.object(backend, "get_items", wraps=backend.get_items) as reads:
with pytest.raises(RuntimeError, match="clear failed"):
await session.run_compaction({"force": True})
assert [call.kwargs.get("limit") for call in reads.await_args_list] == [3, None, 3, 3]
assert await backend.get_items() == history
@pytest.mark.asyncio
@pytest.mark.parametrize("native", [False, True])
async def test_automatic_compaction_rollback_budget(self, native: bool) -> None:
backend = SQLiteSession("test") if native else SimpleListSession()
client = MagicMock()
client.responses.compact = AsyncMock(return_value=SimpleNamespace(output=[]))
session = OpenAIResponsesCompactionSession(
"test",
backend,
client=client,
max_rollback_items=1,
should_trigger_compaction=lambda _: True,
)
agent = Agent(name="test", model=ScriptedModel(steps=[[get_text_message("reply")]]))
try:
if native:
await Runner.run(agent, "hello", session=session)
client.responses.compact.assert_awaited_once()
assert await backend.get_items() == []
else:
with pytest.raises(ValueError, match="exceeds max_rollback_items"):
await Runner.run(agent, "hello", session=session)
client.responses.compact.assert_not_awaited()
assert len(await backend.get_items()) == 2
finally:
if isinstance(backend, SQLiteSession):
backend.close()
@pytest.mark.asyncio
async def test_exact_rollback_budget_refreshes_complete_snapshot(self) -> None:
backend = SimpleListSession(history=[{"role": "user", "content": "hello"}])
client = MagicMock()
client.responses.compact = AsyncMock(return_value=SimpleNamespace(output=[]))
session = OpenAIResponsesCompactionSession(
"test", backend, client=client, max_rollback_items=1
)
with patch.object(backend, "get_items", wraps=backend.get_items) as reads:
await session.run_compaction({"force": True})
assert [call.kwargs.get("limit") for call in reads.await_args_list] == [2, None, 2]
client.responses.compact.assert_awaited_once()
assert await backend.get_items() == []
def test_client_preserves_falsy_default_client(self) -> None:
mock_client = MagicMock()
mock_client.__bool__.return_value = False
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=self.create_mock_session(),
)
with patch(
"agents.memory.openai_responses_compaction_session.get_default_openai_client",
return_value=mock_client,
):
assert session.client is mock_client
def create_mock_session(self) -> MagicMock:
mock = MagicMock(spec=Session)
mock.session_id = "test-session"
mock.get_items = AsyncMock(return_value=[])
mock.add_items = AsyncMock()
mock.pop_item = AsyncMock(return_value=None)
mock.clear_session = AsyncMock()
return mock
@pytest.mark.parametrize("model", ["claude-3", "anthropic/claude-3"])
def test_init_validates_model(self, model: str) -> None:
mock_session = self.create_mock_session()
with pytest.raises(ValueError, match="Unsupported model"):
OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
model=model,
)
def test_init_accepts_valid_model(self) -> None:
mock_session = self.create_mock_session()
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
model="gpt-4.1",
)
assert session.model == "gpt-4.1"
@pytest.mark.asyncio
async def test_add_items_delegates(self) -> None:
mock_session = self.create_mock_session()
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
)
items: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "message", "role": "assistant", "content": "test"})
]
await session.add_items(items)
mock_session.add_items.assert_called_once_with(items)
@pytest.mark.asyncio
async def test_pop_item_invalidates_response_chain(self) -> None:
item: TResponseInputItem = {"role": "assistant", "content": "remove me"}
underlying = SimpleListSession(history=[item])
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(
return_value=SimpleNamespace(output=[], usage=None)
)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=underlying,
client=mock_client,
compaction_mode="previous_response_id",
should_trigger_compaction=lambda ctx: False,
)
await session.run_compaction({"response_id": "resp-old", "store": False})
# Seed deferred work through the runner's compaction hook.
session.should_trigger_compaction = lambda ctx: True
await session._defer_compaction("resp-old")
assert await session.pop_item() == item
assert await session.get_items() == []
with pytest.raises(ValueError, match="requires a response_id"):
await session.run_compaction({"force": True})
mock_client.responses.compact.assert_not_awaited()
assert session._get_deferred_compaction_response_id() is None
assert session._last_unstored_response_id is None
await session.run_compaction({"response_id": "resp-new", "force": True})
assert mock_client.responses.compact.await_args is not None
assert mock_client.responses.compact.await_args.kwargs["previous_response_id"] == "resp-new"
@pytest.mark.asyncio
async def test_empty_pop_preserves_response_chain(self) -> None:
underlying = self.create_mock_session()
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(
return_value=SimpleNamespace(output=[], usage=None)
)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=underlying,
client=mock_client,
compaction_mode="previous_response_id",
should_trigger_compaction=lambda ctx: False,
)
await session.run_compaction({"response_id": "resp-old", "store": False})
session.should_trigger_compaction = lambda ctx: True
await session._defer_compaction("resp-old")
assert await session.pop_item() is None
assert session._get_deferred_compaction_response_id() == "resp-old"
assert session._last_unstored_response_id == "resp-old"
await session.run_compaction({"force": True})
assert mock_client.responses.compact.await_args is not None
assert mock_client.responses.compact.await_args.kwargs["previous_response_id"] == "resp-old"
@pytest.mark.asyncio
@pytest.mark.parametrize("outcome", ["cancelled", "error"])
async def test_settled_pop_failure_invalidates_response_chain(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, outcome: str
) -> None:
# Gate the real SQLite commit acknowledgement so cancellation cannot undo the pop.
committed = threading.Event()
allow_return = threading.Event()
class PausingCommitConnection(sqlite3.Connection):
pause_commit = True
def commit(self) -> None:
super().commit()
if self.pause_commit:
self.pause_commit = False
committed.set()
assert allow_return.wait(timeout=10)
if outcome == "error":
raise RuntimeError("commit acknowledgement failed")
underlying = SQLiteSession("settled-pop", tmp_path / "settled-pop.db")
history: list[TResponseInputItem] = [
{"role": "user", "content": "keep me"},
{"role": "assistant", "content": "remove me"},
]
await underlying.add_items(history)
connection = sqlite3.connect(
str(tmp_path / "settled-pop.db"),
check_same_thread=False,
factory=PausingCommitConnection,
)
with underlying._connections_lock:
underlying._connections.add(connection)
monkeypatch.setattr(underlying, "_get_connection", lambda: connection)
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock()
session = OpenAIResponsesCompactionSession(
session_id="settled-pop",
underlying_session=underlying,
client=mock_client,
compaction_mode="previous_response_id",
should_trigger_compaction=lambda ctx: False,
)
await session.run_compaction({"response_id": "resp-old", "store": False})
session.should_trigger_compaction = lambda ctx: True
await session._defer_compaction("resp-old")
mutation = asyncio.create_task(session.pop_item())
try:
assert await asyncio.to_thread(committed.wait, 10)
if outcome == "cancelled":
mutation.cancel()
allow_return.set()
if outcome == "cancelled":
with pytest.raises(asyncio.CancelledError):
await mutation
else:
with pytest.raises(RuntimeError, match="commit acknowledgement failed"):
await mutation
assert await session.get_items() == history[:1]
assert not session._mutation_lock.locked()
with pytest.raises(ValueError, match="requires a response_id"):
await session.run_compaction({"force": True})
mock_client.responses.compact.assert_not_awaited()
assert session._get_deferred_compaction_response_id() is None
assert session._last_unstored_response_id is None
assert await underlying.get_items() == history[:1]
finally:
allow_return.set()
if not mutation.done():
mutation.cancel()
await asyncio.gather(mutation, return_exceptions=True)
underlying.close()
@pytest.mark.asyncio
async def test_clear_session_invalidates_response_chain(self) -> None:
item: TResponseInputItem = {"role": "assistant", "content": "remove me"}
underlying = SimpleListSession(history=[item])
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(
return_value=SimpleNamespace(output=[], usage=None)
)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=underlying,
client=mock_client,
compaction_mode="previous_response_id",
should_trigger_compaction=lambda ctx: False,
)
await session.run_compaction({"response_id": "resp-old", "store": False})
# Seed deferred work through the runner's compaction hook.
session.should_trigger_compaction = lambda ctx: True
await session._defer_compaction("resp-old")
await session.clear_session()
assert await session.get_items() == []
with pytest.raises(ValueError, match="requires a response_id"):
await session.run_compaction({"force": True})
mock_client.responses.compact.assert_not_awaited()
assert session._get_deferred_compaction_response_id() is None
assert session._last_unstored_response_id is None
await session.run_compaction({"response_id": "resp-new", "force": True})
assert mock_client.responses.compact.await_args is not None
assert mock_client.responses.compact.await_args.kwargs["previous_response_id"] == "resp-new"
@pytest.mark.asyncio
@pytest.mark.parametrize("outcome", ["cancelled", "error"])
async def test_settled_clear_failure_invalidates_response_chain(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, outcome: str
) -> None:
# Gate the real SQLite commit acknowledgement so cancellation cannot undo the clear.
committed = threading.Event()
allow_return = threading.Event()
class PausingCommitConnection(sqlite3.Connection):
pause_commit = True
def commit(self) -> None:
super().commit()
if self.pause_commit:
self.pause_commit = False
committed.set()
assert allow_return.wait(timeout=10)
if outcome == "error":
raise RuntimeError("commit acknowledgement failed")
underlying = SQLiteSession("settled-clear", tmp_path / "settled-clear.db")
history: list[TResponseInputItem] = [
{"role": "user", "content": "keep me"},
{"role": "assistant", "content": "remove me"},
]
await underlying.add_items(history)
connection = sqlite3.connect(
str(tmp_path / "settled-clear.db"),
check_same_thread=False,
factory=PausingCommitConnection,
)
with underlying._connections_lock:
underlying._connections.add(connection)
monkeypatch.setattr(underlying, "_get_connection", lambda: connection)
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(
return_value=SimpleNamespace(output=[], usage=None)
)
session = OpenAIResponsesCompactionSession(
session_id="settled-clear",
underlying_session=underlying,
client=mock_client,
compaction_mode="previous_response_id",
should_trigger_compaction=lambda ctx: False,
)
await session.run_compaction({"response_id": "resp-old", "store": False})
session.should_trigger_compaction = lambda ctx: True
await session._defer_compaction("resp-old")
mutation = asyncio.create_task(session.clear_session())
try:
assert await asyncio.to_thread(committed.wait, 10)
if outcome == "cancelled":
mutation.cancel()
allow_return.set()
if outcome == "cancelled":
with pytest.raises(asyncio.CancelledError):
await mutation
else:
with pytest.raises(RuntimeError, match="commit acknowledgement failed"):
await mutation
# The deletion committed before the failure reached the caller.
assert await session.get_items() == []
assert not session._mutation_lock.locked()
with pytest.raises(ValueError, match="requires a response_id"):
await session.run_compaction({"force": True})
mock_client.responses.compact.assert_not_awaited()
assert session._get_deferred_compaction_response_id() is None
assert session._last_unstored_response_id is None
# The session stays usable: a subsequent write survives.
follow_up: TResponseInputItem = {"role": "user", "content": "after clear"}
await session.add_items([follow_up])
assert await session.get_items() == [follow_up]
await session.run_compaction({"response_id": "resp-new", "force": True})
assert mock_client.responses.compact.await_args is not None
compact_kwargs = mock_client.responses.compact.await_args.kwargs
assert compact_kwargs["previous_response_id"] == "resp-new"
finally:
allow_return.set()
if not mutation.done():
mutation.cancel()
await asyncio.gather(mutation, return_exceptions=True)
underlying.close()
@pytest.mark.asyncio
async def test_run_compaction_auto_uses_input_after_clear(self) -> None:
item: TResponseInputItem = {"role": "assistant", "content": "old turn"}
underlying = SimpleListSession(history=[item])
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(
return_value=SimpleNamespace(output=[], usage=None)
)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=underlying,
client=mock_client,
)
# Default auto mode follows the stored response chain first.
await session.run_compaction({"response_id": "resp-old", "force": True})
first_kwargs = mock_client.responses.compact.call_args.kwargs
assert first_kwargs.get("previous_response_id") == "resp-old"
assert "input" not in first_kwargs
await session.clear_session()
new_items: list[TResponseInputItem] = [
cast(TResponseInputItem, {"role": "user", "content": "fresh start"}),
cast(TResponseInputItem, {"role": "assistant", "content": "fresh reply"}),
]
await session.add_items(new_items)
# After clearing the stored response, auto mode compacts from the
# current local input instead of reusing the cleared response chain.
await session.run_compaction({"force": True})
assert mock_client.responses.compact.call_count == 2
second_kwargs = mock_client.responses.compact.call_args.kwargs
assert "previous_response_id" not in second_kwargs
assert second_kwargs.get("input") == new_items
@pytest.mark.asyncio
async def test_get_items_delegates(self) -> None:
mock_session = self.create_mock_session()
mock_session.get_items.return_value = [{"type": "message", "content": "test"}]
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
)
result = await session.get_items()
assert len(result) == 1
mock_session.get_items.assert_called_once()
@pytest.mark.asyncio
async def test_run_compaction_requires_response_id(self) -> None:
mock_session = self.create_mock_session()
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
compaction_mode="previous_response_id",
)
with pytest.raises(ValueError, match="previous_response_id compaction"):
await session.run_compaction()
@pytest.mark.asyncio
async def test_run_compaction_honors_falsey_decision_hook(self) -> None:
class FalseyDecisionHook:
def __init__(self) -> None:
self.calls = 0
def __bool__(self) -> bool:
return False
def __call__(self, context: dict[str, Any]) -> bool:
self.calls += 1
return False
items = [
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": f"message {index}"},
)
for index in range(DEFAULT_COMPACTION_THRESHOLD)
]
underlying = SimpleListSession(history=items)
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock()
decision_hook = FalseyDecisionHook()
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=underlying,
client=mock_client,
compaction_mode="input",
should_trigger_compaction=decision_hook,
)
await session.run_compaction()
assert decision_hook.calls == 1
mock_client.responses.compact.assert_not_awaited()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"model",
[
"gpt-4.1",
"ft:gpt-4.1:my-org::id",
"openai/gpt-4.1",
"openai/openai/gpt-5.6-terra",
"openai/o3",
"openai/ft:gpt-4.1:org:proj:id",
],
)
async def test_run_compaction_input_mode_without_response_id(self, model: str) -> None:
mock_session = self.create_mock_session()
items: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "message", "role": "user", "content": "hello"}),
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "world"},
),
]
mock_session.get_items.return_value = items
mock_compact_response = MagicMock()
mock_compact_response.output = [
{
"type": "message",
"role": "assistant",
"content": "compacted",
}
]
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
client=mock_client,
model=model,
compaction_mode="input",
)
await session.run_compaction({"force": True})
mock_client.responses.compact.assert_called_once()
call_kwargs = mock_client.responses.compact.call_args.kwargs
assert call_kwargs.get("model") == model
assert "previous_response_id" not in call_kwargs
assert call_kwargs.get("input") == items
@pytest.mark.asyncio
async def test_run_compaction_auto_without_response_id_uses_input(self) -> None:
mock_session = self.create_mock_session()
items: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "message", "role": "user", "content": "hello"}),
]
mock_session.get_items.return_value = items
mock_compact_response = MagicMock()
mock_compact_response.output = []
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
client=mock_client,
)
await session.run_compaction({"force": True})
mock_client.responses.compact.assert_called_once()
call_kwargs = mock_client.responses.compact.call_args.kwargs
assert "previous_response_id" not in call_kwargs
assert call_kwargs.get("input") == items
@pytest.mark.asyncio
async def test_run_compaction_input_mode_strips_internal_tool_call_metadata(self) -> None:
mock_session = self.create_mock_session()
items: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{
"type": "function_call",
"call_id": "call_123",
"name": "lookup_account",
"arguments": "{}",
TOOL_CALL_SESSION_DESCRIPTION_KEY: "Lookup customer records.",
TOOL_CALL_SESSION_TITLE_KEY: "Lookup Account",
},
),
cast(
TResponseInputItem,
{
"type": "function_call_output",
"call_id": "call_123",
"output": "ok",
},
),
]
mock_session.get_items.return_value = items
mock_compact_response = MagicMock()
mock_compact_response.output = []
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
client=mock_client,
compaction_mode="input",
)
await session.run_compaction({"force": True})
call_kwargs = mock_client.responses.compact.call_args.kwargs
compact_input = cast(list[dict[str, Any]], call_kwargs["input"])
assert compact_input[0]["type"] == "function_call"
assert TOOL_CALL_SESSION_DESCRIPTION_KEY not in compact_input[0]
assert TOOL_CALL_SESSION_TITLE_KEY not in compact_input[0]
@pytest.mark.asyncio
async def test_run_compaction_uses_sanitized_cached_items_after_add(self) -> None:
mock_session = self.create_mock_session()
mock_session.get_items.return_value = []
mock_compact_response = MagicMock()
mock_compact_response.output = []
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
client=mock_client,
compaction_mode="input",
)
await session._ensure_compaction_candidates()
await session.add_items(
[
cast(
TResponseInputItem,
{
"type": "function_call",
"call_id": "call_cached",
"name": "lookup_account",
"arguments": "{}",
TOOL_CALL_SESSION_DESCRIPTION_KEY: "Lookup customer records.",
TOOL_CALL_SESSION_TITLE_KEY: "Lookup Account",
},
),
cast(
TResponseInputItem,
{
"type": "function_call_output",
"call_id": "call_cached",
"output": "ok",
},
),
]
)
await session.run_compaction({"force": True})
call_kwargs = mock_client.responses.compact.call_args.kwargs
compact_input = cast(list[dict[str, Any]], call_kwargs["input"])
assert compact_input[0]["type"] == "function_call"
assert TOOL_CALL_SESSION_DESCRIPTION_KEY not in compact_input[0]
assert TOOL_CALL_SESSION_TITLE_KEY not in compact_input[0]
@pytest.mark.asyncio
async def test_run_compaction_auto_uses_input_when_store_false(self) -> None:
mock_session = self.create_mock_session()
items: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "message", "role": "user", "content": "hello"}),
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "world"},
),
]
mock_session.get_items.return_value = items
mock_compact_response = MagicMock()
mock_compact_response.output = []
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
client=mock_client,
compaction_mode="auto",
)
await session.run_compaction({"response_id": "resp-auto", "store": False, "force": True})
mock_client.responses.compact.assert_called_once()
call_kwargs = mock_client.responses.compact.call_args.kwargs
assert call_kwargs.get("model") == "gpt-6-luna"
assert "previous_response_id" not in call_kwargs
assert call_kwargs.get("input") == items
@pytest.mark.asyncio
async def test_run_compaction_auto_uses_default_store_when_unset(self) -> None:
mock_session = self.create_mock_session()
items: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "message", "role": "user", "content": "hello"}),
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "world"},
),
]
mock_session.get_items.return_value = items
mock_compact_response = MagicMock()
mock_compact_response.output = []
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
client=mock_client,
compaction_mode="auto",
)
await session.run_compaction({"response_id": "resp-auto", "store": False, "force": True})
await session.run_compaction({"response_id": "resp-stored", "force": True})
assert mock_client.responses.compact.call_count == 2
first_kwargs = mock_client.responses.compact.call_args_list[0].kwargs
second_kwargs = mock_client.responses.compact.call_args_list[1].kwargs
assert "previous_response_id" not in first_kwargs
assert second_kwargs.get("previous_response_id") == "resp-stored"
assert "input" not in second_kwargs
@pytest.mark.asyncio
async def test_run_compaction_auto_uses_input_when_last_response_unstored(self) -> None:
mock_session = self.create_mock_session()
items: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "message", "role": "user", "content": "hello"}),
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "world"},
),
]
mock_session.get_items.return_value = items
mock_compact_response = MagicMock()
mock_compact_response.output = [
{
"type": "message",
"role": "assistant",
"content": "compacted",
}
]
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
client=mock_client,
compaction_mode="auto",
)
await session.run_compaction(
{"response_id": "resp-unstored", "store": False, "force": True}
)
await session.run_compaction({"force": True})
assert mock_client.responses.compact.call_count == 2
first_kwargs = mock_client.responses.compact.call_args_list[0].kwargs
second_kwargs = mock_client.responses.compact.call_args_list[1].kwargs
assert "previous_response_id" not in first_kwargs
assert "previous_response_id" not in second_kwargs
assert second_kwargs.get("input") == mock_compact_response.output
@pytest.mark.asyncio
async def test_run_compaction_skips_when_below_threshold(self) -> None:
mock_session = self.create_mock_session()
# Return fewer than threshold items
mock_session.get_items.return_value = [
cast(TResponseInputItem, {"type": "message", "role": "assistant", "content": f"msg{i}"})
for i in range(DEFAULT_COMPACTION_THRESHOLD - 1)
]
mock_client = MagicMock()
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
client=mock_client,
)
await session.run_compaction({"response_id": "resp-123"})
# Should not have called the compact API
mock_client.responses.compact.assert_not_called()
@pytest.mark.asyncio
async def test_run_compaction_executes_when_threshold_met(self) -> None:
mock_session = self.create_mock_session()
# Return exactly threshold items (all assistant messages = candidates)
mock_session.get_items.return_value = [
cast(TResponseInputItem, {"type": "message", "role": "assistant", "content": f"msg{i}"})
for i in range(DEFAULT_COMPACTION_THRESHOLD)
]
mock_compact_response = MagicMock()
mock_compact_response.output = [{"type": "compaction", "summary": "compacted"}]
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
client=mock_client,
model="gpt-4.1",
)
await session.run_compaction({"response_id": "resp-123"})
mock_client.responses.compact.assert_called_once_with(
previous_response_id="resp-123",
model="gpt-4.1",
)
mock_session.clear_session.assert_called_once()
mock_session.add_items.assert_called()
@pytest.mark.asyncio
async def test_run_compaction_restores_history_when_replacement_add_fails(self) -> None:
history: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "message", "role": "user", "content": "original"}),
cast(
TResponseInputItem,
{
"type": "function_call",
"call_id": "call_123",
"name": "lookup",
"arguments": "{}",
TOOL_CALL_SESSION_DESCRIPTION_KEY: "Lookup private records.",
},
),
]
compacted_items: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "compacted"},
)
]
class PartiallyFailingReplacementSession(SimpleListSession):
def __init__(self, history: list[TResponseInputItem]) -> None:
super().__init__(history=history)
self.add_calls = 0
self.clear_calls = 0
async def add_items(self, items: list[TResponseInputItem]) -> None:
self.add_calls += 1
if self.add_calls == 1:
await super().add_items(items[:1])
raise RuntimeError("replacement failed")
await super().add_items(items)
async def clear_session(self) -> None:
self.clear_calls += 1
await super().clear_session()
failing_session = PartiallyFailingReplacementSession(history=history)
mock_compact_response = MagicMock()
mock_compact_response.output = compacted_items
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=failing_session,
client=mock_client,
compaction_mode="input",
)
with pytest.raises(RuntimeError, match="replacement failed"):
await session.run_compaction({"force": True})
assert await failing_session.get_items() == history
assert failing_session.clear_calls == 2
assert failing_session.add_calls == 2
@pytest.mark.asyncio
async def test_run_compaction_restores_history_when_replacement_add_is_cancelled(
self,
) -> None:
"""CancelledError after clear must restore history (BaseException, not Exception)."""
history: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "message", "role": "user", "content": "original"}),
cast(
TResponseInputItem,
{
"type": "function_call",
"call_id": "call_123",
"name": "lookup",
"arguments": "{}",
TOOL_CALL_SESSION_DESCRIPTION_KEY: "Lookup private records.",
},
),
]
compacted_items: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "compacted"},
)
]
class CancelOnReplacementAddSession(SimpleListSession):
def __init__(self, history: list[TResponseInputItem]) -> None:
super().__init__(history=history)
self.add_calls = 0
self.clear_calls = 0
async def add_items(self, items: list[TResponseInputItem]) -> None:
self.add_calls += 1
if self.add_calls == 1:
raise asyncio.CancelledError()
await super().add_items(items)
async def clear_session(self) -> None:
self.clear_calls += 1
await super().clear_session()
failing_session = CancelOnReplacementAddSession(history=history)
mock_compact_response = MagicMock()
mock_compact_response.output = compacted_items
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=failing_session,
client=mock_client,
compaction_mode="input",
)
with pytest.raises(asyncio.CancelledError):
await session.run_compaction({"force": True})
assert await failing_session.get_items() == history
assert failing_session.clear_calls == 2
assert failing_session.add_calls == 2
@pytest.mark.asyncio
@pytest.mark.parametrize("max_rollback_items", [None, 3])
async def test_run_compaction_restores_history_when_clear_is_cancelled_after_mutation(
self,
max_rollback_items: int | None,
) -> None:
"""CancelledError after a mutating clear must restore without a second destructive clear."""
history: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "message", "role": "user", "content": "original"}),
]
compacted_items: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "compacted"},
)
]
class CancelAfterMutatingClearSession(SimpleListSession):
def __init__(self, history: list[TResponseInputItem]) -> None:
super().__init__(history=history)
self.add_calls = 0
self.clear_calls = 0
async def add_items(self, items: list[TResponseInputItem]) -> None:
self.add_calls += 1
await super().add_items(items)
async def clear_session(self) -> None:
self.clear_calls += 1
await super().clear_session()
raise asyncio.CancelledError()
failing_session = CancelAfterMutatingClearSession(history=history)
mock_compact_response = MagicMock()
mock_compact_response.output = compacted_items
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=failing_session,
client=mock_client,
compaction_mode="input",
max_rollback_items=max_rollback_items,
)
with pytest.raises(asyncio.CancelledError):
await session.run_compaction({"force": True})
assert await failing_session.get_items() == history
assert failing_session.clear_calls == 1
assert failing_session.add_calls == 1
@pytest.mark.asyncio
@pytest.mark.parametrize("max_rollback_items", [None, 3])
async def test_run_compaction_restores_history_when_cancelled_again_during_restore(
self,
max_rollback_items: int | None,
) -> None:
"""A second cancel during restore must still finish rewriting previous history."""
history: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "message", "role": "user", "content": "original"}),
cast(TResponseInputItem, {"type": "message", "role": "assistant", "content": "reply"}),
]
compacted_items: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "compacted"},
)
]
class CancelThenGateRestoreSession(SimpleListSession):
def __init__(self, history: list[TResponseInputItem]) -> None:
super().__init__(history=history)
self.add_calls = 0
self.clear_calls = 0
self.restore_add_started = asyncio.Event()
self.allow_restore_add = asyncio.Event()
async def add_items(self, items: list[TResponseInputItem]) -> None:
self.add_calls += 1
if self.add_calls == 1:
raise asyncio.CancelledError()
# Second add is the restore rewrite after clear.
self.restore_add_started.set()
await self.allow_restore_add.wait()
await super().add_items(items)
async def clear_session(self) -> None:
self.clear_calls += 1
await super().clear_session()
def snapshot(self) -> list[TResponseInputItem]:
return list(self._items)
failing_session = CancelThenGateRestoreSession(history=history)
mock_compact_response = MagicMock()
mock_compact_response.output = compacted_items
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=failing_session,
client=mock_client,
compaction_mode="input",
max_rollback_items=max_rollback_items,
)
compaction_task = asyncio.create_task(session.run_compaction({"force": True}))
await failing_session.restore_add_started.wait()
# Deliver a second cancel while restore add is still blocked on the gate.
compaction_task.cancel()
await asyncio.sleep(0)
assert not failing_session.allow_restore_add.is_set()
assert failing_session.snapshot() == []
failing_session.allow_restore_add.set()
with pytest.raises(asyncio.CancelledError):
await compaction_task
# History must already be restored when CancelledError surfaces — not later
# via an orphaned background rewrite after the await returns.
assert failing_session.snapshot() == history
assert failing_session.clear_calls == 2
assert failing_session.add_calls == 2
@pytest.mark.asyncio
async def test_cancel_restore_waits_for_mutation_lock_before_newer_writes(
self, tmp_path
) -> None:
"""Newer wrapper writes must wait out cancel-restore and survive chronologically."""
history: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "message", "role": "user", "content": "original"}),
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "reply"},
),
]
newer_item: TResponseInputItem = cast(
TResponseInputItem,
{"type": "message", "role": "user", "content": "newer-after-cancel"},
)
compacted_items: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "compacted"},
)
]
class GatedSQLiteSession(SQLiteSession):
def __init__(self, session_id: str, db_path: str) -> None:
super().__init__(session_id, db_path)
self.add_calls = 0
self.clear_calls = 0
self.cancel_replacement_add = False
self.restore_clear_started = asyncio.Event()
self.allow_restore_clear = asyncio.Event()
async def add_items(self, items: list[TResponseInputItem]) -> None:
self.add_calls += 1
if self.cancel_replacement_add and self.add_calls == 1:
raise asyncio.CancelledError()
await super().add_items(items)
async def clear_session(self) -> None:
self.clear_calls += 1
if self.clear_calls == 2:
self.restore_clear_started.set()
await self.allow_restore_clear.wait()
await super().clear_session()
underlying = GatedSQLiteSession("lock-test", str(tmp_path / "compaction_lock.db"))
await underlying.add_items(history)
underlying.add_calls = 0
underlying.clear_calls = 0
underlying.cancel_replacement_add = True
mock_compact_response = MagicMock()
mock_compact_response.output = compacted_items
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="lock-test",
underlying_session=underlying,
client=mock_client,
compaction_mode="input",
)
# Warm wrapper caches so later add_items updates _session_items in place.
await session._ensure_compaction_candidates()
compaction_task = asyncio.create_task(session.run_compaction({"force": True}))
await underlying.restore_clear_started.wait()
newer_write = asyncio.create_task(session.add_items([newer_item]))
await asyncio.sleep(0)
assert not newer_write.done()
assert underlying.clear_calls == 2
assert not underlying.allow_restore_clear.is_set()
underlying.allow_restore_clear.set()
with pytest.raises(asyncio.CancelledError):
await compaction_task
await newer_write
stored = await session.get_items()
assert stored == [*history, newer_item]
assert session._session_items == [*history, newer_item]
assert underlying.clear_calls == 2
# 1) cancelled replacement add, 2) restore rewrite, 3) newer wrapper write.
assert underlying.add_calls == 3
@pytest.mark.asyncio
async def test_exception_restore_drains_when_compaction_is_cancelled(self, tmp_path) -> None:
"""Cancel during Exception-path restore must still finish rewriting history."""
history: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "message", "role": "user", "content": "original"}),
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "reply"},
),
]
compacted_items: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "compacted"},
)
]
class ExceptionThenGateRestoreSQLiteSession(SQLiteSession):
def __init__(self, session_id: str, db_path: str) -> None:
super().__init__(session_id, db_path)
self.add_calls = 0
self.clear_calls = 0
self.fail_replacement_add = False
self.restore_add_started = asyncio.Event()
self.allow_restore_add = asyncio.Event()
self.restore_tasks_seen: list[asyncio.Task[Any]] = []
async def add_items(self, items: list[TResponseInputItem]) -> None:
self.add_calls += 1
if self.fail_replacement_add and self.add_calls == 1:
raise RuntimeError("replacement failed")
if self.fail_replacement_add and self.add_calls == 2:
current = asyncio.current_task()
if current is not None:
self.restore_tasks_seen.append(current)
self.restore_add_started.set()
await self.allow_restore_add.wait()
await super().add_items(items)
async def clear_session(self) -> None:
self.clear_calls += 1
await super().clear_session()
underlying = ExceptionThenGateRestoreSQLiteSession(
"exception-cancel-restore", str(tmp_path / "exception_cancel_restore.db")
)
await underlying.add_items(history)
underlying.add_calls = 0
underlying.clear_calls = 0
underlying.fail_replacement_add = True
mock_compact_response = MagicMock()
mock_compact_response.output = compacted_items
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="exception-cancel-restore",
underlying_session=underlying,
client=mock_client,
compaction_mode="input",
)
await session._ensure_compaction_candidates()
warmed_items = list(session._session_items or [])
compaction_task = asyncio.create_task(session.run_compaction({"force": True}))
await underlying.restore_add_started.wait()
compaction_task.cancel()
await asyncio.sleep(0)
assert not compaction_task.done()
assert not underlying.allow_restore_add.is_set()
assert await underlying.get_items() == []
underlying.allow_restore_add.set()
with pytest.raises(asyncio.CancelledError):
await compaction_task
stored = await session.get_items()
assert stored == history
assert session._session_items == warmed_items
assert not session._mutation_lock.locked()
assert underlying.clear_calls == 2
assert underlying.add_calls == 2
assert all(task.done() for task in underlying.restore_tasks_seen)
@pytest.mark.asyncio
@pytest.mark.parametrize("max_rollback_items", [None, 3])
async def test_run_compaction_restores_full_history_when_session_limit_applies(
self,
max_rollback_items: int | None,
) -> None:
history: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "message", "role": "user", "content": "oldest"}),
cast(TResponseInputItem, {"type": "message", "role": "assistant", "content": "middle"}),
cast(TResponseInputItem, {"type": "message", "role": "user", "content": "newest"}),
]
compacted_items: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "compacted"},
)
]
class LimitedFailingReplacementSession(SimpleListSession):
def __init__(self, history: list[TResponseInputItem]) -> None:
super().__init__(history=history)
self.session_settings = SessionSettings(limit=1)
self.add_calls = 0
self.clear_calls = 0
async def get_items(self, limit: int | None = None) -> list[TResponseInputItem]:
if limit is None and self.session_settings is not None:
limit = self.session_settings.limit
return await super().get_items(limit)
async def add_items(self, items: list[TResponseInputItem]) -> None:
self.add_calls += 1
if self.add_calls == 1:
await super().add_items(items[:1])
raise RuntimeError("replacement failed")
await super().add_items(items)
async def clear_session(self) -> None:
self.clear_calls += 1
await super().clear_session()
failing_session = LimitedFailingReplacementSession(history=history)
mock_compact_response = MagicMock()
mock_compact_response.output = compacted_items
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=failing_session,
client=mock_client,
compaction_mode="input",
max_rollback_items=max_rollback_items,
)
with pytest.raises(RuntimeError, match="replacement failed"):
await session.run_compaction({"force": True})
assert await failing_session.get_items(limit=10) == history
assert failing_session.clear_calls == 2
assert failing_session.add_calls == 2
@pytest.mark.asyncio
async def test_run_compaction_does_not_restore_when_clear_fails_without_mutation(
self,
) -> None:
history: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "message", "role": "user", "content": "original"}),
]
compacted_items: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "compacted"},
)
]
class FailingClearBeforeMutationSession(SimpleListSession):
def __init__(self, history: list[TResponseInputItem]) -> None:
super().__init__(history=history)
self.add_calls = 0
self.clear_calls = 0
async def add_items(self, items: list[TResponseInputItem]) -> None:
self.add_calls += 1
await super().add_items(items)
async def clear_session(self) -> None:
self.clear_calls += 1
raise RuntimeError("clear failed")
failing_session = FailingClearBeforeMutationSession(history=history)
mock_compact_response = MagicMock()
mock_compact_response.output = compacted_items
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=failing_session,
client=mock_client,
compaction_mode="input",
)
with pytest.raises(RuntimeError, match="clear failed"):
await session.run_compaction({"force": True})
assert await failing_session.get_items() == history
assert failing_session.clear_calls == 1
assert failing_session.add_calls == 0
@pytest.mark.asyncio
async def test_run_compaction_restores_history_when_clear_fails_after_mutation(
self,
) -> None:
history: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "message", "role": "user", "content": "original"}),
]
compacted_items: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "compacted"},
)
]
class PartiallyFailingClearSession(SimpleListSession):
def __init__(self, history: list[TResponseInputItem]) -> None:
super().__init__(history=history)
self.add_calls = 0
self.clear_calls = 0
async def add_items(self, items: list[TResponseInputItem]) -> None:
self.add_calls += 1
await super().add_items(items)
async def clear_session(self) -> None:
self.clear_calls += 1
await super().clear_session()
raise RuntimeError("clear failed")
failing_session = PartiallyFailingClearSession(history=history)
mock_compact_response = MagicMock()
mock_compact_response.output = compacted_items
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=failing_session,
client=mock_client,
compaction_mode="input",
)
with pytest.raises(RuntimeError, match="clear failed"):
await session.run_compaction({"force": True})
assert await failing_session.get_items() == history
assert failing_session.clear_calls == 1
assert failing_session.add_calls == 1
@pytest.mark.asyncio
@pytest.mark.parametrize("redacted", [True, False])
async def test_run_compaction_reraises_replacement_error_when_restore_fails(
self, monkeypatch, caplog: pytest.LogCaptureFixture, redacted: bool
) -> None:
monkeypatch.setattr(_debug, "DONT_LOG_MODEL_DATA", redacted)
monkeypatch.setattr(_debug, "DONT_LOG_TOOL_DATA", redacted)
history: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "message", "role": "user", "content": "original"}),
]
compacted_items: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "compacted"},
)
]
class FailingRestoreSession(SimpleListSession):
def __init__(self, history: list[TResponseInputItem]) -> None:
super().__init__(history=history)
self.add_calls = 0
self.clear_calls = 0
async def add_items(self, items: list[TResponseInputItem]) -> None:
self.add_calls += 1
if self.add_calls == 1:
await super().add_items(items[:1])
raise RuntimeError("replacement failed")
raise RuntimeError("SECRET_COMPACTION_RESTORE_FAILURE")
async def clear_session(self) -> None:
self.clear_calls += 1
await super().clear_session()
failing_session = FailingRestoreSession(history=history)
mock_compact_response = MagicMock()
mock_compact_response.output = compacted_items
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=failing_session,
client=mock_client,
compaction_mode="input",
)
with caplog.at_level(logging.WARNING, logger="openai-agents.openai.compaction"):
with pytest.raises(RuntimeError, match="replacement failed"):
await session.run_compaction({"force": True})
assert (
"Failed to restore session history after compaction replacement failed." in caplog.text
)
assert ("SECRET_COMPACTION_RESTORE_FAILURE" not in caplog.text) is redacted
assert failing_session.clear_calls == 2
assert failing_session.add_calls == 2
@pytest.mark.asyncio
async def test_run_compaction_force_bypasses_threshold(self) -> None:
mock_session = self.create_mock_session()
mock_session.get_items.return_value = []
mock_compact_response = MagicMock()
mock_compact_response.output = []
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
client=mock_client,
)
await session.run_compaction({"response_id": "resp-123", "force": True})
mock_client.responses.compact.assert_called_once()
@pytest.mark.asyncio
async def test_run_compaction_retains_deferred_marker_when_api_call_fails(self) -> None:
"""A forced compaction driven by a previously-deferred response must not lose that
"this must be forced" signal if the compact API call itself fails: a later retry needs
_deferred_response_id to still be set so it recomputes force=True, not force=False.
"""
mock_session = self.create_mock_session()
mock_session.get_items.return_value = []
call_count = 0
async def compact(**kwargs: Any) -> MagicMock:
nonlocal call_count
call_count += 1
if call_count == 1:
raise RuntimeError("compact API blew up")
response = MagicMock()
response.output = []
return response
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(side_effect=compact)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
client=mock_client,
should_trigger_compaction=lambda _ctx: False,
)
# Simulate a prior turn (e.g. a handoff with local tool outputs) having deferred
# compaction for this response, the way _defer_compaction() would.
session._deferred_response_id = "resp-handoff"
with pytest.raises(RuntimeError, match="compact API blew up"):
await session.run_compaction(
{
"response_id": "resp-delegate",
"force": session._get_deferred_compaction_response_id() is not None,
}
)
assert session._get_deferred_compaction_response_id() == "resp-handoff"
# Retry, recomputing force the same way the checkpoint-recovery code does.
await session.run_compaction(
{
"response_id": "resp-delegate",
"force": session._get_deferred_compaction_response_id() is not None,
}
)
assert call_count == 2
assert session._get_deferred_compaction_response_id() is None
@pytest.mark.asyncio
async def test_run_compaction_suppresses_model_dump_warnings(self) -> None:
mock_session = self.create_mock_session()
mock_session.get_items.return_value = [
cast(TResponseInputItem, {"type": "message", "role": "assistant", "content": "hi"})
for _ in range(DEFAULT_COMPACTION_THRESHOLD)
]
class WarningModel:
def __init__(self) -> None:
self.received_warnings_arg: bool | None = None
def model_dump(
self, *, exclude_unset: bool, warnings: bool | None = None
) -> dict[str, Any]:
self.received_warnings_arg = warnings
if warnings:
warnings_module.warn("unexpected warning", stacklevel=2)
return {"type": "message", "role": "assistant", "content": "ok"}
warning_model = WarningModel()
mock_compact_response = MagicMock()
mock_compact_response.output = [warning_model]
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
client=mock_client,
)
with warnings_module.catch_warnings():
warnings_module.simplefilter("error")
await session.run_compaction({"response_id": "resp-123"})
assert warning_model.received_warnings_arg is False
mock_client.responses.compact.assert_called_once_with(
previous_response_id="resp-123",
model="gpt-6-luna",
)
@pytest.mark.asyncio
async def test_run_compaction_normalizes_compacted_user_image_messages(self) -> None:
mock_session = self.create_mock_session()
mock_session.get_items.return_value = []
mock_compact_response = MagicMock()
mock_compact_response.output = [
{
"type": "message",
"role": "user",
"content": [
{"type": "input_text", "text": "analyze this input"},
{
"type": "input_image",
"image_url": "https://example.com/image.png",
"file_id": None,
"detail": "auto",
},
],
}
]
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
client=mock_client,
compaction_mode="input",
)
await session.run_compaction({"force": True, "compaction_mode": "input"})
stored_items = mock_session.add_items.call_args[0][0]
assert stored_items == [
{
"type": "message",
"role": "user",
"content": [
{"type": "input_text", "text": "analyze this input"},
{
"type": "input_image",
"image_url": "https://example.com/image.png",
"detail": "auto",
},
],
}
]
@pytest.mark.asyncio
async def test_run_compaction_normalizes_compacted_user_file_messages(self) -> None:
mock_session = self.create_mock_session()
mock_session.get_items.return_value = []
mock_compact_response = MagicMock()
mock_compact_response.output = [
{
"type": "message",
"role": "user",
"content": [
{"type": "input_text", "text": "analyze this input"},
{
"type": "input_file",
"file_url": "https://example.com/report.pdf",
"file_id": None,
"filename": "report.pdf",
"detail": "high",
},
],
}
]
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
client=mock_client,
compaction_mode="input",
)
await session.run_compaction({"force": True, "compaction_mode": "input"})
stored_items = mock_session.add_items.call_args[0][0]
assert stored_items == [
{
"type": "message",
"role": "user",
"content": [
{"type": "input_text", "text": "analyze this input"},
{
"type": "input_file",
"file_url": "https://example.com/report.pdf",
"filename": "report.pdf",
"detail": "high",
},
],
}
]
@pytest.mark.asyncio
async def test_run_compaction_normalizes_file_id_inputs_and_preserves_metadata(self) -> None:
mock_session = self.create_mock_session()
mock_session.get_items.return_value = []
mock_compact_response = MagicMock()
mock_compact_response.output = [
{
"type": "message",
"role": "user",
"content": [
{"type": "input_text", "text": "analyze this input"},
{
"type": "input_file",
"file_id": "file_123",
"file_url": None,
"filename": "report.pdf",
"detail": "low",
},
],
}
]
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
client=mock_client,
compaction_mode="input",
)
await session.run_compaction({"force": True, "compaction_mode": "input"})
stored_items = mock_session.add_items.call_args[0][0]
assert stored_items == [
{
"type": "message",
"role": "user",
"content": [
{"type": "input_text", "text": "analyze this input"},
{
"type": "input_file",
"file_id": "file_123",
"filename": "report.pdf",
"detail": "low",
},
],
}
]
@pytest.mark.asyncio
async def test_run_compaction_preserves_history_when_output_normalization_fails(self) -> None:
history = [
{
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "hello"}],
},
{
"type": "message",
"role": "assistant",
"status": "completed",
"content": [{"type": "output_text", "text": "world"}],
},
]
underlying = SimpleListSession(history=cast(list[TResponseInputItem], history))
mock_compact_response = MagicMock()
mock_compact_response.output = [
{
"type": "message",
"role": "user",
"content": [
{"type": "input_text", "text": "hello"},
{"type": "input_image", "detail": "auto"},
],
}
]
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=underlying,
client=mock_client,
compaction_mode="input",
)
with pytest.raises(
ValueError, match="Compaction input_image item missing image_url or file_id."
):
await session.run_compaction({"force": True, "compaction_mode": "input"})
assert await session.get_items() == history
@pytest.mark.asyncio
async def test_compaction_runs_during_runner_flow(self) -> None:
"""Ensure Runner triggers compaction when using a compaction-aware session."""
underlying = SimpleListSession()
compacted = SimpleNamespace(
output=[{"type": "compaction", "encrypted_content": "enc"}],
usage=ResponseUsage(
input_tokens=150_000,
input_tokens_details=InputTokensDetails(
cached_tokens=50_000,
cache_write_tokens=0,
),
output_tokens=42_000,
output_tokens_details=OutputTokensDetails(reasoning_tokens=10_000),
total_tokens=192_000,
),
)
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=compacted)
session = OpenAIResponsesCompactionSession(
session_id="demo",
underlying_session=underlying,
client=mock_client,
should_trigger_compaction=lambda ctx: True,
)
model = ScriptedModel(steps=[[get_text_message("ok")]])
agent = Agent(name="assistant", model=model)
result = await Runner.run(agent, "hello", session=session)
mock_client.responses.compact.assert_awaited_once()
assert result.context_wrapper.usage.requests == 2
assert result.context_wrapper.usage.input_tokens == 150_000
assert result.context_wrapper.usage.output_tokens == 42_000
assert result.context_wrapper.usage.total_tokens == 192_000
assert result.context_wrapper.usage.input_tokens_details.cached_tokens == 50_000
assert result.context_wrapper.usage.output_tokens_details.reasoning_tokens == 10_000
assert len(result.context_wrapper.usage.request_usage_entries) == 1
assert result.context_wrapper.usage.request_usage_entries[0].total_tokens == 192_000
items = await session.get_items()
assert any(isinstance(item, dict) and item.get("type") == "compaction" for item in items)
@pytest.mark.asyncio
async def test_compaction_skips_when_tool_outputs_present(self) -> None:
underlying = SimpleListSession()
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock()
session = OpenAIResponsesCompactionSession(
session_id="demo",
underlying_session=underlying,
client=mock_client,
should_trigger_compaction=lambda ctx: True,
)
tool = get_function_tool(name="do_thing", return_value="done")
model = ScriptedModel(steps=[[get_function_tool_call("do_thing")]])
agent = Agent(
name="assistant",
model=model,
tools=[tool],
tool_use_behavior="stop_on_first_tool",
)
await Runner.run(agent, "hello", session=session)
mock_client.responses.compact.assert_not_called()
@pytest.mark.asyncio
async def test_deferred_compaction_includes_compaction_mode_in_context(self) -> None:
underlying = SimpleListSession()
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock()
observed = {}
def should_trigger_compaction(context: dict[str, Any]) -> bool:
observed["mode"] = context["compaction_mode"]
return False
session = OpenAIResponsesCompactionSession(
session_id="demo",
underlying_session=underlying,
client=mock_client,
compaction_mode="input",
should_trigger_compaction=should_trigger_compaction,
)
tool = get_function_tool(name="do_thing", return_value="done")
model = ScriptedModel(steps=[[get_function_tool_call("do_thing")]])
agent = Agent(
name="assistant",
model=model,
tools=[tool],
tool_use_behavior="stop_on_first_tool",
)
await Runner.run(agent, "hello", session=session)
assert observed["mode"] == "input"
mock_client.responses.compact.assert_not_called()
@pytest.mark.asyncio
async def test_compaction_runs_after_deferred_tool_outputs_when_due(self) -> None:
underlying = SimpleListSession()
compacted = SimpleNamespace(
output=[{"type": "compaction", "summary": "compacted"}],
)
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=compacted)
def should_trigger_compaction(context: dict[str, Any]) -> bool:
return any(
isinstance(item, dict) and item.get("type") == "function_call_output"
for item in context["session_items"]
)
session = OpenAIResponsesCompactionSession(
session_id="demo",
underlying_session=underlying,
client=mock_client,
should_trigger_compaction=should_trigger_compaction,
)
tool = get_function_tool(name="do_thing", return_value="done")
model = ScriptedModel()
model.extend(
[
[get_function_tool_call("do_thing")],
[get_text_message("ok")],
]
)
agent = Agent(
name="assistant",
model=model,
tools=[tool],
tool_use_behavior="stop_on_first_tool",
)
await Runner.run(agent, "hello", session=session)
await Runner.run(agent, "followup", session=session)
mock_client.responses.compact.assert_awaited_once()
@pytest.mark.asyncio
async def test_deferred_compaction_persists_across_tool_turns(self) -> None:
underlying = SimpleListSession()
compacted = SimpleNamespace(
output=[{"type": "compaction", "summary": "compacted"}],
)
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=compacted)
should_compact_calls = {"count": 0}
def should_trigger_compaction(context: dict[str, Any]) -> bool:
should_compact_calls["count"] += 1
return should_compact_calls["count"] == 1
session = OpenAIResponsesCompactionSession(
session_id="demo",
underlying_session=underlying,
client=mock_client,
should_trigger_compaction=should_trigger_compaction,
)
tool = get_function_tool(name="do_thing", return_value="done")
model = ScriptedModel()
model.extend(
[
[get_function_tool_call("do_thing", call_id="call-first")],
[get_function_tool_call("do_thing", call_id="call-second")],
[get_text_message("ok")],
]
)
agent = Agent(
name="assistant",
model=model,
tools=[tool],
tool_use_behavior="stop_on_first_tool",
)
await Runner.run(agent, "hello", session=session)
await Runner.run(agent, "again", session=session)
await Runner.run(agent, "final", session=session)
mock_client.responses.compact.assert_awaited_once()
class TestStripOrphanedAssistantIds:
def test_noop_when_empty(self) -> None:
assert _strip_orphaned_assistant_ids([]) == []
def test_strips_id_from_assistant_when_no_reasoning(self) -> None:
items: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "id": "msg_abc", "content": "hi"},
),
cast(
TResponseInputItem,
{"type": "message", "role": "user", "content": "hello"},
),
]
result = _strip_orphaned_assistant_ids(items)
assert "id" not in result[0]
# user message untouched
assert result[1] == items[1]
def test_preserves_id_when_reasoning_present(self) -> None:
items: list[TResponseInputItem] = [
cast(TResponseInputItem, {"type": "reasoning", "id": "rs_123", "content": "..."}),
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "id": "msg_abc", "content": "hi"},
),
]
result = _strip_orphaned_assistant_ids(items)
assert result[1].get("id") == "msg_abc"
def test_preserves_assistant_without_id(self) -> None:
items: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "hi"},
),
]
result = _strip_orphaned_assistant_ids(items)
assert result == items
def test_strips_multiple_assistant_ids(self) -> None:
items: list[TResponseInputItem] = [
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "id": "msg_1", "content": "a"},
),
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "id": "msg_2", "content": "b"},
),
cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "id": "msg_3", "content": "c"},
),
]
result = _strip_orphaned_assistant_ids(items)
for item in result:
assert "id" not in item
class TestCompactionMutationSerialization:
@pytest.mark.asyncio
async def test_resumed_save_carries_generation_into_compaction(self) -> None:
"""A resumed append uses the same ownership handoff as a fresh save."""
underlying = SimpleListSession()
client = MagicMock()
client.responses.compact = AsyncMock(return_value=SimpleNamespace(output=[]))
resumed_persisted = asyncio.Event()
release_resumed = asyncio.Event()
add_calls = 0
class PausingCompactionSession(OpenAIResponsesCompactionSession):
async def _add_items_with_generation(
self,
write_items: Callable[[], Awaitable[None]],
*,
expected_generation: int | None,
) -> int | None:
nonlocal add_calls
generation = await super()._add_items_with_generation(
write_items,
expected_generation=expected_generation,
)
add_calls += 1
if add_calls == 1:
resumed_persisted.set()
await release_resumed.wait()
return generation
session = PausingCompactionSession(
session_id="resumed-interleaved-persist",
underlying_session=underlying,
client=client,
compaction_mode="previous_response_id",
should_trigger_compaction=lambda context: context["response_id"] == "resp-a",
)
agent = Agent(name="worker-a")
wrapper = RunContextWrapper(context=None)
state: RunState[Any] = RunState(
context=wrapper,
original_input=[],
starting_agent=agent,
)
resumed_item = MessageOutputItem(agent=agent, raw_item=get_text_message("run-A"))
await prepare_input_with_session([], session, None, wrapper=wrapper)
resumed_save = asyncio.create_task(
save_result_to_session(
session,
[],
[resumed_item],
state,
response_id="resp-a",
wrapper=wrapper,
resumed_write_state=state,
)
)
await asyncio.wait_for(resumed_persisted.wait(), timeout=1)
await asyncio.wait_for(
Runner.run(
Agent(
name="worker-b",
model=ScriptedModel(
steps=[
ModelStep(
output=[get_text_message("run-B")],
response_id="resp-b",
)
]
),
),
"input-B",
session=session,
),
timeout=1,
)
release_resumed.set()
await resumed_save
client.responses.compact.assert_not_awaited()
stored = str(await underlying.get_items())
assert "run-A" in stored
assert "run-B" in stored
@pytest.mark.asyncio
async def test_runner_skips_compaction_after_interleaved_model_wait(self) -> None:
"""A later run that completes during A's model wait revokes A's replacement."""
underlying = SimpleListSession()
client = MagicMock()
client.responses.compact = AsyncMock(return_value=SimpleNamespace(output=[]))
model_entered = asyncio.Event()
release_model = asyncio.Event()
async def respond_after_b(_: Any) -> ModelStep:
model_entered.set()
await release_model.wait()
return ModelStep(output=[get_text_message("run-A")], response_id="resp-a")
session = OpenAIResponsesCompactionSession(
session_id="interleaved-model-wait",
underlying_session=underlying,
client=client,
compaction_mode="previous_response_id",
should_trigger_compaction=lambda context: context["response_id"] == "resp-a",
)
run_a = asyncio.create_task(
Runner.run(
Agent(
name="worker-a",
model=ScriptedModel(steps=[ModelStep.respond(respond_after_b)]),
),
"input-A",
session=session,
)
)
await asyncio.wait_for(model_entered.wait(), timeout=1)
await asyncio.wait_for(
Runner.run(
Agent(
name="worker-b",
model=ScriptedModel(
steps=[
ModelStep(
output=[get_text_message("run-B")],
response_id="resp-b",
)
]
),
),
"input-B",
session=session,
),
timeout=1,
)
release_model.set()
await run_a
client.responses.compact.assert_not_awaited()
stored = str(await underlying.get_items())
assert "run-A" in stored
assert "run-B" in stored
@pytest.mark.asyncio
async def test_runner_skips_compaction_after_interleaved_persist(self) -> None:
"""A later Runner append between save and compact revokes replacement."""
underlying = SimpleListSession()
client = MagicMock()
client.responses.compact = AsyncMock(return_value=SimpleNamespace(output=[]))
run_a_persisted = asyncio.Event()
release_run_a = asyncio.Event()
add_calls = 0
class PausingCompactionSession(OpenAIResponsesCompactionSession):
async def _add_items_with_generation(
self,
write_items: Callable[[], Awaitable[None]],
*,
expected_generation: int | None,
) -> int | None:
nonlocal add_calls
generation = await super()._add_items_with_generation(
write_items,
expected_generation=expected_generation,
)
add_calls += 1
if add_calls == 2:
run_a_persisted.set()
await release_run_a.wait()
return generation
session = PausingCompactionSession(
session_id="interleaved-persist",
underlying_session=underlying,
client=client,
compaction_mode="previous_response_id",
should_trigger_compaction=lambda context: context["response_id"] == "resp-a",
)
run_a = asyncio.create_task(
Runner.run(
Agent(
name="worker-a",
model=ScriptedModel(
steps=[
ModelStep(
output=[get_text_message("run-A")],
response_id="resp-a",
)
]
),
),
"input-A",
session=session,
)
)
await asyncio.wait_for(run_a_persisted.wait(), timeout=1)
await asyncio.wait_for(
Runner.run(
Agent(
name="worker-b",
model=ScriptedModel(
steps=[
ModelStep(
output=[get_text_message("run-B")],
response_id="resp-b",
)
]
),
),
"input-B",
session=session,
),
timeout=1,
)
release_run_a.set()
await run_a
client.responses.compact.assert_not_awaited()
stored = str(await underlying.get_items())
assert "run-A" in stored
assert "run-B" in stored
@pytest.mark.asyncio
async def test_add_waits_for_in_flight_compaction_and_survives(self) -> None:
old_item = cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "old"},
)
concurrent_item = cast(
TResponseInputItem,
{"type": "message", "role": "user", "content": "concurrent"},
)
compacted_item = cast(
TResponseInputItem,
{"type": "compaction", "summary": "compacted"},
)
underlying = SimpleListSession(history=[old_item])
compact_entered = asyncio.Event()
release_compact = asyncio.Event()
async def compact(**_: Any) -> SimpleNamespace:
compact_entered.set()
await release_compact.wait()
return SimpleNamespace(output=[compacted_item])
client = MagicMock()
client.responses.compact = AsyncMock(side_effect=compact)
session = OpenAIResponsesCompactionSession(
session_id="serialized-add",
underlying_session=underlying,
client=client,
compaction_mode="input",
)
compaction_task = asyncio.create_task(session.run_compaction({"force": True}))
await compact_entered.wait()
add_task = asyncio.create_task(session.add_items([concurrent_item]))
await asyncio.sleep(0)
assert not add_task.done()
release_compact.set()
await compaction_task
await add_task
assert await underlying.get_items() == [compacted_item, concurrent_item]
@pytest.mark.asyncio
async def test_clear_waits_for_in_flight_compaction_and_stays_empty(self) -> None:
old_item = cast(
TResponseInputItem,
{"type": "message", "role": "assistant", "content": "old"},
)
compacted_item = cast(
TResponseInputItem,
{"type": "compaction", "summary": "compacted"},
)
underlying = SimpleListSession(history=[old_item])
compact_entered = asyncio.Event()
release_compact = asyncio.Event()
async def compact(**_: Any) -> SimpleNamespace:
compact_entered.set()
await release_compact.wait()
return SimpleNamespace(output=[compacted_item])
client = MagicMock()
client.responses.compact = AsyncMock(side_effect=compact)
session = OpenAIResponsesCompactionSession(
session_id="serialized-clear",
underlying_session=underlying,
client=client,
compaction_mode="input",
)
compaction_task = asyncio.create_task(session.run_compaction({"force": True}))
await compact_entered.wait()
clear_task = asyncio.create_task(session.clear_session())
await asyncio.sleep(0)
assert not clear_task.done()
release_compact.set()
await compaction_task
await clear_task
assert await underlying.get_items() == []
class TestCompactionStripsOrphanedIds:
"""Regression test for #2727: gpt-5.4 compact retains assistant msg IDs after
stripping reasoning items, causing 400 errors on the next responses.create call."""
def create_mock_session(self) -> MagicMock:
mock = MagicMock(spec=Session)
mock.session_id = "test-session"
mock.get_items = AsyncMock(return_value=[])
mock.add_items = AsyncMock()
mock.pop_item = AsyncMock(return_value=None)
mock.clear_session = AsyncMock()
return mock
@pytest.mark.asyncio
async def test_run_compaction_strips_orphaned_assistant_ids(self) -> None:
"""Compacted output with assistant IDs but no reasoning items should
have those IDs removed before being stored."""
mock_session = self.create_mock_session()
mock_session.get_items.return_value = [
cast(TResponseInputItem, {"type": "message", "role": "assistant", "content": f"m{i}"})
for i in range(DEFAULT_COMPACTION_THRESHOLD)
]
# Simulate gpt-5.4 compact output: assistant msgs WITH ids, NO reasoning items
mock_compact_response = MagicMock()
mock_compact_response.output = [
{"type": "message", "role": "assistant", "id": "msg_aaa", "content": "summary 1"},
{"type": "message", "role": "assistant", "id": "msg_bbb", "content": "summary 2"},
{"type": "message", "role": "assistant", "id": "msg_ccc", "content": "summary 3"},
]
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
client=mock_client,
)
await session.run_compaction({"response_id": "resp-123"})
# Verify stored items have no orphaned ids
stored_items = mock_session.add_items.call_args[0][0]
for item in stored_items:
assert "id" not in item, f"orphaned id not stripped: {item}"
@pytest.mark.asyncio
async def test_run_compaction_keeps_ids_when_reasoning_present(self) -> None:
"""When compact output includes reasoning items, assistant IDs should be kept."""
mock_session = self.create_mock_session()
mock_session.get_items.return_value = [
cast(TResponseInputItem, {"type": "message", "role": "assistant", "content": f"m{i}"})
for i in range(DEFAULT_COMPACTION_THRESHOLD)
]
mock_compact_response = MagicMock()
mock_compact_response.output = [
{"type": "reasoning", "id": "rs_111", "content": "thinking..."},
{"type": "message", "role": "assistant", "id": "msg_aaa", "content": "answer"},
]
mock_client = MagicMock()
mock_client.responses.compact = AsyncMock(return_value=mock_compact_response)
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_session,
client=mock_client,
)
await session.run_compaction({"response_id": "resp-123"})
stored_items = mock_session.add_items.call_args[0][0]
assistant_items = [i for i in stored_items if i.get("role") == "assistant"]
assert assistant_items[0]["id"] == "msg_aaa"
class TestTypeGuard:
def test_is_compaction_aware_session_true(self) -> None:
mock_underlying = MagicMock(spec=Session)
mock_underlying.session_id = "test"
mock_underlying.get_items = AsyncMock(return_value=[])
mock_underlying.add_items = AsyncMock()
mock_underlying.pop_item = AsyncMock(return_value=None)
mock_underlying.clear_session = AsyncMock()
session = OpenAIResponsesCompactionSession(
session_id="test",
underlying_session=mock_underlying,
)
assert is_openai_responses_compaction_aware_session(session) is True
def test_is_compaction_aware_session_false(self) -> None:
mock_session = MagicMock(spec=Session)
assert is_openai_responses_compaction_aware_session(mock_session) is False
def test_is_compaction_aware_session_none(self) -> None:
assert is_openai_responses_compaction_aware_session(None) is False