Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion python/packages/core/agent_framework/_sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2465,8 +2465,15 @@ def _quarantine_corrupt_snapshot(file_path: Path, serialized: bytes) -> Path | N
return None
if current_serialized != serialized:
return None
quarantine_path = file_path.with_name(f".{file_path.name}.{uuid.uuid4().hex}.corrupt")
quarantine_path = file_path.with_name(f".{uuid.uuid4().hex}.corrupt")
os.replace(file_path, quarantine_path)
# The bounded name no longer carries the session id, so log the snapshot path here: the
# quarantine file is otherwise unattributable to the session it came from.
logger.warning(
"Session snapshot %s was corrupt; moved it aside to %s so the session can be created again.",
file_path,
quarantine_path,
)
return quarantine_path

@classmethod
Expand Down
112 changes: 112 additions & 0 deletions python/packages/core/tests/core/test_sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import asyncio
import json
import logging
import math
import os
import threading
Expand Down Expand Up @@ -1361,6 +1362,117 @@ async def test_corrupt_session_file_is_quarantined_and_retry_returns_none(self,
assert len(quarantined_files) == 1
assert await store.get("session-1") is None

async def test_corrupt_quarantine_name_does_not_grow_with_the_session_id(self, tmp_path: Path) -> None:
"""The quarantine destination must not embed the snapshot name.

On Windows with legacy MAX_PATH handling, a 128-character session id already puts the
snapshot near the limit; adding the full snapshot name plus a UUID to the quarantine
destination makes the rename fail and leaves the corrupt file in place (#9885).
"""
store = FileSessionStore(tmp_path)
session_id = "x" * FileSessionStore.MAX_SESSION_ID_LENGTH
session_file = store._session_file_path(session_id)
await asyncio.to_thread(session_file.write_bytes, b"not-json")

with pytest.raises(ValueError, match="quarantined.*retry"):
await store.get(session_id)

assert not session_file.exists()
quarantined_files = await asyncio.to_thread(lambda: list(tmp_path.glob(".*.corrupt")))
assert len(quarantined_files) == 1
assert len(quarantined_files[0].name) <= 41 # "." + 32 hex chars + ".corrupt"

async def test_corrupt_quarantine_logs_the_snapshot_path(
self, tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""The bounded quarantine name drops the session id, so the warning must keep it attributable."""
store = FileSessionStore(tmp_path)
session_file = store._session_file_path("session-1")
await asyncio.to_thread(session_file.write_bytes, b"not-json")

with (
caplog.at_level(logging.WARNING, logger="agent_framework"),
pytest.raises(ValueError, match="quarantined.*retry"),
):
await store.get("session-1")

messages = [record.getMessage() for record in caplog.records]
assert any(session_file.name in message and ".corrupt" in message for message in messages), messages

async def test_corrupt_quarantine_survives_legacy_windows_max_path(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A 253-character snapshot path must still be quarantined when rename is capped at 260.

Simulates the Windows legacy limit on the destination of ``os.replace`` so the case runs
on every platform; with the snapshot name embedded in the quarantine name the destination
is ~295 characters and the rename raises, which is the reported failure.
"""
store = FileSessionStore(tmp_path)
session_id = "x" * FileSessionStore.MAX_SESSION_ID_LENGTH
sample_path = store._session_file_path(session_id)
padding = 252 - len(str(tmp_path)) - 1 - len(sample_path.name)
if padding <= 0:
pytest.skip("pytest temporary root is too long to build a near-MAX_PATH case")
deep_root = tmp_path / ("d" * padding)
deep_root.mkdir()
deep_store = FileSessionStore(deep_root)
session_file = deep_store._session_file_path(session_id)
assert len(str(session_file)) == 253
await asyncio.to_thread(session_file.write_bytes, b"not-json")

real_replace = os.replace

def limited_replace(src: str | os.PathLike[str], dst: str | os.PathLike[str]) -> None:
if len(str(dst)) >= 260:
raise FileNotFoundError(3, "The system cannot find the path specified", str(dst))
real_replace(src, dst)

monkeypatch.setattr(os, "replace", limited_replace)

with pytest.raises(ValueError, match="quarantined.*retry"):
await deep_store.get(session_id)

assert not session_file.exists()
quarantined_files = await asyncio.to_thread(lambda: list(deep_root.glob(".*.corrupt")))
assert len(quarantined_files) == 1

async def test_corrupt_quarantine_short_id_at_deep_root_does_not_regress(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A short session id at a deep root must keep the quarantine path it had before.

The previous destination embedded the snapshot name, so for a one-character id it was 48
characters long. The bounded name is 41 characters, so a root where the quarantine used to
fit keeps fitting.
"""
padding = 206 - len(str(tmp_path)) - 1
if padding <= 1:
pytest.skip("pytest temporary root is too long to build the 206-character root")
deep_root = tmp_path / ("d" * padding)
deep_root.mkdir()
assert len(str(deep_root)) == 206
store = FileSessionStore(deep_root)
session_file = store._session_file_path("x")
await asyncio.to_thread(session_file.write_bytes, b"not-json")

real_replace = os.replace

def limited_replace(src: str | os.PathLike[str], dst: str | os.PathLike[str]) -> None:
if len(str(dst)) >= 260:
raise FileNotFoundError(3, "The system cannot find the path specified", str(dst))
real_replace(src, dst)

monkeypatch.setattr(os, "replace", limited_replace)

with pytest.raises(ValueError, match="quarantined.*retry"):
await store.get("x")

assert not session_file.exists()
quarantined_files = await asyncio.to_thread(lambda: list(deep_root.glob(".*.corrupt")))
assert len(quarantined_files) == 1
assert len(str(quarantined_files[0])) < 260

async def test_invalid_registered_payload_preserves_snapshot(self, tmp_path: Path) -> None:
store = FileSessionStore(tmp_path)
session_file = store._session_file_path("session-1")
Expand Down
Loading