: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(warehouse_sources): retry a resumable-state write after a Redis failover (#96399)
Tom Owers2ad6314deee3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.pyindex 7d49d46f23b0..a97c8cefba4a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/resumable.py@@ -1,11 +1,14 @@import jsonimport dataclasses+from collections.abc import Callablefrom contextlib import contextmanagerfrom typing import Genericfrom django.conf import settingsimport orjson+from redis import Redis+from redis.exceptions import ReadOnlyErrorfrom structlog.types import FilteringBoundLoggerfrom posthog.redis import get_client@@ -81,12 +84,26 @@ class ResumableSourceManager(Generic[ResumableData]):self._logger.debug(f"Dropping unknown resumable state fields. key={self._key}, fields={unknown}")return self._data_class(**{name: value for name, value in parsed_data.items() if name in known})+ def _write_with_readonly_retry(self, client: Redis, write: Callable[[], object]) -> None:+ """Retry a write once after `ReadOnlyError`.++ A connection held open across a Redis failover keeps talking to what is now a demoted+ replica, so a write on it fails until the client reconnects — the same stale-connection+ failure mode Postgres writes hit after a failover (see `is_stale_connection_read_only_error`).+ Disconnecting the pool forces the retry onto a fresh connection to the current primary.+ """+ try:+ write()+ except ReadOnlyError:+ client.connection_pool.disconnect()+ write()+def save_state(self, data: ResumableData) -> None:with self._get_redis() as redis:json_data = self._dump_json(data)self._logger.debug(f"Saving resumable source state. key={self._key}, data={json_data}")- redis.set(self._key, json_data, ex=60 * 60 * 24) # 24 hours expiration+ self._write_with_readonly_retry(redis, lambda: redis.set(self._key, json_data, ex=60 * 60 * 24))def clear_state(self) -> None:"""Drop any saved resume state so a subsequent attempt starts from scratch.@@ -96,7 +113,7 @@ class ResumableSourceManager(Generic[ResumableData]):"""with self._get_redis() as redis:self._logger.debug(f"Clearing resumable source state. key={self._key}")- redis.delete(self._key)+ self._write_with_readonly_retry(redis, lambda: redis.delete(self._key))def can_resume(self) -> bool:with self._get_redis() as redis:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.pyindex 23bf0c59fcb4..1cfe4d8b3c24 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_resumable.py@@ -1,5 +1,8 @@+import pytestfrom unittest.mock import MagicMock, patch+from redis.exceptions import ReadOnlyError+from posthog.dataclasses import frozenfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -21,3 +24,27 @@ class TestResumableSourceManager:state = manager.load_state()assert state == _SweepPosition(cursor="cus_1")++ def test_save_state_retries_once_after_stale_connection_read_only_error(self):+ manager = ResumableSourceManager[_SweepPosition](MagicMock(team_id=1, job_id="job-1"), _SweepPosition)+ redis = MagicMock()+ redis.set.side_effect = [ReadOnlyError("You can't write against a read only replica."), None]++ with patch.object(ResumableSourceManager, "_get_redis") as get_redis:+ get_redis.return_value.__enter__.return_value = redis+ manager.save_state(_SweepPosition(cursor="cus_1"))++ assert redis.set.call_count == 2+ redis.connection_pool.disconnect.assert_called_once()++ def test_save_state_raises_when_retry_also_hits_read_only_error(self):+ manager = ResumableSourceManager[_SweepPosition](MagicMock(team_id=1, job_id="job-1"), _SweepPosition)+ redis = MagicMock()+ redis.set.side_effect = ReadOnlyError("You can't write against a read only replica.")++ with patch.object(ResumableSourceManager, "_get_redis") as get_redis:+ get_redis.return_value.__enter__.return_value = redis+ with pytest.raises(ReadOnlyError):+ manager.save_state(_SweepPosition(cursor="cus_1"))++ assert redis.set.call_count == 2