: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(flags): make the last-called sync recover from ClickHouse failures (#74411)
posthog[bot]38087724fc5f
diff --git a/posthog/settings/feature_flags.py b/posthog/settings/feature_flags.pyindex 06104344af9b..ec84c07a93e6 100644--- a/posthog/settings/feature_flags.py+++ b/posthog/settings/feature_flags.py@@ -48,6 +48,23 @@ FEATURE_FLAG_LAST_CALLED_AT_SYNC_MAX_LOOKBACK_HOURS: int = max(1,get_from_env("FEATURE_FLAG_LAST_CALLED_AT_SYNC_MAX_LOOKBACK_HOURS", 6, type_cast=int),)+# The sync reads distributed_events_recent, which either replica of the batch-export shard can+# answer, so rows inserted moments ago may be missing from whichever one serves a given query.+# Ending the scan window this far before now keeps the checkpoint from advancing past those+# rows, so a row still missing at read time is picked up by the next run instead of being+# skipped for good.+FEATURE_FLAG_LAST_CALLED_AT_SYNC_REPLICATION_BUFFER_SECONDS: int = max(+ 0,+ get_from_env("FEATURE_FLAG_LAST_CALLED_AT_SYNC_REPLICATION_BUFFER_SECONDS", 60, type_cast=int),+)+# Per-chunk ClickHouse execution cap. sync_execute sets no max_execution_time of its own, so+# without this a hung query is bounded only by the server profile, and a run can outlive the+# 30-minute lock that stops two of these from overlapping. Prod chunks take a few seconds each+# and whole runs peak under two minutes, so this only trips on a genuine hang.+FEATURE_FLAG_LAST_CALLED_AT_SYNC_QUERY_TIMEOUT_SECONDS: int = max(+ 1,+ get_from_env("FEATURE_FLAG_LAST_CALLED_AT_SYNC_QUERY_TIMEOUT_SECONDS", 120, type_cast=int),+)# Feature flag cache refresh settingsFLAGS_CACHE_REFRESH_TTL_THRESHOLD_HOURS: int = get_from_env(diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.pyindex cbd16601c7d7..e5ab0030db34 100644--- a/posthog/tasks/tasks.py+++ b/posthog/tasks/tasks.py@@ -47,6 +47,11 @@ FEATURE_FLAG_LAST_CALLED_AT_SYNC_LIMIT_HIT_COUNTER = Counter("Times the ClickHouse query result limit was reached during feature flag last_called_at sync",)+FEATURE_FLAG_LAST_CALLED_AT_SYNC_CHUNK_FAILURE_COUNTER = Counter(+ "posthog_feature_flag_last_called_at_sync_chunk_failures_total",+ "ClickHouse chunk queries that failed during feature flag last_called_at sync",+)+COHORT_DELETION_MARK_FAILURE_COUNTER = Counter("posthog_cohort_deletion_mark_failure_total",@@ -1351,7 +1356,11 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:)last_sync_timestamp = max_lookback- current_sync_timestamp = now+ # Stop short of now so rows that have not reached the replica answering this query yet+ # fall into the next run's window rather than being skipped for good.+ current_sync_timestamp = now - timedelta(+ seconds=settings.FEATURE_FLAG_LAST_CALLED_AT_SYNC_REPLICATION_BUFFER_SECONDS+ )window_seconds = (current_sync_timestamp - last_sync_timestamp).total_seconds()logger.info(@@ -1375,14 +1384,24 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:merged_results: dict[tuple[int, str], tuple[datetime | None, int]] = {}total_clickhouse_results = 0- # ORDER BY ensures the most recent rows survive if LIMIT truncates results+ # ORDER BY ensures the most recent rows survive if LIMIT truncates results.+ # Celery forces Workload.OFFLINE, so this query lands on+ # CLICKHOUSE_OFFLINE_CLUSTER_HOST. There, `events_recent` and+ # `distributed_events_recent` are both Distributed proxies over the same+ # `sharded_events_recent` data, but they resolve through different clusters:+ # `distributed_events_recent` reads the batch-export shard through both of its+ # replicas, while `events_recent` is pinned to a single replica, so one+ # unavailable node fails the entire scan with nothing to fall back to.+ # `posthog/models/event/sql.py` defines the two identically, so dev and CI cannot+ # tell them apart and no test covers the difference. Check the live offline host+ # rather than this repo before changing the table.chunk_query = """SELECTteam_id,JSONExtractString(properties, '$feature_flag') as flag_key,max(timestamp) as last_called_at,count() as call_count- FROM events_recent+ FROM distributed_events_recentPREWHERE event = '$feature_flag_called'AND inserted_at > %(last_sync_timestamp)sAND inserted_at <= %(current_sync_timestamp)s@@ -1394,16 +1413,56 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:"""limit_hit = False+ chunk_failures = 0+ first_chunk_error: Exception | None = None++ # The checkpoint may only advance over an unbroken run of successful chunks from+ # the start of the window. A chunk that fails leaves its window unread, so+ # everything from that point on has to be retried by the next run rather than+ # skipped, which would silently lose flag calls.+ checkpoint_timestamp = last_sync_timestampfor chunk_start_ts, chunk_end_ts in chunks:- chunk_result = sync_execute(- chunk_query,- {- "last_sync_timestamp": chunk_start_ts,- "current_sync_timestamp": chunk_end_ts,- "limit": settings.FEATURE_FLAG_LAST_CALLED_AT_SYNC_CLICKHOUSE_LIMIT,- },- )+ try:+ chunk_result = sync_execute(+ chunk_query,+ {+ "last_sync_timestamp": chunk_start_ts,+ "current_sync_timestamp": chunk_end_ts,+ "limit": settings.FEATURE_FLAG_LAST_CALLED_AT_SYNC_CLICKHOUSE_LIMIT,+ },+ settings={"max_execution_time": settings.FEATURE_FLAG_LAST_CALLED_AT_SYNC_QUERY_TIMEOUT_SECONDS},+ )+ except Exception as e:+ # Transient errors are what autoretry_for is for. ClickHouseAtCapacity in+ # particular means the cluster is already shedding load, so the useful+ # response is to abandon the run and let Celery retry it with backoff rather+ # than keep querying. Swallowing one here would report a successful sync and+ # skip the retry that recovers these runs today.+ if isinstance(e, CH_TRANSIENT_ERRORS):+ raise++ chunk_failures += 1+ if first_chunk_error is None:+ first_chunk_error = e+ logger.warning(+ "Feature flag sync chunk failed",+ chunk_start=chunk_start_ts.isoformat(),+ chunk_end=chunk_end_ts.isoformat(),+ error=str(e),+ )+ # Nothing has been read yet, so the checkpoint cannot advance and the run+ # re-raises below. Sweeping the rest of the window would query every+ # remaining chunk against a cluster that just failed one and then discard+ # every result. A failure after a successful chunk is different: the later+ # chunks are still worth reading, they just cannot move the checkpoint+ # past the gap.+ if checkpoint_timestamp == last_sync_timestamp:+ break+ continue++ if not chunk_failures:+ checkpoint_timestamp = chunk_end_tsif chunk_result:total_clickhouse_results += len(chunk_result)@@ -1427,15 +1486,33 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:if limit_hit:FEATURE_FLAG_LAST_CALLED_AT_SYNC_LIMIT_HIT_COUNTER.inc()+ if chunk_failures:+ FEATURE_FLAG_LAST_CALLED_AT_SYNC_CHUNK_FAILURE_COUNTER.inc(chunk_failures)+ logger.warning(+ "Feature flag sync had failed chunks",+ chunk_failures=chunk_failures,+ chunks_total=len(chunks),+ checkpoint_timestamp=checkpoint_timestamp.isoformat(),+ )+ # The checkpoint did not move, so this run made no forward progress at all and+ # the next one will rescan the same window. Re-raise the first error rather+ # than reporting a successful sync, both so the failure is visible and so the+ # transient ClickHouse errors in autoretry_for still trigger a Celery retry.+ # Results from any later chunk that did succeed are dropped, which is safe:+ # they are re-read on the next run, and last_called_at is only ever advanced.+ if first_chunk_error is not None and checkpoint_timestamp == last_sync_timestamp:+ raise first_chunk_error+if not merged_results:- # Update checkpoint even when no results so next run starts from current time- redis_client.set(FEATURE_FLAG_LAST_CALLED_SYNC_KEY, current_sync_timestamp.isoformat())+ # Advance the checkpoint even when no results, so the next run starts from the+ # end of the window that was read instead of rescanning it+ redis_client.set(FEATURE_FLAG_LAST_CALLED_SYNC_KEY, checkpoint_timestamp.isoformat())# Emit metrics for no-results caseupdated_count_gauge.set(0)events_processed_gauge.set(0)clickhouse_results_gauge.set(0)- checkpoint_lag_gauge.set(0.0)+ checkpoint_lag_gauge.set((timezone.now() - checkpoint_timestamp).total_seconds())logger.info("Feature flag sync completed with no events",@@ -1453,7 +1530,7 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:flag_updates[(team_id, flag_key)] = tsif not flag_updates:- redis_client.set(FEATURE_FLAG_LAST_CALLED_SYNC_KEY, current_sync_timestamp.isoformat())+ redis_client.set(FEATURE_FLAG_LAST_CALLED_SYNC_KEY, checkpoint_timestamp.isoformat())logger.info("Feature flag sync: no valid timestamps to update",chunks_processed=len(chunks),@@ -1461,7 +1538,7 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:clickhouse_results_gauge.set(total_clickhouse_results)updated_count_gauge.set(0)events_processed_gauge.set(0)- checkpoint_lag_gauge.set(0.0)+ checkpoint_lag_gauge.set((timezone.now() - checkpoint_timestamp).total_seconds())return# Fetch flags matching any (team_id, key) combination from updates.@@ -1503,14 +1580,14 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:)raise- # Set final checkpoint to current time- redis_client.set(FEATURE_FLAG_LAST_CALLED_SYNC_KEY, current_sync_timestamp.isoformat())+ # Set final checkpoint to the end of the last window that was read successfully+ redis_client.set(FEATURE_FLAG_LAST_CALLED_SYNC_KEY, checkpoint_timestamp.isoformat())duration = (timezone.now() - start_time).total_seconds()processed_events = sum(count for _ts, count in merged_results.values())# Emit metrics for successful completion- checkpoint_lag_seconds = (timezone.now() - current_sync_timestamp).total_seconds()+ checkpoint_lag_seconds = (timezone.now() - checkpoint_timestamp).total_seconds()updated_count_gauge.set(updated_count)events_processed_gauge.set(processed_events)clickhouse_results_gauge.set(total_clickhouse_results)diff --git a/products/feature_flags/backend/test/test_feature_flag_sync.py b/products/feature_flags/backend/test/test_feature_flag_sync.pyindex 9172a7d79ef5..9f55c514f396 100644--- a/products/feature_flags/backend/test/test_feature_flag_sync.py+++ b/products/feature_flags/backend/test/test_feature_flag_sync.py@@ -8,7 +8,9 @@ from django.core.cache import cachefrom django.test import override_settingsfrom django.utils import timezone as tz-from posthog.errors import CH_TRANSIENT_ERRORS, CHQueryErrorTooManyBytes+from prometheus_client import REGISTRY++from posthog.errors import CH_TRANSIENT_ERRORS, CHQueryErrorTooManyBytes, CHQueryErrorUnknownTablefrom posthog.exceptions import ClickHouseAtCapacityfrom posthog.tasks.tasks import sync_feature_flag_last_called@@ -333,7 +335,7 @@ class TestSyncFeatureFlagLastCalled(BaseTest):self, mock_get_client: MagicMock, mock_sync_execute: MagicMock) -> None:"""- Checkpoint should be updated to the wall-clock time of the sync run, not max event timestamp+ Checkpoint should be updated to the window end, not the max event timestamp"""redis_mock = mock_redis_client()mock_get_client.return_value = redis_mock@@ -346,12 +348,13 @@ class TestSyncFeatureFlagLastCalled(BaseTest):sync_feature_flag_last_called()- # Checkpoint should be set to current_sync_timestamp (frozen at 2024-06-15T12:00:00Z)+ # Checkpoint should be set to the window end, which is the replication buffer (60s)+ # short of the frozen wall clock of 2024-06-15T12:00:00Zcheckpoint_key = "posthog:feature_flag_last_called_sync:last_timestamp"stored_timestamp = redis_mock.storage.get(checkpoint_key)assert stored_timestamp is not Noneassert "2024-06-15" in stored_timestamp- assert "2024-06-15T12:00:00" in stored_timestamp+ assert "2024-06-15T11:59:00" in stored_timestamp@freeze_time("2024-06-15 12:00:00")@patch("posthog.clickhouse.client.sync_execute")@@ -452,8 +455,9 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):@freeze_time("2024-06-15 12:00:00")@patch("posthog.clickhouse.client.sync_execute")@patch("posthog.tasks.tasks.get_client")- def test_checkpoint_not_updated_on_failure(self, mock_get_client: MagicMock, mock_sync_execute: MagicMock) -> None:- """On scan failure, checkpoint should remain unchanged so the window is retried"""+ def test_checkpoint_stops_at_first_failed_chunk(+ self, mock_get_client: MagicMock, mock_sync_execute: MagicMock+ ) -> None:redis_mock = mock_redis_client()checkpoint_key = "posthog:feature_flag_last_called_sync:last_timestamp"# 15 min ago = 3 chunks@@ -461,15 +465,88 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):redis_mock.storage[checkpoint_key] = checkpoint_time.isoformat().encode()mock_get_client.return_value = redis_mock- # First chunk succeeds, second chunk fails- mock_sync_execute.side_effect = [[], Exception("ClickHouse error")]+ called_at = tz.make_aware(datetime(2024, 6, 15, 11, 47, 0))+ # First and third chunks succeed, second one fails+ mock_sync_execute.side_effect = [+ [(self.team.pk, self.flag1.key, called_at, 5)],+ Exception("ClickHouse error"),+ [],+ ]+ failures_metric = "posthog_feature_flag_last_called_at_sync_chunk_failures_total"+ failures_before = REGISTRY.get_sample_value(failures_metric) or 0.0- with self.assertRaises(Exception):- sync_feature_flag_last_called()+ sync_feature_flag_last_called()++ # A failed chunk must not abort the remaining chunks, nor discard what was read+ assert mock_sync_execute.call_count == 3+ self.flag1.refresh_from_db()+ assert self.flag1.last_called_at == called_at++ # This run does not raise, so the counter is the only signal that a window went unread+ assert (REGISTRY.get_sample_value(failures_metric) or 0.0) == failures_before + 1- # Checkpoint should remain at the original value (no per-chunk advancement)+ # Checkpoint stops at the end of the first chunk, so the unread window from 11:50+ # onwards is retried next run rather than skippedstored = redis_mock.storage.get(checkpoint_key)- assert stored == checkpoint_time.isoformat().encode()+ assert stored == tz.make_aware(datetime(2024, 6, 15, 11, 50, 0)).isoformat()++ @freeze_time("2024-06-15 12:00:00")+ @patch("posthog.clickhouse.client.sync_execute")+ @patch("posthog.tasks.tasks.get_client")+ def test_every_chunk_failing_raises_and_leaves_checkpoint(+ self, mock_get_client: MagicMock, mock_sync_execute: MagicMock+ ) -> None:+ redis_mock = mock_redis_client()+ checkpoint_key = "posthog:feature_flag_last_called_sync:last_timestamp"+ # 10 min ago = 2 chunks+ checkpoint_time = tz.make_aware(datetime(2024, 6, 15, 11, 50, 0))+ redis_mock.storage[checkpoint_key] = checkpoint_time.isoformat().encode()+ mock_get_client.return_value = redis_mock+ mock_sync_execute.side_effect = CHQueryErrorUnknownTable("Table posthog.events_recent does not exist")++ # Nothing could be read, so the run must fail loudly instead of reporting an empty+ # sync, and it must re-raise the original ClickHouse error rather than a generic one+ # so Celery's autoretry_for sees the real class+ with self.assertRaises(CHQueryErrorUnknownTable):+ sync_feature_flag_last_called()++ # The first chunk failing means no chunk can be committed, so the run stops there+ # instead of querying the rest of the window and discarding the results+ assert mock_sync_execute.call_count == 1+ assert redis_mock.storage.get(checkpoint_key) == checkpoint_time.isoformat().encode()++ @freeze_time("2024-06-15 12:00:00")+ @patch("posthog.clickhouse.client.sync_execute")+ @patch("posthog.tasks.tasks.get_client")+ def test_transient_error_propagates_instead_of_being_tolerated(+ self, mock_get_client: MagicMock, mock_sync_execute: MagicMock+ ) -> None:+ redis_mock = mock_redis_client()+ checkpoint_key = "posthog:feature_flag_last_called_sync:last_timestamp"+ # 15 min ago = 3 chunks+ checkpoint_time = tz.make_aware(datetime(2024, 6, 15, 11, 45, 0))+ redis_mock.storage[checkpoint_key] = checkpoint_time.isoformat().encode()+ mock_get_client.return_value = redis_mock++ called_at = tz.make_aware(datetime(2024, 6, 15, 11, 47, 0))+ mock_sync_execute.side_effect = [+ [(self.team.pk, self.flag1.key, called_at, 5)],+ ClickHouseAtCapacity(),+ [],+ ]++ # A cluster shedding load is what autoretry_for handles, so the error has to escape+ # the chunk loop. Tolerating it would report a successful sync and skip the retry.+ with self.assertRaises(ClickHouseAtCapacity):+ sync_feature_flag_last_called()++ # The run stops at the failing chunk rather than querying the rest of the window+ assert mock_sync_execute.call_count == 2++ # Nothing is committed, so the next run re-reads the whole window+ assert redis_mock.storage.get(checkpoint_key) == checkpoint_time.isoformat().encode()+ self.flag1.refresh_from_db()+ assert self.flag1.last_called_at is None@freeze_time("2024-06-15 12:00:00")@patch("posthog.clickhouse.client.sync_execute")@@ -545,7 +622,7 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):# Checkpoint should still be updatedstored = redis_mock.storage.get(checkpoint_key)assert stored is not None- assert "2024-06-15T12:00:00" in stored+ assert "2024-06-15T11:59:00" in stored# Flag should remain unchangedself.flag1.refresh_from_db()