: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): expose ranking sweep capacity and backlog (#116851)
Alessandro Pogliaghid2bb1e77e5c9
diff --git a/products/replay_vision/backend/jev_watch_feed.py b/products/replay_vision/backend/jev_watch_feed.pyindex 98020329e9ac..f6567a7b3e61 100644--- a/products/replay_vision/backend/jev_watch_feed.py+++ b/products/replay_vision/backend/jev_watch_feed.py@@ -243,6 +243,11 @@ _CALLS = Counter("Jev watch rank chunk requests by outcome.",["outcome"],)+_REQUESTS = Counter(+ "replay_vision_jev_watch_rank_requests_total",+ "Ranking requests by kind and HTTP status; non-HTTP failures use unknown",+ ["kind", "status"],+)_LATENCY = Histogram("replay_vision_jev_watch_rank_latency_seconds","Jev watch rank chunk request wall-clock latency.",@@ -327,6 +332,7 @@ class WindowJudgment:stopped_early: boolinput_tokens: intestimated_cost_usd: float+ estimated_prompt_tokens: int = 0def _is_rate_limited(error: Exception) -> bool:@@ -492,6 +498,7 @@ def judge_scanner_window(rate_limited = Falseinput_tokens = 0estimated_cost = 0.0+ estimated_prompt_tokens = 0def charge(result: Any) -> None:nonlocal input_tokens, estimated_cost@@ -536,11 +543,14 @@ def judge_scanner_window(if out_of_time():breakchunks_started += 1+ estimated_prompt_tokens += state_tokens + len(chunk) * _WINDOW_QUESTION_TOKENSstarted = perf_counter()try:chunk_probabilities, result = _judge_chunk(team_id, trace_id, chunk, chunk_context)except Exception as error:_LATENCY.observe(perf_counter() - started)+ status = str(error.status_code) if isinstance(error, DecisionGatewayError) else "unknown"+ _REQUESTS.labels("judgment", status).inc()error_type = type(error).__name___CALLS.labels(error_type).inc()failed_chunks += 1@@ -567,6 +577,7 @@ def judge_scanner_window(continue_LATENCY.observe(perf_counter() - started)_CALLS.labels("ok").inc()+ _REQUESTS.labels("judgment", "200").inc()probabilities.update(chunk_probabilities)model = result.modelcharge(result)@@ -581,6 +592,7 @@ def judge_scanner_window(# The judgments above still land; only the reasons are left off, as on a failed pick.breakstarted = perf_counter()+ estimated_prompt_tokens += state_tokens + len(watchable_ids) * _REASON_QUESTION_TOKENStry:chunk_reasons, reason_result = _pick_watch_reasons(team_id, trace_id, chunk, chunk_context, watchable_ids)except Exception as error:@@ -588,6 +600,8 @@ def judge_scanner_window(# not retried: the rows are judged, and the feed shows them without a reason._LATENCY.observe(perf_counter() - started)_CALLS.labels(f"reason_{type(error).__name__}").inc()+ status = str(error.status_code) if isinstance(error, DecisionGatewayError) else "unknown"+ _REQUESTS.labels("reason", status).inc()failed_reason_chunks += 1logger.warning("Jev watch reason chunk failed",@@ -601,6 +615,7 @@ def judge_scanner_window(continue_LATENCY.observe(perf_counter() - started)_CALLS.labels("reason_ok").inc()+ _REQUESTS.labels("reason", "200").inc()reasons.update(chunk_reasons)charge(reason_result)return WindowJudgment(@@ -617,6 +632,7 @@ def judge_scanner_window(stopped_early=stopped_early,input_tokens=input_tokens,estimated_cost_usd=estimated_cost,+ estimated_prompt_tokens=estimated_prompt_tokens,)diff --git a/products/replay_vision/backend/temporal/jev_watch_rank/activities.py b/products/replay_vision/backend/temporal/jev_watch_rank/activities.pyindex 700ba2e62bfa..c220d7f6f4f0 100644--- a/products/replay_vision/backend/temporal/jev_watch_rank/activities.py+++ b/products/replay_vision/backend/temporal/jev_watch_rank/activities.py@@ -63,6 +63,7 @@ from products.replay_vision.backend.temporal.jev_watch_rank.constants import (WATCH_RANK_WINDOW,WINDOW_SCAN_CAP,)+from products.replay_vision.backend.temporal.jev_watch_rank.metrics import push_sweep_metricsfrom products.replay_vision.backend.temporal.jev_watch_rank.types import (JevWatchRankSweepInputs,JevWatchRankSweepResult,@@ -111,11 +112,11 @@ def _team_scanner_ids(team_id: int, window_start: datetime) -> list[UUID]:)-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+def _scanner_window(team_id: int, scanner_id: UUID, window_start: datetime) -> dict[UUID, datetime]:+ """Newest first, without prose: cheap enough to list the whole capped window every sweep, so thesweep can tell which rows still lack a judgment and which cached entries left the window."""with bounded_queries(_QUERY_BUDGET, from_attempt_start=False):- return list(+ return dict(ReplayObservation.objects.filter(team_id=team_id,scanner_id=scanner_id,@@ -123,7 +124,7 @@ def _scanner_window_ids(team_id: int, scanner_id: UUID, window_start: datetime)created_at__gte=window_start,).order_by("-created_at")- .values_list("id", flat=True)[:WINDOW_SCAN_CAP]+ .values_list("id", "created_at")[:WINDOW_SCAN_CAP])@@ -165,6 +166,12 @@ class _ScannerOutcome:failed_chunks: int = 0input_tokens: int = 0estimated_cost_usd: float = 0.0+ estimated_prompt_tokens: int = 0+ failed_reason_chunks: int = 0+ inspected: bool = False+ window_capped: bool = False+ pending_observations: int = 0+ oldest_pending_age_seconds: float = 0.0class _TokenPacer:@@ -198,9 +205,10 @@ async def _sweep_scanner(pace: Callable[[int], None],stop_after: float,) -> _ScannerOutcome:- window_ids = await sync_to_async(_scanner_window_ids)(team_id, scanner_id, window_start)+ window = await sync_to_async(_scanner_window)(team_id, scanner_id, window_start)+ window_ids = list(window)if not window_ids:- return _ScannerOutcome()+ return _ScannerOutcome(inspected=True)# Judgments accumulate: each sweep judges only the rows the judged set does not hold,# newest first, and cache entries whose rows left the window are pruned. Coverage# therefore grows across sweeps at MAX_JUDGED_PER_SCANNER per hour whatever the@@ -221,7 +229,7 @@ async def _sweep_scanner(unjudged_ids = [row_id for row_id in window_ids if str(row_id) not in judged][:MAX_JUDGED_PER_SCANNER]if not unjudged_ids:await asyncio.to_thread(refresh_watch_ranks_ttl, team_id, scanner_id)- return _ScannerOutcome(skipped_unchanged=True)+ return _ScannerOutcome(skipped_unchanged=True, inspected=True, window_capped=len(window) == WINDOW_SCAN_CAP)judged_context_ids = [row_id for row_id in window_ids if str(row_id) in judged][:WINDOW_CHUNK_SIZE]rows = await sync_to_async(_rows_by_id)(team_id, unjudged_ids)context_rows = await sync_to_async(_rows_by_id)(team_id, judged_context_ids)@@ -264,6 +272,8 @@ async def _sweep_scanner(# The batch is re-bought next run, which beats one write failure ending the sweep.logger.exception("Jev watch rank cache write failed", team_id=team_id, scanner_id=str(scanner_id))cache_errors += 1+ persisted_judged = all_judged if cache_errors == 0 else judged+ pending = [created_at for row_id, created_at in window.items() if str(row_id) not in persisted_judged]with suppress(Exception):# Sub-threshold scores are cached nowhere, so this event is the only record of the# score distribution — it is the data JEV_WATCHABLE_MIN is calibrated from.@@ -309,13 +319,22 @@ async def _sweep_scanner(failed_chunks=judgment.failed_chunks,input_tokens=judgment.input_tokens,estimated_cost_usd=judgment.estimated_cost_usd,+ estimated_prompt_tokens=judgment.estimated_prompt_tokens,+ failed_reason_chunks=judgment.failed_reason_chunks,+ inspected=True,+ window_capped=len(window) == WINDOW_SCAN_CAP,+ pending_observations=len(pending),+ oldest_pending_age_seconds=max(0.0, (datetime.now(UTC) - min(pending)).total_seconds()) if pending else 0.0,)async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSweepResult:if not decision_api.decisions_available_here():- return JevWatchRankSweepResult(decisions_unavailable=True)- deadline = monotonic() + SWEEP_TIME_BUDGET.total_seconds()+ result = JevWatchRankSweepResult(decisions_unavailable=True)+ await asyncio.to_thread(push_sweep_metrics, result)+ return result+ started = monotonic()+ deadline = started + SWEEP_TIME_BUDGET.total_seconds()window_start = datetime.now(UTC) - WATCH_RANK_WINDOWteam_ids = await sync_to_async(_teams_with_scanners)()team_uuids = await sync_to_async(_team_uuids)(team_ids[:MAX_TEAMS_PER_SWEEP])@@ -357,6 +376,7 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSwereturn outcometeams_enrolled = 0+ teams_evaluated = 0teams_without_consent = 0scanners_seen = 0hit_scanner_cap = False@@ -371,6 +391,7 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSweif team_uuid is None:continuemode = await asyncio.to_thread(watch_feed_ranker, team_id, team_uuid)+ teams_evaluated += 1if mode == "weighted-score":continue# The scan prose the sweep sends to the model derives from recordings, so a revoked consent@@ -392,6 +413,7 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSweresult = JevWatchRankSweepResult(teams_seen=min(len(team_ids), MAX_TEAMS_PER_SWEEP),+ teams_evaluated=teams_evaluated,teams_enrolled=teams_enrolled,teams_without_consent=teams_without_consent,scanners_consent_revoked=sum(outcome.consent_revoked for outcome in outcomes),@@ -409,6 +431,20 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSwehit_team_cap=len(team_ids) > MAX_TEAMS_PER_SWEEP,hit_scanner_cap=hit_scanner_cap,hit_time_budget=hit_time_budget or any(outcome.out_of_time for outcome in outcomes),+ estimated_prompt_tokens=sum(outcome.estimated_prompt_tokens for outcome in outcomes),+ duration_seconds=monotonic() - started,+ failed_reason_chunks=sum(outcome.failed_reason_chunks for outcome in outcomes),+ scanners_seen=scanners_seen,+ scanners_inspected=sum(outcome.inspected for outcome in outcomes),+ scanners_window_capped=sum(outcome.window_capped for outcome in outcomes),+ pending_observations=sum(outcome.pending_observations for outcome in outcomes),+ oldest_pending_age_seconds=max((outcome.oldest_pending_age_seconds for outcome in outcomes), default=0.0),+ backlog_complete=(+ len(team_ids) <= MAX_TEAMS_PER_SWEEP+ and not hit_scanner_cap+ and not hit_time_budget+ and all(outcome.inspected and not outcome.window_capped for outcome in outcomes)+ ),)logger.info("replay_vision.jev_watch_rank.cycle_complete",@@ -429,5 +465,10 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSwehit_team_cap=result.hit_team_cap,hit_scanner_cap=result.hit_scanner_cap,hit_time_budget=result.hit_time_budget,+ estimated_prompt_tokens=result.estimated_prompt_tokens,+ pending_observations=result.pending_observations,+ oldest_pending_age_seconds=result.oldest_pending_age_seconds,+ backlog_complete=result.backlog_complete,)+ await asyncio.to_thread(push_sweep_metrics, result)return resultdiff --git a/products/replay_vision/backend/temporal/jev_watch_rank/metrics.py b/products/replay_vision/backend/temporal/jev_watch_rank/metrics.pynew file mode 100644index 000000000000..5e8656b26c4f--- /dev/null+++ b/products/replay_vision/backend/temporal/jev_watch_rank/metrics.py@@ -0,0 +1,56 @@+import time++from prometheus_client import Gauge++from posthog.metrics import pushed_metrics_registry++from products.replay_vision.backend.temporal.jev_watch_rank.constants import JUDGE_TOKENS_PER_SECOND, SWEEP_TIME_BUDGET+from products.replay_vision.backend.temporal.jev_watch_rank.types import JevWatchRankSweepResult+++def push_sweep_metrics(result: JevWatchRankSweepResult) -> None:+ # Each worker can run the singleton sweep, so replace one regional snapshot instead of retaining per-worker gauges.+ with pushed_metrics_registry("replay_vision_jev_watch_rank_sweep") as registry:+ values = {+ "last_run_timestamp_seconds": (time.time(), "Unix time the last sweep returned"),+ "duration_seconds": (result.duration_seconds, "Duration of the last sweep"),+ "estimated_prompt_tokens": (+ result.estimated_prompt_tokens,+ "Estimated prompt tokens attempted in judgment and reason requests; excludes unsent pacing reservations",+ ),+ "token_budget": (+ JUDGE_TOKENS_PER_SECOND * SWEEP_TIME_BUDGET.total_seconds(),+ "Nominal estimated token envelope; request latency and backoff reduce the achievable work",+ ),+ "teams_evaluated": (result.teams_evaluated, "Teams whose ranking flag was evaluated in the last sweep"),+ "teams_enrolled": (result.teams_enrolled, "Teams enrolled with AI consent in the last sweep"),+ "teams_without_consent": (result.teams_without_consent, "Enrolled teams skipped without AI consent"),+ "scanners_seen": (result.scanners_seen, "Scanner turns queued in the last sweep"),+ "scanners_inspected": (result.scanners_inspected, "Scanner windows whose pending work was inspected"),+ "scanners_window_capped": (result.scanners_window_capped, "Scanner windows at the row limit"),+ "pending_observations": (+ result.pending_observations,+ "Unjudged rows remaining in inspected bounded windows; a lower bound unless backlog_complete is one",+ ),+ "oldest_pending_age_seconds": (+ result.oldest_pending_age_seconds,+ "Age of the oldest pending row in inspected bounded windows at inspection time",+ ),+ "backlog_complete": (result.backlog_complete, "One when every enrolled scanner window was fully inspected"),+ "observations_judged": (result.observations_judged, "Observations judged in the last sweep"),+ "observations_given_up": (+ result.observations_given_up,+ "Observations abandoned after repeated batch faults",+ ),+ "cache_errors": (result.cache_errors, "Cache failures in the last sweep"),+ "failed_chunks": (result.failed_chunks, "Failed judgment requests in the last sweep"),+ "failed_reason_chunks": (result.failed_reason_chunks, "Failed reason requests in the last sweep"),+ "scanners_rate_limited": (result.scanners_rate_limited, "Scanner turns with a rate-limited request"),+ "scanners_backed_off": (result.scanners_backed_off, "Scanner turns skipped after repeated rate limits"),+ "hit_time_budget": (result.hit_time_budget, "One when the last sweep reached its time limit"),+ "hit_team_cap": (result.hit_team_cap, "One when the last sweep reached its team limit"),+ "hit_scanner_cap": (result.hit_scanner_cap, "One when the last sweep reached its scanner limit"),+ "decisions_unavailable": (result.decisions_unavailable, "One when the decision service was unavailable"),+ }+ for name, (value, help_text) in values.items():+ Gauge(f"replay_vision_jev_watch_rank_sweep_{name}", help_text, registry=registry).set(value)diff --git a/products/replay_vision/backend/temporal/jev_watch_rank/types.py b/products/replay_vision/backend/temporal/jev_watch_rank/types.pyindex e55be35965a5..935a883d54ab 100644--- a/products/replay_vision/backend/temporal/jev_watch_rank/types.py+++ b/products/replay_vision/backend/temporal/jev_watch_rank/types.py@@ -9,6 +9,7 @@ class JevWatchRankSweepResult(BaseModel, frozen=True):# True when this region serves no decisions at all, in which case every other count is zero.decisions_unavailable: bool = Falseteams_seen: int = 0+ teams_evaluated: int = 0teams_enrolled: int = 0# Enrolled in the flag, but the organization has not approved AI data processing.teams_without_consent: int = 0@@ -37,3 +38,12 @@ class JevWatchRankSweepResult(BaseModel, frozen=True):hit_team_cap: bool = Falsehit_scanner_cap: bool = Falsehit_time_budget: bool = False+ estimated_prompt_tokens: int = 0+ duration_seconds: float = 0.0+ failed_reason_chunks: int = 0+ scanners_seen: int = 0+ scanners_inspected: int = 0+ scanners_window_capped: int = 0+ pending_observations: int = 0+ oldest_pending_age_seconds: float = 0.0+ backlog_complete: bool = Falsediff --git a/products/replay_vision/backend/tests/test_jev_watch_feed.py b/products/replay_vision/backend/tests/test_jev_watch_feed.pyindex 6e42068f4f98..a0d34d987936 100644--- a/products/replay_vision/backend/tests/test_jev_watch_feed.py+++ b/products/replay_vision/backend/tests/test_jev_watch_feed.py@@ -317,11 +317,12 @@ class TestJudgeScannerWindow(SimpleTestCase):paid: list[int] = []with patch(_API) as api:api.decide_when_available.side_effect = _answer_every_question(0.7)- judge_scanner_window(1, uuid4(), rows, pace=paid.append)+ judgment = judge_scanner_window(1, uuid4(), rows, pace=paid.append)# One judgment request plus one reason request (the rows are watchable), each paced.assert api.decide_when_available.call_count == 2assert len(paid) == 2assert all(tokens > 0 for tokens in paid)+ assert judgment.estimated_prompt_tokens == sum(paid)def test_a_window_starts_no_chunk_past_its_stop_time(self) -> None:# Rows past the deadline stay unjudged and retry next sweep, charging no retry budget.@@ -334,6 +335,7 @@ class TestJudgeScannerWindow(SimpleTestCase):# The cut-off is visible: no chunk counts as attempted, and the window says it stopped early.assert judgment.stopped_earlyassert judgment.chunks == 0+ assert judgment.estimated_prompt_tokens == 0def test_an_empty_window_makes_no_request(self) -> None:with patch(_API) as api:@@ -611,6 +613,10 @@ class TestJevWatchRankSweep(BaseTest):assert result.teams_enrolled == 1assert result.scanners_judged == 1assert result.observations_judged == 2+ assert result.estimated_prompt_tokens > 0+ assert result.pending_observations == 0+ assert result.oldest_pending_age_seconds == 0+ assert result.backlog_completeassert load_watch_ranks(self.team.id, [scanner.id]).probabilities == {str(first.id): 0.7, str(second.id): 0.7}# Sub-threshold scores are cached nowhere, so the judged event must carry the score sample# the threshold is calibrated from.@@ -633,6 +639,8 @@ class TestJevWatchRankSweep(BaseTest):# Every row is judged already, so the second run keeps the cache without a Jev call.api.decide_when_available.assert_not_called()assert result.scanners_skipped_unchanged == 1+ assert result.estimated_prompt_tokens == 0+ assert result.backlog_completeassert load_watch_ranks(self.team.id, [scanner.id]).probabilities == {str(first.id): 0.7, str(second.id): 0.7}third = self._succeeded_observation(scanner, "s3", "The user deleted the whole workspace.")@@ -684,9 +692,48 @@ class TestJevWatchRankSweep(BaseTest):result = async_to_sync(_judge_watch_ranks)(JevWatchRankSweepInputs())api.decide_when_available.assert_not_called()assert result.cache_errors == 1+ assert not result.backlog_completeassert result.scanners_judged == 0assert load_watch_ranks(self.team.id, [scanner.id]).probabilities == {"judged-earlier": 0.9}+ @parameterized.expand([(2, False), (3, True)])+ def test_pending_work_includes_rows_beyond_the_judging_limit(self, window_cap: int, complete: bool) -> None:+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ scanner = ReplayScanner.objects.create(+ team=self.team,+ name="example",+ scanner_type=ScannerType.SUMMARIZER,+ scanner_config={"prompt": "Example workflow", "length": "short"},+ model=ScannerModel.GEMINI_3_8_FLASH,+ )+ older = self._succeeded_observation(scanner, "old", "An example user opens a menu.")+ newer = self._succeeded_observation(scanner, "new", "An example user closes a menu.")+ now = timezone.now()+ ReplayObservation.objects.filter(id=older.id).update(created_at=now - timedelta(hours=2))+ ReplayObservation.objects.filter(id=newer.id).update(created_at=now - timedelta(minutes=30))+ activities = "products.replay_vision.backend.temporal.jev_watch_rank.activities"+ with (+ patch(f"{activities}.watch_feed_ranker", side_effect=self._flag_arm("jev-shadow")),+ patch(f"{activities}.decision_api.decisions_available_here", return_value=True),+ patch(f"{activities}.MAX_JUDGED_PER_SCANNER", 1),+ patch(f"{activities}.WINDOW_SCAN_CAP", window_cap),+ patch(f"{activities}.datetime") as clock,+ patch("posthog.metrics.push_to_gateway") as push,+ self.settings(PROM_PUSHGATEWAY_ADDRESS="http://pushgateway.example.com"),+ patch(_API) as api,+ ):+ clock.now.return_value = now+ api.decide_when_available.side_effect = _answer_every_question(0.1)+ result = async_to_sync(_judge_watch_ranks)(JevWatchRankSweepInputs())+ assert result.observations_judged == 1+ assert result.pending_observations == 1+ assert result.oldest_pending_age_seconds == 7200+ assert result.backlog_complete == complete+ registry = push.call_args.kwargs["registry"]+ assert registry.get_sample_value("replay_vision_jev_watch_rank_sweep_pending_observations") == 1+ assert registry.get_sample_value("replay_vision_jev_watch_rank_sweep_backlog_complete") == int(complete)+def test_scanners_are_judged_concurrently(self) -> None:# One scanner at a time cannot cover a half rollout inside the time budget. The barrier only# opens while both scanners' Jev calls are in flight, so a sequential sweep fails every chunk.@@ -769,10 +816,13 @@ class TestJevWatchRankSweep(BaseTest):if gives_up:assert RATE_LIMIT_GIVE_UP_AFTER <= result.scanners_rate_limited < scanner_countassert result.scanners_backed_off == scanner_count - result.scanners_rate_limited+ assert not result.backlog_completeelse:assert result.scanners_rate_limited >= 3assert result.scanners_backed_off == 0assert result.scanners_judged == scanner_count+ assert result.backlog_complete+ assert result.pending_observations == result.scanners_rate_limiteddef test_a_rate_limited_turn_delays_the_next_request(self) -> None:# The pause is what gives the shared capacity back, so the request after a 429 must wait it out.