Skip to content

Commit bc03568

Browse files
committed
test: cover settled clear failures and auto mode after clearing
Add the regressions requested in review: a clear whose deletion commits before cancellation or an acknowledgement error reaches the caller still propagates the original failure, cannot reuse the cleared response chain, and leaves the session writable. Also cover default auto mode compacting from current local input after a previously stored response is cleared.
1 parent 84ca255 commit bc03568

1 file changed

Lines changed: 120 additions & 0 deletions

File tree

‎tests/memory/test_openai_responses_compaction_session.py‎

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,126 @@ async def test_clear_session_invalidates_response_chain(self) -> None:
326326
assert mock_client.responses.compact.await_args is not None
327327
assert mock_client.responses.compact.await_args.kwargs["previous_response_id"] == "resp-new"
328328

329+
@pytest.mark.asyncio
330+
@pytest.mark.parametrize("outcome", ["cancelled", "error"])
331+
async def test_settled_clear_failure_invalidates_response_chain(
332+
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, outcome: str
333+
) -> None:
334+
# Gate the real SQLite commit acknowledgement so cancellation cannot undo the clear.
335+
committed = threading.Event()
336+
allow_return = threading.Event()
337+
338+
class PausingCommitConnection(sqlite3.Connection):
339+
pause_commit = True
340+
341+
def commit(self) -> None:
342+
super().commit()
343+
if self.pause_commit:
344+
self.pause_commit = False
345+
committed.set()
346+
assert allow_return.wait(timeout=10)
347+
if outcome == "error":
348+
raise RuntimeError("commit acknowledgement failed")
349+
350+
underlying = SQLiteSession("settled-clear", tmp_path / "settled-clear.db")
351+
history: list[TResponseInputItem] = [
352+
{"role": "user", "content": "keep me"},
353+
{"role": "assistant", "content": "remove me"},
354+
]
355+
await underlying.add_items(history)
356+
connection = sqlite3.connect(
357+
str(tmp_path / "settled-clear.db"),
358+
check_same_thread=False,
359+
factory=PausingCommitConnection,
360+
)
361+
with underlying._connections_lock:
362+
underlying._connections.add(connection)
363+
monkeypatch.setattr(underlying, "_get_connection", lambda: connection)
364+
mock_client = MagicMock()
365+
mock_client.responses.compact = AsyncMock(
366+
return_value=SimpleNamespace(output=[], usage=None)
367+
)
368+
session = OpenAIResponsesCompactionSession(
369+
session_id="settled-clear",
370+
underlying_session=underlying,
371+
client=mock_client,
372+
compaction_mode="previous_response_id",
373+
should_trigger_compaction=lambda ctx: False,
374+
)
375+
await session.run_compaction({"response_id": "resp-old", "store": False})
376+
session.should_trigger_compaction = lambda ctx: True
377+
await session._defer_compaction("resp-old")
378+
mutation = asyncio.create_task(session.clear_session())
379+
try:
380+
assert await asyncio.to_thread(committed.wait, 10)
381+
if outcome == "cancelled":
382+
mutation.cancel()
383+
allow_return.set()
384+
if outcome == "cancelled":
385+
with pytest.raises(asyncio.CancelledError):
386+
await mutation
387+
else:
388+
with pytest.raises(RuntimeError, match="commit acknowledgement failed"):
389+
await mutation
390+
391+
# The deletion committed before the failure reached the caller.
392+
assert await session.get_items() == []
393+
assert not session._mutation_lock.locked()
394+
with pytest.raises(ValueError, match="requires a response_id"):
395+
await session.run_compaction({"force": True})
396+
mock_client.responses.compact.assert_not_awaited()
397+
assert session._get_deferred_compaction_response_id() is None
398+
assert session._last_unstored_response_id is None
399+
400+
# The session stays usable: a subsequent write survives.
401+
follow_up: TResponseInputItem = {"role": "user", "content": "after clear"}
402+
await session.add_items([follow_up])
403+
assert await session.get_items() == [follow_up]
404+
await session.run_compaction({"response_id": "resp-new", "force": True})
405+
assert mock_client.responses.compact.await_args is not None
406+
compact_kwargs = mock_client.responses.compact.await_args.kwargs
407+
assert compact_kwargs["previous_response_id"] == "resp-new"
408+
finally:
409+
allow_return.set()
410+
if not mutation.done():
411+
mutation.cancel()
412+
await asyncio.gather(mutation, return_exceptions=True)
413+
underlying.close()
414+
415+
@pytest.mark.asyncio
416+
async def test_run_compaction_auto_uses_input_after_clear(self) -> None:
417+
item: TResponseInputItem = {"role": "assistant", "content": "old turn"}
418+
underlying = SimpleListSession(history=[item])
419+
mock_client = MagicMock()
420+
mock_client.responses.compact = AsyncMock(
421+
return_value=SimpleNamespace(output=[], usage=None)
422+
)
423+
session = OpenAIResponsesCompactionSession(
424+
session_id="test",
425+
underlying_session=underlying,
426+
client=mock_client,
427+
)
428+
# Default auto mode follows the stored response chain first.
429+
await session.run_compaction({"response_id": "resp-old", "force": True})
430+
first_kwargs = mock_client.responses.compact.call_args.kwargs
431+
assert first_kwargs.get("previous_response_id") == "resp-old"
432+
assert "input" not in first_kwargs
433+
434+
await session.clear_session()
435+
new_items: list[TResponseInputItem] = [
436+
cast(TResponseInputItem, {"role": "user", "content": "fresh start"}),
437+
cast(TResponseInputItem, {"role": "assistant", "content": "fresh reply"}),
438+
]
439+
await session.add_items(new_items)
440+
441+
# After clearing the stored response, auto mode compacts from the
442+
# current local input instead of reusing the cleared response chain.
443+
await session.run_compaction({"force": True})
444+
assert mock_client.responses.compact.call_count == 2
445+
second_kwargs = mock_client.responses.compact.call_args.kwargs
446+
assert "previous_response_id" not in second_kwargs
447+
assert second_kwargs.get("input") == new_items
448+
329449
@pytest.mark.asyncio
330450
async def test_get_items_delegates(self) -> None:
331451
mock_session = self.create_mock_session()

0 commit comments

Comments
 (0)