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.

feat(replay): prioritize on-demand vision observations (#85236)

Tue Haulund1fab11f9a7ea
diff --git a/products/replay_vision/backend/api/prompt_suggestions.py b/products/replay_vision/backend/api/prompt_suggestions.py
index 1941b99d528b..5eac36bd4a91 100644
--- a/products/replay_vision/backend/api/prompt_suggestions.py
+++ b/products/replay_vision/backend/api/prompt_suggestions.py
@@ -50,6 +50,7 @@ from products.replay_vision.backend.scanner_config import scanner_config_error
from products.replay_vision.backend.temporal.constants import (
EVALUATE_PROMPT_SUGGESTION_WORKFLOW_NAME,
build_evaluate_prompt_suggestion_workflow_id,
+ on_demand_priority,
)
from products.replay_vision.backend.temporal.evaluation_types import EvaluatePromptSuggestionInputs
from products.replay_vision.backend.temporal.metrics import record_scanner_limit_reached
@@ -478,6 +479,8 @@ class ReplayScannerPromptSuggestionViewSet(
id=build_evaluate_prompt_suggestion_workflow_id(suggestion.id),
task_queue=settings.REPLAY_VISION_TASK_QUEUE,
execution_timeout=EVALUATE_PROMPT_SUGGESTION_EXECUTION_TIMEOUT,
+ # A user waiting on "test this prompt" ranks with the other user-initiated starts.
+ priority=on_demand_priority(scanner.team_id),
search_attributes=TypedSearchAttributes(
search_attributes=[SearchAttributePair(key=POSTHOG_TEAM_ID_KEY, value=scanner.team_id)]
),
diff --git a/products/replay_vision/backend/api/trigger.py b/products/replay_vision/backend/api/trigger.py
index 07b7a3eaed16..0d3fda9b4ee9 100644
--- a/products/replay_vision/backend/api/trigger.py
+++ b/products/replay_vision/backend/api/trigger.py
@@ -42,6 +42,7 @@ from products.replay_vision.backend.temporal.constants import (
PROCESS_VISION_ACTION_WORKFLOW_NAME,
build_apply_scanner_workflow_id,
build_process_vision_action_workflow_id,
+ on_demand_priority,
)
from products.replay_vision.backend.temporal.metrics import record_scanner_limit_reached
from products.replay_vision.backend.temporal.types import ApplyScannerInputs
@@ -197,6 +198,8 @@ def start_apply_scanner_workflow(
id=workflow_id,
task_queue=settings.REPLAY_VISION_TASK_QUEUE,
execution_timeout=APPLY_SCANNER_EXECUTION_TIMEOUT,
+ # Every caller of this trigger is user-initiated (observe, bulk, inline, retry), so all runs qualify.
+ priority=on_demand_priority(scanner.team_id),
# Stamp the scanner id so on-demand applies count toward the sweep's in-flight cap.
search_attributes=TypedSearchAttributes(
search_attributes=[
@@ -259,6 +262,7 @@ def start_process_vision_action_workflow(
id=workflow_id,
task_queue=settings.REPLAY_VISION_TASK_QUEUE,
execution_timeout=PROCESS_VISION_ACTION_EXECUTION_TIMEOUT,
+ priority=on_demand_priority(team_id),
)
except WorkflowAlreadyStartedError as exc:
if exc.workflow_id != workflow_id:
diff --git a/products/replay_vision/backend/enqueue_claims.py b/products/replay_vision/backend/enqueue_claims.py
index b188c6acc8d3..648521efb396 100644
--- a/products/replay_vision/backend/enqueue_claims.py
+++ b/products/replay_vision/backend/enqueue_claims.py
@@ -17,6 +17,8 @@ from products.replay_vision.backend.temporal.constants import (
MAX_IN_FLIGHT_APPLIES_PER_BACKFILL,
MAX_IN_FLIGHT_APPLIES_PER_SCANNER,
MAX_IN_FLIGHT_APPLIES_PER_TEAM,
+ ON_DEMAND_RESERVED_SCANNER_SLOTS,
+ ON_DEMAND_RESERVED_TEAM_SLOTS,
)
from products.replay_vision.backend.temporal.metrics import record_enqueue_claim_failure
@@ -82,16 +84,20 @@ def try_claim_enqueue_slot(
scanner_in_flight_rows: int,
backfill_id: UUID | None = None,
backfill_in_flight_rows: int = 0,
+ scheduled: bool = False,
) -> bool:
"""Atomically claim one enqueue slot against every in-flight cap; True when the scan may start.
Passing `backfill_id` also holds the claim against that backfill's sub-cap, so successive ticks
- see the slots an earlier tick took before its children persisted their rows.
+ see the slots an earlier tick took before its children persisted their rows. `scheduled` claims
+ stop at the reserved ceilings, so racing scheduled dispatchers cannot eat the on-demand reserve.
"""
+ team_cap = MAX_IN_FLIGHT_APPLIES_PER_TEAM - (ON_DEMAND_RESERVED_TEAM_SLOTS if scheduled else 0)
+ scanner_cap = MAX_IN_FLIGHT_APPLIES_PER_SCANNER - (ON_DEMAND_RESERVED_SCANNER_SLOTS if scheduled else 0)
keys = [_team_key(team_id), _scanner_key(scanner_id)]
allowances = [
- MAX_IN_FLIGHT_APPLIES_PER_TEAM - team_in_flight_rows,
- MAX_IN_FLIGHT_APPLIES_PER_SCANNER - scanner_in_flight_rows,
+ team_cap - team_in_flight_rows,
+ scanner_cap - scanner_in_flight_rows,
]
if backfill_id is not None:
keys.append(_backfill_key(backfill_id))
@@ -122,6 +128,7 @@ def claim_enqueue_slot_prefix(
scanner_in_flight_rows: int,
backfill_id: UUID | None = None,
backfill_in_flight_rows: int = 0,
+ scheduled: bool = False,
) -> int:
"""Claim slots for an ordered batch, returning how many leading ids were admitted.
@@ -142,6 +149,7 @@ def claim_enqueue_slot_prefix(
scanner_in_flight_rows=scanner_in_flight_rows,
backfill_id=backfill_id,
backfill_in_flight_rows=backfill_in_flight_rows,
+ scheduled=scheduled,
):
return admitted
return len(workflow_ids)
diff --git a/products/replay_vision/backend/temporal/activities/backfill.py b/products/replay_vision/backend/temporal/activities/backfill.py
index f9200464c956..a5e1bef9868a 100644
--- a/products/replay_vision/backend/temporal/activities/backfill.py
+++ b/products/replay_vision/backend/temporal/activities/backfill.py
@@ -226,6 +226,7 @@ def find_backfill_candidates_activity(inputs: FindBackfillCandidatesInputs) -> F
scanner_in_flight_rows=rows["scanner"],
backfill_id=backfill.id,
backfill_in_flight_rows=rows["backfill"],
+ scheduled=True,
)
# The cursor may step over an already-observed session, because nothing will ever need doing for
diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.py
index 941df1009b0f..f5779e5bbbb6 100644
--- a/products/replay_vision/backend/temporal/constants.py
+++ b/products/replay_vision/backend/temporal/constants.py
@@ -1,6 +1,8 @@
import datetime as dt
from uuid import UUID
+from temporalio.common import Priority
+
APPLY_SCANNER_WORKFLOW_NAME = "replay-vision-apply-scanner"
SWEEP_SCANNER_WORKFLOW_NAME = "replay-vision-sweep-scanner"
@@ -12,6 +14,16 @@ SWEEP_SCANNER_WORKFLOW_NAME = "replay-vision-sweep-scanner"
# row is stranded in `running` until the reaper's cutoff below.
APPLY_SCANNER_EXECUTION_TIMEOUT = dt.timedelta(minutes=110)
+
+def on_demand_priority(team_id: int) -> Priority:
+ """Task priority for user-initiated starts (1 = highest of 5, default 3): Temporal inherits it into
+ the rasterize-recording child and its rasterization-queue activity, so on-demand runs jump the sweep
+ and backfill backlog on every queue they touch. The fairness key shares priority-1 dispatch across
+ teams, so one team's burst cannot starve another team's on-demand work.
+ """
+ return Priority(priority_key=1, fairness_key=str(team_id))
+
+
# A pending/running row is created inside its workflow, and the workflow cannot outlive its execution timeout
# (which spans Temporal-level retries), so any such row older than the timeout plus a margin for clock skew
# and late state writes is provably orphaned.
@@ -150,16 +162,23 @@ COUNT_IN_FLIGHT_APPLIES_TIMEOUT = dt.timedelta(seconds=30)
CHECK_SCANNER_BUDGET_TIMEOUT = dt.timedelta(seconds=30)
+# Slots at each cap that scheduled dispatch (sweep, backfill) must leave free, so a user-initiated
+# observe still admits when scheduled work is saturated; on-demand admission checks the full caps.
+ON_DEMAND_RESERVED_SCANNER_SLOTS = 25
+ON_DEMAND_RESERVED_TEAM_SLOTS = 50
+
+
def in_flight_headroom(scanner_in_flight: int, team_in_flight: int) -> int:
- """Dispatch headroom for a sweep tick: the tighter of the per-scanner and per-team caps.
+ """Scheduled-dispatch headroom for a sweep or backfill tick: the tighter of the per-scanner and
+ per-team caps, minus the slots reserved for on-demand admission.
The sweep workflow throttles on this and the count activity records the throttled
metric from it, so the decision and the metric can't drift apart. Pure, so it is safe
inside deterministic workflow code.
"""
return 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 - ON_DEMAND_RESERVED_SCANNER_SLOTS - scanner_in_flight,
+ MAX_IN_FLIGHT_APPLIES_PER_TEAM - ON_DEMAND_RESERVED_TEAM_SLOTS - team_in_flight,
)
diff --git a/products/replay_vision/backend/temporal/sweep_workflow.py b/products/replay_vision/backend/temporal/sweep_workflow.py
index 39a9a84cd1ad..a8f7683c9c10 100644
--- a/products/replay_vision/backend/temporal/sweep_workflow.py
+++ b/products/replay_vision/backend/temporal/sweep_workflow.py
@@ -39,6 +39,8 @@ from products.replay_vision.backend.temporal.constants import (
CHECK_SCANNER_BUDGET_TIMEOUT,
COUNT_IN_FLIGHT_APPLIES_TIMEOUT,
FIND_SCANNER_CANDIDATES_TIMEOUT,
+ MAX_IN_FLIGHT_APPLIES_PER_SCANNER,
+ MAX_IN_FLIGHT_APPLIES_PER_TEAM,
PROCESS_VISION_ACTION_EXECUTION_TIMEOUT,
PROCESS_VISION_ACTION_WORKFLOW_NAME,
REFRESH_PROMPT_SUGGESTION_TIMEOUT,
@@ -138,7 +140,15 @@ class SweepScannerWorkflow(PostHogWorkflow):
retry_policy=common.RetryPolicy(maximum_attempts=1),
)
team_in_flight = 0
- headroom = in_flight_headroom(scanner_in_flight, team_in_flight)
+ # Patched: a history recorded without the reserve must replay the un-reserved arithmetic it ran,
+ # or the tick can flip between dispatching and returning early mid-replay.
+ if wf.patched("replay-vision-on-demand-reserved-headroom"):
+ headroom = in_flight_headroom(scanner_in_flight, team_in_flight)
+ else:
+ headroom = min(
+ MAX_IN_FLIGHT_APPLIES_PER_SCANNER - scanner_in_flight,
+ MAX_IN_FLIGHT_APPLIES_PER_TEAM - team_in_flight,
+ )
if headroom <= 0:
# At a cap — drain before fetching more. Don't advance the watermark; resume next tick.
wf.logger.info(
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 622feba6c4d4..9e82afe0c57d 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -48,6 +48,7 @@ from products.replay_vision.backend.temporal.constants import (
APPLY_SCANNER_EXECUTION_TIMEOUT,
APPLY_SCANNER_WORKFLOW_NAME,
build_apply_scanner_workflow_id,
+ on_demand_priority,
)
from products.replay_vision.backend.tests.helpers import (
create_experiment,
@@ -2104,6 +2105,7 @@ class TestObserveAction(_VisionAPITestCase):
self.assertEqual(args[0], APPLY_SCANNER_WORKFLOW_NAME)
self.assertEqual(kwargs["id"], expected_workflow_id)
self.assertEqual(kwargs["execution_timeout"], APPLY_SCANNER_EXECUTION_TIMEOUT)
+ self.assertEqual(kwargs["priority"], on_demand_priority(self.team.id))
inputs = args[1]
self.assertEqual(inputs.scanner_id, self.scanner.id)
self.assertEqual(inputs.session_id, "sess-42")
diff --git a/products/replay_vision/backend/tests/test_backfills.py b/products/replay_vision/backend/tests/test_backfills.py
index 4e983db4b33d..c423fd97f88d 100644
--- a/products/replay_vision/backend/tests/test_backfills.py
+++ b/products/replay_vision/backend/tests/test_backfills.py
@@ -61,6 +61,8 @@ from products.replay_vision.backend.temporal.constants import (
MAX_IN_FLIGHT_APPLIES_PER_BACKFILL,
MAX_IN_FLIGHT_APPLIES_PER_SCANNER,
MAX_IN_FLIGHT_APPLIES_PER_TEAM,
+ ON_DEMAND_RESERVED_SCANNER_SLOTS,
+ ON_DEMAND_RESERVED_TEAM_SLOTS,
backfill_dispatch_budget,
build_apply_scanner_workflow_id,
)
@@ -108,11 +110,12 @@ def _make_backfill(scanner: ReplayScanner, **overrides) -> ReplayScannerBackfill
@pytest.mark.parametrize(
"scanner_in_flight,team_in_flight,backfill_in_flight,expected",
[
- # One case per cap that can win, plus the fully-saturated floor.
+ # One case per cap that can win, plus the fully-saturated floor. Scheduled dispatch caps
+ # exclude the slots reserved for on-demand admission.
(0, 0, 0, MAX_IN_FLIGHT_APPLIES_PER_BACKFILL),
(0, 0, MAX_IN_FLIGHT_APPLIES_PER_BACKFILL, 0),
- (MAX_IN_FLIGHT_APPLIES_PER_SCANNER - 10, 0, 0, 10),
- (0, MAX_IN_FLIGHT_APPLIES_PER_TEAM - 5, 0, 5),
+ (MAX_IN_FLIGHT_APPLIES_PER_SCANNER - ON_DEMAND_RESERVED_SCANNER_SLOTS - 10, 0, 0, 10),
+ (0, MAX_IN_FLIGHT_APPLIES_PER_TEAM - ON_DEMAND_RESERVED_TEAM_SLOTS - 5, 0, 5),
],
)
def test_backfill_dispatch_budget_takes_the_tightest_cap(
diff --git a/products/replay_vision/backend/tests/test_enqueue_claims.py b/products/replay_vision/backend/tests/test_enqueue_claims.py
index 93ecb24699a6..eaf1ac0f1e80 100644
--- a/products/replay_vision/backend/tests/test_enqueue_claims.py
+++ b/products/replay_vision/backend/tests/test_enqueue_claims.py
@@ -30,13 +30,14 @@ class TestEnqueueClaims(SimpleTestCase):
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:
+ def _claim(self, workflow_id: str, *, team_rows: int = 0, scanner_rows: int = 0, scheduled: bool = False) -> 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,
+ scheduled=scheduled,
)
@parameterized.expand(
@@ -51,6 +52,16 @@ class TestEnqueueClaims(SimpleTestCase):
assert self._claim("wf-1") is True
assert self._claim("wf-2") is False
+ def test_scheduled_claims_stop_at_the_reserved_ceiling(self) -> None:
+ # Racing scheduled dispatchers must not claim into the on-demand reserve; user claims still may.
+ with (
+ patch("products.replay_vision.backend.enqueue_claims.MAX_IN_FLIGHT_APPLIES_PER_TEAM", 2),
+ patch("products.replay_vision.backend.enqueue_claims.ON_DEMAND_RESERVED_TEAM_SLOTS", 1),
+ ):
+ assert self._claim("wf-1", scheduled=True) is True
+ assert self._claim("wf-2", scheduled=True) is False
+ assert self._claim("wf-2") is True
+
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):
diff --git a/products/replay_vision/backend/tests/test_sweep.py b/products/replay_vision/backend/tests/test_sweep.py
index 705b50066ff5..e06d76d286cc 100644
--- a/products/replay_vision/backend/tests/test_sweep.py
+++ b/products/replay_vision/backend/tests/test_sweep.py
@@ -52,6 +52,8 @@ from products.replay_vision.backend.temporal.constants import (
DEEP_SWEEP_READ_BUDGET_BYTES_PER_DAY,
MAX_IN_FLIGHT_APPLIES_PER_SCANNER,
MAX_IN_FLIGHT_APPLIES_PER_TEAM,
+ ON_DEMAND_RESERVED_SCANNER_SLOTS,
+ ON_DEMAND_RESERVED_TEAM_SLOTS,
SWEEP_READ_BUDGET_BYTES_24H,
build_process_vision_action_workflow_id,
)
@@ -1423,13 +1425,33 @@ async def test_child_start_failure_propagates_and_skips_advance() -> None:
(InFlightApplyCounts(scanner=MAX_IN_FLIGHT_APPLIES_PER_SCANNER, team=0), None), # scanner cap → throttled
(InFlightApplyCounts(scanner=MAX_IN_FLIGHT_APPLIES_PER_SCANNER + 10, team=0), None), # over → throttled
(InFlightApplyCounts(scanner=0, team=MAX_IN_FLIGHT_APPLIES_PER_TEAM), None), # team cap → throttled
- (InFlightApplyCounts(scanner=MAX_IN_FLIGHT_APPLIES_PER_SCANNER - 10, team=0), 10), # partial scanner headroom
+ (
+ # At the reserved scanner ceiling the sweep throttles even though on-demand still admits.
+ InFlightApplyCounts(scanner=MAX_IN_FLIGHT_APPLIES_PER_SCANNER - ON_DEMAND_RESERVED_SCANNER_SLOTS, team=0),
+ None,
+ ),
+ (
+ # Same for the reserved team ceiling.
+ InFlightApplyCounts(scanner=0, team=MAX_IN_FLIGHT_APPLIES_PER_TEAM - ON_DEMAND_RESERVED_TEAM_SLOTS),
+ None,
+ ),
+ (
+ # Partial scanner headroom below the reserved ceiling.
+ InFlightApplyCounts(
+ scanner=MAX_IN_FLIGHT_APPLIES_PER_SCANNER - ON_DEMAND_RESERVED_SCANNER_SLOTS - 10, team=0
+ ),
+ 10,
+ ),
(
# Team headroom smaller than scanner headroom → team cap binds the fetch.
- InFlightApplyCounts(scanner=0, team=MAX_IN_FLIGHT_APPLIES_PER_TEAM - 5),
+ InFlightApplyCounts(scanner=0, team=MAX_IN_FLIGHT_APPLIES_PER_TEAM - ON_DEMAND_RESERVED_TEAM_SLOTS - 5),
5,
),
- (InFlightApplyCounts(scanner=0, team=0), MAX_IN_FLIGHT_APPLIES_PER_SCANNER), # idle → full headroom
+ (
+ # Idle → full scheduled headroom, i.e. the scanner cap minus the on-demand reserve.
+ InFlightApplyCounts(scanner=0, team=0),
+ MAX_IN_FLIGHT_APPLIES_PER_SCANNER - ON_DEMAND_RESERVED_SCANNER_SLOTS,
+ ),
],
)
@pytest.mark.asyncio
diff --git a/products/replay_vision/backend/tests/test_vision_actions_api.py b/products/replay_vision/backend/tests/test_vision_actions_api.py
index 40165ad4e2a9..76a243e476af 100644
--- a/products/replay_vision/backend/tests/test_vision_actions_api.py
+++ b/products/replay_vision/backend/tests/test_vision_actions_api.py
@@ -739,6 +739,7 @@ class TestVisionActionRunNow(_VisionActionAPITestCase):
from products.replay_vision.backend.temporal.constants import (
PROCESS_VISION_ACTION_WORKFLOW_NAME,
build_process_vision_action_workflow_id,
+ on_demand_priority,
)
mock_sync_connect.return_value = MagicMock()
@@ -756,6 +757,7 @@ class TestVisionActionRunNow(_VisionActionAPITestCase):
args, kwargs = start_workflow.call_args
self.assertEqual(args[0], PROCESS_VISION_ACTION_WORKFLOW_NAME)
+ self.assertEqual(kwargs["priority"], on_demand_priority(self.team.id))
inputs = args[1]
self.assertEqual(inputs.vision_action_id, action.id)
self.assertEqual(inputs.mode, "group_summary")