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(personhog): retry client-side response deserialization failures (#111653)

Tom Owers7895cafffba8
diff --git a/posthog/personhog_client/interceptor.py b/posthog/personhog_client/interceptor.py
index 48a8fad467fe..562e18ff8a83 100644
--- a/posthog/personhog_client/interceptor.py
+++ b/posthog/personhog_client/interceptor.py
@@ -158,6 +158,19 @@ _RETRYABLE_CODES = frozenset(
}
)
+# grpcio reports this exact, hardcoded message - never sent by the server - when the client fails to
+# deserialize the response bytes (e.g. a connection cut mid-stream). That's a transport corruption,
+# not an application-level failure, so unlike INTERNAL in general it's always safe to retry.
+_DESERIALIZATION_FAILURE_DETAILS = "Exception deserializing response!"
+
+
+def _is_retryable(code: grpc.StatusCode | None, details: str | None, codes: Collection[grpc.StatusCode]) -> bool:
+ if code is None:
+ return False
+ if code in codes:
+ return True
+ return code == grpc.StatusCode.INTERNAL and details == _DESERIALIZATION_FAILURE_DETAILS
+
def is_transient_rpc_error(exc: BaseException, codes: Collection[grpc.StatusCode] = _RETRYABLE_CODES) -> bool:
"""Whether ``exc``, or the error it was raised from, is a gRPC failure with a status in ``codes``.
@@ -170,7 +183,10 @@ def is_transient_rpc_error(exc: BaseException, codes: Collection[grpc.StatusCode
while current is not None:
if isinstance(current, grpc.RpcError):
code = getattr(current, "code", None)
- return callable(code) and code() in codes
+ if not callable(code):
+ return False
+ details = getattr(current, "details", None)
+ return _is_retryable(code(), details() if callable(details) else None, codes)
current = current.__cause__
return False
@@ -178,11 +194,15 @@ def is_transient_rpc_error(exc: BaseException, codes: Collection[grpc.StatusCode
class RetryInterceptor(grpc.UnaryUnaryClientInterceptor):
"""Retries transient gRPC errors with jittered backoff.
- Covers four failure modes:
+ Covers five failure modes:
- UNAVAILABLE: client-to-router connection failure
- ABORTED: HTTP/2 stream reset during router deploys
- DEADLINE_EXCEEDED: transient timeout (event loop saturation, brief backend slowness)
- UNKNOWN: catch-all for transient failures that don't map to a specific code
+ - INTERNAL, but only the client-side response deserialization failure (see
+ ``_DESERIALIZATION_FAILURE_DETAILS``) - INTERNAL otherwise stays terminal here since personhog
+ also maps DB-level conditions (lock timeouts, a read-only primary) to it, and those must not be
+ hammered with a fast in-process retry.
Sits outside MetricsInterceptor so each attempt gets its own per-call metrics.
"""
@@ -210,8 +230,10 @@ class RetryInterceptor(grpc.UnaryUnaryClientInterceptor):
return continuation(client_call_details, request)
except grpc.RpcError as exc:
code = exc.code()
+ details_fn = getattr(exc, "details", None)
+ details = details_fn() if callable(details_fn) else None
error_type = _grpc_error_type(code) if code else "Unknown"
- retryable = code in _RETRYABLE_CODES if code else False
+ retryable = _is_retryable(code, details, _RETRYABLE_CODES)
if not retryable or attempt == self._max_retries:
PERSONHOG_TERMINAL_ERRORS_TOTAL.labels(
diff --git a/posthog/personhog_client/test_retry_interceptor.py b/posthog/personhog_client/test_retry_interceptor.py
index 5f96a4dcd44b..3493779fd6d9 100644
--- a/posthog/personhog_client/test_retry_interceptor.py
+++ b/posthog/personhog_client/test_retry_interceptor.py
@@ -29,32 +29,33 @@ def _make_call_details(
)
-def _make_rpc_error(status_code: grpc.StatusCode) -> grpc.RpcError:
+def _make_rpc_error(status_code: grpc.StatusCode, details: str | None = None) -> grpc.RpcError:
error = grpc.RpcError()
error.code = MagicMock(return_value=status_code)
+ error.details = MagicMock(return_value=details)
return error
-def _make_transient_then_ok(fail_count: int, status_code: grpc.StatusCode):
+def _make_transient_then_ok(fail_count: int, status_code: grpc.StatusCode, details: str | None = None):
"""Returns a continuation that fails fail_count times then succeeds."""
calls: list[int] = []
- def continuation(details, request):
+ def continuation(details_, request):
calls.append(1)
if len(calls) <= fail_count:
- raise _make_rpc_error(status_code)
+ raise _make_rpc_error(status_code, details)
return "ok"
return continuation, calls
-def _make_always_failing(status_code: grpc.StatusCode):
+def _make_always_failing(status_code: grpc.StatusCode, details: str | None = None):
"""Returns a continuation that always raises the given status code."""
calls: list[int] = []
- def continuation(details, request):
+ def continuation(details_, request):
calls.append(1)
- raise _make_rpc_error(status_code)
+ raise _make_rpc_error(status_code, details)
return continuation, calls
@@ -88,6 +89,32 @@ class TestRetryInterceptorBehavior:
assert len(calls) == 2
assert mock_sleep.call_count == 1
+ @patch("posthog.personhog_client.interceptor.time.sleep")
+ def test_retries_internal_deserialization_failure_then_succeeds(self, mock_sleep):
+ interceptor = RetryInterceptor("test-client", max_retries=1, initial_backoff_ms=1, max_backoff_ms=10)
+ details = _make_call_details()
+ continuation, calls = _make_transient_then_ok(
+ 1, grpc.StatusCode.INTERNAL, details="Exception deserializing response!"
+ )
+
+ result = interceptor.intercept_unary_unary(continuation, details, request=b"")
+
+ assert result == "ok"
+ assert len(calls) == 2
+ assert mock_sleep.call_count == 1
+
+ def test_does_not_retry_internal_error_with_unrelated_details(self):
+ # Plain INTERNAL stays terminal — personhog also maps DB-level conditions (lock timeouts,
+ # a read-only primary) to it, which an in-process retry must not hammer.
+ interceptor = RetryInterceptor("test-client", max_retries=1, initial_backoff_ms=1, max_backoff_ms=10)
+ details = _make_call_details()
+ continuation, calls = _make_always_failing(grpc.StatusCode.INTERNAL, details="deadlock detected")
+
+ with pytest.raises(grpc.RpcError):
+ interceptor.intercept_unary_unary(continuation, details, request=b"")
+
+ assert len(calls) == 1
+
@parameterized.expand(
[
("not_found", grpc.StatusCode.NOT_FOUND),
@@ -219,6 +246,18 @@ class TestIsTransientRpcError:
{grpc.StatusCode.RESOURCE_EXHAUSTED},
True,
),
+ (
+ "internal_deserialization_failure",
+ _make_rpc_error(grpc.StatusCode.INTERNAL, details="Exception deserializing response!"),
+ _RETRYABLE_CODES,
+ True,
+ ),
+ (
+ "internal_unrelated_details",
+ _make_rpc_error(grpc.StatusCode.INTERNAL, details="deadlock detected"),
+ _RETRYABLE_CODES,
+ False,
+ ),
]
)
def test_classifies_transport_failures(self, _name: str, exc: BaseException, codes, expected: bool):