: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): send smaller jev sweep requests and pause on rate limits (#115687)
posthog[bot]84a121cd8f72
diff --git a/products/replay_vision/backend/jev_watch_feed.py b/products/replay_vision/backend/jev_watch_feed.pyindex 5c3753fbad55..5f50a64714a6 100644--- a/products/replay_vision/backend/jev_watch_feed.py+++ b/products/replay_vision/backend/jev_watch_feed.py@@ -95,10 +95,12 @@ JEV_WATCHABLE_MIN = 0.3JEV_MAX_SCANNER_SHARE = 0.4_SCANNER_SPREAD_FLOOR = 3# Observations per Jev request: the request carries the chunk as shared state and one question per-# observation, so the facade's per-request question cap is the most context one judgment can get. A-# judgment is therefore relative to its chunk, not to the whole window at once.-WINDOW_CHUNK_SIZE = MAX_QUESTIONS_PER_REQUEST-# Per-entry prose caps, so a 24-entry chunk state stays small and per-chunk latency predictable+# observation, so a judgment is relative to its chunk, not to the whole window at once. Half the+# facade's per-request question cap: a request's prompt grows with its state, and a full 32-entry+# state was larger than the decision service admits in flight on one host, so while it ran that host+# refused every other product's requests.+WINDOW_CHUNK_SIZE = MAX_QUESTIONS_PER_REQUEST // 2+# Per-entry prose caps, so a chunk state stays small and per-chunk latency predictable# whatever the scanner's configured summary length._MAX_TITLE_CHARS = 300_MAX_PROSE_CHARS = 1500diff --git a/products/replay_vision/backend/temporal/jev_watch_rank/activities.py b/products/replay_vision/backend/temporal/jev_watch_rank/activities.pyindex fbc85b982ab7..b757c12731e1 100644--- a/products/replay_vision/backend/temporal/jev_watch_rank/activities.py+++ b/products/replay_vision/backend/temporal/jev_watch_rank/activities.py@@ -53,7 +53,8 @@ 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,+ RATE_LIMIT_GIVE_UP_AFTER,+ RATE_LIMIT_PAUSE,SWEEP_ACTIVITY_HEARTBEAT_TIMEOUT,SWEEP_TIME_BUDGET,WATCH_RANK_WINDOW,@@ -152,8 +153,8 @@ class _ScannerOutcome: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.+ # The run had been rate-limited RATE_LIMIT_GIVE_UP_AFTER turns in a row, so the scanner waits for+ # the next run.backed_off: bool = Falseobservations_judged: int = 0observations_given_up: int = 0@@ -286,16 +287,21 @@ 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+ # Every product's Jev calls share the decision service's capacity. A rate-limited turn pauses new+ # turns for RATE_LIMIT_PAUSE, so the run gives that capacity back instead of retrying into it. Only+ # a run that stays rate-limited leaves its remaining scanners for the next run.+ paused_until = 0.0+ consecutive_rate_limited = 0async def take_turn(team_id: int, scanner_id: UUID, mode: str) -> _ScannerOutcome:- nonlocal rate_limited_turns+ nonlocal paused_until, consecutive_rate_limitedasync with turns:+ pause = min(paused_until, deadline) - monotonic()+ if pause > 0:+ await asyncio.sleep(pause)if monotonic() > deadline:return _ScannerOutcome(out_of_time=True)- if rate_limited_turns >= RATE_LIMIT_BACKOFF_AFTER:+ if consecutive_rate_limited >= RATE_LIMIT_GIVE_UP_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.@@ -303,7 +309,10 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSwereturn _ScannerOutcome(consent_revoked=True)outcome = await _sweep_scanner(team_id, scanner_id, mode, window_start)if outcome.rate_limited:- rate_limited_turns += 1+ consecutive_rate_limited += 1+ paused_until = monotonic() + RATE_LIMIT_PAUSE.total_seconds()+ elif outcome.judged:+ consecutive_rate_limited = 0return outcometeams_enrolled = 0diff --git a/products/replay_vision/backend/temporal/jev_watch_rank/constants.py b/products/replay_vision/backend/temporal/jev_watch_rank/constants.pyindex 02798b35c178..e01f83a74015 100644--- a/products/replay_vision/backend/temporal/jev_watch_rank/constants.py+++ b/products/replay_vision/backend/temporal/jev_watch_rank/constants.py@@ -33,8 +33,12 @@ MAX_SCANNERS_PER_SWEEP = 20_000# 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+# A rate-limited turn pauses new turns this long. The decision service frees capacity within+# seconds, so a pause lets the run continue without taking capacity from other products' calls.+RATE_LIMIT_PAUSE = timedelta(seconds=30)+# Rate-limited turns in a row, with no clean turn between, after which the rest of the run waits for+# the next sweep.+RATE_LIMIT_GIVE_UP_AFTER = 5# 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 a9c5c2fe297a..62598edbb90c 100644--- a/products/replay_vision/backend/temporal/jev_watch_rank/types.py+++ b/products/replay_vision/backend/temporal/jev_watch_rank/types.py@@ -26,7 +26,7 @@ class JevWatchRankSweepResult(BaseModel, frozen=True):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.+ # the run had been rate-limited RATE_LIMIT_GIVE_UP_AFTER turns in a row.scanners_rate_limited: int = 0scanners_backed_off: int = 0input_tokens: int = 0diff --git a/products/replay_vision/backend/tests/test_jev_watch_feed.py b/products/replay_vision/backend/tests/test_jev_watch_feed.pyindex 5c6d99b3c4cc..a9f133030146 100644--- a/products/replay_vision/backend/tests/test_jev_watch_feed.py+++ b/products/replay_vision/backend/tests/test_jev_watch_feed.py@@ -1,5 +1,7 @@+import itertoolsimport threadingfrom datetime import UTC, datetime, timedelta+from time import monotonicfrom typing import Anyfrom uuid import uuid4@@ -44,7 +46,7 @@ from products.replay_vision.backend.models.replay_scanner import ReplayScanner,from products.replay_vision.backend.temporal.jev_watch_rank.activities import _judge_watch_ranks, _teams_with_scannersfrom products.replay_vision.backend.temporal.jev_watch_rank.constants import (MAX_JUDGE_ATTEMPTS,- RATE_LIMIT_BACKOFF_AFTER,+ RATE_LIMIT_GIVE_UP_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@@ -635,11 +637,21 @@ 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.+ @parameterized.expand(+ [+ # A run that keeps sending into the shared rate limit takes capacity from other features.+ ("every_call_rate_limited", 1, True),+ # Occasional 429s clear within seconds, so a pause must not cost the run its remaining scanners.+ ("every_other_call_rate_limited", 2, False),+ ]+ )+ def test_a_rate_limited_run_pauses_and_gives_up_only_when_the_limit_persists(+ self, _name: str, rate_limit_every: int, gives_up: bool+ ) -> None:self.organization.is_ai_data_processing_approved = Trueself.organization.save()- scanner_count = RATE_LIMIT_BACKOFF_AFTER + 3+ # Enough scanners that some are still queued when the run would give up.+ scanner_count = 2 * RATE_LIMIT_GIVE_UP_AFTER + 4for index in range(scanner_count):scanner = ReplayScanner.objects.create(team=self.team,@@ -649,19 +661,73 @@ class TestJevWatchRankSweep(BaseTest):model=ScannerModel.GEMINI_3_8_FLASH,)self._succeeded_observation(scanner, f"session-{index}", "The user hit an error at checkout.")+ answer = _answer_every_question(0.1)+ calls = itertools.count()+ lock = threading.Lock()++ def _decide(request: DecisionRequest, **kwargs: Any) -> DecisionResult:+ with lock:+ call = next(calls)+ if call % rate_limit_every == 0:+ raise DecisionGatewayError(429, "rate limited")+ return answer(request)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}.RATE_LIMIT_PAUSE", timedelta(0)),patch(_API) as api,patch("posthoganalytics.capture"),):- api.decide_when_available.side_effect = DecisionGatewayError(429, "rate limited")+ api.decide_when_available.side_effect = _decide+ result = async_to_sync(_judge_watch_ranks)(JevWatchRankSweepInputs())+ if gives_up:+ assert RATE_LIMIT_GIVE_UP_AFTER <= result.scanners_rate_limited < scanner_count+ assert result.scanners_backed_off == scanner_count - result.scanners_rate_limited+ else:+ assert result.scanners_rate_limited >= 3+ assert result.scanners_backed_off == 0+ assert result.scanners_judged == scanner_count++ def 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.+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ for index in range(2):+ 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.")+ pause = timedelta(seconds=0.3)+ answer = _answer_every_question(0.1)+ call_times: list[float] = []++ def _decide(request: DecisionRequest, **kwargs: Any) -> DecisionResult:+ call_times.append(monotonic())+ if len(call_times) == 1:+ raise DecisionGatewayError(429, "rate limited")+ return answer(request)++ 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}.RATE_LIMIT_PAUSE", pause),+ # One turn at a time, so the second request can only start after the first turn ends.+ patch(f"{activities}.JUDGE_CONCURRENCY", 1),+ patch(_API) as api,+ patch("posthoganalytics.capture"),+ ):+ api.decide_when_available.side_effect = _decideresult = 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+ assert result.scanners_rate_limited == 1+ assert result.scanners_judged == 2+ assert call_times[1] - call_times[0] >= pause.total_seconds()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,