Skip to content

Commit 92a2c60

Browse files
fix: refresh encrypted session visibility before compaction (#5209)
1 parent ee9a12a commit 92a2c60

2 files changed

Lines changed: 62 additions & 5 deletions

File tree

‎src/agents/memory/openai_responses_compaction_session.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -778,18 +778,18 @@ async def _ensure_compaction_candidates(
778778
*,
779779
limit: int | None = None,
780780
) -> tuple[list[TResponseInputItem], list[TResponseInputItem], bool]:
781-
"""Lazy-load candidates, or read a bounded snapshot for automatic coverage checks."""
781+
"""Load policy-visible candidates, or a bounded automatic coverage snapshot."""
782+
if read_items is None:
783+
# Resolve the wrapped policy before consulting the cache: visibility can
784+
# change without a wrapper mutation, for example when encrypted items expire.
785+
read_items = getattr(self.underlying_session, "_read_compaction_items", None)
782786
cache_snapshot = read_items is None and limit is None
783787
if (
784788
cache_snapshot
785789
and self._compaction_candidate_items is not None
786790
and self._session_items is not None
787791
):
788792
return (self._compaction_candidate_items[:], self._session_items[:], False)
789-
if read_items is None:
790-
# Storage wrappers own the logical policy view and bounded raw reads,
791-
# including when compaction is the outer wrapper.
792-
read_items = getattr(self.underlying_session, "_read_compaction_items", None)
793793
if read_items is not None:
794794
items, complete = await read_items(limit)
795795
else:

‎tests/memory/test_compaction_model_visibility.py‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -561,6 +561,63 @@ def add_context(data: CallModelData[Any]) -> ModelInputData:
561561
assert await session.get_items() == []
562562

563563

564+
@pytest.mark.parametrize("outer", [False, True])
565+
async def test_manual_compaction_refreshes_expired_encrypted_history(
566+
outer: bool, monkeypatch: pytest.MonkeyPatch
567+
) -> None:
568+
pytest.importorskip("cryptography")
569+
from agents.extensions.memory.encrypt_session import EncryptedSession
570+
571+
clock = [1000]
572+
monkeypatch.setattr("cryptography.fernet.time.time", lambda: clock[0])
573+
backend = SQLiteSession("manual-expiry")
574+
client = MagicMock()
575+
# Echo the request so stale input would also be written back with a fresh TTL.
576+
client.responses.compact = AsyncMock(
577+
side_effect=lambda **kwargs: SimpleNamespace(output=kwargs["input"])
578+
)
579+
session: SessionABC
580+
if outer:
581+
session = EncryptedSession(
582+
"manual-expiry",
583+
OpenAIResponsesCompactionSession(
584+
"manual-expiry",
585+
backend,
586+
client=client,
587+
compaction_mode="input",
588+
should_trigger_compaction=lambda _: False,
589+
),
590+
encryption_key="synthetic-test-key",
591+
ttl=10,
592+
)
593+
else:
594+
session = OpenAIResponsesCompactionSession(
595+
"manual-expiry",
596+
EncryptedSession("manual-expiry", backend, encryption_key="synthetic-test-key", ttl=10),
597+
client=client,
598+
compaction_mode="input",
599+
should_trigger_compaction=lambda _: False,
600+
)
601+
try:
602+
await session.add_items([{"role": "assistant", "content": "synthetic expired item"}])
603+
await session.run_compaction() # A declined policy check can populate the cache.
604+
client.responses.compact.assert_not_awaited()
605+
606+
clock[0] += 11
607+
assert await session.get_items() == []
608+
await session.run_compaction({"force": True})
609+
client.responses.compact.assert_awaited_once_with(model="gpt-4.1", input=[])
610+
assert await session.get_items() == []
611+
612+
live: TResponseInputItem = {"role": "user", "content": "synthetic live item"}
613+
await session.add_items([live])
614+
await session.run_compaction({"force": True})
615+
assert client.responses.compact.call_args.kwargs["input"] == [live]
616+
assert await session.get_items() == [live]
617+
finally:
618+
backend.close()
619+
620+
564621
@pytest.mark.parametrize("streamed", [False, True])
565622
@pytest.mark.parametrize("outer", [False, True])
566623
@pytest.mark.parametrize("limited_default", [False, True])

0 commit comments

Comments
 (0)