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.

fix(max-ai): stop masking original error when redis stream write fails (#70824)

posthog[bot]d5340a23a72f
diff --git a/ee/hogai/stream/redis_stream.py b/ee/hogai/stream/redis_stream.py
index b3e07d2d0cfc..94e912f46fdc 100644
--- a/ee/hogai/stream/redis_stream.py
+++ b/ee/hogai/stream/redis_stream.py
@@ -418,5 +418,11 @@ class ConversationRedisStream:
await self._write_status(StatusPayload(status="complete"))
except Exception as e:
- await self._write_status(StatusPayload(status="error", error=str(e)))
- raise StreamError("Failed to write to stream")
+ # Best-effort error status back to the client. If Redis is itself the
+ # problem this write will fail too, so guard it so the secondary error
+ # can't mask the original one.
+ try:
+ await self._write_status(StatusPayload(status="error", error=str(e)))
+ except Exception:
+ logger.exception("Failed to write error status to stream", stream_key=self._stream_key)
+ raise StreamError("Failed to write to stream") from e
diff --git a/ee/hogai/stream/test/test_redis_stream.py b/ee/hogai/stream/test/test_redis_stream.py
index 49714c33380e..a6c376b88d18 100644
--- a/ee/hogai/stream/test/test_redis_stream.py
+++ b/ee/hogai/stream/test/test_redis_stream.py
@@ -375,6 +375,28 @@ class TestRedisStream(BaseTest):
# First write flush fails; the error-status write then attempts its own flush.
self.assertEqual(pipe.execute.call_count, 2)
+ @pytest.mark.asyncio
+ async def test_write_to_stream_error_status_write_failure_preserves_original(self):
+ # When the primary write fails and the fallback error-status write also fails
+ # (e.g. Redis is unreachable), the original error must not be masked by the
+ # secondary one: we still raise StreamError chained from the real cause.
+ with patch.object(self.redis_stream, "_redis_client") as mock_client:
+ original_error = redis_exceptions.TimeoutError("connect timeout")
+ masking_error = redis_exceptions.TimeoutError("masking error from dead redis")
+ pipe = MagicMock()
+ pipe.execute = AsyncMock(side_effect=[original_error, masking_error])
+ mock_client.pipeline = MagicMock(return_value=pipe)
+
+ async def test_generator():
+ yield (AssistantEventType.MESSAGE, AssistantMessage(content="test message"))
+
+ with self.assertRaises(StreamError) as context:
+ await self.redis_stream.write_to_stream(test_generator())
+
+ self.assertIs(context.exception.__cause__, original_error)
+ # Both the data write and the fallback status write were attempted
+ self.assertEqual(pipe.execute.call_count, 2)
+
@pytest.mark.asyncio
async def test_write_to_stream_empty_generator(self):
with patch.object(self.redis_stream, "_redis_client") as mock_client:
diff --git a/posthog/redis.py b/posthog/redis.py
index 38bc751a694b..fc835c7a364d 100644
--- a/posthog/redis.py
+++ b/posthog/redis.py
@@ -7,7 +7,10 @@ import weakref
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
import redis
+import redis.exceptions as redis_exceptions
from redis import asyncio as aioredis
+from redis.asyncio.retry import Retry
+from redis.backoff import ExponentialBackoff
_client_map: Dict[str, Any] = {}
@@ -145,6 +148,10 @@ def get_async_client(redis_url: Optional[str] = None):
db=0,
socket_timeout=settings.REDIS_SOCKET_TIMEOUT_SECONDS,
socket_connect_timeout=settings.REDIS_SOCKET_CONNECT_TIMEOUT_SECONDS,
+ # Retry transient connect/timeout blips a couple of times with a
+ # short exponential backoff instead of failing the caller outright.
+ retry=Retry(ExponentialBackoff(cap=0.5, base=0.05), retries=2),
+ retry_on_error=[redis_exceptions.ConnectionError, redis_exceptions.TimeoutError],
)
pool_map[redis_url] = client
diff --git a/posthog/test/test_redis.py b/posthog/test/test_redis.py
index 3a4d24267c1f..c30bf1a977d5 100644
--- a/posthog/test/test_redis.py
+++ b/posthog/test/test_redis.py
@@ -5,6 +5,7 @@ from unittest.mock import ANY, AsyncMock, patch
from django.conf import settings
from django.test.testcases import TestCase
+import redis
import fakeredis
from posthog.redis import TEST_clear_clients, _client_map, _loop_clients, get_async_client, get_client
@@ -101,6 +102,8 @@ class TestRedis(TestCase):
db=0,
socket_timeout=settings.REDIS_SOCKET_TIMEOUT_SECONDS,
socket_connect_timeout=settings.REDIS_SOCKET_CONNECT_TIMEOUT_SECONDS,
+ retry=ANY,
+ retry_on_error=[redis.exceptions.ConnectionError, redis.exceptions.TimeoutError],
)
def test_sync_redis_client_passes_socket_timeouts(self):