: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
perf(aio): cache team api token for evaluation event emission (#75742)
posthog[bot]3c1b1290214f
diff --git a/posthog/temporal/ai_observability/conftest.py b/posthog/temporal/ai_observability/conftest.pynew file mode 100644index 000000000000..8239c7704bd3--- /dev/null+++ b/posthog/temporal/ai_observability/conftest.py@@ -0,0 +1,12 @@+import pytest++from posthog.temporal.ai_observability.team_capture import clear_team_api_token_cache++[email protected](autouse=True)+def _clear_team_api_token_cache():+ # The token cache is per worker process, so it would otherwise leak across tests that+ # reuse team ids from a rolled-back transaction.+ clear_team_api_token_cache()+ yield+ clear_team_api_token_cache()diff --git a/posthog/temporal/ai_observability/evaluation_workflow_activities.py b/posthog/temporal/ai_observability/evaluation_workflow_activities.pyindex d7732ef90a28..c6d5d7945da1 100644--- a/posthog/temporal/ai_observability/evaluation_workflow_activities.py+++ b/posthog/temporal/ai_observability/evaluation_workflow_activities.py@@ -10,12 +10,13 @@ import structlogimport temporaliofrom structlog.contextvars import bind_contextvars-from posthog.api.capture import CaptureInternalError, capture_internal+from posthog.api.capture import CaptureInternalErrorfrom posthog.models.team import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.ai_observability.evaluation_llm_judge import DEFAULT_JUDGE_MODELfrom posthog.temporal.ai_observability.evaluation_types import EvaluationActivityResultfrom posthog.temporal.ai_observability.metrics import increment_emit_event_outcome+from posthog.temporal.ai_observability.team_capture import capture_internal_for_teamfrom products.ai_observability.backend.models.evaluations import Evaluation, EvaluationStatusfrom products.ai_observability.backend.models.provider_keys import LLMProviderKey@@ -281,12 +282,6 @@ async def emit_evaluation_event_activity(inputs: EmitEvaluationEventInputs) -> Nstart_time = inputs.start_timedef _emit() -> None:- try:- team = Team.objects.get(id=event_data["team_id"])- except Team.DoesNotExist:- logger.exception("Team not found", team_id=event_data["team_id"])- raise ValueError(f"Team {event_data['team_id']} not found")-source_props = (json.loads(event_data["properties"])if isinstance(event_data["properties"], str)@@ -309,18 +304,14 @@ async def emit_evaluation_event_activity(inputs: EmitEvaluationEventInputs) -> Nif source_props.get(property_name) is not None:properties[property_name] = source_props[property_name]- event_timestamp = datetime.now(UTC)-- capture_result = capture_internal(- token=team.api_token,+ capture_internal_for_team(+ team_id=event_data["team_id"],event_name="$ai_evaluation",event_source="llm_analytics_evaluation",distinct_id=event_data["distinct_id"],- timestamp=event_timestamp,+ timestamp=datetime.now(UTC),properties=properties,- process_person_profile=True,)- capture_result.raise_for_status()try:await database_sync_to_async(_emit, thread_sensitive=False)()@@ -361,8 +352,7 @@ async def emit_internal_telemetry_activity(inputs: EmitInternalTelemetryInputs)result = inputs.resultdef _emit_telemetry() -> None:- team = Team.objects.get(id=team_id)- organization_id = str(team.organization_id)+ organization_id = str(Team.objects.filter(id=team_id).values_list("organization_id", flat=True).get())ph_client = get_ph_client(sync_mode=True)ph_client.capture(diff --git a/posthog/temporal/ai_observability/run_tagger.py b/posthog/temporal/ai_observability/run_tagger.pyindex 4c842faaa09c..f604d703c06a 100644--- a/posthog/temporal/ai_observability/run_tagger.py+++ b/posthog/temporal/ai_observability/run_tagger.py@@ -10,13 +10,13 @@ from structlog.contextvars import bind_contextvarsfrom temporalio.common import RetryPolicyfrom temporalio.exceptions import ApplicationError-from posthog.api.capture import CaptureInternalError, capture_internal-from posthog.models.team import Team+from posthog.api.capture import CaptureInternalErrorfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.ai_observability.evaluation_event_io import extract_event_iofrom posthog.temporal.ai_observability.evaluation_workflow_activities import update_key_state_activityfrom posthog.temporal.ai_observability.message_utils import extract_text_from_messagesfrom posthog.temporal.ai_observability.model_resolution import model_spec+from posthog.temporal.ai_observability.team_capture import capture_internal_for_teamfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.scoped import scoped_temporal@@ -472,12 +472,6 @@ async def emit_tagger_event_activity(inputs: EmitTaggerEventInputs) -> None:start_time = inputs.start_timedef _emit():- try:- team = Team.objects.get(id=event_data["team_id"])- except Team.DoesNotExist:- logger.exception("Team not found", team_id=event_data["team_id"])- raise ValueError(f"Team {event_data['team_id']} not found")-properties_raw = (json.loads(event_data["properties"])if isinstance(event_data["properties"], str)@@ -514,18 +508,14 @@ async def emit_tagger_event_activity(inputs: EmitTaggerEventInputs) -> None:})- event_timestamp = datetime.now(UTC)-- routed_result = capture_internal(- token=team.api_token,+ capture_internal_for_team(+ team_id=event_data["team_id"],event_name="$ai_tag",event_source="llm_analytics_tagger",distinct_id=event_data["distinct_id"],- timestamp=event_timestamp,+ timestamp=datetime.now(UTC),properties=properties,- process_person_profile=True,)- routed_result.raise_for_status()try:await database_sync_to_async(_emit, thread_sensitive=False)()diff --git a/posthog/temporal/ai_observability/run_trace_evaluation.py b/posthog/temporal/ai_observability/run_trace_evaluation.pyindex 85c265318b31..7cdf585ef29a 100644--- a/posthog/temporal/ai_observability/run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/run_trace_evaluation.py@@ -29,7 +29,7 @@ from posthog.schema import DateRange, LLMTrace, QueryLogTags, TraceQueryfrom posthog.hogql import astfrom posthog.hogql.parser import parse_select-from posthog.api.capture import CaptureInternalError, capture_internal+from posthog.api.capture import CaptureInternalErrorfrom posthog.hogql_queries.ai.ai_table_resolver import query_ai_eventsfrom posthog.hogql_queries.ai.trace_query_runner import TraceQueryRunnerfrom posthog.models.team import Team@@ -67,6 +67,7 @@ from posthog.temporal.ai_observability.run_evaluation import (handle_llm_judge_activity_error,handle_terminal_user_error_result,)+from posthog.temporal.ai_observability.team_capture import capture_internal_for_teamfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.utils import close_db_connections@@ -615,12 +616,6 @@ async def emit_trace_evaluation_event_activity(inputs: EmitTraceEvaluationEventI"""Emit the $ai_evaluation event for a trace-level run, targeting the trace id."""def _emit():- try:- team = Team.objects.get(id=inputs.team_id)- except Team.DoesNotExist:- logger.exception("Team not found", team_id=inputs.team_id)- raise ValueError(f"Team {inputs.team_id} not found")-# No single source event to inherit from, so SOURCE_AI_PROPERTIES_TO_COPY (span/parent# linkage copied in the generation path) intentionally does not apply here.properties = build_evaluation_event_properties(inputs.evaluation, inputs.result, inputs.start_time)@@ -647,16 +642,14 @@ async def emit_trace_evaluation_event_activity(inputs: EmitTraceEvaluationEventI})- capture_result = capture_internal(- token=team.api_token,+ capture_internal_for_team(+ team_id=inputs.team_id,event_name="$ai_evaluation",event_source="llm_analytics_evaluation",distinct_id=inputs.distinct_id,timestamp=datetime.now(UTC),properties=properties,- process_person_profile=True,)- capture_result.raise_for_status()try:await database_sync_to_async(_emit, thread_sensitive=False)()diff --git a/posthog/temporal/ai_observability/team_capture.py b/posthog/temporal/ai_observability/team_capture.pynew file mode 100644index 000000000000..e47d5e4f83bd--- /dev/null+++ b/posthog/temporal/ai_observability/team_capture.py@@ -0,0 +1,100 @@+"""Emitting AI observability events on behalf of a team, without a Postgres read per event.++Every emitted `$ai_evaluation` / `$ai_tag` event needs the team's `api_token` to call+`capture_internal`. Those emit closures run under `database_sync_to_async(thread_sensitive=False)`,+so each one lands on a fresh executor thread and grabs a pooled Postgres connection for a+single-row read — under pool pressure pgbouncer answers with `query_wait_timeout` instead.+`api_token` is effectively static, so cache it per worker process and only pay for the query+once per team per TTL.+"""++import time+import threading+from datetime import datetime+from http import HTTPStatus+from typing import Any++from posthog.api.capture import CaptureInternalError, capture_internal+from posthog.models.team import Team++# Also bounds how long emits keep using a rotated token: capture-rs accepts stale tokens at+# the edge, so rotation is only picked up once this TTL lapses.+TOKEN_CACHE_TTL_SECONDS = 300+# Backstop so a worker seeing a very large number of teams can't grow the cache unbounded.+_MAX_CACHED_TEAMS = 10_000++_AUTH_REJECTED_STATUSES = (HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN)++_lock = threading.Lock()+_cache: dict[int, tuple[float, str]] = {}+++class TeamNotFound(Exception):+ pass+++def get_team_api_token(team_id: int) -> str:+ """Return the team's API token, reading Postgres at most once per TTL per worker process."""+ now = time.monotonic()+ with _lock:+ entry = _cache.get(team_id)+ if entry is not None and entry[0] > now:+ return entry[1]++ token = Team.objects.filter(id=team_id).values_list("api_token", flat=True).first()+ if token is None:+ raise TeamNotFound(f"Team {team_id} not found")++ with _lock:+ if len(_cache) >= _MAX_CACHED_TEAMS:+ # Evict the half closest to expiry rather than clearing, so a full cache doesn't+ # send every team back to Postgres at once.+ for evicted_id in sorted(_cache, key=lambda cached_id: _cache[cached_id][0])[: _MAX_CACHED_TEAMS // 2]:+ del _cache[evicted_id]+ _cache[team_id] = (time.monotonic() + TOKEN_CACHE_TTL_SECONDS, token)+ return token+++def invalidate_team_api_token(team_id: int) -> None:+ """Drop a cached token so the next emit re-reads it from Postgres."""+ with _lock:+ _cache.pop(team_id, None)+++def clear_team_api_token_cache() -> None:+ with _lock:+ _cache.clear()+++def capture_internal_for_team(+ *,+ team_id: int,+ event_name: str,+ event_source: str,+ distinct_id: str,+ timestamp: datetime,+ properties: dict[str, Any],+ process_person_profile: bool = True,+) -> None:+ """Capture one event for a team, raising on a non-2xx capture response."""+ token = get_team_api_token(team_id)+ try:+ result = capture_internal(+ token=token,+ event_name=event_name,+ event_source=event_source,+ distinct_id=distinct_id,+ timestamp=timestamp,+ properties=properties,+ process_person_profile=process_person_profile,+ )+ result.raise_for_status()+ except CaptureInternalError as e:+ # Only an explicit auth rejection means the cached token is stale. Timeouts, 5xx, and+ # billing-limit 402s say nothing about the token, and invalidating on them would+ # reintroduce the per-event Postgres read exactly while capture is unhealthy.+ # capture-rs doesn't verify tokens against Postgres at the edge yet, so until it does,+ # a rotated token recovers via the TTL rather than through this branch.+ if e.status_code in _AUTH_REJECTED_STATUSES:+ invalidate_team_api_token(team_id)+ raisediff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex b8b857d7f971..096739c2f48f 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -345,13 +345,9 @@ class TestRunEvaluationWorkflow:"output_tokens": 18,}- with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get"- ) as mock_team_get:- with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal"- ) as mock_capture:- mock_team_get.return_value = team+ with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token") as mock_team_get:+ with patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture:+ mock_team_get.return_value = team.api_tokenmock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())await emit_evaluation_event_activity(@@ -410,11 +406,11 @@ class TestRunEvaluationWorkflow:)with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get",- return_value=team,+ "posthog.temporal.ai_observability.team_capture.get_team_api_token",+ return_value=team.api_token,):with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal",+ "posthog.temporal.ai_observability.team_capture.capture_internal",return_value=capture_result,):if should_raise:@@ -454,13 +450,9 @@ class TestRunEvaluationWorkflow:"skip_reason": "trace_errored",}- with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get"- ) as mock_team_get:- with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal"- ) as mock_capture:- mock_team_get.return_value = team+ with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token") as mock_team_get:+ with patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture:+ mock_team_get.return_value = team.api_tokenmock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())await emit_evaluation_event_activity(@@ -514,13 +506,9 @@ class TestRunEvaluationWorkflow:"sentiment_message_count": 1,}- with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get"- ) as mock_team_get:- with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal"- ) as mock_capture:- mock_team_get.return_value = team+ with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token") as mock_team_get:+ with patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture:+ mock_team_get.return_value = team.api_tokenmock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())await emit_evaluation_event_activity(@@ -563,13 +551,9 @@ class TestRunEvaluationWorkflow:"skip_reason": "no_user_messages",}- with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get"- ) as mock_team_get:- with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal"- ) as mock_capture:- mock_team_get.return_value = team+ with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token") as mock_team_get:+ with patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture:+ mock_team_get.return_value = team.api_tokenmock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())await emit_evaluation_event_activity(@@ -1019,13 +1003,9 @@ class TestRunEvaluationWorkflow:"allows_na": True,}- with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get"- ) as mock_team_get:- with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal"- ) as mock_capture:- mock_team_get.return_value = team+ with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token") as mock_team_get:+ with patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture:+ mock_team_get.return_value = team.api_tokenmock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())await emit_evaluation_event_activity(@@ -1066,13 +1046,9 @@ class TestRunEvaluationWorkflow:"allows_na": True,}- with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.Team.objects.get"- ) as mock_team_get:- with patch(- "posthog.temporal.ai_observability.evaluation_workflow_activities.capture_internal"- ) as mock_capture:- mock_team_get.return_value = team+ with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token") as mock_team_get:+ with patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture:+ mock_team_get.return_value = team.api_tokenmock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())await emit_evaluation_event_activity(diff --git a/posthog/temporal/ai_observability/test_run_tagger.py b/posthog/temporal/ai_observability/test_run_tagger.pyindex 45cac9e96d27..a206ad5661ad 100644--- a/posthog/temporal/ai_observability/test_run_tagger.py+++ b/posthog/temporal/ai_observability/test_run_tagger.py@@ -382,9 +382,9 @@ class TestRunTaggerWorkflow:event_data = create_mock_event_data(team.id, properties={})- with patch("posthog.temporal.ai_observability.run_tagger.Team.objects.get") as mock_team_get:- with patch("posthog.temporal.ai_observability.run_tagger.capture_internal") as mock_capture:- mock_team_get.return_value = team+ with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token") as mock_team_get:+ with patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture:+ mock_team_get.return_value = team.api_tokenmock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())await emit_tagger_event_activity(@@ -449,8 +449,8 @@ class TestRunTaggerWorkflow:tagger=tagger, event_data=event_data, result=result, start_time=datetime(2024, 1, 1, 12, 0, 0))- with patch("posthog.temporal.ai_observability.run_tagger.Team.objects.get", return_value=team):- with patch("posthog.temporal.ai_observability.run_tagger.capture_internal", return_value=capture_result):+ with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token", return_value=team.api_token):+ with patch("posthog.temporal.ai_observability.team_capture.capture_internal", return_value=capture_result):if should_raise:with pytest.raises(CaptureInternalError):await emit_tagger_event_activity(inputs)diff --git a/posthog/temporal/ai_observability/test_run_trace_evaluation.py b/posthog/temporal/ai_observability/test_run_trace_evaluation.pyindex d0ab1ea97287..3da5c616eb96 100644--- a/posthog/temporal/ai_observability/test_run_trace_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_trace_evaluation.py@@ -561,8 +561,8 @@ class TestEmitTraceEvaluationEventActivity:"output_tokens": 18,}- with patch("posthog.temporal.ai_observability.run_trace_evaluation.Team.objects.get", return_value=team):- with patch("posthog.temporal.ai_observability.run_trace_evaluation.capture_internal") as mock_capture:+ with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token", return_value=team.api_token):+ with patch("posthog.temporal.ai_observability.team_capture.capture_internal") as mock_capture:mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())await emit_trace_evaluation_event_activity(@@ -623,10 +623,8 @@ class TestEmitTraceEvaluationEventActivity:start_time=datetime(2024, 1, 1, 12, 0, 0),)- with patch("posthog.temporal.ai_observability.run_trace_evaluation.Team.objects.get", return_value=team):- with patch(- "posthog.temporal.ai_observability.run_trace_evaluation.capture_internal", return_value=capture_result- ):+ with patch("posthog.temporal.ai_observability.team_capture.get_team_api_token", return_value=team.api_token):+ with patch("posthog.temporal.ai_observability.team_capture.capture_internal", return_value=capture_result):if should_raise:with pytest.raises(CaptureInternalError):await emit_trace_evaluation_event_activity(inputs)@@ -659,8 +657,8 @@ class TestEmitSessionEvaluationEvent:return responsewith (- patch("posthog.temporal.ai_observability.run_trace_evaluation.capture_internal", side_effect=_capture),- patch("posthog.temporal.ai_observability.run_trace_evaluation.Team.objects.get", return_value=MagicMock()),+ patch("posthog.temporal.ai_observability.team_capture.get_team_api_token", return_value="phc_test"),+ patch("posthog.temporal.ai_observability.team_capture.capture_internal", side_effect=_capture),):async_to_sync(emit_trace_evaluation_event_activity)(EmitTraceEvaluationEventInputs(@@ -696,8 +694,8 @@ class TestEmitSessionEvaluationEvent:return responsewith (- patch("posthog.temporal.ai_observability.run_trace_evaluation.capture_internal", side_effect=_capture),- patch("posthog.temporal.ai_observability.run_trace_evaluation.Team.objects.get", return_value=MagicMock()),+ patch("posthog.temporal.ai_observability.team_capture.get_team_api_token", return_value="phc_test"),+ patch("posthog.temporal.ai_observability.team_capture.capture_internal", side_effect=_capture),):async_to_sync(emit_trace_evaluation_event_activity)(EmitTraceEvaluationEventInputs(diff --git a/posthog/temporal/ai_observability/test_team_capture.py b/posthog/temporal/ai_observability/test_team_capture.pynew file mode 100644index 000000000000..48012ecacd6b--- /dev/null+++ b/posthog/temporal/ai_observability/test_team_capture.py@@ -0,0 +1,89 @@+import time+from datetime import UTC, datetime++from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.api.capture import CaptureInternalError+from posthog.models.team import Team+from posthog.temporal.ai_observability.team_capture import (+ TOKEN_CACHE_TTL_SECONDS,+ TeamNotFound,+ capture_internal_for_team,+ get_team_api_token,+)+++def _emit(team_id: int) -> None:+ capture_internal_for_team(+ team_id=team_id,+ event_name="$ai_evaluation",+ event_source="llm_analytics_evaluation",+ distinct_id="user-1",+ timestamp=datetime(2026, 1, 1, tzinfo=UTC),+ properties={},+ )+++class TestTeamCapture(BaseTest):+ def test_token_is_read_from_postgres_only_once_per_team(self):+ assert get_team_api_token(self.team.id) == self.team.api_token+ with self.assertNumQueries(0):+ assert get_team_api_token(self.team.id) == self.team.api_token++ def test_missing_team_raises(self):+ with self.assertRaises(TeamNotFound):+ get_team_api_token(self.team.id + 10_000)++ def test_expired_ttl_picks_up_a_rotated_token(self):+ # Capture accepts stale tokens at the edge, so TTL expiry is the only path through+ # which a rotated token recovers.+ get_team_api_token(self.team.id)+ Team.objects.filter(id=self.team.id).update(api_token="phc_rotated")+ with patch(+ "posthog.temporal.ai_observability.team_capture.time.monotonic",+ return_value=time.monotonic() + TOKEN_CACHE_TTL_SECONDS + 1,+ ):+ assert get_team_api_token(self.team.id) == "phc_rotated"++ def test_auth_rejection_invalidates_the_cached_token(self):+ get_team_api_token(self.team.id)+ with patch(+ "posthog.temporal.ai_observability.team_capture.capture_internal",+ side_effect=CaptureInternalError("unauthorized", status_code=401),+ ):+ with self.assertRaises(CaptureInternalError):+ _emit(self.team.id)++ with patch(+ "posthog.temporal.ai_observability.team_capture.capture_internal",+ return_value=MagicMock(raise_for_status=MagicMock()),+ ) as mock_capture:+ with self.assertNumQueries(1):+ _emit(self.team.id)+ assert mock_capture.call_args[1]["token"] == self.team.api_token++ @parameterized.expand(+ [+ ("billing_limit_402", CaptureInternalError("quota limited", status_code=402)),+ ("capture_5xx", CaptureInternalError("whole-request failure", status_code=502)),+ ("transport_error", CaptureInternalError("timed out", status_code=0)),+ ]+ )+ def test_non_auth_capture_failure_keeps_the_cached_token(self, _name, error):+ get_team_api_token(self.team.id)+ with patch(+ "posthog.temporal.ai_observability.team_capture.capture_internal",+ side_effect=error,+ ):+ with self.assertRaises(CaptureInternalError):+ _emit(self.team.id)++ with patch(+ "posthog.temporal.ai_observability.team_capture.capture_internal",+ return_value=MagicMock(raise_for_status=MagicMock()),+ ):+ with self.assertNumQueries(0):+ _emit(self.team.id)diff --git a/posthog/temporal/common/db_errors.py b/posthog/temporal/common/db_errors.pynew file mode 100644index 000000000000..e377a34d3d34--- /dev/null+++ b/posthog/temporal/common/db_errors.py@@ -0,0 +1,31 @@+from django.db import InterfaceError, OperationalError++# Substrings identifying transient Postgres failures. pgbouncer kills queries that wait too long+# for a backend connection with `query_wait_timeout`, and surfaces dropped/reset backend+# connections as closed or reset connections. Both clear on their own, so a Temporal retry+# resolves them. Deliberately excludes psycopg's generic "connection failed:" prefix, which+# covers every failed connect including persistent misconfiguration (bad credentials,+# nonexistent database, unresolvable host) that must keep reaching error tracking.+_TRANSIENT_DB_ERROR_MARKERS = (+ "query_wait_timeout",+ "server closed the connection unexpectedly",+ "connection reset by peer",+ "the database system is starting up",+ "the database system is shutting down",+)++# SQLSTATE class 57P (operator intervention): the server is shutting down or restarting and+# refusing work while it does, which clears once it comes back. Available on the wrapped+# psycopg error for server-raised failures; connect failures carry no SQLSTATE and fall+# through to the message markers above.+_TRANSIENT_SQLSTATE_PREFIXES = ("57P",)+++def is_transient_db_error(error: BaseException) -> bool:+ if not isinstance(error, OperationalError | InterfaceError):+ return False+ sqlstate = getattr(error.__cause__, "sqlstate", None)+ if isinstance(sqlstate, str) and sqlstate.startswith(_TRANSIENT_SQLSTATE_PREFIXES):+ return True+ message = str(error)+ return any(marker in message for marker in _TRANSIENT_DB_ERROR_MARKERS)diff --git a/posthog/temporal/common/posthog_client.py b/posthog/temporal/common/posthog_client.pyindex 080bc8b3f415..28e08680592c 100644--- a/posthog/temporal/common/posthog_client.py+++ b/posthog/temporal/common/posthog_client.py@@ -16,6 +16,7 @@ from temporalio.worker import (from posthog.egress.transport.transport import EgressBudgetExhaustedfrom posthog.exceptions_capture import ambient_exception_properties+from posthog.temporal.common.db_errors import is_transient_db_errorfrom posthog.temporal.common.errors import NonReportableErrorfrom posthog.temporal.common.interceptor import ALL_TASK_QUEUESfrom posthog.temporal.common.logger import get_write_only_logger@@ -92,6 +93,17 @@ class _PostHogClientActivityInboundInterceptor(ActivityInboundInterceptor):):raiseactivity_info = activity.info()+ # A saturated connection pool clears on its own and Temporal retries the activity, so+ # a burst of them would otherwise mint a fresh error tracking issue per module for a+ # condition nobody can action per-activity. Log it instead, and leave the retry to+ # Temporal — a pool problem that outlives the retries surfaces as a workflow failure.+ if is_transient_db_error(e):+ await logger.awarning(+ "Transient database error in activity %s, leaving retry to Temporal",+ activity_info.activity_type,+ exc_info=e,+ )+ raisecapture_kwargs = {"properties": {# Ambient properties (e.g. warehouse-sources JobContext) first so the explicitdiff --git a/posthog/temporal/tests/common/test_posthog_client_transient_db.py b/posthog/temporal/tests/common/test_posthog_client_transient_db.pynew file mode 100644index 000000000000..23d3b93ca7ef--- /dev/null+++ b/posthog/temporal/tests/common/test_posthog_client_transient_db.py@@ -0,0 +1,81 @@+import pytest+from unittest.mock import AsyncMock, MagicMock, patch++from django.db import InterfaceError, OperationalError++import psycopg.errors+from parameterized import parameterized+from temporalio.worker import ExecuteActivityInput++from posthog.dataclasses import frozen+from posthog.temporal.common.posthog_client import _PostHogClientActivityInboundInterceptor+++def _wrapped_by_django(message: str, cause: Exception) -> OperationalError:+ error = OperationalError(message)+ error.__cause__ = cause+ return error+++@frozen+class _Input:+ team_id: int+++async def _run_and_capture(error: Exception) -> MagicMock:+ next_interceptor = AsyncMock()+ next_interceptor.execute_activity.side_effect = error+ interceptor = _PostHogClientActivityInboundInterceptor(next_interceptor)++ mock_input = MagicMock(spec=ExecuteActivityInput)+ mock_input.args = [_Input(team_id=1)]+ mock_input.fn = _run_and_capture++ with (+ patch("posthog.temporal.common.posthog_client.api_key", "phc_test"),+ patch("posthog.temporal.common.posthog_client.activity.info", return_value=MagicMock()),+ patch("posthog.temporal.common.posthog_client.capture_exception") as mock_capture,+ ):+ with pytest.raises(type(error)):+ await interceptor.execute_activity(mock_input)+ return mock_capture+++class TestTransientDatabaseErrorReporting:+ @parameterized.expand(+ [+ ("pool_wait_timeout", OperationalError("query_wait_timeout")),+ ("connection_dropped", OperationalError("server closed the connection unexpectedly")),+ ("interface_error", InterfaceError("connection reset by peer")),+ (+ "server_shutdown_sqlstate",+ _wrapped_by_django(+ "terminating connection due to administrator command",+ psycopg.errors.AdminShutdown("terminating connection due to administrator command"),+ ),+ ),+ ]+ )+ async def test_transient_db_errors_are_not_reported(self, _name, error):+ # Temporal retries the activity, so a burst of pool timeouts must not mint an issue each.+ mock_capture = await _run_and_capture(error)+ mock_capture.assert_not_called()++ @parameterized.expand(+ [+ ("deadlock", OperationalError("deadlock detected")),+ # psycopg prefixes every failed connect with "connection failed:", so persistent+ # misconfiguration must not be swallowed as transient.+ (+ "bad_credentials",+ OperationalError(+ 'connection failed: connection to server at "127.0.0.1", port 6432 failed: '+ 'FATAL: password authentication failed for user "posthog"'+ ),+ ),+ ]+ )+ async def test_other_database_errors_are_still_reported(self, _name, error):+ mock_capture = await _run_and_capture(error)+ mock_capture.assert_called_once()