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.

feat(personhog): keep database timeouts out of the python fast retry (#116658)

Phil Haack704c99eee145
diff --git a/posthog/dags/person_pg_cleanup_drain.py b/posthog/dags/person_pg_cleanup_drain.py
index ec4e583be30f..8c3b75cd58cc 100644
--- a/posthog/dags/person_pg_cleanup_drain.py
+++ b/posthog/dags/person_pg_cleanup_drain.py
@@ -118,8 +118,9 @@ FATAL_RPC_CODES = frozenset(
grpc.StatusCode.UNAUTHENTICATED,
}
)
-# Codes a request that outran the router's deadline comes back with: the router answers
-# UNAVAILABLE once its own retries of the backend call time out.
+# Codes a request that outran a deadline comes back with. The router answers UNAVAILABLE once its
+# own retries of the backend call time out. Personhog answers DEADLINE_EXCEEDED when a Postgres
+# statement or lock timeout cancels the delete.
SLOW_RPC_CODES = frozenset({grpc.StatusCode.DEADLINE_EXCEEDED, grpc.StatusCode.UNAVAILABLE})
_T = TypeVar("_T")
diff --git a/posthog/models/person/util.py b/posthog/models/person/util.py
index b648b8f49e96..31e9e020034d 100644
--- a/posthog/models/person/util.py
+++ b/posthog/models/person/util.py
@@ -980,7 +980,7 @@ class PersonVersionFloorResult:
def _retry_lost_race(fn: Callable[[], _T]) -> _T:
- """Retry ``fn`` only on a lost race; every other error, including the INTERNAL lock timeout, propagates."""
+ """Retry ``fn`` only on a lost race. Every other error, including the DEADLINE_EXCEEDED lock timeout, propagates."""
for attempt in range(1, VERSION_FLOOR_ATTEMPTS):
try:
return fn()
diff --git a/posthog/personhog_client/interceptor.py b/posthog/personhog_client/interceptor.py
index 562e18ff8a83..e64d6021d378 100644
--- a/posthog/personhog_client/interceptor.py
+++ b/posthog/personhog_client/interceptor.py
@@ -163,6 +163,9 @@ _RETRYABLE_CODES = frozenset(
# not an application-level failure, so unlike INTERNAL in general it's always safe to retry.
_DESERIALIZATION_FAILURE_DETAILS = "Exception deserializing response!"
+# Must match DB_TIMEOUT_METADATA_KEY in rust/personhog-common/src/grpc.rs.
+_DB_TIMEOUT_METADATA_KEY = "x-db-timeout"
+
def _is_retryable(code: grpc.StatusCode | None, details: str | None, codes: Collection[grpc.StatusCode]) -> bool:
if code is None:
@@ -172,12 +175,16 @@ def _is_retryable(code: grpc.StatusCode | None, details: str | None, codes: Coll
return 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_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``.
Follows ``__cause__`` so a caller that wrapped the RpcError (``personhog_call(reraise_as=...)``)
still classifies the underlying transport failure. ``codes`` defaults to the in-process
- RetryInterceptor policy; a caller that retries at a slower tier passes its own set.
+ RetryInterceptor's code set. A caller that retries at a slower tier passes its own set.
"""
current: BaseException | None = exc
while current is not None:
@@ -197,12 +204,14 @@ class RetryInterceptor(grpc.UnaryUnaryClientInterceptor):
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)
+ - DEADLINE_EXCEEDED: transient timeout (event loop saturation, brief backend slowness), but not a
+ Postgres statement or lock timeout, which personhog marks with ``_DB_TIMEOUT_METADATA_KEY``
- 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.
+ also maps DB-level conditions (a deadlock, a read-only primary) to it.
+
+ 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.
"""
@@ -233,7 +242,7 @@ class RetryInterceptor(grpc.UnaryUnaryClientInterceptor):
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)
+ 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(
diff --git a/posthog/personhog_client/test_retry_interceptor.py b/posthog/personhog_client/test_retry_interceptor.py
index 3493779fd6d9..1ecf5d7c4e87 100644
--- a/posthog/personhog_client/test_retry_interceptor.py
+++ b/posthog/personhog_client/test_retry_interceptor.py
@@ -29,33 +29,47 @@ def _make_call_details(
)
-def _make_rpc_error(status_code: grpc.StatusCode, details: str | None = None) -> grpc.RpcError:
+def _make_rpc_error(
+ status_code: grpc.StatusCode,
+ details: str | None = None,
+ trailing_metadata: tuple[tuple[str, str], ...] = (),
+) -> grpc.RpcError:
error = grpc.RpcError()
error.code = MagicMock(return_value=status_code)
error.details = MagicMock(return_value=details)
+ error.trailing_metadata = MagicMock(return_value=trailing_metadata)
return error
-def _make_transient_then_ok(fail_count: int, status_code: grpc.StatusCode, details: str | None = None):
+def _make_transient_then_ok(
+ fail_count: int,
+ status_code: grpc.StatusCode,
+ details: str | None = None,
+ trailing_metadata: tuple[tuple[str, str], ...] = (),
+):
"""Returns a continuation that fails fail_count times then succeeds."""
calls: list[int] = []
def continuation(details_, request):
calls.append(1)
if len(calls) <= fail_count:
- raise _make_rpc_error(status_code, details)
+ raise _make_rpc_error(status_code, details, trailing_metadata)
return "ok"
return continuation, calls
-def _make_always_failing(status_code: grpc.StatusCode, details: str | None = None):
+def _make_always_failing(
+ status_code: grpc.StatusCode,
+ details: str | None = None,
+ trailing_metadata: tuple[tuple[str, str], ...] = (),
+):
"""Returns a continuation that always raises the given status code."""
calls: list[int] = []
def continuation(details_, request):
calls.append(1)
- raise _make_rpc_error(status_code, details)
+ raise _make_rpc_error(status_code, details, trailing_metadata)
return continuation, calls
@@ -71,17 +85,24 @@ class TestRetryInterceptorBehavior:
@parameterized.expand(
[
- ("unavailable", grpc.StatusCode.UNAVAILABLE),
- ("deadline_exceeded", grpc.StatusCode.DEADLINE_EXCEEDED),
- ("aborted", grpc.StatusCode.ABORTED),
- ("unknown", grpc.StatusCode.UNKNOWN),
+ ("unavailable", grpc.StatusCode.UNAVAILABLE, ()),
+ ("deadline_exceeded", grpc.StatusCode.DEADLINE_EXCEEDED, ()),
+ ("aborted", grpc.StatusCode.ABORTED, ()),
+ ("unknown", grpc.StatusCode.UNKNOWN, ()),
+ ("unavailable_load_shed", grpc.StatusCode.UNAVAILABLE, (("x-not-applied", "load_shed"),)),
]
)
@patch("posthog.personhog_client.interceptor.time.sleep")
- def test_retries_transient_error_then_succeeds(self, _name: str, status_code: grpc.StatusCode, mock_sleep):
+ def test_retries_transient_error_then_succeeds(
+ self,
+ _name: str,
+ status_code: grpc.StatusCode,
+ trailing_metadata: tuple[tuple[str, str], ...],
+ 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, status_code)
+ continuation, calls = _make_transient_then_ok(1, status_code, trailing_metadata=trailing_metadata)
result = interceptor.intercept_unary_unary(continuation, details, request=b"")
@@ -103,12 +124,27 @@ class TestRetryInterceptorBehavior:
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.
+ @parameterized.expand(
+ [
+ ("internal_db_error", grpc.StatusCode.INTERNAL, "deadlock detected", ()),
+ (
+ "db_timeout",
+ grpc.StatusCode.DEADLINE_EXCEEDED,
+ "Database lock_timeout: canceling statement due to lock timeout",
+ (("x-db-timeout", "lock_timeout"),),
+ ),
+ ]
+ )
+ def test_does_not_retry_db_error(
+ self,
+ _name: str,
+ status_code: grpc.StatusCode,
+ error_details: str,
+ trailing_metadata: tuple[tuple[str, str], ...],
+ ):
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")
+ continuation, calls = _make_always_failing(status_code, error_details, trailing_metadata)
with pytest.raises(grpc.RpcError):
interceptor.intercept_unary_unary(continuation, details, request=b"")
diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.py
index a64aaf56b460..aa0c07be9a68 100644
--- a/posthog/tasks/calculate_cohort.py
+++ b/posthog/tasks/calculate_cohort.py
@@ -63,10 +63,11 @@ STATIC_POPULATION_SOFT_TIME_LIMIT_SECONDS = 4 * 60 * 60
# The RetryInterceptor set plus RESOURCE_EXHAUSTED and INTERNAL, which an in-process retry must not
# hammer but a task backoff of minutes is the right answer to. Personhog sheds load with
-# RESOURCE_EXHAUSTED and maps every Postgres query error (deadlock, lock or statement timeout, a
-# read-only primary after a failover) to INTERNAL. UNKNOWN stays in because an HTTP/2 stream reset
-# ("Stream removed") surfaces as UNKNOWN, and that is the outage shape that leaves a static cohort
-# half-synced.
+# RESOURCE_EXHAUSTED. It answers a Postgres lock or statement timeout with DEADLINE_EXCEEDED. It maps
+# every other Postgres query error (deadlock, a read-only primary after a failover) to INTERNAL. The
+# RetryInterceptor does not retry those timeouts, so this set is where they get their retry. UNKNOWN
+# stays in because an HTTP/2 stream reset ("Stream removed") surfaces as UNKNOWN, and that is the
+# outage shape that leaves a static cohort half-synced.
STATIC_POPULATION_RETRYABLE_RPC_CODES = frozenset(
{
grpc.StatusCode.UNAVAILABLE,