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(flags): retry the flag sync on a desynced ClickHouse socket (#103277)

posthog[bot]3f2f2e269873
diff --git a/posthog/errors.py b/posthog/errors.py
index dc7d5455a93a..40dcb30217b5 100644
--- a/posthog/errors.py
+++ b/posthog/errors.py
@@ -1044,12 +1044,20 @@ CLICKHOUSE_ERROR_CODE_LOOKUP: dict[int, ErrorCodeMeta] = {
# Transient ClickHouse infrastructure errors that are safe to retry.
# This can be used in things like celery `autoretry_for` to increase resiliency.
# Capacity errors (codes 202/439) are wrapped as ClickHouseAtCapacity by wrap_clickhouse_query_error.
+# For every entry the client knows the query did not complete. Either it never reached the server, or
+# the client holds the server's own error for that query. Keep it that way: this tuple is shared with
+# write callers such as calculate_cohort_ch, whose INSERT INTO cohortpeople appends rows at a version
+# it does not delete first. An error that leaves the outcome unknown must not go in here. A repeated
+# write duplicates the membership rows of a live cohort version.
# CHQueryErrorQueryWasCancelled (394) is deliberately absent: a deploy cancelling in-flight queries
# and an operator or user deliberately killing one are indistinguishable at this layer, so callers
# that want the deploy case retried opt in themselves (see COHORT_RECALCULATION_TRANSIENT_ERRORS).
-# The two clickhouse_driver classes are raised only while a connection is being opened (connect, or
+# UnknownPacketFromServerError is deliberately absent for the write reason above: it means a pooled
+# socket is out of sync, and the driver can read that unexpected packet after the server already ran
+# the query. Read-only callers opt in themselves (see FEATURE_FLAG_SYNC_TRANSIENT_ERRORS).
+# NetworkError and SocketTimeoutError are raised only while a connection is being opened (connect, or
# the ping-then-reconnect on a stale pooled socket), before any query is sent, so nothing has run and
-# a retry is safe. They are not ServerExceptions, so wrap_clickhouse_query_error passes them through
+# a retry is safe. Neither is a ServerException, so wrap_clickhouse_query_error passes them through
# untouched: a bare "Code: 209. (host:9440)" is the driver's 10s connect_timeout firing, typically
# because a node dropped out of the cluster's load balancer for a few seconds.
CH_TRANSIENT_ERRORS = (
diff --git a/posthog/tasks/tasks.py b/posthog/tasks/tasks.py
index 1ac68c577f88..ee6a45c27053 100644
--- a/posthog/tasks/tasks.py
+++ b/posthog/tasks/tasks.py
@@ -13,6 +13,7 @@ from django.utils import timezone
import requests
from celery import shared_task
+from clickhouse_driver.errors import UnknownPacketFromServerError
from prometheus_client import Counter, Gauge
from redis import Redis
from rest_framework.exceptions import APIException
@@ -52,6 +53,17 @@ FEATURE_FLAG_LAST_CALLED_AT_SYNC_CHUNK_FAILURE_COUNTER = Counter(
"ClickHouse chunk queries that failed during feature flag last_called_at sync",
)
+FEATURE_FLAG_LAST_CALLED_AT_SYNC_RETRY_RECOVERY_COUNTER = Counter(
+ "posthog_feature_flag_last_called_at_sync_retry_recoveries_total",
+ "Feature flag last_called_at sync runs that completed on a Celery retry after an earlier attempt failed",
+)
+
+# CH_TRANSIENT_ERRORS plus the desynced pooled socket, which the sync opts into here rather than in
+# the shared tuple: the driver can read that unexpected packet after ClickHouse already ran the
+# query, so a write caller retrying it would land the write twice. This task only reads from
+# ClickHouse - it writes to Postgres from the merged results - so repeating the query is safe.
+FEATURE_FLAG_SYNC_TRANSIENT_ERRORS = (*CH_TRANSIENT_ERRORS, UnknownPacketFromServerError)
+
STALE_QUEUED_TASK_RUN_SWEPT_COUNTER = Counter(
"posthog_task_run_stale_queued_swept_total",
@@ -1244,7 +1256,7 @@ def _queue_delete_team_recordings(team_ids: list[int], deleted_by: str) -> None:
queue=CeleryQueue.FEATURE_FLAGS_LONG_RUNNING.value,
# sync_execute wraps TOO_MANY_SIMULTANEOUS_QUERIES/CANNOT_SCHEDULE_TASK into
# ClickHouseAtCapacity, which CH_TRANSIENT_ERRORS includes.
- autoretry_for=CH_TRANSIENT_ERRORS,
+ autoretry_for=FEATURE_FLAG_SYNC_TRANSIENT_ERRORS,
retry_backoff=30,
retry_backoff_max=120,
max_retries=3,
@@ -1318,6 +1330,8 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:
registry=self.metrics_registry,
)
+ run_failed = False
+
try:
redis_client = get_client()
@@ -1435,7 +1449,7 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:
# 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):
+ if isinstance(e, FEATURE_FLAG_SYNC_TRANSIENT_ERRORS):
raise
chunk_failures += 1
@@ -1610,13 +1624,20 @@ def sync_feature_flag_last_called(self: PushGatewayTask) -> None:
)
except Exception as e:
+ run_failed = True
duration = (timezone.now() - start_time).total_seconds()
logger.exception("Feature flag sync failed", error=e, duration_seconds=duration)
- capture_exception(
- e, additional_properties={"feature": "feature_flags", "task": "sync_feature_flag_last_called"}
- )
+ properties = {"feature": "feature_flags", "task": "sync_feature_flag_last_called"}
+ if isinstance(e, UnknownPacketFromServerError):
+ # The driver puts the unexpected packet number and the host in the message, so every
+ # occurrence fingerprints as a new error tracking issue. Group them under one issue.
+ properties["$exception_fingerprint"] = "sync_feature_flag_last_called.UnknownPacketFromServerError"
+ capture_exception(e, additional_properties=properties)
raise
finally:
+ if not run_failed and (self.request.retries or 0) > 0:
+ FEATURE_FLAG_LAST_CALLED_AT_SYNC_RETRY_RECOVERY_COUNTER.inc()
+
# Always release the lock
cache.delete(LOCK_KEY)
diff --git a/products/feature_flags/backend/test/test_feature_flag_sync.py b/products/feature_flags/backend/test/test_feature_flag_sync.py
index cbcd54f6488a..afbab864ed8c 100644
--- a/products/feature_flags/backend/test/test_feature_flag_sync.py
+++ b/products/feature_flags/backend/test/test_feature_flag_sync.py
@@ -8,6 +8,8 @@ from django.core.cache import cache
from django.test import override_settings
from django.utils import timezone as tz
+from clickhouse_driver.errors import UnknownPacketFromServerError
+from parameterized import parameterized
from prometheus_client import REGISTRY
from posthog.errors import CH_TRANSIENT_ERRORS, CHQueryErrorTooManyBytes, CHQueryErrorUnknownTable
@@ -515,11 +517,21 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):
assert mock_sync_execute.call_count == 1
assert redis_mock.storage.get(checkpoint_key) == checkpoint_time.isoformat().encode()
+ @parameterized.expand(
+ [
+ ("at_capacity", ClickHouseAtCapacity),
+ ("unknown_packet", UnknownPacketFromServerError),
+ ]
+ )
@time_machine.travel("2024-06-15 12:00:00", tick=False)
@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
+ self,
+ _name: str,
+ error_cls: type[Exception],
+ mock_get_client: MagicMock,
+ mock_sync_execute: MagicMock,
) -> None:
redis_mock = mock_redis_client()
checkpoint_key = "posthog:feature_flag_last_called_sync:last_timestamp"
@@ -531,13 +543,14 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):
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(),
+ error_cls("boom"),
[],
]
- # 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):
+ # A cluster shedding load, or a desynced pooled socket, 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(error_cls):
sync_feature_flag_last_called()
# The run stops at the failing chunk rather than querying the rest of the window
@@ -638,3 +651,81 @@ class TestSyncFeatureFlagLastCalledChunking(BaseTest):
# sync_execute wraps capacity errors (code 202) into ClickHouseAtCapacity,
# so the wrapped form must be retryable too
assert ClickHouseAtCapacity in autoretry_for
+ # A desynced pooled socket is retryable for this task, which only reads from ClickHouse,
+ # but it has to stay out of the shared tuple: the driver can raise it after the server ran
+ # the query, so a write caller retrying it would land the write twice
+ assert UnknownPacketFromServerError in autoretry_for
+ assert UnknownPacketFromServerError not in CH_TRANSIENT_ERRORS
+
+ @parameterized.expand(
+ [
+ (
+ "unknown_packet",
+ UnknownPacketFromServerError,
+ "sync_feature_flag_last_called.UnknownPacketFromServerError",
+ ),
+ ("unknown_table", CHQueryErrorUnknownTable, None),
+ ]
+ )
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
+ @patch("posthog.tasks.tasks.capture_exception")
+ @patch("posthog.clickhouse.client.sync_execute")
+ @patch("posthog.tasks.tasks.get_client")
+ def test_failure_fingerprint_is_set_only_for_the_desynced_socket(
+ self,
+ _name: str,
+ error_cls: type[Exception],
+ expected_fingerprint: str | None,
+ mock_get_client: MagicMock,
+ mock_sync_execute: MagicMock,
+ mock_capture_exception: MagicMock,
+ ) -> None:
+ mock_get_client.return_value = mock_redis_client()
+ # The driver names the packet it did not expect, and the number moves between
+ # occurrences. Without a fixed fingerprint every occurrence opens its own issue.
+ # Every other failure keeps the automatic grouping, so one triaged issue cannot
+ # swallow an unrelated one.
+ mock_sync_execute.side_effect = error_cls("boom")
+
+ with self.assertRaises(error_cls):
+ sync_feature_flag_last_called()
+
+ properties = mock_capture_exception.call_args.kwargs["additional_properties"]
+ assert properties.get("$exception_fingerprint") == expected_fingerprint
+
+ @time_machine.travel("2024-06-15 12:00:00", tick=False)
+ @patch("posthog.clickhouse.client.sync_execute")
+ @patch("posthog.tasks.tasks.get_client")
+ def test_run_that_completes_on_a_retry_is_counted(
+ self, mock_get_client: MagicMock, mock_sync_execute: MagicMock
+ ) -> None:
+ mock_get_client.return_value = mock_redis_client()
+ mock_sync_execute.return_value = []
+ recoveries_metric = "posthog_feature_flag_last_called_at_sync_retry_recoveries_total"
+ recoveries_before = REGISTRY.get_sample_value(recoveries_metric) or 0.0
+
+ sync_feature_flag_last_called()
+
+ # A first attempt that succeeds is not a recovery
+ assert (REGISTRY.get_sample_value(recoveries_metric) or 0.0) == recoveries_before
+
+ cache.clear()
+ sync_feature_flag_last_called.push_request(retries=1)
+ try:
+ sync_feature_flag_last_called()
+ finally:
+ sync_feature_flag_last_called.pop_request()
+
+ assert (REGISTRY.get_sample_value(recoveries_metric) or 0.0) == recoveries_before + 1
+
+ cache.clear()
+ mock_sync_execute.side_effect = CHQueryErrorUnknownTable("boom")
+ sync_feature_flag_last_called.push_request(retries=1)
+ try:
+ with self.assertRaises(CHQueryErrorUnknownTable):
+ sync_feature_flag_last_called()
+ finally:
+ sync_feature_flag_last_called.pop_request()
+
+ # A retry that fails is not a recovery
+ assert (REGISTRY.get_sample_value(recoveries_metric) or 0.0) == recoveries_before + 1