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): make in-flight cap admission race-safe with atomic enqueue claims (#73112)

Hayne Ryu88808510c55d
diff --git a/products/replay_vision/backend/api/observations.py b/products/replay_vision/backend/api/observations.py
index eff5fc1f0391..2ae5b5c5695a 100644
--- a/products/replay_vision/backend/api/observations.py
+++ b/products/replay_vision/backend/api/observations.py
@@ -18,7 +18,7 @@ from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema
from pydantic import ValidationError as PydanticValidationError
from rest_framework import mixins, serializers, status, viewsets
from rest_framework.decorators import action
-from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
+from rest_framework.exceptions import NotFound, PermissionDenied, Throttled, ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
@@ -859,6 +859,9 @@ class ReplayObservationViewSet(
ReplayObservation.objects.filter(pk=original_pk, team_id=observation.team_id).update(
created_at=original_created_at
)
+ if outcome is WorkflowStartOutcome.CAPPED:
+ # The pre-check above passed on a snapshot; the atomic claim is the authoritative gate.
+ raise Throttled(detail="This team is at its in-flight observation limit. Try again in a few minutes.")
if outcome is WorkflowStartOutcome.ALREADY_RUNNING:
# The prior run is still closing, so its deterministic id blocks the restart and no new row will appear.
return Response(
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 6993977b124b..810d3cd36640 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -12,7 +12,7 @@ from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema
from pydantic import ValidationError as PydanticValidationError
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
-from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
+from rest_framework.exceptions import NotFound, PermissionDenied, Throttled, ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
@@ -40,6 +40,10 @@ from products.replay_vision.backend.api.trigger import (
)
from products.replay_vision.backend.billing import observation_credits_case, observation_credits_for_model
from products.replay_vision.backend.digest import provision_scanner_digest
+from products.replay_vision.backend.enqueue_claims import (
+ pending_enqueue_claims_for_scanner,
+ pending_enqueue_claims_for_team,
+)
from products.replay_vision.backend.feature_flag import ReplayVisionEnabledPermission, is_replay_vision_actions_enabled
from products.replay_vision.backend.feedback_themes import cached_feedback_themes
from products.replay_vision.backend.impact import (
@@ -1086,6 +1090,9 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
workflow_id, outcome = start_apply_scanner_workflow(
scanner, session_id, triggered_by_user_id=user.id, trigger=ObservationTrigger.ON_DEMAND
)
+ if outcome is WorkflowStartOutcome.CAPPED:
+ # The pre-check above passed on a snapshot; the atomic claim is the authoritative gate.
+ raise Throttled(detail="This team is at its in-flight observation limit. Try again in a few minutes.")
if outcome is WorkflowStartOutcome.FAILED:
return Response(
{"error": "Failed to start observation workflow"},
@@ -1125,7 +1132,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
# in-flight caps and the remaining monthly quota bounds it; the loser names the skip reason so
# the user knows which limit they hit. Decrementing a local counter as we start models each new
# in-flight row without re-querying (a started scan consumes exactly one slot).
- max_starts, skip_reason = self._bulk_observe_headroom(scanner)
+ max_starts, skip_reason, team_rows, scanner_rows = self._bulk_observe_headroom(scanner)
results: list[dict[str, str]] = []
started = 0
for session_id in session_ids:
@@ -1133,7 +1140,14 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
results.append({"session_id": session_id, "scan_outcome": skip_reason})
continue
workflow_id, outcome = start_apply_scanner_workflow(
- scanner, session_id, triggered_by_user_id=user.id, trigger=ObservationTrigger.ON_DEMAND
+ scanner,
+ session_id,
+ triggered_by_user_id=user.id,
+ trigger=ObservationTrigger.ON_DEMAND,
+ # Row counts are this request's snapshot; the atomic claim inside makes racing
+ # requests visible to each other, which the snapshot alone cannot.
+ team_in_flight_rows=team_rows,
+ scanner_in_flight_rows=scanner_rows,
)
if outcome is WorkflowStartOutcome.STARTED:
started += 1
@@ -1141,6 +1155,11 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
elif outcome is WorkflowStartOutcome.ALREADY_RUNNING:
# Already in flight — counted in the caps already, so it consumes no new headroom.
results.append({"session_id": session_id, "scan_outcome": "already_running"})
+ elif outcome is WorkflowStartOutcome.CAPPED:
+ # A racing request consumed the remaining slots, so the in-flight cap binds the rest.
+ results.append({"session_id": session_id, "scan_outcome": "skipped_limit"})
+ max_starts = started
+ skip_reason = "skipped_limit"
else:
results.append({"session_id": session_id, "scan_outcome": "failed"})
@@ -1149,15 +1168,17 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
status=status.HTTP_202_ACCEPTED,
)
- def _bulk_observe_headroom(self, scanner: ReplayScanner) -> tuple[int, str]:
- """(max_starts, skip_reason): how many new scans can start, and the reason once that's used up."""
+ def _bulk_observe_headroom(self, scanner: ReplayScanner) -> tuple[int, str, int, int]:
+ """(max_starts, skip_reason, team_rows, scanner_rows): how many new scans can start, the
+ reason once that's used up, and the row counts reused by the per-start slot claims."""
team_in_flight = ReplayObservation.in_flight_for_team(self.team_id).count()
scanner_in_flight = ReplayObservation.in_flight_for_team(self.team_id).filter(scanner_id=scanner.id).count()
+ # Enqueued-but-not-yet-persisted scans hold claims instead of rows.
in_flight_limit = max(
0,
min(
- MAX_IN_FLIGHT_APPLIES_PER_SCANNER - scanner_in_flight,
- MAX_IN_FLIGHT_APPLIES_PER_TEAM - team_in_flight,
+ MAX_IN_FLIGHT_APPLIES_PER_SCANNER - scanner_in_flight - pending_enqueue_claims_for_scanner(scanner.id),
+ MAX_IN_FLIGHT_APPLIES_PER_TEAM - team_in_flight - pending_enqueue_claims_for_team(self.team_id),
),
)
snapshot = compute_quota_snapshot(self.team.organization_id)
@@ -1166,8 +1187,8 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
quota_limit = in_flight_limit if snapshot.remaining is None else (snapshot.remaining // cost if cost else 0)
# Report quota as the reason only when it's the strictly tighter limit.
if quota_limit < in_flight_limit:
- return quota_limit, "skipped_quota"
- return in_flight_limit, "skipped_limit"
+ return quota_limit, "skipped_quota", team_in_flight, scanner_in_flight
+ return in_flight_limit, "skipped_limit", team_in_flight, scanner_in_flight
@extend_schema(parameters=[ScannerImpactQuerySerializer], responses={200: ScannerImpactSerializer})
@action(
diff --git a/products/replay_vision/backend/api/trigger.py b/products/replay_vision/backend/api/trigger.py
index 7c414d894829..aba89499e056 100644
--- a/products/replay_vision/backend/api/trigger.py
+++ b/products/replay_vision/backend/api/trigger.py
@@ -20,12 +20,19 @@ from posthog.temporal.common.search_attributes import (
POSTHOG_TEAM_ID_KEY,
)
+from products.replay_vision.backend.enqueue_claims import (
+ pending_enqueue_claims_for_scanner,
+ pending_enqueue_claims_for_team,
+ release_enqueue_claim,
+ try_claim_enqueue_slot,
+)
from products.replay_vision.backend.models.replay_observation import ObservationTrigger, ReplayObservation
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
from products.replay_vision.backend.quota import compute_quota_snapshot
from products.replay_vision.backend.temporal.constants import (
APPLY_SCANNER_EXECUTION_TIMEOUT,
APPLY_SCANNER_WORKFLOW_NAME,
+ MAX_IN_FLIGHT_APPLIES_PER_SCANNER,
MAX_IN_FLIGHT_APPLIES_PER_TEAM,
PROCESS_VISION_ACTION_EXECUTION_TIMEOUT,
PROCESS_VISION_ACTION_WORKFLOW_NAME,
@@ -41,12 +48,14 @@ class WorkflowStartOutcome(enum.Enum):
STARTED = "started"
# A workflow with our deterministic id is already running — the scan is effectively in progress.
ALREADY_RUNNING = "already_running"
+ # The atomic enqueue-slot claim was refused: the in-flight caps have no headroom.
+ CAPPED = "capped"
FAILED = "failed"
def check_team_in_flight_capacity(team_id: int) -> None:
- """Raise 429 when the team is already at its in-flight apply cap."""
- count = ReplayObservation.in_flight_for_team(team_id).count()
+ """Raise 429 when in-flight rows plus enqueued-but-not-yet-persisted claims hit the team cap."""
+ count = ReplayObservation.in_flight_for_team(team_id).count() + pending_enqueue_claims_for_team(team_id)
if count >= MAX_IN_FLIGHT_APPLIES_PER_TEAM:
raise Throttled(detail=f"This team already has {count} observations running. Try again in a few minutes.")
@@ -66,15 +75,46 @@ def check_observation_quota(organization_id: UUID, observation_credits: int) ->
)
+def _admission_still_within_caps(scanner: ReplayScanner) -> bool:
+ """Validate a fresh claim against fresh counts. The claim is already registered, so this read
+ sees every competitor, and rows younger than the decay grace are still covered by their claims;
+ a pre-claim row snapshot staler than the grace self-corrects here instead of over-admitting."""
+ in_flight = ReplayObservation.in_flight_for_team(scanner.team_id)
+ if in_flight.count() + pending_enqueue_claims_for_team(scanner.team_id) > MAX_IN_FLIGHT_APPLIES_PER_TEAM:
+ return False
+ scanner_rows = in_flight.filter(scanner_id=scanner.id).count()
+ return scanner_rows + pending_enqueue_claims_for_scanner(scanner.id) <= MAX_IN_FLIGHT_APPLIES_PER_SCANNER
+
+
def start_apply_scanner_workflow(
scanner: ReplayScanner,
session_id: str,
*,
triggered_by_user_id: int,
trigger: ObservationTrigger,
+ team_in_flight_rows: int | None = None,
+ scanner_in_flight_rows: int | None = None,
) -> tuple[str, WorkflowStartOutcome]:
- """Start the deterministic apply-scanner workflow for one (scanner, session); never raises."""
+ """Start the deterministic apply-scanner workflow for one (scanner, session); never raises.
+ An atomic enqueue-slot claim guards the in-flight caps; pass row counts to save two queries."""
workflow_id = build_apply_scanner_workflow_id(scanner.id, session_id)
+ if team_in_flight_rows is None:
+ team_in_flight_rows = ReplayObservation.in_flight_for_team(scanner.team_id).count()
+ if scanner_in_flight_rows is None:
+ scanner_in_flight_rows = (
+ ReplayObservation.in_flight_for_team(scanner.team_id).filter(scanner_id=scanner.id).count()
+ )
+ if not try_claim_enqueue_slot(
+ team_id=scanner.team_id,
+ scanner_id=scanner.id,
+ workflow_id=workflow_id,
+ team_in_flight_rows=team_in_flight_rows,
+ scanner_in_flight_rows=scanner_in_flight_rows,
+ ):
+ return workflow_id, WorkflowStartOutcome.CAPPED
+ if not _admission_still_within_caps(scanner):
+ release_enqueue_claim(team_id=scanner.team_id, scanner_id=scanner.id, workflow_id=workflow_id)
+ return workflow_id, WorkflowStartOutcome.CAPPED
try:
client = sync_connect()
async_to_sync(client.start_workflow)( # type: ignore[misc]
@@ -102,11 +142,19 @@ def start_apply_scanner_workflow(
# Pin to our own workflow_id so a future id_reuse_policy change can't silently accept an unrelated run.
if exc.workflow_id != workflow_id:
logger.exception("replay_vision.observe.workflow_id_mismatch", workflow_id=workflow_id)
+ release_enqueue_claim(team_id=scanner.team_id, scanner_id=scanner.id, workflow_id=workflow_id)
return workflow_id, WorkflowStartOutcome.FAILED
logger.info("replay_vision.observe.workflow_already_started", workflow_id=workflow_id)
+ # A persisted row already counts this run, so our claim is a resurrected duplicate — drop
+ # it. Without a row the running workflow is still in the enqueue gap: keep the claim.
+ if ReplayObservation.objects.filter(scanner_id=scanner.id, session_id=session_id).exists():
+ release_enqueue_claim(
+ team_id=scanner.team_id, scanner_id=scanner.id, workflow_id=workflow_id, immediately=True
+ )
return workflow_id, WorkflowStartOutcome.ALREADY_RUNNING
except Exception:
logger.exception("replay_vision.observe.workflow_start_failed", workflow_id=workflow_id)
+ release_enqueue_claim(team_id=scanner.team_id, scanner_id=scanner.id, workflow_id=workflow_id)
return workflow_id, WorkflowStartOutcome.FAILED
return workflow_id, WorkflowStartOutcome.STARTED
diff --git a/products/replay_vision/backend/enqueue_claims.py b/products/replay_vision/backend/enqueue_claims.py
new file mode 100644
index 000000000000..260119d589de
--- /dev/null
+++ b/products/replay_vision/backend/enqueue_claims.py
@@ -0,0 +1,131 @@
+"""Atomic enqueue-slot claims for on-demand scans.
+
+The in-flight caps count ReplayObservation rows, but a row only appears once the apply workflow's
+first activity runs, so concurrent requests could race past the caps in that gap. A claim is taken
+atomically (single Lua eval, same shape as posthog/clickhouse/client/limit.py) before the workflow
+starts and decays once the row exists. Fail-open: the caps are backpressure guardrails, not billing.
+"""
+
+import time
+from uuid import UUID
+
+import structlog
+
+from posthog import redis
+
+from products.replay_vision.backend.temporal.constants import (
+ MAX_IN_FLIGHT_APPLIES_PER_SCANNER,
+ MAX_IN_FLIGHT_APPLIES_PER_TEAM,
+)
+
+logger = structlog.get_logger(__name__)
+
+# Must exceed worst-case enqueue-to-first-activity lag; crashed claims are reclaimed after this long.
+_CLAIM_TTL_SECONDS = 15 * 60
+
+# Decay window: claim and just-persisted row overlap, so stale row counts can't under-count.
+_RELEASE_GRACE_SECONDS = 60
+
+_TEAM_KEY_PREFIX = "@posthog/replay-vision/enqueued-team"
+_SCANNER_KEY_PREFIX = "@posthog/replay-vision/enqueued-scanner"
+
+# Re-claiming an existing member (same deterministic workflow id) never consumes a second slot.
+_CLAIM_LUA = """
+local team_key = KEYS[1]
+local scanner_key = KEYS[2]
+local now = tonumber(ARGV[1])
+local member = ARGV[2]
+local team_allowance = tonumber(ARGV[3])
+local scanner_allowance = tonumber(ARGV[4])
+local ttl = tonumber(ARGV[5])
+
+redis.call('ZREMRANGEBYSCORE', team_key, '-inf', now)
+redis.call('ZREMRANGEBYSCORE', scanner_key, '-inf', now)
+
+if not redis.call('ZSCORE', team_key, member) then
+ if redis.call('ZCARD', team_key) >= team_allowance then
+ return 0
+ end
+ if redis.call('ZCARD', scanner_key) >= scanner_allowance then
+ return 0
+ end
+end
+
+local expiry = now + ttl
+redis.call('ZADD', team_key, expiry, member)
+redis.call('ZADD', scanner_key, expiry, member)
+redis.call('EXPIRE', team_key, ttl)
+redis.call('EXPIRE', scanner_key, ttl)
+return 1
+"""
+
+
+def _team_key(team_id: int) -> str:
+ return f"{_TEAM_KEY_PREFIX}:{team_id}"
+
+
+def _scanner_key(scanner_id: UUID) -> str:
+ return f"{_SCANNER_KEY_PREFIX}:{scanner_id}"
+
+
+def try_claim_enqueue_slot(
+ *,
+ team_id: int,
+ scanner_id: UUID,
+ workflow_id: str,
+ team_in_flight_rows: int,
+ scanner_in_flight_rows: int,
+) -> bool:
+ """Atomically claim one enqueue slot against both in-flight caps; True when the scan may start."""
+ team_allowance = MAX_IN_FLIGHT_APPLIES_PER_TEAM - team_in_flight_rows
+ scanner_allowance = MAX_IN_FLIGHT_APPLIES_PER_SCANNER - scanner_in_flight_rows
+ try:
+ allowed = redis.get_client().eval(
+ _CLAIM_LUA,
+ 2,
+ _team_key(team_id),
+ _scanner_key(scanner_id),
+ time.time(),
+ workflow_id,
+ team_allowance,
+ scanner_allowance,
+ _CLAIM_TTL_SECONDS,
+ )
+ return bool(allowed)
+ except Exception:
+ logger.warning("replay_vision.enqueue_claim.failed_open", team_id=team_id, exc_info=True)
+ return True
+
+
+def release_enqueue_claim(*, team_id: int, scanner_id: UUID, workflow_id: str, immediately: bool = False) -> None:
+ """Decay a claim once its observation row exists (or the start failed); unreleased claims
+ self-expire. `immediately` removes it outright, for claims that never covered anything."""
+ expiry = time.time() + _RELEASE_GRACE_SECONDS
+ try:
+ pipeline = redis.get_client().pipeline()
+ if immediately:
+ pipeline.zrem(_team_key(team_id), workflow_id)
+ pipeline.zrem(_scanner_key(scanner_id), workflow_id)
+ else:
+ pipeline.zadd(_team_key(team_id), {workflow_id: expiry}, xx=True)
+ pipeline.zadd(_scanner_key(scanner_id), {workflow_id: expiry}, xx=True)
+ pipeline.execute()
+ except Exception:
+ logger.warning("replay_vision.enqueue_claim.release_failed", team_id=team_id, exc_info=True)
+
+
+def pending_enqueue_claims_for_team(team_id: int) -> int:
+ """Live claims for scans enqueued but not yet persisted."""
+ return _pending(_team_key(team_id))
+
+
+def pending_enqueue_claims_for_scanner(scanner_id: UUID) -> int:
+ return _pending(_scanner_key(scanner_id))
+
+
+def _pending(key: str) -> int:
+ try:
+ return int(redis.get_client().zcount(key, f"({time.time()}", "+inf"))
+ except Exception:
+ logger.warning("replay_vision.enqueue_claim.count_failed", key=key, exc_info=True)
+ return 0
diff --git a/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py b/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py
index 4b47ac8afa85..dee483063c1f 100644
--- a/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py
+++ b/products/replay_vision/backend/temporal/activities/count_in_flight_applies.py
@@ -5,6 +5,10 @@ from temporalio import activity
from posthog.temporal.common.client import async_connect
+from products.replay_vision.backend.enqueue_claims import (
+ pending_enqueue_claims_for_scanner,
+ pending_enqueue_claims_for_team,
+)
from products.replay_vision.backend.models.replay_observation import ReplayObservation
from products.replay_vision.backend.temporal.constants import in_flight_headroom
from products.replay_vision.backend.temporal.decorators import track_activity
@@ -44,8 +48,11 @@ def count_in_flight_by_team_activity(inputs: CountInFlightAppliesInputs) -> InFl
team=Count("id"),
scanner=Count("id", filter=Q(scanner_id=inputs.scanner_id)),
)
+ # On-demand scans hold enqueue claims until their rows persist.
+ team = counts["team"] + pending_enqueue_claims_for_team(inputs.team_id)
+ scanner = counts["scanner"] + pending_enqueue_claims_for_scanner(inputs.scanner_id)
# The workflow makes the same call on these counts; recorded here because metrics
# can't be emitted from deterministic workflow code.
- if in_flight_headroom(counts["scanner"], counts["team"]) <= 0:
+ if in_flight_headroom(scanner, team) <= 0:
record_sweep_outcome("throttled")
- return InFlightApplyCounts(scanner=counts["scanner"], team=counts["team"])
+ return InFlightApplyCounts(scanner=scanner, team=team)
diff --git a/products/replay_vision/backend/temporal/activities/create_observation.py b/products/replay_vision/backend/temporal/activities/create_observation.py
index 16960437456e..9f848fbaa583 100644
--- a/products/replay_vision/backend/temporal/activities/create_observation.py
+++ b/products/replay_vision/backend/temporal/activities/create_observation.py
@@ -9,6 +9,7 @@ from temporalio.exceptions import ApplicationError
from posthog.models.organization import OrganizationMembership
from products.replay_vision.backend.billing import observation_credits_for_model
+from products.replay_vision.backend.enqueue_claims import release_enqueue_claim
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
from products.replay_vision.backend.models.replay_scanner import ReplayScanner
from products.replay_vision.backend.quota import compute_quota_snapshot
@@ -37,6 +38,14 @@ 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."""
+ try:
+ return _create_observation(inputs)
+ 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)
+
+
+def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOutput:
scanner = ReplayScanner.objects.filter(pk=inputs.scanner_id, team_id=inputs.team_id).select_related("team").first()
if scanner is None:
raise ValueError(f"ReplayScanner {inputs.scanner_id} not found for team {inputs.team_id}")
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 9506c082cf24..1750178a6bac 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -12,10 +12,13 @@ from temporalio.exceptions import WorkflowAlreadyStartedError
from posthog.models import Organization, PersonalAPIKey, Team, User
from posthog.models.utils import generate_random_token_personal, hash_key_value, uuid7
+from posthog.redis import get_client
from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
+from products.replay_vision.backend.api.trigger import WorkflowStartOutcome, start_apply_scanner_workflow
from products.replay_vision.backend.billing import observation_credits_for_model
from products.replay_vision.backend.digest import SCANNER_DIGEST_RRULE
+from products.replay_vision.backend.enqueue_claims import _scanner_key, _team_key, pending_enqueue_claims_for_team
from products.replay_vision.backend.models.replay_observation import (
ObservationStatus,
ObservationTrigger,
@@ -1474,10 +1477,84 @@ class TestObserveAction(_VisionAPITestCase):
def setUp(self) -> None:
super().setUp()
self.scanner = self._create_scanner()
+ # Claims from earlier tests' mocked starts are never released by an activity.
+ get_client().delete(_team_key(self.team.id), _scanner_key(self.scanner.id))
def observe_url(self, scanner_id: str) -> str:
return f"{self.scanners_url}{scanner_id}/observe/"
+ @parameterized.expand(
+ [
+ ("row_persisted_drops_duplicate_claim", True, 0),
+ ("row_not_yet_persisted_keeps_claim", False, 1),
+ ]
+ )
+ def test_already_running_claim_follows_row_existence(
+ self,
+ mock_sync_connect: MagicMock,
+ mock_async_to_sync: MagicMock,
+ _name: str,
+ row_exists: bool,
+ expected_claims: int,
+ ) -> None:
+ # Resubmitting an active session must not mint a phantom claim on top of its persisted row,
+ # but a claim for a run still inside the enqueue gap has to survive.
+ session_id = "sess-running"
+ if row_exists:
+ ReplayObservation.objects.create(
+ scanner=self.scanner,
+ session_id=session_id,
+ scanner_snapshot=_snapshot_for(self.scanner),
+ triggered_by=ObservationTrigger.ON_DEMAND,
+ status=ObservationStatus.PENDING,
+ )
+ mock_sync_connect.return_value = MagicMock()
+ mock_async_to_sync.return_value = MagicMock(
+ side_effect=WorkflowAlreadyStartedError(
+ workflow_id=build_apply_scanner_workflow_id(self.scanner.id, session_id),
+ workflow_type=APPLY_SCANNER_WORKFLOW_NAME,
+ )
+ )
+
+ _, outcome = start_apply_scanner_workflow(
+ self.scanner, session_id, triggered_by_user_id=self.user.id, trigger=ObservationTrigger.ON_DEMAND
+ )
+
+ assert outcome is WorkflowStartOutcome.ALREADY_RUNNING
+ assert pending_enqueue_claims_for_team(self.team.id) == expected_claims
+
+ def test_stale_row_snapshot_self_corrects_after_claim(
+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
+ ) -> None:
+ # A row count staler than the claim decay grace must not admit past the cap: the post-claim
+ # validation re-reads rows with the claim already registered.
+ mock_sync_connect.return_value = MagicMock()
+ start_workflow = MagicMock()
+ mock_async_to_sync.return_value = start_workflow
+ ReplayObservation.objects.create(
+ scanner=self.scanner,
+ session_id="already-running",
+ scanner_snapshot=_snapshot_for(self.scanner),
+ triggered_by=ObservationTrigger.ON_DEMAND,
+ status=ObservationStatus.PENDING,
+ )
+
+ with (
+ patch("products.replay_vision.backend.api.trigger.MAX_IN_FLIGHT_APPLIES_PER_TEAM", 1),
+ patch("products.replay_vision.backend.enqueue_claims.MAX_IN_FLIGHT_APPLIES_PER_TEAM", 1),
+ ):
+ _, outcome = start_apply_scanner_workflow(
+ self.scanner,
+ "sess-stale",
+ triggered_by_user_id=self.user.id,
+ trigger=ObservationTrigger.ON_DEMAND,
+ team_in_flight_rows=0,
+ scanner_in_flight_rows=0,
+ )
+
+ assert outcome is WorkflowStartOutcome.CAPPED
+ start_workflow.assert_not_called()
+
def test_observe_returns_workflow_id_and_starts_workflow(
self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
) -> None:
@@ -1609,6 +1686,24 @@ class TestObserveAction(_VisionAPITestCase):
)
self.assertEqual(resp.status_code, 503, resp.json())
+ def test_observe_returns_429_when_the_atomic_claim_is_refused(
+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
+ ) -> None:
+ # The snapshot pre-check can pass while a racing request holds the last slot; the atomic claim
+ # is the authoritative gate, so its refusal must surface as 429 and start no workflow.
+ mock_sync_connect.return_value = MagicMock()
+ start_workflow = MagicMock()
+ mock_async_to_sync.return_value = start_workflow
+
+ with patch("products.replay_vision.backend.api.trigger.try_claim_enqueue_slot", return_value=False):
+ resp = self.client.post(
+ self.observe_url(str(self.scanner.id)), data={"session_id": "sess-capped"}, format="json"
+ )
+
+ self.assertEqual(resp.status_code, 429, resp.json())
+ start_workflow.assert_not_called()
+ self.assertFalse(ReplayObservation.objects.filter(scanner=self.scanner, session_id="sess-capped").exists())
+
@patch("products.replay_vision.backend.api.trigger.async_to_sync")
@patch("products.replay_vision.backend.api.trigger.sync_connect")
@@ -1693,6 +1788,27 @@ class TestBulkObserveAction(_VisionAPITestCase):
self.assertEqual(body["started"], 1)
self.assertEqual([r["scan_outcome"] for r in body["results"]], ["started", "skipped_quota"])
+ def test_concurrent_claim_exhaustion_maps_to_skipped_limit(
+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
+ ) -> None:
+ # The headroom pre-slice passed, but a racing request consumed the remaining slots before we
+ # could start — the atomic claim refuses, and the result must read as the limit, not a failure.
+ mock_sync_connect.return_value = MagicMock()
+ mock_async_to_sync.return_value = MagicMock()
+ with patch(
+ "products.replay_vision.backend.api.trigger.try_claim_enqueue_slot", side_effect=[True, False]
+ ) as claim:
+ resp = self.client.post(
+ self.bulk_url(str(self.scanner.id)), data={"session_ids": ["a", "b", "c"]}, format="json"
+ )
+
+ self.assertEqual(resp.status_code, 202, resp.json())
+ body = resp.json()
+ self.assertEqual(body["started"], 1)
+ self.assertEqual([r["scan_outcome"] for r in body["results"]], ["started", "skipped_limit", "skipped_limit"])
+ # The refused claim short-circuits the batch; no third claim attempt is made.
+ self.assertEqual(claim.call_count, 2)
+
def test_already_running_session_is_a_no_op_and_consumes_no_headroom(
self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
) -> None:
@@ -1852,6 +1968,26 @@ class TestRetryActions(_VisionAPITestCase):
self.assertEqual(restored.status, ObservationStatus.FAILED)
self.assertEqual(restored.created_at, original_created_at)
+ def test_retry_returns_429_and_restores_row_when_the_atomic_claim_is_refused(
+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
+ ) -> None:
+ # The claim can refuse after the snapshot pre-check passed; the retry must 429 and bring the
+ # failed row back rather than deleting it while no replacement run started.
+ mock_sync_connect.return_value = MagicMock()
+ start_workflow = MagicMock()
+ mock_async_to_sync.return_value = start_workflow
+ observation = self._create_failed("sess-capped")
+ original_created_at = observation.created_at
+
+ with patch("products.replay_vision.backend.api.trigger.try_claim_enqueue_slot", return_value=False):
+ resp = self.client.post(self.retry_url(str(observation.id)))
+
+ self.assertEqual(resp.status_code, 429, resp.json())
+ start_workflow.assert_not_called()
+ restored = ReplayObservation.objects.get(id=observation.id)
+ self.assertEqual(restored.status, ObservationStatus.FAILED)
+ self.assertEqual(restored.created_at, original_created_at)
+
def _personal_api_key(self, scopes: list[str]) -> str:
value = generate_random_token_personal()
PersonalAPIKey.objects.create(
diff --git a/products/replay_vision/backend/tests/test_enqueue_claims.py b/products/replay_vision/backend/tests/test_enqueue_claims.py
new file mode 100644
index 000000000000..93ecb24699a6
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_enqueue_claims.py
@@ -0,0 +1,93 @@
+import time
+from uuid import uuid4
+
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.redis import get_client
+
+from products.replay_vision.backend.enqueue_claims import (
+ _RELEASE_GRACE_SECONDS,
+ _scanner_key,
+ _team_key,
+ pending_enqueue_claims_for_scanner,
+ pending_enqueue_claims_for_team,
+ release_enqueue_claim,
+ try_claim_enqueue_slot,
+)
+
+
+class TestEnqueueClaims(SimpleTestCase):
+ def setUp(self) -> None:
+ self.team_id = 990_001
+ self.scanner_id = uuid4()
+ self._flush()
+ self.addCleanup(self._flush)
+
+ def _flush(self) -> None:
+ get_client().delete(_team_key(self.team_id), _scanner_key(self.scanner_id))
+
+ def _claim(self, workflow_id: str, *, team_rows: int = 0, scanner_rows: int = 0) -> bool:
+ return try_claim_enqueue_slot(
+ team_id=self.team_id,
+ scanner_id=self.scanner_id,
+ workflow_id=workflow_id,
+ team_in_flight_rows=team_rows,
+ scanner_in_flight_rows=scanner_rows,
+ )
+
+ @parameterized.expand(
+ [
+ ("team_cap_binds", "MAX_IN_FLIGHT_APPLIES_PER_TEAM"),
+ ("scanner_cap_binds", "MAX_IN_FLIGHT_APPLIES_PER_SCANNER"),
+ ]
+ )
+ def test_claims_beyond_the_allowance_are_rejected(self, _name: str, cap_constant: str) -> None:
+ # A read-then-write regression would admit both concurrent callers.
+ with patch(f"products.replay_vision.backend.enqueue_claims.{cap_constant}", 1):
+ assert self._claim("wf-1") is True
+ assert self._claim("wf-2") is False
+
+ def test_rows_count_against_the_allowance(self) -> None:
+ # Persisted in-flight rows consume cap headroom before any claims do.
+ with patch("products.replay_vision.backend.enqueue_claims.MAX_IN_FLIGHT_APPLIES_PER_TEAM", 2):
+ assert self._claim("wf-1", team_rows=2) is False
+
+ def test_reclaiming_the_same_workflow_id_consumes_no_new_slot(self) -> None:
+ # Duplicate requests and retries re-claim the same member; consuming a slot would starve headroom.
+ with patch("products.replay_vision.backend.enqueue_claims.MAX_IN_FLIGHT_APPLIES_PER_TEAM", 1):
+ assert self._claim("wf-1") is True
+ assert self._claim("wf-1") is True
+ assert self._claim("wf-2") is False
+
+ def test_release_decays_the_claim_instead_of_deleting_it(self) -> None:
+ # Deleting on release would reopen the stale-row-count race; the slot frees after the grace.
+ with patch("products.replay_vision.backend.enqueue_claims.MAX_IN_FLIGHT_APPLIES_PER_TEAM", 1):
+ assert self._claim("wf-1") is True
+ release_enqueue_claim(team_id=self.team_id, scanner_id=self.scanner_id, workflow_id="wf-1")
+ assert self._claim("wf-2") is False
+ with patch(
+ "products.replay_vision.backend.enqueue_claims.time.time",
+ return_value=time.time() + _RELEASE_GRACE_SECONDS + 1,
+ ):
+ assert self._claim("wf-2") is True
+
+ def test_expired_claims_are_evicted_and_do_not_count(self) -> None:
+ # The TTL score is the crash net: a claim whose workflow died must not hold its slot forever.
+ client = get_client()
+ client.zadd(_team_key(self.team_id), {"wf-dead": time.time() - 1})
+ client.zadd(_scanner_key(self.scanner_id), {"wf-dead": time.time() - 1})
+ with patch("products.replay_vision.backend.enqueue_claims.MAX_IN_FLIGHT_APPLIES_PER_TEAM", 1):
+ assert self._claim("wf-live") is True
+ assert pending_enqueue_claims_for_team(self.team_id) == 1
+ assert pending_enqueue_claims_for_scanner(self.scanner_id) == 1
+
+ def test_fails_open_when_redis_is_unavailable(self) -> None:
+ # The caps are backstops, not billing: a Redis outage must never block scans.
+ with patch("products.replay_vision.backend.enqueue_claims.redis.get_client", side_effect=RuntimeError("down")):
+ assert self._claim("wf-1") is True
+ release_enqueue_claim(team_id=self.team_id, scanner_id=self.scanner_id, workflow_id="wf-1")
+ assert pending_enqueue_claims_for_team(self.team_id) == 0
diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.py
index 0ef5c1091f9c..5cf4041a3c86 100644
--- a/products/replay_vision/backend/tests/test_temporal.py
+++ b/products/replay_vision/backend/tests/test_temporal.py
@@ -1,3 +1,4 @@
+import time
import uuid
import datetime as dt
from typing import Any
@@ -30,6 +31,12 @@ from posthog.session_recordings.queries.session_replay_events import SessionEven
from products.exports.backend.models.exported_asset import ExportedAsset
from products.replay_vision.backend.api.observation_progress import stream_observation_progress
from products.replay_vision.backend.billing import observation_credits_for_model
+from products.replay_vision.backend.enqueue_claims import (
+ _RELEASE_GRACE_SECONDS,
+ pending_enqueue_claims_for_scanner,
+ pending_enqueue_claims_for_team,
+ try_claim_enqueue_slot,
+)
from products.replay_vision.backend.models.replay_observation import (
ObservationStatus,
ObservationTrigger,
@@ -189,6 +196,24 @@ class TestCountInFlightAppliesActivity:
assert result == InFlightApplyCounts(scanner=2, team=3)
+ def test_counts_include_enqueued_claims(self) -> None:
+ # Missing claims here lets the sweep dispatch on top of an on-demand burst.
+ scanner = _make_scanner()
+ _make_observation(scanner, session_id="s1", status=ObservationStatus.PENDING)
+ assert try_claim_enqueue_slot(
+ team_id=scanner.team_id,
+ scanner_id=scanner.id,
+ workflow_id="wf-enqueued",
+ team_in_flight_rows=1,
+ scanner_in_flight_rows=1,
+ )
+
+ result = count_in_flight_by_team_activity(
+ CountInFlightAppliesInputs(scanner_id=scanner.id, team_id=scanner.team_id)
+ )
+
+ assert result == InFlightApplyCounts(scanner=2, team=2)
+
@pytest.mark.django_db(transaction=True)
class TestCreateObservationActivity:
@@ -222,6 +247,37 @@ class TestCreateObservationActivity:
assert observation.started_at is None # set when transitioning to running, not here
assert observation.completed_at is None
+ def test_decays_enqueue_claim_once_the_row_exists(self) -> None:
+ # A claim that never decays holds a phantom cap slot for the full TTL.
+ scanner = _make_scanner()
+ assert try_claim_enqueue_slot(
+ team_id=scanner.team_id,
+ scanner_id=scanner.id,
+ workflow_id="wf-claimed",
+ team_in_flight_rows=0,
+ scanner_in_flight_rows=0,
+ )
+
+ create_observation_activity(
+ CreateObservationInputs(
+ scanner_id=scanner.id,
+ team_id=scanner.team_id,
+ session_id="sess-claimed",
+ triggered_by=ObservationTrigger.ON_DEMAND,
+ triggered_by_user_id=None,
+ workflow_id="wf-claimed",
+ )
+ )
+
+ # The claim decays: it overlaps its new row for the grace, then expires.
+ assert pending_enqueue_claims_for_team(scanner.team_id) == 1
+ with patch(
+ "products.replay_vision.backend.enqueue_claims.time.time",
+ return_value=time.time() + _RELEASE_GRACE_SECONDS + 1,
+ ):
+ assert pending_enqueue_claims_for_team(scanner.team_id) == 0
+ assert pending_enqueue_claims_for_scanner(scanner.id) == 0
+
def test_snapshot_is_frozen_against_later_scanner_edits(self) -> None:
scanner = _make_scanner()
original_config = dict(scanner.scanner_config)