: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
fix(replay-vision): back the jev sweep off the shared gateway rate limit (#114566)
Kim Svatos Dugan8a56907090c1
diff --git a/products/replay_vision/backend/jev_watch_feed.py b/products/replay_vision/backend/jev_watch_feed.pyindex cbc10764161c..5c3753fbad55 100644--- a/products/replay_vision/backend/jev_watch_feed.py+++ b/products/replay_vision/backend/jev_watch_feed.py@@ -73,6 +73,9 @@ JEV_TIMEOUT_SECONDS = 30.0# wrongly not charging re-buys one batch next sweep. Auth and routing refusals, rate limits, server# errors, contract breaks reported as 200, and unknown statuses all retry free._BATCH_FAULT_STATUSES = frozenset({400, 413, 422})+# The gateway's rate limit. Every product's Jev calls share that limit, so a sweep that keeps+# sending after it would take capacity from features people are waiting on.+_RATE_LIMITED_STATUS = 429# How far a viewed row drops on the 0-1 probability scale, the same intent as WATCH_SEEN_PENALTY in# the weighted ranker: an unviewed peer with comparable evidence comes first, and a very strong seen# row still holds its place above weak unseen rows.@@ -266,10 +269,17 @@ class WindowJudgment:# breakdown, but prod workers do not ship their metrics into the product; the sweep's# judged event does, so a failing sweep names its error without log or cluster access.chunk_error_types: dict[str, int]+ # The gateway rate-limited a request, so the window stopped there. The rows it did not reach+ # retry free on the next sweep.+ rate_limited: boolinput_tokens: intestimated_cost_usd: float+def _is_rate_limited(error: Exception) -> bool:+ return isinstance(error, DecisionGatewayError) and error.status_code == _RATE_LIMITED_STATUS++def _window_entry(row: dict[str, Any]) -> dict[str, Any] | None:"""The judgeable view of one observation row, or None when the row carries no prose to judge."""result = row.get("scanner_result")@@ -415,6 +425,7 @@ def judge_scanner_window(failed_chunks = 0failed_reason_chunks = 0chunk_error_types: dict[str, int] = {}+ rate_limited = Falseinput_tokens = 0estimated_cost = 0.0@@ -454,6 +465,9 @@ def judge_scanner_window(scanner_id=str(scanner_id),error_type=error_type,)+ if _is_rate_limited(error):+ rate_limited = True+ breakcontinue_LATENCY.observe(perf_counter() - started)_CALLS.labels("ok").inc()@@ -478,6 +492,9 @@ def judge_scanner_window(scanner_id=str(scanner_id),error_type=type(error).__name__,)+ if _is_rate_limited(error):+ rate_limited = True+ breakcontinue_LATENCY.observe(perf_counter() - started)_CALLS.labels("reason_ok").inc()@@ -493,6 +510,7 @@ def judge_scanner_window(chunks=len(chunks),failed_chunks=failed_chunks,chunk_error_types=chunk_error_types,+ rate_limited=rate_limited,input_tokens=input_tokens,estimated_cost_usd=estimated_cost,)diff --git a/products/replay_vision/backend/temporal/jev_watch_rank/activities.py b/products/replay_vision/backend/temporal/jev_watch_rank/activities.pyindex 584a08af4649..fbc85b982ab7 100644--- a/products/replay_vision/backend/temporal/jev_watch_rank/activities.py+++ b/products/replay_vision/backend/temporal/jev_watch_rank/activities.py@@ -53,6 +53,7 @@ from products.replay_vision.backend.temporal.jev_watch_rank.constants import (MAX_SCANNERS_PER_SWEEP,MAX_TEAMS_PER_SWEEP,PINNED_TEAM_IDS,+ RATE_LIMIT_BACKOFF_AFTER,SWEEP_ACTIVITY_HEARTBEAT_TIMEOUT,SWEEP_TIME_BUDGET,WATCH_RANK_WINDOW,@@ -149,6 +150,11 @@ class _ScannerOutcome:out_of_time: bool = False# The organization revoked AI data-processing consent while the scanner waited for its turn.consent_revoked: bool = False+ # The gateway rate-limited the scanner's requests.+ rate_limited: bool = False+ # The run had already been rate-limited RATE_LIMIT_BACKOFF_AFTER times, so the scanner waits+ # for the next run.+ backed_off: bool = Falseobservations_judged: int = 0observations_given_up: int = 0cache_errors: int = 0@@ -250,6 +256,7 @@ async def _sweep_scanner(team_id: int, scanner_id: UUID, mode: str, window_start"chunk_error_types": judgment.chunk_error_types,"watch_reasons": dict(Counter(judgment.reasons.values())),"failed_reason_chunks": judgment.failed_reason_chunks,+ "rate_limited": judgment.rate_limited,"jev_model": judgment.model,"input_tokens": judgment.input_tokens,"estimated_cost_usd": judgment.estimated_cost_usd,@@ -257,6 +264,7 @@ async def _sweep_scanner(team_id: int, scanner_id: UUID, mode: str, window_start)return _ScannerOutcome(judged=True,+ rate_limited=judgment.rate_limited,observations_judged=len(judgment.probabilities),observations_given_up=len(exhausted),cache_errors=cache_errors,@@ -278,15 +286,25 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSwe# teams loop only flag-checks and lists scanners, so it runs ahead and queues them.turns = asyncio.Semaphore(JUDGE_CONCURRENCY)+ # Every product's Jev calls share the gateway's rate limit, so once the run keeps hitting it the+ # remaining scanners wait for the next run instead of taking capacity from other features.+ rate_limited_turns = 0+async def take_turn(team_id: int, scanner_id: UUID, mode: str) -> _ScannerOutcome:+ nonlocal rate_limited_turnsasync with turns:if monotonic() > deadline:return _ScannerOutcome(out_of_time=True)+ if rate_limited_turns >= RATE_LIMIT_BACKOFF_AFTER:+ return _ScannerOutcome(backed_off=True)# A turn can wait most of the run after its team was queued, so consent is read again# here: a revocation in between must stop the prose before it reaches the model.if not await sync_to_async(is_ai_data_processing_approved)(team_id):return _ScannerOutcome(consent_revoked=True)- return await _sweep_scanner(team_id, scanner_id, mode, window_start)+ outcome = await _sweep_scanner(team_id, scanner_id, mode, window_start)+ if outcome.rate_limited:+ rate_limited_turns += 1+ return outcometeams_enrolled = 0teams_without_consent = 0@@ -333,6 +351,8 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSweobservations_given_up=sum(outcome.observations_given_up for outcome in outcomes),cache_errors=sum(outcome.cache_errors for outcome in outcomes),failed_chunks=sum(outcome.failed_chunks for outcome in outcomes),+ scanners_rate_limited=sum(outcome.rate_limited for outcome in outcomes),+ scanners_backed_off=sum(outcome.backed_off for outcome in outcomes),input_tokens=sum(outcome.input_tokens for outcome in outcomes),estimated_cost_usd=sum(outcome.estimated_cost_usd for outcome in outcomes),hit_team_cap=len(team_ids) > MAX_TEAMS_PER_SWEEP,@@ -351,6 +371,8 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSweobservations_given_up=result.observations_given_up,cache_errors=result.cache_errors,failed_chunks=result.failed_chunks,+ scanners_rate_limited=result.scanners_rate_limited,+ scanners_backed_off=result.scanners_backed_off,input_tokens=result.input_tokens,hit_team_cap=result.hit_team_cap,hit_scanner_cap=result.hit_scanner_cap,diff --git a/products/replay_vision/backend/temporal/jev_watch_rank/constants.py b/products/replay_vision/backend/temporal/jev_watch_rank/constants.pyindex a6ab2d39d5e2..02798b35c178 100644--- a/products/replay_vision/backend/temporal/jev_watch_rank/constants.py+++ b/products/replay_vision/backend/temporal/jev_watch_rank/constants.py@@ -30,9 +30,11 @@ PINNED_TEAM_IDS = (2,)# experiment scale the time budget, not these counts, decides how far a run gets.MAX_TEAMS_PER_SWEEP = 50_000MAX_SCANNERS_PER_SWEEP = 20_000-# Scanners judged at once. A turn mostly waits on Jev, so this multiplies throughput; it stays low-# enough that one sweep cannot flood the decision gateway.-JUDGE_CONCURRENCY = 8+# Scanners judged at once. A turn mostly waits on Jev, so this multiplies throughput. Eight at once+# kept hitting the gateway's rate limit, which every product's Jev calls share, so it stays low.+JUDGE_CONCURRENCY = 2+# Rate-limited scanner turns after which the rest of the run waits for the next sweep.+RATE_LIMIT_BACKOFF_AFTER = 3# Judging stops here even under the caps: worst-case chunks x the 30s request timeout run far past# any reasonable activity timeout, so the wall clock is the binding limit, not the counts. Scanners# cut off by the budget wait for the next hourly run, where already-judged rows cost nothing.diff --git a/products/replay_vision/backend/temporal/jev_watch_rank/types.py b/products/replay_vision/backend/temporal/jev_watch_rank/types.pyindex 6c3947deda0c..a9c5c2fe297a 100644--- a/products/replay_vision/backend/temporal/jev_watch_rank/types.py+++ b/products/replay_vision/backend/temporal/jev_watch_rank/types.py@@ -25,6 +25,10 @@ class JevWatchRankSweepResult(BaseModel, frozen=True):# overwrite it), plus writes that failed after judging.cache_errors: int = 0failed_chunks: int = 0+ # Scanners whose requests the gateway rate-limited, and scanners left for the next run because+ # the run had already been rate-limited RATE_LIMIT_BACKOFF_AFTER times.+ scanners_rate_limited: int = 0+ scanners_backed_off: int = 0input_tokens: int = 0estimated_cost_usd: float = 0.0hit_team_cap: 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 b44c641e6b87..5c6d99b3c4cc 100644--- a/products/replay_vision/backend/tests/test_jev_watch_feed.py+++ b/products/replay_vision/backend/tests/test_jev_watch_feed.py@@ -42,7 +42,10 @@ from products.replay_vision.backend.models.replay_observation import ()from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerTypefrom products.replay_vision.backend.temporal.jev_watch_rank.activities import _judge_watch_ranks, _teams_with_scanners-from products.replay_vision.backend.temporal.jev_watch_rank.constants import MAX_JUDGE_ATTEMPTS+from products.replay_vision.backend.temporal.jev_watch_rank.constants import (+ MAX_JUDGE_ATTEMPTS,+ RATE_LIMIT_BACKOFF_AFTER,+)from products.replay_vision.backend.temporal.jev_watch_rank.types import JevWatchRankSweepInputsfrom products.replay_vision.backend.tests.helpers import snapshot_for as _snapshot_for@@ -263,6 +266,17 @@ class TestJudgeScannerWindow(SimpleTestCase):assert judgment.failed_chunks == 0assert judgment.failed_reason_chunks == (1 if reason_error else 0)+ def test_a_rate_limit_stops_the_window_and_charges_no_retry_budget(self) -> None:+ # The rate limit is shared with every product's Jev calls, so the window must not keep+ # sending after it. The rows it did not reach retry free on the next sweep.+ rows = [_prose_row(uuid4(), f"summary {index}") for index in range(WINDOW_CHUNK_SIZE + 6)]+ with patch(_API) as api:+ api.decide_when_available.side_effect = DecisionGatewayError(429, "rate limited")+ judgment = judge_scanner_window(1, uuid4(), rows)+ assert api.decide_when_available.call_count == 1+ assert judgment.rate_limited+ assert judgment.batch_failed_ids == ()+def test_an_empty_window_makes_no_request(self) -> None:with patch(_API) as api:judgment = judge_scanner_window(1, uuid4(), [])@@ -621,6 +635,34 @@ class TestJevWatchRankSweep(BaseTest):assert result.observations_judged == 2assert result.failed_chunks == 0+ def test_a_rate_limited_run_leaves_the_remaining_scanners_for_the_next_run(self) -> None:+ # A run that keeps sending after the shared rate limit takes capacity from other features.+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ scanner_count = RATE_LIMIT_BACKOFF_AFTER + 3+ for index in range(scanner_count):+ scanner = ReplayScanner.objects.create(+ team=self.team,+ name=f"s{index}",+ scanner_type=ScannerType.SUMMARIZER,+ scanner_config={"prompt": "p", "length": "short"},+ model=ScannerModel.GEMINI_3_8_FLASH,+ )+ self._succeeded_observation(scanner, f"session-{index}", "The user hit an error at checkout.")++ 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(_API) as api,+ patch("posthoganalytics.capture"),+ ):+ api.decide_when_available.side_effect = DecisionGatewayError(429, "rate limited")+ result = async_to_sync(_judge_watch_ranks)(JevWatchRankSweepInputs())+ assert RATE_LIMIT_BACKOFF_AFTER <= result.scanners_rate_limited < scanner_count+ assert api.decide_when_available.call_count == result.scanners_rate_limited+ assert result.scanners_backed_off == scanner_count - result.scanners_rate_limited+def test_a_consent_revoked_while_a_scanner_waits_sends_nothing(self) -> None:# Scanners are queued when their team passes the consent check but judged at their turn,# which can come most of the run later. A revocation in between must stop the prose from