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): bound activity query time and speed up team listing (#111574)

Tue Haulund5af6f60a785c
diff --git a/products/replay_vision/backend/search_suggestions.py b/products/replay_vision/backend/search_suggestions.py
index 4943da231b4d..da69b9c5c0e1 100644
--- a/products/replay_vision/backend/search_suggestions.py
+++ b/products/replay_vision/backend/search_suggestions.py
@@ -16,7 +16,7 @@ from itertools import zip_longest
from django.conf import settings
from django.core.cache import cache
-from django.db.models import DateTimeField, Exists, F, OuterRef, Q, QuerySet, Subquery, Value
+from django.db.models import DateTimeField, DurationField, Exists, F, OuterRef, Q, QuerySet, Subquery, Value
from django.db.models.functions import Coalesce
from django.utils import timezone
@@ -65,6 +65,8 @@ FIRST_PHRASES_RETRY = dt.timedelta(minutes=10)
# The view stamp is one Postgres write per scope per this window, whatever the page traffic.
_VIEW_STAMP_THROTTLE = dt.timedelta(hours=1)
_EPOCH = dt.datetime(1970, 1, 1, tzinfo=dt.UTC)
+# Longer than the apply workflow's execution timeout, so a row created this long before a watermark completed before it.
+COMPLETION_LAG = dt.timedelta(hours=2)
# Daily model-call counter across every refresh run, the backstop against a bug that makes every scanner look stale.
_BUDGET_TTL_S = 2 * 24 * 3600
# Cross-scanner search merges phrases from this many of the team's most recently active scanners.
@@ -220,23 +222,32 @@ def stale_team_candidates(limit: int) -> list[int]:
"""Teams whose cross-scanner phrases are due: AI processing on, past their back-off, and with enough new
observations across the scanners that may feed them. Counted across the team, because a team sample draws
from several scanners at once."""
- config = TeamReplayVisionConfig.objects.filter(team_id=OuterRef("team_id"))
- team_watermark = Coalesce(
- Subquery(config.values("search_suggestions_watermark")[:1]), Value(_EPOCH), output_field=DateTimeField()
+ not_due = TeamReplayVisionConfig.objects.exclude(_due()).values("team_id")
+ sources = (
+ _team_sources()
+ .filter(team__organization__is_ai_data_processing_approved=True)
+ .exclude(team_id__in=not_due)
+ .values("team_id")
+ )
+ watermark = Coalesce(
+ Subquery(
+ TeamReplayVisionConfig.objects.filter(team_id=OuterRef("pk")).values("search_suggestions_watermark")[:1]
+ ),
+ Value(_EPOCH),
+ output_field=DateTimeField(),
)
newer = _team_rows().filter(
- team_id=OuterRef("team_id"),
+ team_id=OuterRef("pk"),
scanner__in=_team_sources(),
- completed_at__gt=team_watermark,
+ completed_at__gt=OuterRef("watermark"),
+ created_at__gt=OuterRef("created_floor"),
)
- not_due = TeamReplayVisionConfig.objects.exclude(_due()).values("team_id")
return list(
- _team_sources()
- .filter(team__organization__is_ai_data_processing_approved=True)
- .exclude(team_id__in=not_due)
+ Team.objects.filter(pk__in=sources)
+ .annotate(watermark=watermark)
+ .annotate(created_floor=F("watermark") - Value(COMPLETION_LAG, output_field=DurationField()))
.filter(_has_enough_new_rows(newer))
- .values_list("team_id", flat=True)
- .distinct()[:limit]
+ .values_list("pk", flat=True)[:limit]
)
diff --git a/products/replay_vision/backend/temporal/activities/backfill.py b/products/replay_vision/backend/temporal/activities/backfill.py
index 94532b10e779..99a49d1e6002 100644
--- a/products/replay_vision/backend/temporal/activities/backfill.py
+++ b/products/replay_vision/backend/temporal/activities/backfill.py
@@ -57,11 +57,13 @@ from products.replay_vision.backend.temporal.constants import (
BACKFILL_SCHEDULE_ID_PREFIX,
BACKFILL_SCHEDULE_TYPE,
FIND_BACKFILL_CANDIDATES_TIMEOUT,
+ REAP_BACKFILL_SCHEDULES_HEARTBEAT_TIMEOUT,
backfill_dispatch_budget,
build_apply_scanner_workflow_id,
)
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.metrics import record_backfill_tick_outcome
+from products.replay_vision.backend.temporal.query_budget import bounded_queries
from products.replay_vision.backend.temporal.schedule import (
a_delete_backfill_schedule,
a_pause_backfill_schedule,
@@ -348,11 +350,13 @@ async def delete_backfill_schedule_activity(inputs: BackfillScheduleOpInputs) ->
def _active_backfills_by_id() -> dict[UUID, tuple[int, UUID, str]]:
"""`{backfill_id: (team_id, scanner_id, status)}` for every non-terminal backfill."""
- rows = ReplayScannerBackfill.objects.unscoped().filter(status__in=ACTIVE_BACKFILL_STATUSES)
- return {
- row_id: (team_id, scanner_id, row_status)
- for row_id, team_id, scanner_id, row_status in rows.values_list("id", "team_id", "scanner_id", "status")
- }
+ with bounded_queries(REAP_BACKFILL_SCHEDULES_HEARTBEAT_TIMEOUT):
+ rows = list(
+ ReplayScannerBackfill.objects.unscoped()
+ .filter(status__in=ACTIVE_BACKFILL_STATUSES)
+ .values_list("id", "team_id", "scanner_id", "status")
+ )
+ return {row_id: (team_id, scanner_id, row_status) for row_id, team_id, scanner_id, row_status in rows}
async def _recreate_schedule(
diff --git a/products/replay_vision/backend/temporal/activities/check_scanner_budget.py b/products/replay_vision/backend/temporal/activities/check_scanner_budget.py
index bc2d2e862fbb..596bb8487114 100644
--- a/products/replay_vision/backend/temporal/activities/check_scanner_budget.py
+++ b/products/replay_vision/backend/temporal/activities/check_scanner_budget.py
@@ -3,8 +3,10 @@ from temporalio import activity
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, initial_watermark
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
+from products.replay_vision.backend.temporal.constants import CHECK_SCANNER_BUDGET_TIMEOUT
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.metrics import record_sweep_outcome
+from products.replay_vision.backend.temporal.query_budget import bounded_queries
from products.replay_vision.backend.temporal.sweep_types import CheckScannerBudgetInputs, CheckScannerBudgetOutput
@@ -109,7 +111,8 @@ def check_scanner_budget_activity(inputs: CheckScannerBudgetInputs) -> CheckScan
return CheckScannerBudgetOutput(capped=False)
# Resolve the period once so the cap decision and the notification stamp cannot straddle a rollover.
period = current_period_bounds(scanner.team.organization_id)
- budget = compute_scanner_budget(scanner, period)
+ with bounded_queries(CHECK_SCANNER_BUDGET_TIMEOUT):
+ budget = compute_scanner_budget(scanner, period)
if not budget.blocked:
return CheckScannerBudgetOutput(capped=False)
if not budget.blocked_by_settled_spend:
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 0e4c42ff7fd0..d8e1144b6828 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
@@ -9,9 +9,10 @@ from posthog.temporal.common.client import async_connect
from products.replay_vision.backend.enqueue_claims import pending_enqueue_claims
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.constants import COUNT_IN_FLIGHT_APPLIES_TIMEOUT, in_flight_headroom
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.metrics import record_sweep_outcome
+from products.replay_vision.backend.temporal.query_budget import bounded_queries
from products.replay_vision.backend.temporal.sweep_types import CountInFlightAppliesInputs, InFlightApplyCounts
logger = structlog.get_logger(__name__)
@@ -69,7 +70,9 @@ def count_in_flight(
@activity.defn
@track_activity()
def count_in_flight_by_team_activity(inputs: CountInFlightAppliesInputs) -> InFlightApplyCounts:
- counts = count_in_flight(inputs.team_id, inputs.scanner_id)
+ with bounded_queries(COUNT_IN_FLIGHT_APPLIES_TIMEOUT):
+ rows = count_in_flight_rows(inputs.team_id, inputs.scanner_id)
+ counts = count_in_flight(inputs.team_id, inputs.scanner_id, rows=rows)
team = counts["team"]
scanner = counts["scanner"]
# The workflow makes the same call on these counts; recorded here because metrics
diff --git a/products/replay_vision/backend/temporal/activities/create_observation.py b/products/replay_vision/backend/temporal/activities/create_observation.py
index 72262d5071cc..20d090d06aa3 100644
--- a/products/replay_vision/backend/temporal/activities/create_observation.py
+++ b/products/replay_vision/backend/temporal/activities/create_observation.py
@@ -33,7 +33,7 @@ from products.replay_vision.backend.quota import (
current_period_bounds,
quota_state,
)
-from products.replay_vision.backend.temporal.constants import ADMISSION_BUDGET_TTL
+from products.replay_vision.backend.temporal.constants import ADMISSION_BUDGET_TTL, CREATE_OBSERVATION_TIMEOUT
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 (
@@ -42,6 +42,7 @@ from products.replay_vision.backend.temporal.metrics import (
record_scanner_admission_busy,
record_scanner_limit_reached,
)
+from products.replay_vision.backend.temporal.query_budget import bounded_queries
from products.replay_vision.backend.temporal.snapshots import BackfillScannerSnapshot, ScannerSnapshot
from products.replay_vision.backend.temporal.types import CreateObservationInputs, CreateObservationOutput
@@ -286,7 +287,8 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOut
# Deliberately check-then-act: the snapshot doesn't count enqueue claims, so a concurrent burst can
# overshoot by at most the in-flight caps allow, which is accepted.
- quota = quota_state(scanner.team.organization_id)
+ with bounded_queries(CREATE_OBSERVATION_TIMEOUT):
+ quota = quota_state(scanner.team.organization_id)
if quota.would_exceed(observation_credits_for_model(priced_model)):
record_quota_exhausted_skip(scanner.scanner_type)
activity.logger.info(
@@ -324,7 +326,7 @@ def _create_observation(inputs: CreateObservationInputs) -> CreateObservationOut
# observation will actually charge, not the scanner's current model.
cost = observation_credits_for_model(priced_model)
try:
- with transaction.atomic():
+ with transaction.atomic(), bounded_queries(CREATE_OBSERVATION_TIMEOUT):
# Capped scanners admit against the cached admission budget so concurrent applies cannot
# overshoot the cap; uncapped scanners keep the lock-free path.
if scanner.credit_limit is not None:
diff --git a/products/replay_vision/backend/temporal/activities/list_stale_scanner_estimates.py b/products/replay_vision/backend/temporal/activities/list_stale_scanner_estimates.py
index d013c655fcc0..28dc71b94d63 100644
--- a/products/replay_vision/backend/temporal/activities/list_stale_scanner_estimates.py
+++ b/products/replay_vision/backend/temporal/activities/list_stale_scanner_estimates.py
@@ -10,9 +10,10 @@ from products.replay_vision.backend.queries import (
ESTIMATE_RETRY_BACKOFF,
ESTIMATE_STALE_AFTER,
)
-from products.replay_vision.backend.temporal.constants import ESTIMATES_MAX_PER_RUN
+from products.replay_vision.backend.temporal.constants import ESTIMATES_MAX_PER_RUN, LIST_STALE_ESTIMATES_TIMEOUT
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.estimates_types import RefreshScannerEstimateInputs
+from products.replay_vision.backend.temporal.query_budget import bounded_queries
@activity.defn
@@ -33,9 +34,10 @@ def list_stale_scanner_estimates_activity() -> list[RefreshScannerEstimateInputs
# A recent failed attempt is skipped, and a never-computed estimate sorts by that attempt rather
# than unconditionally first, so one always-failing scanner can't hog the head of every batch.
backoff = Q(estimate_attempted_at__isnull=True) | Q(estimate_attempted_at__lt=now - ESTIMATE_RETRY_BACKOFF)
- rows = (
- ReplayScanner.objects.filter(stale, backoff)
- .order_by("-enabled", Coalesce("estimated_at", "estimate_attempted_at").asc(nulls_first=True))
- .values_list("id", "team_id")[:ESTIMATES_MAX_PER_RUN]
- )
+ with bounded_queries(LIST_STALE_ESTIMATES_TIMEOUT):
+ rows = list(
+ ReplayScanner.objects.filter(stale, backoff)
+ .order_by("-enabled", Coalesce("estimated_at", "estimate_attempted_at").asc(nulls_first=True))
+ .values_list("id", "team_id")[:ESTIMATES_MAX_PER_RUN]
+ )
return [RefreshScannerEstimateInputs(scanner_id=scanner_id, team_id=team_id) for scanner_id, team_id in rows]
diff --git a/products/replay_vision/backend/temporal/activities/reap_childless_inline_scanners.py b/products/replay_vision/backend/temporal/activities/reap_childless_inline_scanners.py
index cb2fa08fbd65..0a20414ec40b 100644
--- a/products/replay_vision/backend/temporal/activities/reap_childless_inline_scanners.py
+++ b/products/replay_vision/backend/temporal/activities/reap_childless_inline_scanners.py
@@ -19,8 +19,13 @@ from posthog.sync import database_sync_to_async
from products.replay_vision.backend.enqueue_claims import pending_enqueue_claims_for_scanner
from products.replay_vision.backend.models.replay_observation import ReplayObservation
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerOrigin
-from products.replay_vision.backend.temporal.constants import INLINE_SCANNER_REAP_BATCH_SIZE, INLINE_SCANNER_REAP_GRACE
+from products.replay_vision.backend.temporal.constants import (
+ INLINE_SCANNER_REAP_BATCH_SIZE,
+ INLINE_SCANNER_REAP_GRACE,
+ REAPER_OP_TIMEOUT,
+)
from products.replay_vision.backend.temporal.decorators import track_activity
+from products.replay_vision.backend.temporal.query_budget import bounded_queries
@database_sync_to_async
@@ -28,12 +33,13 @@ def _reap_childless_inline_scanners() -> int:
# The grace period covers the gap between minting a scanner and its first observation row landing,
# which spans a Temporal workflow start and an activity.
cutoff = timezone.now() - INLINE_SCANNER_REAP_GRACE
- candidates = list(
- ReplayScanner.all_origins.filter(origin=ScannerOrigin.INLINE, created_at__lt=cutoff)
- .annotate(has_observations=Exists(ReplayObservation.objects.filter(scanner_id=OuterRef("pk"))))
- .filter(has_observations=False)
- .values_list("id", flat=True)[:INLINE_SCANNER_REAP_BATCH_SIZE]
- )
+ with bounded_queries(REAPER_OP_TIMEOUT):
+ candidates = list(
+ ReplayScanner.all_origins.filter(origin=ScannerOrigin.INLINE, created_at__lt=cutoff)
+ .annotate(has_observations=Exists(ReplayObservation.objects.filter(scanner_id=OuterRef("pk"))))
+ .filter(has_observations=False)
+ .values_list("id", flat=True)[:INLINE_SCANNER_REAP_BATCH_SIZE]
+ )
if not candidates:
return 0
# A childless scanner can still have a scan in flight: reuse resolves an old row, starts a workflow,
@@ -46,11 +52,12 @@ def _reap_childless_inline_scanners() -> int:
return 0
# Re-check emptiness in the DELETE itself: an observation can land between the two statements, and
# the FK cascade would take it with the scanner.
- deleted, _ = (
- ReplayScanner.all_origins.filter(id__in=unclaimed)
- .exclude(id__in=ReplayObservation.objects.filter(scanner_id__in=unclaimed).values("scanner_id"))
- .delete()
- )
+ with bounded_queries(REAPER_OP_TIMEOUT):
+ deleted, _ = (
+ ReplayScanner.all_origins.filter(id__in=unclaimed)
+ .exclude(id__in=ReplayObservation.objects.filter(scanner_id__in=unclaimed).values("scanner_id"))
+ .delete()
+ )
return deleted
diff --git a/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py b/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py
index 3ff5ca35e83d..3980efdf5058 100644
--- a/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py
+++ b/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py
@@ -17,10 +17,12 @@ from products.replay_vision.backend.temporal.activities.reaping import classify_
from products.replay_vision.backend.temporal.constants import (
OBSERVATION_ORPHAN_CUTOFF,
REAP_ORPHANED_OBSERVATIONS_BATCH_SIZE,
+ REAP_ORPHANED_OBSERVATIONS_HEARTBEAT_TIMEOUT,
)
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.errors import FailureKind
from products.replay_vision.backend.temporal.metrics import record_failure_kind
+from products.replay_vision.backend.temporal.query_budget import bounded_queries
logger = structlog.get_logger(__name__)
@@ -30,13 +32,15 @@ _ORPHANED_ERROR_REASON = f"{FailureKind.ORPHANED.value}:The analysis stopped wit
def _list_stale_observations() -> list[dict[str, Any]]:
cutoff = datetime.now(UTC) - OBSERVATION_ORPHAN_CUTOFF
- rows = (
- ReplayObservation.objects.filter(status__in=_LIVE_STATUSES, created_at__lt=cutoff)
- .order_by("created_at")
- .values("id", "workflow_id", "scanner_snapshot")[:REAP_ORPHANED_OBSERVATIONS_BATCH_SIZE]
- )
+ # The listing runs before the first heartbeat, so the heartbeat timeout ends a slow attempt.
+ with bounded_queries(REAP_ORPHANED_OBSERVATIONS_HEARTBEAT_TIMEOUT):
+ rows = list(
+ ReplayObservation.objects.filter(status__in=_LIVE_STATUSES, created_at__lt=cutoff)
+ .order_by("created_at")
+ .values("id", "workflow_id", "scanner_snapshot")[:REAP_ORPHANED_OBSERVATIONS_BATCH_SIZE]
+ )
# cast: django-stubs types `.values()` rows as a TypedDict, which mypy won't widen to dict[str, Any].
- return cast(list[dict[str, Any]], list(rows))
+ return cast(list[dict[str, Any]], rows)
def _mark_orphaned(observation_id: UUID, scanner_type: str) -> bool:
diff --git a/products/replay_vision/backend/temporal/activities/reconciler_activities.py b/products/replay_vision/backend/temporal/activities/reconciler_activities.py
index 8a9c8177c21c..d38e7a1dbc2a 100644
--- a/products/replay_vision/backend/temporal/activities/reconciler_activities.py
+++ b/products/replay_vision/backend/temporal/activities/reconciler_activities.py
@@ -8,11 +8,13 @@ from posthog.temporal.common.client import async_connect
from posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_FINGERPRINT_KEY
from products.replay_vision.backend.temporal.constants import (
+ LIST_ENABLED_SCANNERS_TIMEOUT,
SCANNER_SCHEDULE_ID_PREFIX,
SCANNER_SCHEDULE_TYPE,
SWEEP_SCANNER_WORKFLOW_NAME,
)
from products.replay_vision.backend.temporal.decorators import track_activity
+from products.replay_vision.backend.temporal.query_budget import bounded_queries
from products.replay_vision.backend.temporal.reconciler_types import (
DeleteScannerScheduleActivityInputs,
EnabledScannerEntry,
@@ -28,11 +30,16 @@ from products.replay_vision.backend.temporal.schedule import (
logger = structlog.get_logger(__name__)
+def _load_enabled_scanner_fingerprints() -> dict[UUID, tuple[int, str]]:
+ with bounded_queries(LIST_ENABLED_SCANNERS_TIMEOUT):
+ return load_enabled_scanner_fingerprints()
+
+
@activity.defn
@track_activity()
async def list_enabled_scanners_activity() -> list[EnabledScannerEntry]:
"""Every enabled ReplayScanner with its current fingerprint."""
- rows = await database_sync_to_async(load_enabled_scanner_fingerprints)()
+ rows = await database_sync_to_async(_load_enabled_scanner_fingerprints)()
return [EnabledScannerEntry(scanner_id=sid, team_id=team_id, fingerprint=fp) for sid, (team_id, fp) in rows.items()]
diff --git a/products/replay_vision/backend/temporal/activities/refresh_learned_rules.py b/products/replay_vision/backend/temporal/activities/refresh_learned_rules.py
index 90bc8046868a..69a93815d13f 100644
--- a/products/replay_vision/backend/temporal/activities/refresh_learned_rules.py
+++ b/products/replay_vision/backend/temporal/activities/refresh_learned_rules.py
@@ -9,16 +9,22 @@ from products.replay_vision.backend.learned_rules import (
refresh_team_learned_rules,
stamp_run,
)
-from products.replay_vision.backend.temporal.constants import LEARNED_RULES_MAX_TEAMS_PER_RUN
+from products.replay_vision.backend.temporal.constants import (
+ LEARNED_RULES_MAX_TEAMS_PER_RUN,
+ LIST_DUE_LEARNED_RULES_TIMEOUT,
+)
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.learned_rules_types import RefreshTeamLearnedRulesInputs
+from products.replay_vision.backend.temporal.query_budget import bounded_queries
@activity.defn
@track_activity()
def list_due_learned_rules_teams_activity() -> list[RefreshTeamLearnedRulesInputs]:
"""Teams with settled new ratings, cut to the per-run cap."""
- return [RefreshTeamLearnedRulesInputs(team_id=team_id) for team_id in due_teams(LEARNED_RULES_MAX_TEAMS_PER_RUN)]
+ with bounded_queries(LIST_DUE_LEARNED_RULES_TIMEOUT):
+ team_ids = due_teams(LEARNED_RULES_MAX_TEAMS_PER_RUN)
+ return [RefreshTeamLearnedRulesInputs(team_id=team_id) for team_id in team_ids]
@activity.defn
diff --git a/products/replay_vision/backend/temporal/activities/refresh_search_suggestions.py b/products/replay_vision/backend/temporal/activities/refresh_search_suggestions.py
index 8580acb81a88..1966f3f817ed 100644
--- a/products/replay_vision/backend/temporal/activities/refresh_search_suggestions.py
+++ b/products/replay_vision/backend/temporal/activities/refresh_search_suggestions.py
@@ -16,10 +16,12 @@ from products.replay_vision.backend.search_suggestions import (
stale_team_candidates,
)
from products.replay_vision.backend.temporal.constants import (
+ LIST_STALE_SEARCH_SUGGESTIONS_TIMEOUT,
SEARCH_SUGGESTIONS_MAX_PER_DAY,
SEARCH_SUGGESTIONS_MAX_PER_RUN,
)
from products.replay_vision.backend.temporal.decorators import track_activity
+from products.replay_vision.backend.temporal.query_budget import bounded_queries
from products.replay_vision.backend.temporal.search_suggestions_types import RefreshScannerSuggestionsInputs
@@ -31,8 +33,9 @@ def list_stale_search_suggestions_activity() -> list[RefreshScannerSuggestionsIn
remaining = min(SEARCH_SUGGESTIONS_MAX_PER_RUN, SEARCH_SUGGESTIONS_MAX_PER_DAY - model_calls_today())
if remaining <= 0:
return []
- teams = [RefreshScannerSuggestionsInputs(team_id=team_id) for team_id in stale_team_candidates(remaining // 4)]
- rows = stale_suggestion_candidates(remaining - len(teams)).values_list("id", "team_id")
+ with bounded_queries(LIST_STALE_SEARCH_SUGGESTIONS_TIMEOUT):
+ teams = [RefreshScannerSuggestionsInputs(team_id=team_id) for team_id in stale_team_candidates(remaining // 4)]
+ rows = list(stale_suggestion_candidates(remaining - len(teams)).values_list("id", "team_id"))
return teams + [RefreshScannerSuggestionsInputs(scanner_id=sid, team_id=team_id) for sid, team_id in rows]
diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.py
index d53b4788db32..77c2d4bdfc4e 100644
--- a/products/replay_vision/backend/temporal/constants.py
+++ b/products/replay_vision/backend/temporal/constants.py
@@ -166,6 +166,7 @@ MAX_IN_FLIGHT_APPLIES_PER_SCANNER = 150
# N x 150 rasterizer slots. Fairness only; the rasterizer scales horizontally for total throughput.
MAX_IN_FLIGHT_APPLIES_PER_TEAM = 300
COUNT_IN_FLIGHT_APPLIES_TIMEOUT = dt.timedelta(seconds=30)
+CREATE_OBSERVATION_TIMEOUT = dt.timedelta(seconds=30)
CHECK_SCANNER_BUDGET_TIMEOUT = dt.timedelta(seconds=30)
diff --git a/products/replay_vision/backend/temporal/jev_watch_rank/activities.py b/products/replay_vision/backend/temporal/jev_watch_rank/activities.py
index 448e29c0b432..982fef3d4712 100644
--- a/products/replay_vision/backend/temporal/jev_watch_rank/activities.py
+++ b/products/replay_vision/backend/temporal/jev_watch_rank/activities.py
@@ -48,6 +48,7 @@ from products.replay_vision.backend.temporal.jev_watch_rank.constants import (
MAX_SCANNERS_PER_SWEEP,
MAX_TEAMS_PER_SWEEP,
PINNED_TEAM_IDS,
+ SWEEP_ACTIVITY_HEARTBEAT_TIMEOUT,
SWEEP_TIME_BUDGET,
WATCH_RANK_WINDOW,
WINDOW_SCAN_CAP,
@@ -56,6 +57,11 @@ from products.replay_vision.backend.temporal.jev_watch_rank.types import (
JevWatchRankSweepInputs,
JevWatchRankSweepResult,
)
+from products.replay_vision.backend.temporal.query_budget import bounded_queries
+
+# The background heartbeat keeps a stalled query's attempt alive for the whole sweep, so each query gets its own
+# heartbeat window instead.
+_QUERY_BUDGET = SWEEP_ACTIVITY_HEARTBEAT_TIMEOUT
logger = structlog.get_logger(__name__)
@@ -68,40 +74,45 @@ def _teams_with_scanners() -> list[int]:
an unordered slice could drop an enrolled team on some runs and not others. Pinned teams go
first, so they never fall past the cap at all.
"""
- team_ids = ReplayScanner.all_origins.values_list("team_id", flat=True).distinct().order_by("team_id")
- return [
- *PINNED_TEAM_IDS,
- *[team_id for team_id in team_ids[: MAX_TEAMS_PER_SWEEP + 1] if team_id not in PINNED_TEAM_IDS],
- ]
+ with bounded_queries(_QUERY_BUDGET, from_attempt_start=False):
+ team_ids = list(
+ ReplayScanner.all_origins.values_list("team_id", flat=True)
+ .distinct()
+ .order_by("team_id")[: MAX_TEAMS_PER_SWEEP + 1]
+ )
+ return [*PINNED_TEAM_IDS, *[team_id for team_id in team_ids if team_id not in PINNED_TEAM_IDS]]
def _team_scanner_ids(team_id: int, window_start: datetime) -> list[UUID]:
- return list(
- ReplayObservation.objects.filter(
- team_id=team_id, status=ObservationStatus.SUCCEEDED, created_at__gte=window_start
+ with bounded_queries(_QUERY_BUDGET, from_attempt_start=False):
+ return list(
+ ReplayObservation.objects.filter(
+ team_id=team_id, status=ObservationStatus.SUCCEEDED, created_at__gte=window_start
+ )
+ .values_list("scanner_id", flat=True)
+ .distinct()
)
- .values_list("scanner_id", flat=True)
- .distinct()
- )
def _scanner_window_ids(team_id: int, scanner_id: UUID, window_start: datetime) -> list[UUID]:
"""Newest first, ids only: cheap enough to list the whole capped window every sweep, so the
sweep can tell which rows still lack a judgment and which cached entries left the window."""
- return list(
- ReplayObservation.objects.filter(
- team_id=team_id,
- scanner_id=scanner_id,
- status=ObservationStatus.SUCCEEDED,
- created_at__gte=window_start,
+ with bounded_queries(_QUERY_BUDGET, from_attempt_start=False):
+ return list(
+ ReplayObservation.objects.filter(
+ team_id=team_id,
+ scanner_id=scanner_id,
+ status=ObservationStatus.SUCCEEDED,
+ created_at__gte=window_start,
+ )
+ .order_by("-created_at")
+ .values_list("id", flat=True)[:WINDOW_SCAN_CAP]
)
- .order_by("-created_at")
- .values_list("id", flat=True)[:WINDOW_SCAN_CAP]
- )
def _rows_by_id(team_id: int, ids: list[UUID]) -> list[dict[str, Any]]:
- rows = ReplayObservation.objects.filter(team_id=team_id, id__in=ids).values("id", "scanner_result")
+ with bounded_queries(_QUERY_BUDGET, from_attempt_start=False):
+ rows = list(ReplayObservation.objects.filter(team_id=team_id, id__in=ids).values("id", "scanner_result"))
by_id = {row["id"]: dict(row) for row in rows}
# `id__in` loses the caller's newest-first order.
return [by_id[row_id] for row_id in ids if row_id in by_id]
diff --git a/products/replay_vision/backend/temporal/query_budget.py b/products/replay_vision/backend/temporal/query_budget.py
new file mode 100644
index 000000000000..77335688e653
--- /dev/null
+++ b/products/replay_vision/backend/temporal/query_budget.py
@@ -0,0 +1,85 @@
+import time
+import datetime as dt
+from collections.abc import Callable, Iterator
+from contextlib import ExitStack, contextmanager, suppress
+from typing import Any
+
+from django.db import DatabaseError, connections, router, transaction
+from django.db.backends.base.base import BaseDatabaseWrapper
+
+from temporalio import activity
+
+from posthog.ingress.dispatch.database import read_aliases
+
+from products.replay_vision.backend.models.replay_observation import ReplayObservation
+from products.replay_vision.backend.models.replay_scanner import ReplayScanner
+
+# Leaves the attempt time to fail cleanly once Postgres cancels the statement.
+_BUDGET_SHARE = 0.75
+_MODELS = [ReplayScanner, ReplayObservation]
+
+
+def _aliases() -> list[str]:
+ aliases = read_aliases(_MODELS)
+ for model in _MODELS:
+ alias = router.db_for_write(model) or "default"
+ if alias not in aliases:
+ aliases.append(alias)
+ return aliases
+
+
+def _attempt_started_at() -> float:
+ if activity.in_activity():
+ return activity.info().started_time.timestamp()
+ return time.time()
+
+
+def _set_statement_timeout(connection: BaseDatabaseWrapper, value: str) -> None:
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT set_config('statement_timeout', %s, true)", [value])
+
+
+@contextmanager
+def _capped(connection: BaseDatabaseWrapper, deadline: float) -> Iterator[None]:
+ def cap_to_deadline(execute: Callable[..., Any], sql: str, params: Any, many: bool, context: dict[str, Any]) -> Any:
+ remaining_ms = max(1, int((deadline - time.time()) * 1000))
+ # The driver cursor runs this outside the wrapper chain, so it does not recurse.
+ driver_cursor = context["cursor"].cursor
+ if connection.in_atomic_block:
+ driver_cursor.execute("SELECT set_config('statement_timeout', %s, true)", [f"{remaining_ms}ms"])
+ return execute(sql, params, many, context)
+ # SET LOCAL needs a transaction, so an autocommit statement gets one of its own.
+ with transaction.atomic(using=connection.alias):
+ driver_cursor.execute("SELECT set_config('statement_timeout', %s, true)", [f"{remaining_ms}ms"])
+ return execute(sql, params, many, context)
+
+ # Inside a caller's transaction the cap must not outlive the block, so the caller's value goes back.
+ previous = None
+ if connection.in_atomic_block:
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT current_setting('statement_timeout')")
+ previous = cursor.fetchone()[0]
+ try:
+ with connection.execute_wrapper(cap_to_deadline):
+ yield
+ finally:
+ if previous is not None:
+ # An aborted transaction rejects the reset, and its rollback undoes the cap anyway.
+ with suppress(DatabaseError):
+ _set_statement_timeout(connection, previous)
+
+
+@contextmanager
+def bounded_queries(attempt_timeout: dt.timedelta, *, from_attempt_start: bool = True) -> Iterator[None]:
+ """Cancel Postgres work in the block once it runs past most of the timeout that ends the attempt.
+
+ A timed-out attempt leaves its thread and query running, so each retry would add another copy holding locks.
+ Every block in one attempt shares the budget counted from the attempt's start; pass `from_attempt_start=False`
+ to give each block its own. No connection opens until a statement runs on it.
+ """
+ started = _attempt_started_at() if from_attempt_start else time.time()
+ deadline = started + attempt_timeout.total_seconds() * _BUDGET_SHARE
+ with ExitStack() as stack:
+ for alias in _aliases():
+ stack.enter_context(_capped(connections[alias], deadline))
+ yield
diff --git a/products/replay_vision/backend/temporal/vision_alerts/activities.py b/products/replay_vision/backend/temporal/vision_alerts/activities.py
index aa8be2ae2e2a..810909704ff5 100644
--- a/products/replay_vision/backend/temporal/vision_alerts/activities.py
+++ b/products/replay_vision/backend/temporal/vision_alerts/activities.py
@@ -61,7 +61,9 @@ from products.replay_vision.backend.models.vision_alert import (
from products.replay_vision.backend.observation_formatting import describe_output, explanation_text, plain_snippet
from products.replay_vision.backend.prompt_questions import scanner_question
from products.replay_vision.backend.temporal.decorators import track_activity
+from products.replay_vision.backend.temporal.query_budget import bounded_queries
from products.replay_vision.backend.temporal.vision_alerts.constants import (
+ ACTIVITY_TIMEOUT,
CLEANUP_BATCH_SIZE,
MATCH_DESCRIPTOR_MAX_CHARS,
MATCH_EXPLANATION_MAX_CHARS,
@@ -163,14 +165,15 @@ def _discover_due(inputs: DiscoverDueAlertsInput) -> DiscoverDueAlertsOutput:
now = datetime.now(UTC)
# Oldest due first, capped so the workflow result stays far below Temporal's payload
# limit; the overflow keeps its next_check_at and is picked up next tick.
- due_ids = list(
- VisionAlertConfiguration.all_teams.filter(
- due_alerts_q(now, broken_state=AlertState.BROKEN.value, snoozed_state=AlertState.SNOOZED.value),
- kind=VisionAlertKind.METRIC,
+ with bounded_queries(ACTIVITY_TIMEOUT):
+ due_ids = list(
+ VisionAlertConfiguration.all_teams.filter(
+ due_alerts_q(now, broken_state=AlertState.BROKEN.value, snoozed_state=AlertState.SNOOZED.value),
+ kind=VisionAlertKind.METRIC,
+ )
+ .order_by("next_check_at", "id")
+ .values_list("id", flat=True)[: MAX_ALERTS_PER_TICK + 1]
)
- .order_by("next_check_at", "id")
- .values_list("id", flat=True)[: MAX_ALERTS_PER_TICK + 1]
- )
if len(due_ids) > MAX_ALERTS_PER_TICK:
logger.warning("vision_alert.discovery_truncated", cap=MAX_ALERTS_PER_TICK)
due_ids = due_ids[:MAX_ALERTS_PER_TICK]
@@ -235,17 +238,18 @@ def _evaluate_single_alert(alert: VisionAlertConfiguration, now: datetime) -> _A
check_result: CheckResult
try:
queryset = _observation_window_qs(alert, window_start, now)
- if alert.metric == VisionAlertMetric.AVG_SCORE:
- # Cast the JSONB score to float and average it; observations without a
- # score (non-scorers) become NULL and fall out of the average.
- metric_value = queryset.annotate(
- _score=Cast(
- KeyTextTransform("score", KeyTextTransform("model_output", "scanner_result")),
- output_field=FloatField(),
- )
- ).aggregate(avg=Avg("_score"))["avg"]
- else:
- metric_value = float(queryset.count())
+ with bounded_queries(ACTIVITY_TIMEOUT):
+ if alert.metric == VisionAlertMetric.AVG_SCORE:
+ # Cast the JSONB score to float and average it; observations without a
+ # score (non-scorers) become NULL and fall out of the average.
+ metric_value = queryset.annotate(
+ _score=Cast(
+ KeyTextTransform("score", KeyTextTransform("model_output", "scanner_result")),
+ output_field=FloatField(),
+ )
+ ).aggregate(avg=Avg("_score"))["avg"]
+ else:
+ metric_value = float(queryset.count())
if metric_value is None:
# An empty window has no average; neither direction can breach.
@@ -591,27 +595,30 @@ def _cleanup_history(inputs: CleanupAlertHistoryInput) -> int:
now = datetime.now(UTC)
deleted = 0
- event_ids = list(
- VisionAlertEvent.objects.filter(created_at__lt=now - timedelta(days=EVENT_RETENTION_DAYS)).values_list(
- "id", flat=True
- )[:CLEANUP_BATCH_SIZE]
- )
- if event_ids:
- deleted += VisionAlertEvent.objects.filter(id__in=event_ids).delete()[0]
-
- delivered_ids = list(
- VisionAlertMatch.all_teams.filter(
- delivered_at__lt=now - timedelta(days=DELIVERED_MATCH_RETENTION_DAYS)
- ).values_list("id", flat=True)[:CLEANUP_BATCH_SIZE]
- )
- stale_ids = list(
- VisionAlertMatch.all_teams.filter(
- delivered_at__isnull=True, created_at__lt=now - timedelta(days=STALE_MATCH_RETENTION_DAYS)
- ).values_list("id", flat=True)[:CLEANUP_BATCH_SIZE]
- )
- match_ids = delivered_ids + stale_ids
- if match_ids:
- deleted += VisionAlertMatch.all_teams.filter(id__in=match_ids).delete()[0]
+ # Separate transactions, so one table that times out does not undo the other's progress.
+ with bounded_queries(ACTIVITY_TIMEOUT):
+ event_ids = list(
+ VisionAlertEvent.objects.filter(created_at__lt=now - timedelta(days=EVENT_RETENTION_DAYS)).values_list(
+ "id", flat=True
+ )[:CLEANUP_BATCH_SIZE]
+ )
+ if event_ids:
+ deleted += VisionAlertEvent.objects.filter(id__in=event_ids).delete()[0]
+
+ with bounded_queries(ACTIVITY_TIMEOUT):
+ delivered_ids = list(
+ VisionAlertMatch.all_teams.filter(
+ delivered_at__lt=now - timedelta(days=DELIVERED_MATCH_RETENTION_DAYS)
+ ).values_list("id", flat=True)[:CLEANUP_BATCH_SIZE]
+ )
+ stale_ids = list(
+ VisionAlertMatch.all_teams.filter(
+ delivered_at__isnull=True, created_at__lt=now - timedelta(days=STALE_MATCH_RETENTION_DAYS)
+ ).values_list("id", flat=True)[:CLEANUP_BATCH_SIZE]
+ )
+ match_ids = delivered_ids + stale_ids
+ if match_ids:
+ deleted += VisionAlertMatch.all_teams.filter(id__in=match_ids).delete()[0]
return deleted
@@ -652,14 +659,15 @@ def _drain_matches(inputs: DrainMatchesInput) -> DrainMatchesOutput:
# each bundle separately, so one high-volume alert cannot fill a global slice and
# starve the rest. Disabled and snoozed alerts are excluded in SQL so their held
# rows cannot occupy the alert budget either.
- due_alert_ids = list(
- VisionAlertMatch.all_teams.filter(delivered_at__isnull=True, alert__enabled=True)
- .exclude(alert__snooze_until__gt=now)
- .values("alert_id")
- .annotate(oldest=Min("created_at"))
- .order_by("oldest")
- .values_list("alert_id", flat=True)[:MAX_DRAIN_ALERTS_PER_TICK]
- )
+ with bounded_queries(ACTIVITY_TIMEOUT):
+ due_alert_ids = list(
+ VisionAlertMatch.all_teams.filter(delivered_at__isnull=True, alert__enabled=True)
+ .exclude(alert__snooze_until__gt=now)
+ .values("alert_id")
+ .annotate(oldest=Min("created_at"))
+ .order_by("oldest")
+ .values_list("alert_id", flat=True)[:MAX_DRAIN_ALERTS_PER_TICK]
+ )
if not due_alert_ids:
return DrainMatchesOutput()
diff --git a/products/replay_vision/backend/temporal/workflow.py b/products/replay_vision/backend/temporal/workflow.py
index cd6d8b681506..5263b6b66564 100644
--- a/products/replay_vision/backend/temporal/workflow.py
+++ b/products/replay_vision/backend/temporal/workflow.py
@@ -51,6 +51,7 @@ from products.replay_vision.backend.temporal.activities import (
)
from products.replay_vision.backend.temporal.constants import (
APPLY_SCANNER_WORKFLOW_NAME,
+ CREATE_OBSERVATION_TIMEOUT,
STATE_ACTIVITY_RETRY,
STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
)
@@ -300,7 +301,7 @@ class ApplyScannerWorkflow(PostHogWorkflow):
backfill_id=inputs.backfill_id,
variant_sampling_rates=inputs.variant_sampling_rates,
),
- start_to_close_timeout=dt.timedelta(seconds=30),
+ start_to_close_timeout=CREATE_OBSERVATION_TIMEOUT,
schedule_to_close_timeout=STATE_ACTIVITY_SCHEDULE_TO_CLOSE,
retry_policy=_CREATE_OBSERVATION_RETRY,
)
diff --git a/products/replay_vision/backend/tests/test_query_budget.py b/products/replay_vision/backend/tests/test_query_budget.py
new file mode 100644
index 000000000000..fa5994128aeb
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_query_budget.py
@@ -0,0 +1,32 @@
+import datetime as dt
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.db import OperationalError, connection
+
+from products.replay_vision.backend.temporal import query_budget
+from products.replay_vision.backend.temporal.query_budget import bounded_queries
+
+
+class TestBoundedQueries(BaseTest):
+ def test_a_later_statement_only_gets_what_is_left_of_the_block_budget(self) -> None:
+ clock = iter([0.0, 0.0, 100.0])
+ with patch.object(query_budget.time, "time", side_effect=lambda: next(clock)):
+ with self.assertRaisesRegex(OperationalError, "statement timeout"):
+ with bounded_queries(dt.timedelta(seconds=60)):
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT 1")
+ cursor.execute("SELECT pg_sleep(0.2)")
+
+ def test_the_caller_transaction_gets_its_timeout_back_when_the_block_raises(self) -> None:
+ with connection.cursor() as cursor:
+ cursor.execute("SET LOCAL statement_timeout = '7s'")
+ with self.assertRaises(ValueError):
+ with bounded_queries(dt.timedelta(seconds=60)):
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT 1")
+ raise ValueError
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT current_setting('statement_timeout')")
+ self.assertEqual(cursor.fetchone()[0], "7s")
diff --git a/products/replay_vision/backend/tests/test_reconciler.py b/products/replay_vision/backend/tests/test_reconciler.py
index 01bf414716c5..2376b9e1ba3b 100644
--- a/products/replay_vision/backend/tests/test_reconciler.py
+++ b/products/replay_vision/backend/tests/test_reconciler.py
@@ -1,5 +1,6 @@
import uuid
import datetime as dt
+import dataclasses
from collections.abc import Callable
from typing import Any
@@ -62,6 +63,13 @@ from products.replay_vision.backend.temporal.schedule import (
)
+def _live_activity_env() -> ActivityEnvironment:
+ env = ActivityEnvironment()
+ # The default start is the epoch, which would put every query budget measured from it in the past.
+ env.info = dataclasses.replace(env.info, started_time=dt.datetime.now(dt.UTC))
+ return env
+
+
@pytest.fixture
def org_team(db) -> tuple[Organization, Team]:
org = Organization.objects.create(name="vision-reconciler-test-org")
@@ -537,7 +545,7 @@ async def test_reap_orphaned_observations_activity(org_team) -> None:
"products.replay_vision.backend.temporal.activities.reap_orphaned_observations.async_connect",
AsyncMock(return_value=temporal),
):
- reaped = await ActivityEnvironment().run(reap_orphaned_observations_activity)
+ reaped = await _live_activity_env().run(reap_orphaned_observations_activity)
assert reaped == 3
statuses = {
@@ -610,7 +618,7 @@ async def test_reap_childless_inline_scanners_activity(org_team) -> None:
rows = await sync_to_async(_setup)()
- reaped = await ActivityEnvironment().run(reap_childless_inline_scanners_activity)
+ reaped = await _live_activity_env().run(reap_childless_inline_scanners_activity)
assert reaped == 1
surviving = await sync_to_async(
diff --git a/products/replay_vision/backend/tests/test_search_suggestions.py b/products/replay_vision/backend/tests/test_search_suggestions.py
index 542ff02f465e..b2ca11c899f3 100644
--- a/products/replay_vision/backend/tests/test_search_suggestions.py
+++ b/products/replay_vision/backend/tests/test_search_suggestions.py
@@ -295,6 +295,25 @@ class TestRefreshAndCandidates(_SuggestionsTestCase):
self.assertFalse(refresh_team_suggestions(self.team))
self.assertEqual(TeamReplayVisionConfig.objects.get(team_id=self.team.id).search_suggestions, [])
+ def test_team_candidates_count_rows_completed_after_the_watermark_even_when_created_before_it(self) -> None:
+ scanner = self._scanner("checkout")
+ watermark = timezone.now() - dt.timedelta(hours=1)
+ TeamReplayVisionConfig.objects.update_or_create(
+ team_id=self.team.id,
+ defaults={
+ "search_suggestions_watermark": watermark,
+ "search_suggestions_generated_at": timezone.now() - dt.timedelta(days=30),
+ },
+ )
+ self._seed(scanner, MIN_OBSERVATIONS_FOR_FIRST_PHRASES)
+ ReplayObservation.objects.filter(scanner=scanner).update(
+ created_at=watermark - dt.timedelta(minutes=30), completed_at=watermark - dt.timedelta(minutes=5)
+ )
+ self.assertEqual(stale_team_candidates(10), [])
+
+ ReplayObservation.objects.filter(scanner=scanner).update(completed_at=watermark + dt.timedelta(minutes=5))
+ self.assertEqual(stale_team_candidates(10), [self.team.id])
+
@patch(_GENERATE_PATH, side_effect=SuggestionError("model down"))
def test_activity_keeps_old_phrases_and_backs_off_on_model_failure(self, _mock: MagicMock) -> None:
scanner = self._scanner("checkout", search_suggestions=["old phrase"], search_last_viewed_at=timezone.now())