: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(tasks): use sync Redis client for task-run stream publish (#67891)
Alessandro Pogliaghi0c9c6e4f0e6b
diff --git a/posthog/redis.py b/posthog/redis.pyindex 1e1aabd5eb48..3e3ec7a6da58 100644--- a/posthog/redis.py+++ b/posthog/redis.py@@ -12,6 +12,15 @@ from redis import asyncio as aioredis_client_map: Dict[str, Any] = {}_test_async_client_map: Dict[str, Any] = {} # For test mode, where we don't need per-loop isolation+_test_fake_server_map: Dict[str, Any] = {} # Shared FakeServer per url so sync + async fake clients see one store+++def _get_test_fake_server(redis_url: str):+ import fakeredis++ if redis_url not in _test_fake_server_map:+ _test_fake_server_map[redis_url] = fakeredis.FakeServer()+ return _test_fake_server_map[redis_url]def get_client(redis_url: Optional[str] = None) -> redis.Redis:@@ -26,7 +35,7 @@ def get_client(redis_url: Optional[str] = None) -> redis.Redis:# This import is only used in tests, we don't want to import it in productionimport fakeredis- client: Any = fakeredis.FakeRedis()+ client: Any = fakeredis.FakeRedis(server=_get_test_fake_server(redis_url))elif redis_url:client = redis.from_url(redis_url, db=0)else:@@ -109,7 +118,7 @@ def get_async_client(redis_url: Optional[str] = None):if redis_url not in _test_async_client_map:import fakeredis- _test_async_client_map[redis_url] = fakeredis.FakeAsyncRedis()+ _test_async_client_map[redis_url] = fakeredis.FakeAsyncRedis(server=_get_test_fake_server(redis_url))return _test_async_client_map[redis_url]else:# Production code: use per-loop caching for real Redis connectionsdiff --git a/products/tasks/backend/logic/stream/redis_stream.py b/products/tasks/backend/logic/stream/redis_stream.pyindex f2139b5855a8..c4635e373faa 100644--- a/products/tasks/backend/logic/stream/redis_stream.py+++ b/products/tasks/backend/logic/stream/redis_stream.py@@ -7,11 +7,10 @@ from django.conf import settingsimport structlogimport redis.exceptions as redis_exceptions-from asgiref.sync import async_to_syncfrom products.tasks.backend.logic.services.connection_token import SANDBOX_EVENT_INGEST_TOKEN_TTLfrom products.tasks.backend.logic.services.sandbox_config import SANDBOX_TTL_SECONDS-from products.tasks.backend.redis import get_tasks_stream_redis_async+from products.tasks.backend.redis import get_tasks_stream_redis_async, get_tasks_stream_redis_synclogger = structlog.get_logger(__name__)@@ -516,14 +515,18 @@ def publish_task_run_stream_event(run_id: str, event: dict, use_dedicated: boolThis is intended for sync Django model/view code that needs to mirroruser-visible task-run events into the live SSE stream.- """-- async def _publish() -> str:- redis_stream = TaskRunRedisStream(get_task_run_stream_key(run_id), use_dedicated)- return await redis_stream.write_event(event)+ Bouncing back to the loop via ``async_to_sync`` would block that executor+ thread. A sync client does the I/O inline on the calling thread with no+ event-loop round-trip.+ """+ stream_key = get_task_run_stream_key(run_id)+ client = get_tasks_stream_redis_sync(use_dedicated)+ raw = json.dumps(event)try:- return async_to_sync(_publish)()+ stream_id = client.xadd(stream_key, {DATA_KEY: raw}, maxlen=TASK_RUN_STREAM_MAX_LENGTH, approximate=True)+ client.expire(stream_key, TASK_RUN_STREAM_TIMEOUT)+ return _normalize_stream_id(stream_id)except Exception:logger.exception("task_run_stream_publish_failed", run_id=run_id)return None@@ -531,12 +534,37 @@ def publish_task_run_stream_event(run_id: str, event: dict, use_dedicated: booldef publish_task_run_stream_complete(run_id: str, use_dedicated: bool = False) -> None:"""Synchronously publish a completion sentinel for a task-run stream."""-- async def _publish() -> None:- redis_stream = TaskRunRedisStream(get_task_run_stream_key(run_id), use_dedicated)- await redis_stream.mark_complete()+ stream_key = get_task_run_stream_key(run_id)+ completed_key = get_task_run_stream_completed_key(stream_key)+ client = get_tasks_stream_redis_sync(use_dedicated)+ raw = json.dumps({"type": "STREAM_STATUS", "status": "complete"})try:- async_to_sync(_publish)()+ if settings.TEST:+ # fakeredis doesn't support WATCH/MULTI; the sequencing race the+ # transaction guards against can't happen under the test harness.+ if client.exists(completed_key):+ return+ client.xadd(stream_key, {DATA_KEY: raw}, maxlen=TASK_RUN_STREAM_MAX_LENGTH, approximate=True)+ client.expire(stream_key, TASK_RUN_STREAM_TIMEOUT)+ client.set(completed_key, "1", ex=TASK_RUN_STREAM_SEQUENCE_TIMEOUT)+ return++ with client.pipeline(transaction=True) as pipe:+ while True:+ try:+ pipe.watch(completed_key)+ if pipe.exists(completed_key):+ pipe.reset()+ return+ pipe.multi()+ pipe.xadd(stream_key, {DATA_KEY: raw}, maxlen=TASK_RUN_STREAM_MAX_LENGTH, approximate=True)+ pipe.expire(stream_key, TASK_RUN_STREAM_TIMEOUT)+ pipe.set(completed_key, "1", ex=TASK_RUN_STREAM_SEQUENCE_TIMEOUT)+ pipe.execute()+ return+ except redis_exceptions.WatchError:+ logger.debug("task_run_stream_complete_watch_retry", run_id=run_id)+ continueexcept Exception:logger.exception("task_run_stream_complete_publish_failed", run_id=run_id)diff --git a/products/tasks/backend/tests/test_redis_stream_routing.py b/products/tasks/backend/tests/test_redis_stream_routing.pyindex ec8362375aab..43a3718fd89b 100644--- a/products/tasks/backend/tests/test_redis_stream_routing.py+++ b/products/tasks/backend/tests/test_redis_stream_routing.py@@ -1,10 +1,15 @@+import asyncio+import concurrent.futures+from unittest.mock import patchfrom django.test import SimpleTestCase, override_settings+from asgiref.sync import sync_to_asyncfrom parameterized import parameterizedfrom products.tasks.backend import redis as tasks_redis+from products.tasks.backend.logic.stream import redis_streamclass TestStreamRouting(SimpleTestCase):@@ -51,3 +56,53 @@ class TestEvaluateDedicatedStreamFlag(SimpleTestCase):def test_fails_safe_to_shared_on_flag_error(self):with patch.object(tasks_redis.posthoganalytics, "feature_enabled", side_effect=RuntimeError("boom")):self.assertFalse(tasks_redis.evaluate_dedicated_stream_flag(organization_id="org", distinct_id="u"))+++class _ThreadHungryAsyncClient:+ """Async Redis stand-in whose ops need a default-executor thread to finish.++ Mirrors real asyncio Redis: connecting resolves the host via+ loop.run_in_executor(None, getaddrinfo), so each op consumes a thread from the+ same bounded pool the activity bodies run on.+ """++ async def _needs_thread(self, value):+ return await asyncio.get_running_loop().run_in_executor(None, lambda: value)++ async def xadd(self, *args, **kwargs):+ return await self._needs_thread("1-0")++ async def expire(self, *args, **kwargs):+ return await self._needs_thread(True)+++class TestSyncPublishDoesNotStarveExecutor(SimpleTestCase):+ def test_publish_event_does_not_deadlock_bounded_executor(self):+ # Asyncified activities run their body on the event loop's bounded default+ # ThreadPoolExecutor (sync_to_async(thread_sensitive=False)). A regression to+ # async_to_sync over the async client would bounce back to the loop and need a+ # *second* executor thread, so once concurrent bodies fill the pool nothing+ # completes. The async client is patched to be thread-hungry precisely to catch+ # that: the fix uses the sync client and never touches it (asserted below), so+ # this run completes; a revert would use it and deadlock this gather().+ workers = 4+ n = workers + 4++ async def main():+ asyncio.get_running_loop().set_default_executor(concurrent.futures.ThreadPoolExecutor(max_workers=workers))++ async def body(i):+ return await sync_to_async(redis_stream.publish_task_run_stream_event, thread_sensitive=False)(+ "run-under-test", {"type": "probe", "i": i}, False+ )++ return await asyncio.wait_for(asyncio.gather(*(body(i) for i in range(n))), timeout=15)++ with patch.object(+ redis_stream, "get_tasks_stream_redis_async", return_value=_ThreadHungryAsyncClient()+ ) as async_client:+ results = asyncio.run(main())++ async_client.assert_not_called() # sync publish path must not build the async client+ self.assertEqual(len(results), n)+ self.assertTrue(all(r is not None for r in results))