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 stranded reconciler activities instead (#88788)

Hayne Ryu7511152d7664
diff --git a/products/replay_vision/backend/temporal/activities/backfill.py b/products/replay_vision/backend/temporal/activities/backfill.py
index c6f8f4e343ea..305b89abfcaf 100644
--- a/products/replay_vision/backend/temporal/activities/backfill.py
+++ b/products/replay_vision/backend/temporal/activities/backfill.py
@@ -360,6 +360,8 @@ async def reap_backfill_schedules_activity() -> None:
seen: set[UUID] = set()
fixes = []
async for listing in await client.list_schedules(query=f'PostHogScheduleType = "{BACKFILL_SCHEDULE_TYPE}"'):
+ # The SDK throttles the RPCs, so per-listing is cheap.
+ activity.heartbeat({"phase": "listing_schedules", "seen": len(seen)})
if not listing.id.startswith(prefix):
continue
try:
@@ -376,4 +378,5 @@ async def reap_backfill_schedules_activity() -> None:
logger.info("replay_vision.backfill_reaper.recreating_missing", backfill_id=str(backfill_id))
fixes.append(_recreate_schedule(backfill_id, team_id, scanner_id, row_status, client))
if fixes:
+ activity.heartbeat({"phase": "applying_fixes", "fixes": len(fixes)})
await asyncio.gather(*fixes)
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 ca408c80eda9..190af173c0da 100644
--- a/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py
+++ b/products/replay_vision/backend/temporal/activities/reap_orphaned_observations.py
@@ -122,6 +122,8 @@ async def _reap_observations(temporal: Client, rows: list[dict[str, Any]]) -> in
scanner_type = snapshot.get("scanner_type") or "unknown"
if await database_sync_to_async(_mark_orphaned, thread_sensitive=False)(row["id"], scanner_type):
reaped += 1
+ # The SDK throttles the RPCs, so per-row is cheap.
+ activity.heartbeat({"phase": "observations_reaping", "reaped": reaped})
logger.info(
"replay_vision.reap_orphaned_observations",
scanned=len(rows),
@@ -139,6 +141,7 @@ async def _reap_evaluations(temporal: Client, rows: list[dict[str, Any]]) -> int
for row in reapable:
if await database_sync_to_async(_fail_evaluation, thread_sensitive=False)(row["id"]):
reaped += 1
+ activity.heartbeat({"phase": "evaluations_reaping", "reaped": reaped})
logger.info("replay_vision.reap_stuck_evaluations", scanned=len(rows), reaped=reaped)
return reaped
diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.py
index 38d5be87f429..cf43b451f21e 100644
--- a/products/replay_vision/backend/temporal/constants.py
+++ b/products/replay_vision/backend/temporal/constants.py
@@ -30,9 +30,8 @@ def on_demand_priority(team_id: int) -> Priority:
OBSERVATION_ORPHAN_CUTOFF = APPLY_SCANNER_EXECUTION_TIMEOUT + dt.timedelta(minutes=30)
# Bounds one reaper pass; a backlog beyond this drains across subsequent reconciler ticks.
REAP_ORPHANED_OBSERVATIONS_BATCH_SIZE = 500
-REAP_ORPHANED_OBSERVATIONS_TIMEOUT = dt.timedelta(minutes=3)
-# The reaper heartbeats between phases; a pass that goes quiet this long is stalled, not slow.
-REAP_ORPHANED_OBSERVATIONS_HEARTBEAT_TIMEOUT = dt.timedelta(seconds=60)
+# The reaper heartbeats as it works, so an attempt quiet this long is stranded or stalled, not slow.
+REAP_ORPHANED_OBSERVATIONS_HEARTBEAT_TIMEOUT = dt.timedelta(seconds=30)
# Per-action vision-action child, fire-and-forgot by the sweep. Name + timeout live here (not in the
# workflow-def module) so the sweep can start it without cross-importing another @wf.defn module.
@@ -43,13 +42,11 @@ PROCESS_VISION_ACTION_EXECUTION_TIMEOUT = dt.timedelta(hours=1)
# update activity failed or the workflow was terminated without reaching it).
VISION_ACTION_RUN_STUCK_CUTOFF = PROCESS_VISION_ACTION_EXECUTION_TIMEOUT * 2
REAP_STUCK_VISION_ACTION_RUNS_BATCH_SIZE = 500
-REAP_STUCK_VISION_ACTION_RUNS_TIMEOUT = dt.timedelta(minutes=3)
# An inline scanner is minted just before its scans start, so anything still childless well after a
# scan could have persisted its first observation never had one.
INLINE_SCANNER_REAP_GRACE = APPLY_SCANNER_EXECUTION_TIMEOUT + dt.timedelta(minutes=30)
INLINE_SCANNER_REAP_BATCH_SIZE = 500
-INLINE_SCANNER_REAP_TIMEOUT = dt.timedelta(minutes=3)
def build_process_vision_action_workflow_id(vision_action_id: UUID) -> str:
@@ -143,6 +140,20 @@ LIST_ENABLED_SCANNERS_TIMEOUT = dt.timedelta(seconds=60)
LIST_SCANNER_SCHEDULES_TIMEOUT = dt.timedelta(seconds=120)
RECONCILE_SCHEDULE_OP_TIMEOUT = dt.timedelta(seconds=60)
+# Short attempts so one stranded on a dying worker reruns on a live one instead of holding the tick.
+REAPER_OP_TIMEOUT = dt.timedelta(seconds=45)
+REAPER_OP_SCHEDULE_TO_CLOSE = dt.timedelta(minutes=2)
+REAPER_MAX_ATTEMPTS = 3
+
+# The backfill reaper pages through every backfill schedule and only applies fixes at the end, so a
+# healthy pass needs minutes; per-page heartbeats catch a dead worker instead of a short attempt cap.
+REAP_BACKFILL_SCHEDULES_TIMEOUT = dt.timedelta(minutes=3)
+REAP_BACKFILL_SCHEDULES_SCHEDULE_TO_CLOSE = dt.timedelta(minutes=4)
+REAP_BACKFILL_SCHEDULES_HEARTBEAT_TIMEOUT = dt.timedelta(seconds=30)
+
+# Priority 1 so a saturated sweep/backfill backlog cannot queue the tick past its execution timeout.
+RECONCILER_ACTIVITY_PRIORITY = Priority(priority_key=1, fairness_key="replay-vision-scanner-reconciler")
+
# Bounded so broker errors surface as activity failures instead of getting lost in the producer buffer.
KAFKA_DELIVERY_TIMEOUT_S = 10.0
@@ -200,7 +211,6 @@ PREPARE_BACKFILL_TICK_TIMEOUT = dt.timedelta(seconds=30)
FIND_BACKFILL_CANDIDATES_TIMEOUT = dt.timedelta(seconds=200)
ADVANCE_BACKFILL_CURSOR_TIMEOUT = dt.timedelta(seconds=30)
BACKFILL_SCHEDULE_OP_TIMEOUT = dt.timedelta(seconds=60)
-REAP_BACKFILL_SCHEDULES_TIMEOUT = dt.timedelta(minutes=3)
# A backfill's dispatches count toward the shared per-scanner/per-team caps but never fill more than
# this many slots, so live sweeps always retain rasterizer + provider capacity.
diff --git a/products/replay_vision/backend/temporal/reconciler.py b/products/replay_vision/backend/temporal/reconciler.py
index 1af84045c3cd..9361bf19672a 100644
--- a/products/replay_vision/backend/temporal/reconciler.py
+++ b/products/replay_vision/backend/temporal/reconciler.py
@@ -1,8 +1,9 @@
"""Syncs per-scanner schedules with the ReplayScanner table on every tick, and reaps orphaned observations."""
import asyncio
+import datetime as dt
from collections.abc import Awaitable, Callable
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
from uuid import UUID
from temporalio import workflow
@@ -12,14 +13,17 @@ from temporalio.exceptions import ApplicationError
from posthog.temporal.common.base import PostHogWorkflow
from products.replay_vision.backend.temporal.constants import (
- INLINE_SCANNER_REAP_TIMEOUT,
LIST_ENABLED_SCANNERS_TIMEOUT,
LIST_SCANNER_SCHEDULES_TIMEOUT,
+ REAP_BACKFILL_SCHEDULES_HEARTBEAT_TIMEOUT,
+ REAP_BACKFILL_SCHEDULES_SCHEDULE_TO_CLOSE,
REAP_BACKFILL_SCHEDULES_TIMEOUT,
REAP_ORPHANED_OBSERVATIONS_HEARTBEAT_TIMEOUT,
- REAP_ORPHANED_OBSERVATIONS_TIMEOUT,
- REAP_STUCK_VISION_ACTION_RUNS_TIMEOUT,
+ REAPER_MAX_ATTEMPTS,
+ REAPER_OP_SCHEDULE_TO_CLOSE,
+ REAPER_OP_TIMEOUT,
RECONCILE_SCHEDULE_OP_TIMEOUT,
+ RECONCILER_ACTIVITY_PRIORITY,
RECONCILER_EXECUTION_TIMEOUT,
RECONCILER_INTERVAL,
RECONCILER_SCHEDULE_ID,
@@ -59,43 +63,34 @@ class ReconcileScannerSchedulesWorkflow(PostHogWorkflow):
async def run(self, inputs: ReconcileScannerSchedulesInputs) -> ReconcileScannerSchedulesResult:
# Best-effort and first: a schedule-sync failure below must not starve the reapers, and vice versa.
try:
- await workflow.execute_activity(
+ await self._run_reaper(
reap_orphaned_observations_activity,
- start_to_close_timeout=REAP_ORPHANED_OBSERVATIONS_TIMEOUT,
- # The activity heartbeats between phases, so a stalled pass is cut loose before it burns
- # the whole tick budget.
heartbeat_timeout=REAP_ORPHANED_OBSERVATIONS_HEARTBEAT_TIMEOUT,
- retry_policy=RetryPolicy(maximum_attempts=1),
)
except Exception:
workflow.logger.exception("replay_vision.reap_orphaned_observations_failed")
if workflow.patched("reap-stuck-vision-action-runs-2026-07"):
try:
- await workflow.execute_activity(
- reap_stuck_vision_action_runs_activity,
- start_to_close_timeout=REAP_STUCK_VISION_ACTION_RUNS_TIMEOUT,
- retry_policy=RetryPolicy(maximum_attempts=1),
- )
+ await self._run_reaper(reap_stuck_vision_action_runs_activity)
except Exception:
workflow.logger.exception("replay_vision.reap_stuck_vision_action_runs_failed")
if workflow.patched("reap-childless-inline-scanners-2026-08"):
try:
- await workflow.execute_activity(
- reap_childless_inline_scanners_activity,
- start_to_close_timeout=INLINE_SCANNER_REAP_TIMEOUT,
- retry_policy=RetryPolicy(maximum_attempts=1),
- )
+ await self._run_reaper(reap_childless_inline_scanners_activity)
except Exception:
workflow.logger.exception("replay_vision.reap_childless_inline_scanners_failed")
if workflow.patched("reap-backfill-schedules-2026-08"):
try:
- await workflow.execute_activity(
+ # A full schedule listing outlives the short reaper attempt, so this one keeps a long
+ # attempt and leans on heartbeats to detect a dead worker.
+ await self._run_reaper(
reap_backfill_schedules_activity,
+ heartbeat_timeout=REAP_BACKFILL_SCHEDULES_HEARTBEAT_TIMEOUT,
start_to_close_timeout=REAP_BACKFILL_SCHEDULES_TIMEOUT,
- retry_policy=RetryPolicy(maximum_attempts=1),
+ schedule_to_close_timeout=REAP_BACKFILL_SCHEDULES_SCHEDULE_TO_CLOSE,
)
except Exception:
workflow.logger.exception("replay_vision.reap_backfill_schedules_failed")
@@ -106,11 +101,13 @@ class ReconcileScannerSchedulesWorkflow(PostHogWorkflow):
list_enabled_scanners_activity,
start_to_close_timeout=LIST_ENABLED_SCANNERS_TIMEOUT,
retry_policy=RetryPolicy(maximum_attempts=3),
+ priority=RECONCILER_ACTIVITY_PRIORITY,
),
workflow.execute_activity(
list_scanner_schedules_activity,
start_to_close_timeout=LIST_SCANNER_SCHEDULES_TIMEOUT,
retry_policy=RetryPolicy(maximum_attempts=3),
+ priority=RECONCILER_ACTIVITY_PRIORITY,
),
)
enabled = {entry.scanner_id: entry for entry in enabled_entries}
@@ -128,6 +125,7 @@ class ReconcileScannerSchedulesWorkflow(PostHogWorkflow):
UpsertScannerScheduleActivityInputs(scanner_id=sid, team_id=enabled[sid].team_id),
start_to_close_timeout=RECONCILE_SCHEDULE_OP_TIMEOUT,
retry_policy=RetryPolicy(maximum_attempts=3),
+ priority=RECONCILER_ACTIVITY_PRIORITY,
),
),
self._fan_out(
@@ -137,6 +135,7 @@ class ReconcileScannerSchedulesWorkflow(PostHogWorkflow):
DeleteScannerScheduleActivityInputs(scanner_id=sid),
start_to_close_timeout=RECONCILE_SCHEDULE_OP_TIMEOUT,
retry_policy=RetryPolicy(maximum_attempts=3),
+ priority=RECONCILER_ACTIVITY_PRIORITY,
),
),
)
@@ -161,6 +160,23 @@ class ReconcileScannerSchedulesWorkflow(PostHogWorkflow):
raise ApplicationError(f"reconciler: all {attempted} fan-out activities failed")
return result
+ async def _run_reaper(
+ self,
+ reaper_activity: Callable[[], Any],
+ *,
+ heartbeat_timeout: dt.timedelta | None = None,
+ start_to_close_timeout: dt.timedelta = REAPER_OP_TIMEOUT,
+ schedule_to_close_timeout: dt.timedelta = REAPER_OP_SCHEDULE_TO_CLOSE,
+ ) -> None:
+ await workflow.execute_activity(
+ reaper_activity,
+ start_to_close_timeout=start_to_close_timeout,
+ schedule_to_close_timeout=schedule_to_close_timeout,
+ heartbeat_timeout=heartbeat_timeout,
+ retry_policy=RetryPolicy(maximum_attempts=REAPER_MAX_ATTEMPTS),
+ priority=RECONCILER_ACTIVITY_PRIORITY,
+ )
+
async def _fan_out(self, scanner_ids: list[UUID], make_coro: Callable[[UUID], Awaitable[None]]) -> list[bool]:
if not scanner_ids:
return []