: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(personhog): make the python client retry transient grpc errors (#116705)
Phil Haack701c1409bf5e
diff --git a/posthog/personhog_client/interceptor.py b/posthog/personhog_client/interceptor.pyindex e64d6021d378..99747e050b8a 100644--- a/posthog/personhog_client/interceptor.py+++ b/posthog/personhog_client/interceptor.py@@ -175,8 +175,8 @@ def _is_retryable(code: grpc.StatusCode | None, details: str | None, codes: Collreturn code == grpc.StatusCode.INTERNAL and details == _DESERIALIZATION_FAILURE_DETAILS-def _is_db_timeout(exc: grpc.RpcError) -> bool:- return any(key == _DB_TIMEOUT_METADATA_KEY for key, _ in exc.trailing_metadata() or ())+def _is_db_timeout(call: grpc.Call) -> bool:+ return any(key == _DB_TIMEOUT_METADATA_KEY for key, _ in call.trailing_metadata() or ())def is_transient_rpc_error(exc: BaseException, codes: Collection[grpc.StatusCode] = _RETRYABLE_CODES) -> bool:@@ -214,6 +214,10 @@ class RetryInterceptor(grpc.UnaryUnaryClientInterceptor):DB-level conditions, timeouts included, must not be hammered with a fast in-process retry.Sits outside MetricsInterceptor so each attempt gets its own per-call metrics.++ grpcio's continuation returns a failed call as an ``RpcError`` instead of raising it. The+ interceptor reads the status from that returned object. It returns a terminal error unchanged.+ The grpcio channel then raises that error from ``.result()``."""def __init__(@@ -235,32 +239,31 @@ class RetryInterceptor(grpc.UnaryUnaryClientInterceptor):delay_ms = self._initial_backoff_mswhile True:- try:- 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 = _is_retryable(code, details, _RETRYABLE_CODES) and not _is_db_timeout(exc)-- if not retryable or attempt == self._max_retries:- PERSONHOG_TERMINAL_ERRORS_TOTAL.labels(- method=method, client=self._client_name, error_type=error_type- ).inc()- raise-- PERSONHOG_RETRIES_TOTAL.labels(method=method, client=self._client_name, error_type=error_type).inc()-- logger.warning(- "personhog_grpc_retry",- method=method,- attempt=attempt + 1,- max_retries=self._max_retries,- error_type=error_type,- )-- base = delay_ms / 2- time.sleep((base + random.uniform(0, base)) / 1000)- delay_ms = min(delay_ms * 2, self._max_backoff_ms)- attempt += 1+ outcome = continuation(client_call_details, request)+ code = outcome.code()+ if code == grpc.StatusCode.OK:+ return outcome++ error_type = _grpc_error_type(code)+ retryable = _is_retryable(code, outcome.details(), _RETRYABLE_CODES) and not _is_db_timeout(outcome)++ if not retryable or attempt == self._max_retries:+ PERSONHOG_TERMINAL_ERRORS_TOTAL.labels(+ method=method, client=self._client_name, error_type=error_type+ ).inc()+ return outcome++ PERSONHOG_RETRIES_TOTAL.labels(method=method, client=self._client_name, error_type=error_type).inc()++ logger.warning(+ "personhog_grpc_retry",+ method=method,+ attempt=attempt + 1,+ max_retries=self._max_retries,+ error_type=error_type,+ )++ base = delay_ms / 2+ time.sleep((base + random.uniform(0, base)) / 1000)+ delay_ms = min(delay_ms * 2, self._max_backoff_ms)+ attempt += 1diff --git a/posthog/personhog_client/test_retry_interceptor.py b/posthog/personhog_client/test_retry_interceptor.pyindex 1ecf5d7c4e87..eeb19ed6da9a 100644--- a/posthog/personhog_client/test_retry_interceptor.py+++ b/posthog/personhog_client/test_retry_interceptor.py@@ -1,19 +1,25 @@from __future__ import annotations-import pytest+from collections.abc import Iterator+from concurrent.futures import ThreadPoolExecutor+from contextlib import contextmanager+from unittest.mock import MagicMock, patchfrom django.db import DatabaseErrorimport grpcfrom parameterized import parameterized+from personhog.service.v1.service_pb2_grpc import PersonHogServiceServicer, add_PersonHogServiceServicer_to_server+from posthog.personhog_client.client import PersonHogClientfrom posthog.personhog_client.interceptor import (_RETRYABLE_CODES,RetryInterceptor,_MutableClientCallDetails,is_transient_rpc_error,)+from posthog.personhog_client.proto import GetPersonRequest, GetPersonResponsedef _make_call_details(@@ -41,6 +47,12 @@ def _make_rpc_error(return error+def _make_ok_outcome() -> MagicMock:+ outcome = MagicMock()+ outcome.code.return_value = grpc.StatusCode.OK+ return outcome++def _make_transient_then_ok(fail_count: int,status_code: grpc.StatusCode,@@ -53,8 +65,8 @@ def _make_transient_then_ok(def continuation(details_, request):calls.append(1)if len(calls) <= fail_count:- raise _make_rpc_error(status_code, details, trailing_metadata)- return "ok"+ return _make_rpc_error(status_code, details, trailing_metadata)+ return _make_ok_outcome()return continuation, calls@@ -64,12 +76,12 @@ def _make_always_failing(details: str | None = None,trailing_metadata: tuple[tuple[str, str], ...] = (),):- """Returns a continuation that always raises the given status code."""+ """Returns a continuation that always returns an error with the given status code."""calls: list[int] = []def continuation(details_, request):calls.append(1)- raise _make_rpc_error(status_code, details, trailing_metadata)+ return _make_rpc_error(status_code, details, trailing_metadata)return continuation, calls@@ -78,10 +90,11 @@ class TestRetryInterceptorBehavior:def test_returns_on_first_success(self):interceptor = RetryInterceptor("test-client", max_retries=1, initial_backoff_ms=1, max_backoff_ms=10)details = _make_call_details()+ ok_outcome = _make_ok_outcome()- result = interceptor.intercept_unary_unary(lambda d, r: "ok", details, request=b"")+ result = interceptor.intercept_unary_unary(lambda d, r: ok_outcome, details, request=b"")- assert result == "ok"+ assert result is ok_outcome@parameterized.expand([@@ -106,7 +119,7 @@ class TestRetryInterceptorBehavior:result = interceptor.intercept_unary_unary(continuation, details, request=b"")- assert result == "ok"+ assert result.code() == grpc.StatusCode.OKassert len(calls) == 2assert mock_sleep.call_count == 1@@ -120,7 +133,7 @@ class TestRetryInterceptorBehavior:result = interceptor.intercept_unary_unary(continuation, details, request=b"")- assert result == "ok"+ assert result.code() == grpc.StatusCode.OKassert len(calls) == 2assert mock_sleep.call_count == 1@@ -146,9 +159,9 @@ class TestRetryInterceptorBehavior:details = _make_call_details()continuation, calls = _make_always_failing(status_code, error_details, trailing_metadata)- with pytest.raises(grpc.RpcError):- interceptor.intercept_unary_unary(continuation, details, request=b"")+ result = interceptor.intercept_unary_unary(continuation, details, request=b"")+ assert result.code() == status_codeassert len(calls) == 1@parameterized.expand(@@ -167,9 +180,9 @@ class TestRetryInterceptorBehavior:details = _make_call_details()continuation, calls = _make_always_failing(status_code)- with pytest.raises(grpc.RpcError):- interceptor.intercept_unary_unary(continuation, details, request=b"")+ result = interceptor.intercept_unary_unary(continuation, details, request=b"")+ assert result.code() == status_codeassert len(calls) == 1@patch("posthog.personhog_client.interceptor.time.sleep")@@ -178,8 +191,9 @@ class TestRetryInterceptorBehavior:details = _make_call_details()continuation, calls = _make_always_failing(grpc.StatusCode.UNAVAILABLE)- with pytest.raises(grpc.RpcError):- interceptor.intercept_unary_unary(continuation, details, request=b"")+ result = interceptor.intercept_unary_unary(continuation, details, request=b"")++ assert result.code() == grpc.StatusCode.UNAVAILABLE# 1 initial + 1 retry = 2 total attemptsassert len(calls) == 2@@ -190,9 +204,9 @@ class TestRetryInterceptorBehavior:details = _make_call_details()continuation, calls = _make_always_failing(grpc.StatusCode.UNAVAILABLE)- with pytest.raises(grpc.RpcError):- interceptor.intercept_unary_unary(continuation, details, request=b"")+ result = interceptor.intercept_unary_unary(continuation, details, request=b"")+ assert result.code() == grpc.StatusCode.UNAVAILABLEassert len(calls) == 1@@ -219,8 +233,7 @@ class TestRetryInterceptorMetrics:details = _make_call_details()continuation, _ = _make_always_failing(grpc.StatusCode.UNAVAILABLE)- with pytest.raises(grpc.RpcError):- interceptor.intercept_unary_unary(continuation, details, request=b"")+ interceptor.intercept_unary_unary(continuation, details, request=b"")mock_terminal.labels.assert_called_with(method="GetPerson", client="test-client", error_type="Unavailable")mock_terminal.labels.return_value.inc.assert_called_once()@@ -233,8 +246,7 @@ class TestRetryInterceptorMetrics:details = _make_call_details()continuation, _ = _make_always_failing(grpc.StatusCode.NOT_FOUND)- with pytest.raises(grpc.RpcError):- interceptor.intercept_unary_unary(continuation, details, request=b"")+ interceptor.intercept_unary_unary(continuation, details, request=b"")mock_terminal.labels.assert_called_with(method="GetPerson", client="test-client", error_type="NotFound")mock_terminal.labels.return_value.inc.assert_called_once()@@ -246,12 +258,74 @@ class TestRetryInterceptorMetrics:interceptor = RetryInterceptor("test-client", max_retries=1, initial_backoff_ms=1, max_backoff_ms=10)details = _make_call_details()- interceptor.intercept_unary_unary(lambda d, r: "ok", details, request=b"")+ interceptor.intercept_unary_unary(lambda d, r: _make_ok_outcome(), details, request=b"")mock_retries.labels.return_value.inc.assert_not_called()mock_terminal.labels.return_value.inc.assert_not_called()+class _FailsOncePersonHogService(PersonHogServiceServicer):+ def __init__(self, code: grpc.StatusCode, trailing_metadata: tuple[tuple[str, str], ...]) -> None:+ self._code = code+ self._trailing_metadata = trailing_metadata+ self.calls = 0++ def GetPerson(self, request, context):+ self.calls += 1+ if self.calls == 1:+ context.set_trailing_metadata(self._trailing_metadata)+ context.abort(self._code, "injected failure")+ return GetPersonResponse()+++@contextmanager+def _client_for(service: PersonHogServiceServicer) -> Iterator[PersonHogClient]:+ with ThreadPoolExecutor(max_workers=1) as pool:+ server = grpc.server(pool)+ add_PersonHogServiceServicer_to_server(service, server)+ port = server.add_insecure_port("localhost:0")+ server.start()+ client = PersonHogClient(f"localhost:{port}", initial_backoff_ms=1, max_backoff_ms=1)+ try:+ yield client+ finally:+ client.close()+ server.stop(None)+++class TestRetryInterceptorOnRealChannel:+ @parameterized.expand(+ [+ ("unavailable_is_retried", grpc.StatusCode.UNAVAILABLE, (), grpc.StatusCode.OK, 2),+ (+ "db_timeout_is_not_retried",+ grpc.StatusCode.DEADLINE_EXCEEDED,+ (("x-db-timeout", "lock_timeout"),),+ grpc.StatusCode.DEADLINE_EXCEEDED,+ 1,+ ),+ ]+ )+ def test_retry_decision_through_the_client_interceptor_chain(+ self,+ _name: str,+ first_failure: grpc.StatusCode,+ trailing_metadata: tuple[tuple[str, str], ...],+ expected_code: grpc.StatusCode,+ expected_calls: int,+ ):+ service = _FailsOncePersonHogService(first_failure, trailing_metadata)++ with _client_for(service) as client:+ try:+ client.get_person(GetPersonRequest())+ code = grpc.StatusCode.OK+ except grpc.RpcError as exc:+ code = exc.code()++ assert (code, service.calls) == (expected_code, expected_calls)++def _wrapped_in_database_error(cause: BaseException) -> BaseException:wrapped = DatabaseError("personhog insert_cohort_members failed")wrapped.__cause__ = cause