Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(hogai): drop legacy pickle read from conversation stream (#73371)

Tom Piccirello4ba4d26af9bf
diff --git a/ee/hogai/stream/redis_stream.py b/ee/hogai/stream/redis_stream.py
index 37f6edf83203..b3e07d2d0cfc 100644
--- a/ee/hogai/stream/redis_stream.py
+++ b/ee/hogai/stream/redis_stream.py
@@ -1,5 +1,4 @@
import time
-import pickle
import asyncio
from collections.abc import AsyncGenerator, Callable
from typing import Literal, Optional, cast
@@ -157,8 +156,6 @@ class ConversationStreamSerializer:
return None
return {
- # Migration Phase 2: emit JSON. Readers already understand both formats (Phase 1);
- # the legacy pickle read path is removed in Phase 3 once older entries have drained.
self.serialization_key: StreamEvent(event=event).model_dump_json().encode("utf-8"),
}
@@ -198,14 +195,7 @@ class ConversationStreamSerializer:
)
def deserialize(self, data: dict[bytes, bytes]) -> StreamEvent:
- raw = data[bytes(self.serialization_key, "utf-8")]
- # Migration Phase 1: read both formats. JSON (the new format) starts with '{';
- # legacy pickle starts with 0x80. Once every writer emits JSON, the pickle
- # branch is removed (Phase 3).
- if raw[:1] == b"{":
- return StreamEvent.model_validate_json(raw)
- # nosemgrep: python.lang.security.deserialization.pickle.avoid-pickle (transitional legacy read, removed in migration Phase 3 once all writers emit JSON)
- return pickle.loads(raw)
+ return StreamEvent.model_validate_json(data[bytes(self.serialization_key, "utf-8")])
class StreamError(Exception):
@@ -325,6 +315,19 @@ class ConversationRedisStream:
for _, stream_messages in messages:
for stream_id, message in stream_messages:
current_id = stream_id
+ raw = message.get(bytes(self._serializer.serialization_key, "utf-8"))
+ if raw is not None and raw[:1] == b"\x80":
+ # Skip a legacy pickle entry (pickle protocol >= 2 starts with 0x80) left in
+ # an un-expired stream from before the JSON migration. current_id has already
+ # advanced, so it isn't re-read. Genuinely-corrupt JSON is not skipped here —
+ # it falls through to deserialize and fails the read as before.
+ logger.warning(
+ "Skipping legacy pickle conversation stream entry",
+ stream_key=self._stream_key,
+ stream_id=stream_id,
+ )
+ continue
+
data = self._serializer.deserialize(message)
latency = time.time() - data.timestamp
diff --git a/ee/hogai/stream/test/test_redis_stream.py b/ee/hogai/stream/test/test_redis_stream.py
index 4637ca8e9864..49714c33380e 100644
--- a/ee/hogai/stream/test/test_redis_stream.py
+++ b/ee/hogai/stream/test/test_redis_stream.py
@@ -1,4 +1,3 @@
-import pickle
import asyncio
from typing import cast
from uuid import uuid4
@@ -98,12 +97,11 @@ class TestRedisStream(BaseTest):
async def test_read_stream_with_data(self):
with patch.object(self.redis_stream, "_redis_client") as mock_client:
# Mock serialized data
- import pickle
test_event = StreamEvent(
event=MessageEvent(type=AssistantEventType.MESSAGE, payload=AssistantMessage(content="test"))
)
- serialized_data = pickle.dumps(test_event)
+ serialized_data = test_event.model_dump_json().encode("utf-8")
mock_client.xread = AsyncMock(return_value=[(self.stream_key, [(b"1234-0", {b"data": serialized_data})])])
chunks = []
@@ -118,10 +116,9 @@ class TestRedisStream(BaseTest):
async def test_read_stream_completion_status(self):
with patch.object(self.redis_stream, "_redis_client") as mock_client:
# Mock xread to return completion status
- import pickle
test_event = StreamEvent(event=StreamStatusEvent(payload=StatusPayload(status="complete")))
- serialized_data = pickle.dumps(test_event)
+ serialized_data = test_event.model_dump_json().encode("utf-8")
mock_client.xread = AsyncMock(return_value=[(self.stream_key, [(b"1234-0", {b"data": serialized_data})])])
chunks = []
@@ -134,10 +131,8 @@ class TestRedisStream(BaseTest):
async def test_read_stream_error_status(self):
# Test that RedisStreamError is raised when there's an error status
with patch.object(self.redis_stream, "_redis_client") as mock_client:
- import pickle
-
test_event = StreamEvent(event=StreamStatusEvent(payload=StatusPayload(status="error", error="Test error")))
- serialized_data = pickle.dumps(test_event)
+ serialized_data = test_event.model_dump_json().encode("utf-8")
mock_client.xread = AsyncMock(return_value=[(self.stream_key, [(b"1234-0", {b"data": serialized_data})])])
with self.assertRaises(StreamError) as context:
@@ -246,12 +241,11 @@ class TestRedisStream(BaseTest):
async def test_read_stream_no_messages_continue_polling(self):
with patch.object(self.redis_stream, "_redis_client") as mock_client:
# First call returns no messages, second call returns data
- import pickle
test_event = StreamEvent(
event=MessageEvent(type=AssistantEventType.MESSAGE, payload=AssistantMessage(content="test chunk"))
)
- serialized_data = pickle.dumps(test_event)
+ serialized_data = test_event.model_dump_json().encode("utf-8")
mock_client.xread = AsyncMock(
side_effect=[
[], # No messages
@@ -272,7 +266,6 @@ class TestRedisStream(BaseTest):
async def test_read_stream_multiple_messages(self):
with patch.object(self.redis_stream, "_redis_client") as mock_client:
# Mock xread to return multiple messages
- import pickle
test_event1 = StreamEvent(
event=MessageEvent(type=AssistantEventType.MESSAGE, payload=AssistantMessage(content="chunk 1"))
@@ -286,9 +279,9 @@ class TestRedisStream(BaseTest):
(
self.stream_key,
[
- (b"1234-0", {b"data": pickle.dumps(test_event1)}),
- (b"1234-1", {b"data": pickle.dumps(test_event2)}),
- (b"1234-2", {b"data": pickle.dumps(complete_event)}),
+ (b"1234-0", {b"data": test_event1.model_dump_json().encode("utf-8")}),
+ (b"1234-1", {b"data": test_event2.model_dump_json().encode("utf-8")}),
+ (b"1234-2", {b"data": complete_event.model_dump_json().encode("utf-8")}),
],
)
]
@@ -303,11 +296,8 @@ class TestRedisStream(BaseTest):
self.assertEqual(chunks[1].event.type, AssistantEventType.MESSAGE)
@pytest.mark.asyncio
- async def test_read_stream_invalid_data_skipped(self):
+ async def test_read_stream_legacy_pickle_entry_skipped(self):
with patch.object(self.redis_stream, "_redis_client") as mock_client:
- # Mock xread to return invalid serialized data
- import pickle
-
valid_event = StreamEvent(
event=MessageEvent(type=AssistantEventType.MESSAGE, payload=AssistantMessage(content="valid chunk"))
)
@@ -317,18 +307,37 @@ class TestRedisStream(BaseTest):
(
self.stream_key,
[
- (b"1234-0", {b"data": b"\xff\xfe"}), # Invalid pickle data
- (b"1234-1", {b"data": pickle.dumps(valid_event)}),
- (b"1234-2", {b"data": pickle.dumps(complete_event)}),
+ (b"1234-0", {b"data": b"\x80\x05legacy"}), # legacy pickle entry (0x80 prefix)
+ (b"1234-1", {b"data": valid_event.model_dump_json().encode("utf-8")}),
+ (b"1234-2", {b"data": complete_event.model_dump_json().encode("utf-8")}),
],
)
]
)
- with self.assertRaises(Exception): # Should raise exception on invalid data
- chunks = []
- async for chunk in self.redis_stream.read_stream():
- chunks.append(chunk)
+ chunks = []
+ async for chunk in self.redis_stream.read_stream():
+ chunks.append(chunk)
+
+ # The legacy entry is skipped; the valid message is still delivered and the completion
+ # marker ends the stream, instead of the whole read failing.
+ self.assertEqual(len(chunks), 1)
+ payload = cast(AssistantMessage, chunks[0].event.payload)
+ self.assertEqual(payload.content, "valid chunk")
+
+ async def test_read_stream_corrupt_entry_raises(self):
+ # A non-legacy entry that fails to parse is a real error, not a stale pre-migration entry,
+ # so the read fails rather than silently dropping it.
+ with patch.object(self.redis_stream, "_redis_client") as mock_client:
+ mock_client.xread = AsyncMock(
+ return_value=[(self.stream_key, [(b"1234-0", {b"data": b"{not valid json"})])]
+ )
+
+ with self.assertRaises(StreamError) as context:
+ async for _ in self.redis_stream.read_stream():
+ pass
+
+ self.assertIn("Unexpected error reading", str(context.exception))
@pytest.mark.asyncio
async def test_write_to_stream_success(self):
@@ -628,10 +637,9 @@ class TestGetSubagentStreamKey(BaseTest):
class TestConversationStreamSerializerJson(SimpleTestCase):
- # Phase 1 of the pickle->JSON migration: the reader must parse JSON entries (and still read
- # legacy pickle) before any writer emits JSON. The inner payload union is resolved by pydantic
- # smart mode, so each member — especially the three that share only `content: str` — is a
- # distinct resolution case that could misresolve or drop fields on the validate-back leg.
+ # The stream payload's inner union is resolved by pydantic smart mode, so each member is a
+ # distinct resolution case. The three that share only `content: str` are the ones most likely
+ # to misresolve or drop fields when validated back from JSON.
@parameterized.expand(
[
("assistant", AssistantMessage(content="hi")),
@@ -645,7 +653,7 @@ class TestConversationStreamSerializerJson(SimpleTestCase):
serializer = ConversationStreamSerializer()
event = StreamEvent(event=MessageEvent(type=AssistantEventType.MESSAGE, payload=payload))
json_bytes = event.model_dump_json().encode("utf-8")
- assert json_bytes[:1] == b"{" # the byte the reader branches on to pick JSON over pickle
+ assert json_bytes[:1] == b"{" # stream entries serialize as JSON objects
result = serializer.deserialize({b"data": json_bytes})
@@ -709,18 +717,8 @@ class TestConversationStreamSerializerJson(SimpleTestCase):
self.assertIs(type(result.event), type(event))
self.assertEqual(result.event, event)
- def test_deserialize_still_reads_legacy_pickle(self):
- serializer = ConversationStreamSerializer()
- event = StreamEvent(event=StreamStatusEvent(payload=StatusPayload(status="complete")))
-
- result = serializer.deserialize({b"data": pickle.dumps(event)})
-
- self.assertEqual(result.event.type, "STREAM_STATUS")
- payload = cast(StatusPayload, result.event.payload)
- self.assertEqual(payload.status, "complete")
-
def test_dumps_emits_json(self):
- # Phase 2: the writer now emits JSON rather than pickle.
+ # the serializer emits JSON, so a stream entry is a JSON object
serializer = ConversationStreamSerializer()
result = serializer.dumps((AssistantEventType.MESSAGE, AssistantMessage(content="hi")))