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): retry contended scanner admissions instead of queueing in Postgres (#88861)

Kim Svatos Dugan7191a9aa2823
diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.py
index 94c30858873d..72ea4a83c719 100644
--- a/products/replay_vision/backend/quota.py
+++ b/products/replay_vision/backend/quota.py
@@ -307,10 +307,11 @@ def compute_scanner_budgets(
if period is None:
period = current_period_bounds(organization_id)
# Limits are read here, not passed in: a caller that forgot them would silently disable enforcement.
+ # `all_origins`: a capped inline scanner must resolve its limit here, or its budget reads as uncapped.
# nosemgrep: idor-lookup-without-team (org-level aggregation, the pk__in list is co-filtered by team__organization_id, so a scanner id outside this org matches nothing)
- scanner_rows = ReplayScanner.objects.filter(team__organization_id=organization_id, pk__in=scanner_ids).values_list(
- "id", "credit_limit", "model"
- )
+ scanner_rows = ReplayScanner.all_origins.filter(
+ team__organization_id=organization_id, pk__in=scanner_ids
+ ).values_list("id", "credit_limit", "model")
configs = {scanner_id: (limit, model) for scanner_id, limit, model in scanner_rows}
# Almost every scanner is uncapped, so the spend aggregates run only for the capped ones; the
# rest report zero usage, and `blocked` is always False without a limit.
diff --git a/products/replay_vision/backend/temporal/activities/create_observation.py b/products/replay_vision/backend/temporal/activities/create_observation.py
index ba50918fba8b..33c5c472067d 100644
--- a/products/replay_vision/backend/temporal/activities/create_observation.py
+++ b/products/replay_vision/backend/temporal/activities/create_observation.py
@@ -1,7 +1,6 @@
-import time
from typing import Any
-from django.db import IntegrityError, transaction
+from django.db import IntegrityError, OperationalError, connection, transaction
from django.utils import timezone
import psycopg.errors
@@ -17,10 +16,11 @@ from products.replay_vision.backend.models.replay_scanner import ReplayScanner
from products.replay_vision.backend.models.replay_scanner_backfill import BackfillStatus, ReplayScannerBackfill
from products.replay_vision.backend.quota import compute_scanner_budget, current_period_bounds, quota_state
from products.replay_vision.backend.temporal.decorators import track_activity
+from products.replay_vision.backend.temporal.errors import SCANNER_ADMISSION_BUSY_ERROR_TYPE
from products.replay_vision.backend.temporal.metrics import (
record_consent_skip,
record_quota_exhausted_skip,
- record_scanner_admission_lock_wait,
+ record_scanner_admission_busy,
record_scanner_limit_reached,
)
from products.replay_vision.backend.temporal.snapshots import BackfillScannerSnapshot, ScannerSnapshot
@@ -35,16 +35,23 @@ def _build_scanner_snapshot(scanner: ReplayScanner) -> dict[str, Any]:
@track_activity()
def create_observation_activity(inputs: CreateObservationInputs) -> CreateObservationOutput:
"""Snapshot the full scanner state and INSERT the row in `pending`; UNIQUE conflicts return `was_created=False` unless the row is this workflow's own lost-result insert, which is reclaimed."""
+ release_claim = True
try:
return _create_observation(inputs)
+ except BaseException as e:
+ # A busy admission keeps its claim: the retry lands in seconds, and decaying the claim here
+ # would let dispatchers admit more applies into the very contention being backed off from.
+ release_claim = not (isinstance(e, ApplicationError) and e.type == SCANNER_ADMISSION_BUSY_ERROR_TYPE)
+ raise
finally:
- # Every exit resolves the row's existence, so the enqueue claim is done; TTL covers a crash.
- release_enqueue_claim(
- team_id=inputs.team_id,
- scanner_id=inputs.scanner_id,
- workflow_id=inputs.workflow_id,
- backfill_id=inputs.backfill_id,
- )
+ # Every non-busy exit resolves the row's existence, so the claim is done; TTL covers a crash.
+ if release_claim:
+ release_enqueue_claim(
+ team_id=inputs.team_id,
+ scanner_id=inputs.scanner_id,
+ workflow_id=inputs.workflow_id,
+ backfill_id=inputs.backfill_id,
+ )
def _reclaim_own_pending_insert(inputs: CreateObservationInputs) -> CreateObservationOutput | None:
@@ -173,12 +180,24 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOut
# Capped scanners serialize admissions on the row lock so concurrent applies cannot overshoot
# the cap; uncapped scanners keep the lock-free path. The limit is re-read under the lock.
if scanner.credit_limit is not None:
- lock_started = time.monotonic()
+ # A short lock_timeout instead of NOWAIT: a contended admission fails fast into the
+ # activity's own backoff instead of camping in Postgres's lock queue, where every
+ # waiter holds an open transaction and an attempt killed at start_to_close leaves its
+ # statement waiting server-side. The 2s grace absorbs the brief blocking holders of
+ # this row (scanner save(), prompt-suggestion apply), which NOWAIT would turn into
+ # instant admission failures. Admissions stay fully serialized.
+ with connection.cursor() as cursor:
+ # SET LOCAL reverts when the transaction ends; lock_timeout raises the same
+ # LockNotAvailable the handler below maps to the retryable busy error.
+ cursor.execute("SET LOCAL lock_timeout = '2s'")
locked = (
- ReplayScanner.objects.select_for_update().filter(pk=scanner.pk).only("pk", "credit_limit").first()
+ # By-pk, so it must resolve whatever origin the row is; `objects` would lock
+ # nothing for an inline scanner and silently skip its budget check.
+ ReplayScanner.all_origins.select_for_update(of=("self",))
+ .filter(pk=scanner.pk)
+ .only("pk", "credit_limit")
+ .first()
)
- # Admissions on a busy capped scanner serialize here; the wait is visible, not guessed at.
- record_scanner_admission_lock_wait(time.monotonic() - lock_started)
if locked is not None and locked.credit_limit is not None:
scanner_budget = compute_scanner_budget(scanner, period)
# Priced from `priced_model` (the frozen snapshot model for backfills), matching
@@ -222,6 +241,22 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOut
session_id=inputs.session_id,
**row_fields,
)
+ except OperationalError as e:
+ if not isinstance(e.__cause__, psycopg.errors.LockNotAvailable):
+ raise
+ record_scanner_admission_busy(scanner.scanner_type)
+ activity.logger.info(
+ "Scanner admission lock busy; deferring to activity retry",
+ extra={
+ "scanner_id": str(inputs.scanner_id),
+ "team_id": inputs.team_id,
+ "session_id": inputs.session_id,
+ },
+ )
+ raise ApplicationError(
+ "Scanner admission lock busy; retried with backoff",
+ type=SCANNER_ADMISSION_BUSY_ERROR_TYPE,
+ ) from e
except IntegrityError as e:
# Only swallow the dedup case; FK / CHECK violations should fail the activity.
if not isinstance(e.__cause__, psycopg.errors.UniqueViolation):
diff --git a/products/replay_vision/backend/temporal/errors.py b/products/replay_vision/backend/temporal/errors.py
index 345109f47fc6..59336cd5e71c 100644
--- a/products/replay_vision/backend/temporal/errors.py
+++ b/products/replay_vision/backend/temporal/errors.py
@@ -6,6 +6,7 @@ from products.replay_vision.backend.error_kinds import FailureKind, IneligibleSe
__all__ = [
"INELIGIBLE_SESSION_ERROR_TYPE",
+ "SCANNER_ADMISSION_BUSY_ERROR_TYPE",
"SCANNER_FAILURE_ERROR_TYPE",
"ConsentWithdrawnError",
"FailureKind",
@@ -18,6 +19,8 @@ __all__ = [
# workflow can dispatch on them without parsing exception messages.
INELIGIBLE_SESSION_ERROR_TYPE = "IneligibleSession"
SCANNER_FAILURE_ERROR_TYPE = "ScannerFailure"
+# Always retryable: the create activity's backoff spreads contenders that Postgres would otherwise queue.
+SCANNER_ADMISSION_BUSY_ERROR_TYPE = "ScannerAdmissionBusy"
class _KindedApplicationError(ApplicationError):
diff --git a/products/replay_vision/backend/temporal/metrics.py b/products/replay_vision/backend/temporal/metrics.py
index 980479f82a41..87060a0a7d89 100644
--- a/products/replay_vision/backend/temporal/metrics.py
+++ b/products/replay_vision/backend/temporal/metrics.py
@@ -84,10 +84,12 @@ REPLAY_VISION_SWEEP_OUTCOMES = Counter(
["outcome"],
)
-REPLAY_VISION_SCANNER_ADMISSION_LOCK_WAIT = Histogram(
- "replay_vision_scanner_admission_lock_wait_seconds",
- "Time spent acquiring the scanner row lock that serializes capped admissions",
- buckets=(0.005, 0.025, 0.1, 0.5, 1.0, 2.5, 5.0, 10.0),
+# The admission lock is taken NOWAIT, so lock waits cannot exist to measure; contention shows up
+# here instead, as attempts that found the row held and deferred to the activity's retry policy.
+REPLAY_VISION_SCANNER_ADMISSION_BUSY = Counter(
+ "replay_vision_scanner_admission_busy_total",
+ "Capped-scanner admissions that found the row lock held and were deferred to the activity retry",
+ ["scanner_type"],
)
REPLAY_VISION_SCANNER_LIMIT_REACHED = Counter(
@@ -203,9 +205,9 @@ def record_quota_exhausted_skip(scanner_type: str) -> None:
_otel.record_counter_twin(REPLAY_VISION_QUOTA_EXHAUSTED_SKIPS, 1, {"scanner_type": scanner_type})
-def record_scanner_admission_lock_wait(seconds: float) -> None:
- REPLAY_VISION_SCANNER_ADMISSION_LOCK_WAIT.observe(seconds)
- _otel.record_histogram_twin(REPLAY_VISION_SCANNER_ADMISSION_LOCK_WAIT, seconds, {})
+def record_scanner_admission_busy(scanner_type: str) -> None:
+ REPLAY_VISION_SCANNER_ADMISSION_BUSY.labels(scanner_type=scanner_type).inc()
+ _otel.record_counter_twin(REPLAY_VISION_SCANNER_ADMISSION_BUSY, 1, {"scanner_type": scanner_type})
def record_scanner_limit_reached(surface: str) -> None:
diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.py
index c80417982c92..a093ea244089 100644
--- a/products/replay_vision/backend/temporal/workflow.py
+++ b/products/replay_vision/backend/temporal/workflow.py
@@ -91,12 +91,17 @@ _STATE_ACTIVITY_RETRY = common.RetryPolicy(
# 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.
+# 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.
+# Unlimited attempts, bounded by schedule_to_close (3m): a ScannerAdmissionBusy rejection must be
+# able to retry across a whole contention wave, or every admission in the wave becomes a dropped
+# scan — the sweep watermark and backfill cursor advance past a session with no observation row.
_CREATE_OBSERVATION_RETRY = common.RetryPolicy(
initial_interval=dt.timedelta(seconds=1),
- maximum_interval=dt.timedelta(seconds=10),
- maximum_attempts=5,
- non_retryable_error_types=["ValueError"],
+ maximum_interval=dt.timedelta(seconds=15),
+ maximum_attempts=0,
+ non_retryable_error_types=["ValueError", "IntegrityError"],
)
# Generous because fetch's deterministic errors are non_retryable; this budget only covers transient infra (e.g. ClickHouse at capacity).
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index e5cc8d22f4b8..f9678eeb5753 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -8,7 +8,7 @@ import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from django.conf import settings
-from django.db import IntegrityError, connections
+from django.db import IntegrityError, OperationalError, connections, transaction
from django.utils import timezone
import httpx
@@ -82,6 +82,7 @@ from products.replay_vision.backend.temporal.activities.observation_state import
from products.replay_vision.backend.temporal.activities.upload_video_to_gemini import upload_video_to_gemini_activity
from products.replay_vision.backend.temporal.errors import (
INELIGIBLE_SESSION_ERROR_TYPE,
+ SCANNER_ADMISSION_BUSY_ERROR_TYPE,
SCANNER_FAILURE_ERROR_TYPE,
ConsentWithdrawnError,
FailureKind,
@@ -556,6 +557,12 @@ class TestCreateObservationActivity:
workflow_id=f"wf-{session_id}",
)
).was_created
+ except ApplicationError as e:
+ if e.type != SCANNER_ADMISSION_BUSY_ERROR_TYPE:
+ raise
+ # The NOWAIT lock refused the loser outright; in production Temporal retries it and the
+ # re-run reads the winner's spend. Either way the cap held: nothing was admitted.
+ created[session_id] = False
finally:
# Dropping the worker's own connection avoids stranding its lock transaction past teardown.
connections.close_all()
@@ -603,6 +610,81 @@ class TestCreateObservationActivity:
assert sorted(created.values()) == [True, True]
assert ReplayObservation.objects.filter(scanner=scanner, status=ObservationStatus.PENDING).count() == 2
+ def test_contended_admission_fails_fast_as_retryable_busy_and_keeps_its_claim(self) -> None:
+ # A held scanner row must map to a retryable ScannerAdmissionBusy, not surface as a raw
+ # OperationalError (which nothing marks retryable-by-design) — and the enqueue claim must
+ # survive so the in-flight caps keep counting the retrying apply.
+ scanner = _make_scanner(credit_limit=100)
+ lock_taken = threading.Event()
+ release_lock = threading.Event()
+
+ def hold_scanner_lock() -> None:
+ try:
+ with transaction.atomic():
+ ReplayScanner.all_origins.select_for_update().filter(pk=scanner.pk).first()
+ lock_taken.set()
+ release_lock.wait(timeout=30)
+ finally:
+ connections.close_all()
+
+ holder = threading.Thread(target=hold_scanner_lock)
+ holder.start()
+ assert lock_taken.wait(timeout=30)
+ try:
+ with (
+ patch(
+ "products.replay_vision.backend.temporal.activities.create_observation.release_enqueue_claim"
+ ) as release,
+ pytest.raises(ApplicationError) as err,
+ ):
+ create_observation_activity(
+ CreateObservationInputs(
+ scanner_id=scanner.id,
+ team_id=scanner.team_id,
+ session_id="sess-busy",
+ triggered_by=ObservationTrigger.SCHEDULE,
+ triggered_by_user_id=None,
+ workflow_id="wf-busy",
+ )
+ )
+ finally:
+ release_lock.set()
+ holder.join(timeout=30)
+
+ assert err.value.type == SCANNER_ADMISSION_BUSY_ERROR_TYPE
+ assert err.value.non_retryable is False
+ release.assert_not_called()
+ assert not ReplayObservation.objects.filter(scanner=scanner, session_id="sess-busy").exists()
+
+ def test_non_lock_operational_error_propagates_and_releases_the_claim(self) -> None:
+ # The busy guard keys on LockNotAvailable alone: a statement timeout must still fail the
+ # attempt as an OperationalError (and give the claim back), not masquerade as retry-forever busy.
+ scanner = _make_scanner(credit_limit=100)
+ error = OperationalError("canceling statement due to statement timeout")
+ error.__cause__ = psycopg.errors.QueryCanceled()
+
+ with (
+ patch(
+ "products.replay_vision.backend.temporal.activities.create_observation.compute_scanner_budget",
+ side_effect=error,
+ ),
+ patch(
+ "products.replay_vision.backend.temporal.activities.create_observation.release_enqueue_claim"
+ ) as release,
+ pytest.raises(OperationalError),
+ ):
+ create_observation_activity(
+ CreateObservationInputs(
+ scanner_id=scanner.id,
+ team_id=scanner.team_id,
+ session_id="sess-timeout",
+ triggered_by=ObservationTrigger.SCHEDULE,
+ triggered_by_user_id=None,
+ workflow_id="wf-timeout",
+ )
+ )
+ release.assert_called_once()
+
def test_concurrent_admissions_for_two_capped_scanners_do_not_serialize_each_other(self) -> None:
# The admission lock is per scanner row: two different capped scanners on one team must both
# admit their own observation, with no cross-scanner budget bleed or lock coupling.