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(replay-vision): evict stale connections before async activities run (#105551)

Tue Haulund32e87cf0610d
diff --git a/products/replay_vision/backend/temporal/activities/observation_media.py b/products/replay_vision/backend/temporal/activities/observation_media.py
index 89fb46cc3d28..f876ec01d8ac 100644
--- a/products/replay_vision/backend/temporal/activities/observation_media.py
+++ b/products/replay_vision/backend/temporal/activities/observation_media.py
@@ -71,7 +71,12 @@ def _pick_video_time_s(
async def prepare_observation_thumbnail_activity(inputs: ObservationMediaInputs) -> PrepareObservationThumbnailOutput:
"""Pick the frame to cut and create the `is_system` PNG asset the Node activity uploads into."""
media_inputs = inputs
- asset = await ExportedAsset.objects.aget(pk=media_inputs.analysis_asset_id, team_id=media_inputs.team_id)
+ try:
+ asset = await ExportedAsset.objects.aget(pk=media_inputs.analysis_asset_id, team_id=media_inputs.team_id)
+ except ExportedAsset.DoesNotExist as error:
+ raise ApplicationError(
+ f"Analysis asset {media_inputs.analysis_asset_id} is gone", non_retryable=True
+ ) from error
if not asset.content_location:
# The analysis render is long finished by now, so an empty location is a lost object, not a race.
raise ApplicationError(f"Analysis asset {asset.id} has no rendered object", non_retryable=True)
diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.py
index cc5d1b85923c..c1e72c781602 100644
--- a/products/replay_vision/backend/temporal/constants.py
+++ b/products/replay_vision/backend/temporal/constants.py
@@ -1,7 +1,7 @@
import datetime as dt
from uuid import UUID
-from temporalio.common import Priority
+from temporalio.common import Priority, RetryPolicy
APPLY_SCANNER_WORKFLOW_NAME = "replay-vision-apply-scanner"
SWEEP_SCANNER_WORKFLOW_NAME = "replay-vision-sweep-scanner"
@@ -19,6 +19,17 @@ ADMISSION_BUDGET_TTL = dt.timedelta(seconds=15)
# row is stranded in `running` until the reaper's cutoff below.
APPLY_SCANNER_EXECUTION_TIMEOUT = dt.timedelta(minutes=110)
+# Retry policy for the short Postgres writes that move an observation or its media between states.
+STATE_ACTIVITY_RETRY = RetryPolicy(
+ initial_interval=dt.timedelta(seconds=1),
+ maximum_interval=dt.timedelta(seconds=10),
+ maximum_attempts=5,
+)
+
+# Bounds each state write's whole retry chain, backoff included, so the failure path provably fits inside
+# APPLY_SCANNER_EXECUTION_TIMEOUT (see the arithmetic on that constant).
+STATE_ACTIVITY_SCHEDULE_TO_CLOSE = dt.timedelta(minutes=3)
+
def on_demand_priority(team_id: int) -> Priority:
"""Task priority for user-initiated starts (1 = highest of 5, default 3): Temporal inherits it into
diff --git a/products/replay_vision/backend/temporal/decorators.py b/products/replay_vision/backend/temporal/decorators.py
index ba2e246ca371..ecd39f268893 100644
--- a/products/replay_vision/backend/temporal/decorators.py
+++ b/products/replay_vision/backend/temporal/decorators.py
@@ -6,6 +6,10 @@ from collections.abc import Callable
from functools import wraps
from typing import Any, TypeVar, cast
+from django.conf import settings
+
+from asgiref.sync import sync_to_async
+
from posthog.temporal.common.utils import close_stale_db_connections
from products.replay_vision.backend.temporal.metrics import record_activity_duration, record_side_effect_failure
@@ -33,6 +37,10 @@ def track_activity(name: str | None = None, side_effect: str | None = None) -> C
@wraps(fn)
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
+ # Async ORM calls run on the same long-lived thread, so the same dead connections pile up there.
+ # Skipped in tests, as close_db_connections does, because it touches Django connections in tests without DB access.
+ if not settings.TEST:
+ await sync_to_async(close_stale_db_connections)()
started = time.monotonic()
try:
result = await fn(*args, **kwargs)
diff --git a/products/replay_vision/backend/temporal/media_workflow.py b/products/replay_vision/backend/temporal/media_workflow.py
index f98b21590502..5239f6941e27 100644
--- a/products/replay_vision/backend/temporal/media_workflow.py
+++ b/products/replay_vision/backend/temporal/media_workflow.py
@@ -12,6 +12,7 @@ with wf.unsafe.imports_passed_through():
finalize_observation_thumbnail_activity,
prepare_observation_thumbnail_activity,
)
+ from products.replay_vision.backend.temporal.constants import STATE_ACTIVITY_RETRY, STATE_ACTIVITY_SCHEDULE_TO_CLOSE
from products.replay_vision.backend.temporal.media_types import (
MEDIA_WORKFLOW_NAME,
THUMBNAIL_SCHEDULE_TO_CLOSE,
@@ -22,7 +23,6 @@ with wf.unsafe.imports_passed_through():
)
_THUMBNAIL_TIMEOUT = dt.timedelta(minutes=5)
-_STATE_RETRY = common.RetryPolicy(maximum_attempts=3)
# Nothing retries a lost poster later, so this chain has to outlast a rasterizer backlog or outage.
_THUMBNAIL_RETRY = common.RetryPolicy(
initial_interval=dt.timedelta(seconds=20),
@@ -43,7 +43,8 @@ class ObservationMediaWorkflow(PostHogWorkflow):
prepare_observation_thumbnail_activity,
inputs,
start_to_close_timeout=dt.timedelta(seconds=30),
- retry_policy=_STATE_RETRY,
+ schedule_to_close_timeout=STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
+ retry_policy=STATE_ACTIVITY_RETRY,
)
raw_result = await wf.execute_activity(
@@ -66,5 +67,6 @@ class ObservationMediaWorkflow(PostHogWorkflow):
result=ExtractThumbnailActivityOutput.model_validate(raw_result),
),
start_to_close_timeout=dt.timedelta(seconds=30),
- retry_policy=_STATE_RETRY,
+ schedule_to_close_timeout=STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
+ retry_policy=STATE_ACTIVITY_RETRY,
)
diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.py
index ce65c619353c..bcdd8cc02da5 100644
--- a/products/replay_vision/backend/temporal/workflow.py
+++ b/products/replay_vision/backend/temporal/workflow.py
@@ -48,7 +48,11 @@ from products.replay_vision.backend.temporal.activities import (
mark_observation_succeeded_activity,
upload_video_to_gemini_activity,
)
-from products.replay_vision.backend.temporal.constants import APPLY_SCANNER_WORKFLOW_NAME
+from products.replay_vision.backend.temporal.constants import (
+ APPLY_SCANNER_WORKFLOW_NAME,
+ STATE_ACTIVITY_RETRY,
+ STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
+)
from products.replay_vision.backend.temporal.errors import (
INELIGIBLE_SESSION_ERROR_TYPE,
SCANNER_FAILURE_ERROR_TYPE,
@@ -93,16 +97,6 @@ from products.replay_vision.backend.temporal.types import (
UploadVideoToGeminiInputs,
)
-_STATE_ACTIVITY_RETRY = common.RetryPolicy(
- initial_interval=dt.timedelta(seconds=1),
- maximum_interval=dt.timedelta(seconds=10),
- maximum_attempts=5,
-)
-
-# Bounds each state write's whole retry chain, backoff included, so the failure path provably fits inside
-# APPLY_SCANNER_EXECUTION_TIMEOUT (see the arithmetic on that constant).
-_STATE_ACTIVITY_SCHEDULE_TO_CLOSE = dt.timedelta(minutes=3)
-
# Create's `ValueError` paths (scanner missing, user not in org) won't recover on retry, and the
# re-raised `IntegrityError`s (FK / CHECK violations; the unique-violation case is handled inside
# the activity) are deterministic — retrying them for the full window would only amplify load.
@@ -302,7 +296,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):
backfill_id=inputs.backfill_id,
),
start_to_close_timeout=dt.timedelta(seconds=30),
- schedule_to_close_timeout=_STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
+ schedule_to_close_timeout=STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
retry_policy=_CREATE_OBSERVATION_RETRY,
)
if not create_result.was_created or create_result.observation_id is None:
@@ -318,8 +312,8 @@ class ApplyScannerWorkflow(PostHogWorkflow):
mark_observation_running_activity,
MarkObservationRunningInputs(observation_id=observation_id),
start_to_close_timeout=dt.timedelta(seconds=30),
- schedule_to_close_timeout=_STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
- retry_policy=_STATE_ACTIVITY_RETRY,
+ schedule_to_close_timeout=STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
+ retry_policy=STATE_ACTIVITY_RETRY,
)
self._advance_phase("fetching")
asset_result = await self._fetch_and_ensure_asset(inputs, observation_id)
@@ -419,16 +413,16 @@ class ApplyScannerWorkflow(PostHogWorkflow):
),
),
start_to_close_timeout=dt.timedelta(seconds=30),
- schedule_to_close_timeout=_STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
- retry_policy=_STATE_ACTIVITY_RETRY,
+ schedule_to_close_timeout=STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
+ retry_policy=STATE_ACTIVITY_RETRY,
)
try:
await wf.execute_activity(
emit_observation_event_activity,
EmitObservationEventInputs(observation_id=observation_id, model_output=call_output.model_output),
start_to_close_timeout=dt.timedelta(seconds=30),
- schedule_to_close_timeout=_STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
- retry_policy=_STATE_ACTIVITY_RETRY,
+ schedule_to_close_timeout=STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
+ retry_policy=STATE_ACTIVITY_RETRY,
)
except Exception:
wf.logger.exception("Event emission failed for succeeded observation %s", observation_id)
@@ -478,7 +472,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):
ensure_session_asset_activity,
EnsureSessionAssetInputs(team_id=inputs.team_id, session_id=inputs.session_id),
start_to_close_timeout=dt.timedelta(seconds=30),
- schedule_to_close_timeout=_STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
+ schedule_to_close_timeout=STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
retry_policy=_ENSURE_ASSET_RETRY,
)
if wf.patched("replay-vision-session-network-2026-09"):
@@ -622,8 +616,8 @@ class ApplyScannerWorkflow(PostHogWorkflow):
error_reason=_encode_reason(kind, message),
),
start_to_close_timeout=dt.timedelta(seconds=30),
- schedule_to_close_timeout=_STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
- retry_policy=_STATE_ACTIVITY_RETRY,
+ schedule_to_close_timeout=STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
+ retry_policy=STATE_ACTIVITY_RETRY,
)
async def _mark_ineligible(self, observation_id: UUID, scanner_type: ScannerType, kind: str, message: str) -> None:
@@ -635,8 +629,8 @@ class ApplyScannerWorkflow(PostHogWorkflow):
error_reason=_encode_reason(kind, message),
),
start_to_close_timeout=dt.timedelta(seconds=30),
- schedule_to_close_timeout=_STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
- retry_policy=_STATE_ACTIVITY_RETRY,
+ schedule_to_close_timeout=STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
+ retry_policy=STATE_ACTIVITY_RETRY,
)
async def _apply_scanner_side_effects(
diff --git a/products/replay_vision/backend/tests/test_observation_media.py b/products/replay_vision/backend/tests/test_observation_media.py
index ba0d58ce0682..e52b8325e266 100644
--- a/products/replay_vision/backend/tests/test_observation_media.py
+++ b/products/replay_vision/backend/tests/test_observation_media.py
@@ -1,6 +1,7 @@
from datetime import datetime, timedelta
from typing import Any
+import pytest
from posthog.test.base import BaseTest
from django.conf import settings
@@ -8,6 +9,7 @@ from django.utils import timezone
from asgiref.sync import async_to_sync
from parameterized import parameterized
+from temporalio.exceptions import ApplicationError
from posthog.models.utils import uuid7
@@ -119,6 +121,15 @@ class TestObservationMedia(BaseTest):
assert prepared.activity_input.video_time_s == expected_s
assert prepared.video_start_ms == int(expected_s * 1000)
+ def test_a_missing_analysis_asset_fails_without_retrying(self) -> None:
+ analysis_asset_id = self.analysis_asset.id
+ self.analysis_asset.delete()
+
+ with pytest.raises(ApplicationError) as caught:
+ self._prepare(analysis_asset_id=analysis_asset_id)
+
+ assert caught.value.non_retryable is True
+
def test_finalize_links_the_rendered_object_to_the_observation(self) -> None:
prepared = self._prepare()