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(aio): retry model resolution reads on transient DB errors (#77122)

posthog[bot]42bf23e7e931
diff --git a/posthog/temporal/ai_observability/model_resolution.py b/posthog/temporal/ai_observability/model_resolution.py
index a74497225855..a3ad0f1b5f91 100644
--- a/posthog/temporal/ai_observability/model_resolution.py
+++ b/posthog/temporal/ai_observability/model_resolution.py
@@ -19,6 +19,8 @@ from django.utils import timezone
from temporalio.exceptions import ApplicationError
+from posthog.temporal.common.utils import retry_on_db_connection_drop
+
from products.ai_observability.backend.llm import DEFAULT_MODEL_BY_PROVIDER
from products.ai_observability.backend.models.evaluation_config import EvaluationConfig
from products.ai_observability.backend.models.provider_keys import LLMProviderKey
@@ -62,7 +64,7 @@ class DefaultModelSpec:
"""Null config: defer to the team's active BYOK key."""
def resolve(self, team_id: int) -> ResolvedModel:
- key = _eval_config(team_id).active_provider_key
+ key = _active_key(_eval_config(team_id))
if key is None:
raise _provider_key_required()
@@ -88,13 +90,25 @@ def model_spec(model_configuration: dict[str, Any] | None) -> ModelSpec:
def active_key_fallback(config: EvaluationConfig, provider: str) -> LLMProviderKey | None:
"""The BYOK key a config with no pinned key resolves to, or None when there is no usable active key."""
- key = config.active_provider_key
+ key = _active_key(config)
return key if key is not None and key.provider == provider else None
def _eval_config(team_id: int) -> EvaluationConfig:
- config, _ = EvaluationConfig.objects.get_or_create(team_id=team_id)
- return config
+ def _get_or_create() -> EvaluationConfig:
+ config, _ = EvaluationConfig.objects.get_or_create(team_id=team_id)
+ return config
+
+ return retry_on_db_connection_drop(_get_or_create)
+
+
+def _active_key(config: EvaluationConfig) -> LLMProviderKey | None:
+ """The team's active BYOK key, or None when the config has none.
+
+ Dereferencing the FK is a second query, and Django caches the relation only once it resolves,
+ so a retry after a failed dereference genuinely re-reads instead of replaying stale state.
+ """
+ return retry_on_db_connection_drop(lambda: config.active_provider_key)
def _provider_key_required() -> ApplicationError:
@@ -107,7 +121,7 @@ def _provider_key_required() -> ApplicationError:
def _resolve_key_by_id(team_id: int, key_id: str) -> LLMProviderKey:
try:
- key = LLMProviderKey.objects.get(id=key_id, team_id=team_id)
+ key = retry_on_db_connection_drop(lambda: LLMProviderKey.objects.get(id=key_id, team_id=team_id))
except LLMProviderKey.DoesNotExist:
raise ApplicationError(
"Provider key not found.",
@@ -124,6 +138,8 @@ def _ensure_usable(key: LLMProviderKey) -> LLMProviderKey:
{"error_type": "key_invalid", "key_id": str(key.id), "key_state": key.state},
non_retryable=True,
)
+ # Retrying this write is safe because the timestamp is fixed before it, so a second attempt
+ # persists the same value rather than drifting it forward.
key.last_used_at = timezone.now()
- key.save(update_fields=["last_used_at"])
+ retry_on_db_connection_drop(lambda: key.save(update_fields=["last_used_at"]))
return key
diff --git a/posthog/temporal/ai_observability/test_model_resolution.py b/posthog/temporal/ai_observability/test_model_resolution.py
index 44e817be20aa..7a02c6186425 100644
--- a/posthog/temporal/ai_observability/test_model_resolution.py
+++ b/posthog/temporal/ai_observability/test_model_resolution.py
@@ -2,6 +2,8 @@ import uuid
import pytest
+from django.db import OperationalError, connection
+
from temporalio.exceptions import ApplicationError
from posthog.models import Organization, Team
@@ -32,6 +34,22 @@ def _error_type(exc_info):
return exc_info.value.details[0]["error_type"]
+# Fails the first SELECT against `table` and passes every other query through. The statement never
+# reaches Postgres, so the retry has to re-issue the real read instead of reusing whatever the
+# failed attempt left on the instance.
+class _FailFirstRead:
+ def __init__(self, table):
+ self.table = table
+ self.reads = 0
+
+ def __call__(self, execute, sql, params, many, context):
+ if sql.lstrip().startswith("SELECT") and self.table in sql:
+ self.reads += 1
+ if self.reads == 1:
+ raise OperationalError("query_wait_timeout")
+ return execute(sql, params, many, context)
+
+
class TestModelSpecFactory:
def test_null_config_returns_default_spec(self):
assert isinstance(model_spec(None), DefaultModelSpec)
@@ -54,6 +72,18 @@ class TestExplicitModelSpec:
key.refresh_from_db()
assert key.last_used_at is not None
+ def test_byok_key_lookup_recovers_from_transient_operational_error(self, team):
+ # A dropped pooled connection surfaces as a transient OperationalError, which must not
+ # fail the whole eval run when a second read on a fresh connection would succeed.
+ key = _key(team, "anthropic")
+ fail_first = _FailFirstRead(LLMProviderKey._meta.db_table)
+
+ with connection.execute_wrapper(fail_first):
+ resolved = ExplicitModelSpec("anthropic", "claude-opus-4-8", str(key.id)).resolve(team.id)
+
+ assert resolved.provider_key == key
+ assert fail_first.reads == 2
+
def test_byok_missing_key_raises_key_not_found(self, team):
with pytest.raises(ApplicationError) as exc_info:
ExplicitModelSpec("openai", "gpt-5", str(uuid.uuid4())).resolve(team.id)
@@ -99,6 +129,20 @@ class TestDefaultModelSpec:
DefaultModelSpec().resolve(team.id)
assert _error_type(exc_info) == "provider_key_required"
+ def test_active_key_dereference_recovers_from_transient_operational_error(self, team):
+ # The active_provider_key FK dereference is a second read after the config load. Django
+ # caches the relation only once it resolves, so the retry must re-read the key rather
+ # than hand back whatever the failed dereference left behind.
+ key = _key(team, "anthropic")
+ EvaluationConfig.objects.create(team=team, active_provider_key=key)
+ fail_first = _FailFirstRead(LLMProviderKey._meta.db_table)
+
+ with connection.execute_wrapper(fail_first):
+ resolved = DefaultModelSpec().resolve(team.id)
+
+ assert resolved.provider_key == key
+ assert fail_first.reads == 2
+
def test_anthropic_active_key_resolves_to_anthropic_default(self, team):
# Regression: a null config with an Anthropic active key used to resolve to openai/gpt-5-mini
# and raise ProviderMismatchError on every generation. It must now follow the key's provider.