diff --git a/src/claude_agent_sdk/_internal/sessions.py b/src/claude_agent_sdk/_internal/sessions.py index 6caae8dd2..e397d1042 100644 --- a/src/claude_agent_sdk/_internal/sessions.py +++ b/src/claude_agent_sdk/_internal/sessions.py @@ -837,7 +837,9 @@ def _try_read_session_file(project_dir: Path, file_name: str) -> str | None: """Tries to read a session JSONL file from a project directory.""" try: return (project_dir / file_name).read_text(encoding="utf-8") - except OSError: + except (OSError, ValueError): + # ValueError covers UnicodeDecodeError: a corrupt transcript degrades + # to None like a missing or unreadable one instead of aborting reads. return None @@ -1351,11 +1353,11 @@ def _entries_to_session_messages( visible = [e for e in chain if _is_visible_message(e)] messages = [_to_session_message(e) for e in visible] - # Apply offset and limit + # Mirror _apply_sort_limit_offset's guards so negative/zero offset and + # non-positive limit behave identically to the other read paths. + messages = messages[offset:] if offset > 0 else messages if limit is not None and limit > 0: - return messages[offset : offset + limit] - if offset > 0: - return messages[offset:] + return messages[:limit] return messages @@ -1618,7 +1620,9 @@ def get_subagent_messages( try: content = match.read_text(encoding="utf-8") - except OSError: + except (OSError, ValueError): + # ValueError covers UnicodeDecodeError: a corrupt subagent transcript + # degrades to [] like a missing or unreadable one. return [] if not content: return [] @@ -1726,10 +1730,11 @@ def _entries_to_subagent_messages( if e.get("type") in ("user", "assistant") ] + # Mirror _apply_sort_limit_offset's guards so negative/zero offset and + # non-positive limit behave identically to the other read paths. + messages = messages[offset:] if offset > 0 else messages if limit is not None and limit > 0: - return messages[offset : offset + limit] - if offset > 0: - return messages[offset:] + return messages[:limit] return messages diff --git a/tests/test_session_helpers_store.py b/tests/test_session_helpers_store.py index 627ab37d9..2b5cd7888 100644 --- a/tests/test_session_helpers_store.py +++ b/tests/test_session_helpers_store.py @@ -375,6 +375,25 @@ async def test_limit_offset(self) -> None: ) assert len(msgs) == 2 + async def test_negative_offset_with_limit_treated_as_absent(self) -> None: + """A negative offset must behave the same with and without a limit. + + Regression for #1519: with ``limit`` set, the slice used the raw + negative offset and returned an empty/wrong page, while the no-limit + branch treated the same offset as absent. + """ + store = InMemorySessionStore() + sid = str(uuid_mod.uuid4()) + await _seed_chain(store, sid, n=3) + page = await get_session_messages_from_store( + store, sid, directory=DIR, limit=2, offset=-1 + ) + expected = await get_session_messages_from_store( + store, sid, directory=DIR, limit=2 + ) + assert page == expected + assert len(page) == 2 + async def test_unknown_session_empty(self) -> None: store = InMemorySessionStore() msgs = await get_session_messages_from_store( diff --git a/tests/test_sessions.py b/tests/test_sessions.py index a5bb63cfe..a518c89fa 100644 --- a/tests/test_sessions.py +++ b/tests/test_sessions.py @@ -795,6 +795,78 @@ def test_simple_chain(self, claude_config_dir: Path, tmp_path: Path): # All SessionMessage instances assert all(isinstance(m, SessionMessage) for m in messages) + def test_negative_offset_with_limit_treated_as_absent( + self, claude_config_dir: Path, tmp_path: Path + ): + """A negative offset behaves the same with and without a limit. + + Regression for #1519: the limited slice used the raw negative offset + and returned an empty/wrong page, while the no-limit branch treated + the same offset as absent. + """ + project_path = str(tmp_path / "proj") + Path(project_path).mkdir(parents=True) + project_dir = _make_project_dir( + claude_config_dir, os.path.realpath(project_path) + ) + sid = str(uuid.uuid4()) + + u1 = str(uuid.uuid4()) + a1 = str(uuid.uuid4()) + u2 = str(uuid.uuid4()) + a2 = str(uuid.uuid4()) + + entries = [ + _make_transcript_entry("user", u1, None, sid, content="hello"), + _make_transcript_entry("assistant", a1, u1, sid, content="hi!"), + _make_transcript_entry("user", u2, a1, sid, content="thanks"), + _make_transcript_entry("assistant", a2, u2, sid, content="welcome"), + ] + _write_transcript(project_dir, sid, entries) + + with_offset = get_session_messages( + sid, directory=project_path, limit=2, offset=-1 + ) + without_offset = get_session_messages(sid, directory=project_path, limit=2) + assert with_offset == without_offset + assert len(with_offset) == 2 + assert with_offset[0].uuid == u1 + + def test_undecodable_transcript_degrades_to_empty( + self, claude_config_dir: Path, tmp_path: Path + ): + """A corrupt (invalid UTF-8) transcript reads like a missing one. + + Regression for #1518: strict UTF-8 decoding raised + UnicodeDecodeError (a ValueError, not OSError) out of + get_session_messages instead of degrading to []. + """ + project_path = str(tmp_path / "proj") + Path(project_path).mkdir(parents=True) + project_dir = _make_project_dir( + claude_config_dir, os.path.realpath(project_path) + ) + sid = str(uuid.uuid4()) + + # Invalid UTF-8 bytes followed by a valid JSONL line. + (project_dir / f"{sid}.jsonl").write_bytes( + b"\xff\xfe\n" + + b'{"type":"user","uuid":"u1","message":{"role":"user","content":"hi"}}\n' + ) + + assert get_session_messages(sid, directory=project_path) == [] + # A corrupt subagent transcript degrades the same way. The parent + # session file must exist (and be non-empty) for the subagents + # directory to resolve, so give it one valid line. + (project_dir / f"{sid}.jsonl").write_bytes( + b'{"type":"user","uuid":"u1","message":{"role":"user","content":"hi"}}\n' + ) + subagents_dir = project_dir / f"{sid}" / "subagents" + subagents_dir.mkdir(parents=True) + agent_id = str(uuid.uuid4()) + (subagents_dir / f"{agent_id}.jsonl").write_bytes(b"\xff\xfe not utf-8\n") + assert get_subagent_messages(sid, agent_id, directory=project_path) == [] + def test_filters_meta_messages(self, claude_config_dir: Path, tmp_path: Path): """isMeta entries in the chain are filtered from output.""" project_path = str(tmp_path / "proj")