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-vision): pace the jev sweep by tokens and cap requests near 5k (#116422)

posthog[bot]4f13c467e901
diff --git a/products/replay_vision/backend/jev_watch_feed.py b/products/replay_vision/backend/jev_watch_feed.py
index 5f50a64714a6..98020329e9ac 100644
--- a/products/replay_vision/backend/jev_watch_feed.py
+++ b/products/replay_vision/backend/jev_watch_feed.py
@@ -23,9 +23,9 @@ bar), so switching the flag switches the whole ranking, not one component of it.
import json
import math
-from collections.abc import Collection
+from collections.abc import Callable, Collection
from datetime import UTC, datetime, timedelta
-from time import perf_counter
+from time import monotonic, perf_counter
from typing import Any, Literal
from uuid import UUID, uuid4
@@ -100,6 +100,47 @@ _SCANNER_SPREAD_FLOOR = 3
# 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
+# About how many estimated prompt tokens one request may carry. A decision-service host admits
+# 12,000 prompt tokens in flight and refuses callers past that, so a ~10k request fills most of a
+# host by itself and the refusals land on whichever product calls next. Half the admission budget
+# leaves room beside our request. Estimated at ~4 JSON characters per token; the judged event's
+# input_tokens carries the measured sizes to calibrate against.
+REQUEST_TOKEN_TARGET = 5_000
+
+
+def _text_tokens(text: str) -> int:
+ """Estimated prompt tokens of a piece of request text."""
+ return max(1, len(text) // 4)
+
+
+def _entry_tokens(entry: dict[str, Any]) -> int:
+ """Estimated prompt tokens one state entry adds to a request."""
+ return _text_tokens(json.dumps(entry, separators=(",", ":")))
+
+
+def _pack_chunks(
+ entries: list[tuple[str, dict[str, Any]]], tokens_per_question: int
+) -> list[tuple[list[tuple[str, dict[str, Any]]], int]]:
+ """Entries packed into request-sized chunks, each returned with its entries' token estimate: at
+ most WINDOW_CHUNK_SIZE questions and about REQUEST_TOKEN_TARGET estimated tokens each — counting
+ the question each entry brings, since its instructions ride along per question — so no request
+ can fill a decision-service host by itself however verbose the entries run. An entry over the
+ target alone still ships, alone."""
+ chunks: list[tuple[list[tuple[str, dict[str, Any]]], int]] = []
+ current: list[tuple[str, dict[str, Any]]] = []
+ current_tokens = 0
+ for entry_id, entry in entries:
+ tokens = _entry_tokens(entry) + tokens_per_question
+ if current and (len(current) >= WINDOW_CHUNK_SIZE or current_tokens + tokens > REQUEST_TOKEN_TARGET):
+ chunks.append((current, current_tokens))
+ current, current_tokens = [], 0
+ current.append((entry_id, entry))
+ current_tokens += tokens
+ if current:
+ chunks.append((current, current_tokens))
+ return chunks
+
+
# 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
@@ -191,6 +232,12 @@ _REASON_INSTRUCTIONS = (
"user experienced."
)
+# What one question adds to a request beyond its state entry: the window instructions ride along
+# per yes/no question, and the reason instructions plus the whole criteria list per CHOICE question.
+# Per-request sizes grow with question count because of these, so packing and pacing count them.
+_WINDOW_QUESTION_TOKENS = _text_tokens(_WINDOW_INSTRUCTIONS)
+_REASON_QUESTION_TOKENS = _text_tokens(_REASON_INSTRUCTIONS) + _text_tokens(json.dumps(_WATCH_REASON_CRITERIA))
+
_CALLS = Counter(
"replay_vision_jev_watch_rank_calls",
"Jev watch rank chunk requests by outcome.",
@@ -265,6 +312,7 @@ class WindowJudgment:
# chunk alike and must not park rows as judged-with-no-score.
batch_failed_ids: tuple[str, ...]
model: str | None
+ # Chunks the window actually sent (or tried to); chunks cut off by stop_after are not counted.
chunks: int
failed_chunks: int
# Failed chunks keyed by exception class name. The Prometheus counter carries the same
@@ -274,6 +322,9 @@ class WindowJudgment:
# 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: bool
+ # The window hit the caller's stop_after deadline and left chunks unsent; their rows retry
+ # on the next sweep.
+ stopped_early: bool
input_tokens: int
estimated_cost_usd: float
@@ -403,7 +454,12 @@ def _pick_watch_reasons(
def judge_scanner_window(
- team_id: int, scanner_id: UUID, rows: list[dict[str, Any]], context_rows: list[dict[str, Any]] | None = None
+ team_id: int,
+ scanner_id: UUID,
+ rows: list[dict[str, Any]],
+ context_rows: list[dict[str, Any]] | None = None,
+ pace: Callable[[int], None] | None = None,
+ stop_after: float | None = None,
) -> WindowJudgment:
"""Ask Jev which of these observations are worth watching, one probability per row.
@@ -411,13 +467,19 @@ def judge_scanner_window(
rows enter the request state without questions, so a small batch of new rows is still judged
against the scanner's routine. Fail-soft per chunk: a failed chunk loses its rows' judgments
and counts as failed, and the other chunks still land, so one bad request never empties a
- scanner's cache entry.
+ scanner's cache entry. `pace` is called with each request's estimated prompt tokens before it
+ is sent, so a caller can spread its requests at a steady token rate; it may block. Chunks are
+ not started past `stop_after` (a time.monotonic deadline): their rows stay unjudged and retry
+ on the next sweep, so a paced window cannot run away past the caller's time budget.
"""
entries = [(str(row["id"]), entry) for row in rows if (entry := _window_entry(row)) is not None]
entry_ids = {entry_id for entry_id, _ in entries}
skipped_no_prose = tuple(str(row["id"]) for row in rows if str(row["id"]) not in entry_ids)
context = [entry for row in context_rows or [] if (entry := _window_entry(row)) is not None]
- chunks = [entries[start : start + WINDOW_CHUNK_SIZE] for start in range(0, len(entries), WINDOW_CHUNK_SIZE)]
+ # Packed with the larger reason-question overhead: the reason pick resends the chunk's state
+ # with a criteria-bearing question per watchable row, so only a chunk sized for the all-watchable
+ # case keeps both requests under the target.
+ chunks = _pack_chunks(entries, max(_WINDOW_QUESTION_TOKENS, _REASON_QUESTION_TOKENS))
# One trace per window run, so a window's chunks group in AI observability without merging runs.
trace_id = str(uuid4())
probabilities: dict[str, float] = {}
@@ -439,9 +501,41 @@ def judge_scanner_window(
_INPUT_TOKENS.inc(result.input_tokens)
_ESTIMATED_COST.inc(chunk_cost)
- for chunk in chunks:
- # The state holds at most WINDOW_CHUNK_SIZE entries, so context only pads short chunks.
- chunk_context = context[: WINDOW_CHUNK_SIZE - len(chunk)]
+ context_with_tokens = [(entry, _entry_tokens(entry)) for entry in context]
+ chunks_started = 0
+ stopped_early = False
+
+ def out_of_time() -> bool:
+ # Checked after each pace() too: the pacing sleep can carry the clock across the deadline,
+ # and a request started past it would overshoot the caller's budget by its whole timeout.
+ nonlocal stopped_early
+ if stop_after is not None and monotonic() > stop_after:
+ # Like rows cut off by the caller's time budget: unjudged, free to retry next sweep.
+ stopped_early = True
+ return stopped_early
+
+ for chunk, packed_tokens in chunks:
+ if out_of_time():
+ break
+ # Context pads only the room the chunk leaves, by question count and by token budget, so a
+ # padded request stays no larger than a full one.
+ budget = REQUEST_TOKEN_TARGET - packed_tokens
+ chunk_context: list[dict[str, Any]] = []
+ context_tokens = 0
+ for context_entry, tokens in context_with_tokens:
+ if len(chunk) + len(chunk_context) >= WINDOW_CHUNK_SIZE or tokens > budget:
+ break
+ chunk_context.append(context_entry)
+ budget -= tokens
+ context_tokens += tokens
+ state_tokens = (
+ packed_tokens - len(chunk) * max(_WINDOW_QUESTION_TOKENS, _REASON_QUESTION_TOKENS) + context_tokens
+ )
+ if pace is not None:
+ pace(state_tokens + len(chunk) * _WINDOW_QUESTION_TOKENS)
+ if out_of_time():
+ break
+ chunks_started += 1
started = perf_counter()
try:
chunk_probabilities, result = _judge_chunk(team_id, trace_id, chunk, chunk_context)
@@ -479,6 +573,13 @@ def judge_scanner_window(
watchable_ids = {oid for oid, probability in chunk_probabilities.items() if probability >= JEV_WATCHABLE_MIN}
if not watchable_ids:
continue
+ if pace is not None:
+ # The reason pick resends the same state, with one criteria-bearing question per
+ # watchable row — usually a few, so this toll is usually smaller than the judgment's.
+ pace(state_tokens + len(watchable_ids) * _REASON_QUESTION_TOKENS)
+ if out_of_time():
+ # The judgments above still land; only the reasons are left off, as on a failed pick.
+ break
started = perf_counter()
try:
chunk_reasons, reason_result = _pick_watch_reasons(team_id, trace_id, chunk, chunk_context, watchable_ids)
@@ -509,10 +610,11 @@ def judge_scanner_window(
skipped_no_prose=skipped_no_prose,
batch_failed_ids=tuple(batch_failed_ids),
model=model,
- chunks=len(chunks),
+ chunks=chunks_started,
failed_chunks=failed_chunks,
chunk_error_types=chunk_error_types,
rate_limited=rate_limited,
+ stopped_early=stopped_early,
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.py
index b757c12731e1..700ba2e62bfa 100644
--- a/products/replay_vision/backend/temporal/jev_watch_rank/activities.py
+++ b/products/replay_vision/backend/temporal/jev_watch_rank/activities.py
@@ -14,11 +14,13 @@ cross-team index on (status, created_at), so the sweep never queries it without
import random
import asyncio
+import threading
from collections import Counter
+from collections.abc import Callable
from contextlib import suppress
from datetime import UTC, datetime
from statistics import fmean
-from time import monotonic
+from time import monotonic, sleep
from typing import Any
from uuid import UUID
@@ -48,6 +50,7 @@ from products.replay_vision.backend.models.replay_scanner import ReplayScanner
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.jev_watch_rank.constants import (
JUDGE_CONCURRENCY,
+ JUDGE_TOKENS_PER_SECOND,
MAX_JUDGE_ATTEMPTS,
MAX_JUDGED_PER_SCANNER,
MAX_SCANNERS_PER_SWEEP,
@@ -164,7 +167,37 @@ class _ScannerOutcome:
estimated_cost_usd: float = 0.0
-async def _sweep_scanner(team_id: int, scanner_id: UUID, mode: str, window_start: datetime) -> _ScannerOutcome:
+class _TokenPacer:
+ """Spreads the run's Jev requests across the hour at a steady token rate.
+
+ Thread-safe, because judging runs in worker threads. wait() reserves the next free slot, sized
+ by the request's tokens, and sleeps until it; the first request in an idle run never waits."""
+
+ def __init__(self, tokens_per_second: float) -> None:
+ self._seconds_per_token = 1.0 / tokens_per_second
+ self._lock = threading.Lock()
+ self._next_start = monotonic()
+ self.waited_seconds = 0.0
+
+ def wait(self, tokens: int) -> None:
+ with self._lock:
+ now = monotonic()
+ start = max(now, self._next_start)
+ self._next_start = start + tokens * self._seconds_per_token
+ waiting = start - now
+ self.waited_seconds += waiting
+ if waiting > 0:
+ sleep(waiting)
+
+
+async def _sweep_scanner(
+ team_id: int,
+ scanner_id: UUID,
+ mode: str,
+ window_start: datetime,
+ pace: Callable[[int], None],
+ stop_after: float,
+) -> _ScannerOutcome:
window_ids = await sync_to_async(_scanner_window_ids)(team_id, scanner_id, window_start)
if not window_ids:
return _ScannerOutcome()
@@ -192,7 +225,7 @@ async def _sweep_scanner(team_id: int, scanner_id: UUID, mode: str, window_start
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)
- judgment = await asyncio.to_thread(judge_scanner_window, team_id, scanner_id, rows, context_rows)
+ judgment = await asyncio.to_thread(judge_scanner_window, team_id, scanner_id, rows, context_rows, pace, stop_after)
# Sub-threshold judgments join only the judged set, keeping the watchable key — which
# the feed loads for every readable scanner on each request — small.
window_strs = {str(row_id) for row_id in window_ids}
@@ -253,6 +286,7 @@ async def _sweep_scanner(team_id: int, scanner_id: UUID, mode: str, window_start
"watchability_max": scores[-1] if scores else None,
"top_scored": top_scored,
"chunks": judgment.chunks,
+ "stopped_early": judgment.stopped_early,
"failed_chunks": judgment.failed_chunks,
"chunk_error_types": judgment.chunk_error_types,
"watch_reasons": dict(Counter(judgment.reasons.values())),
@@ -266,6 +300,9 @@ async def _sweep_scanner(team_id: int, scanner_id: UUID, mode: str, window_start
return _ScannerOutcome(
judged=True,
rate_limited=judgment.rate_limited,
+ # A window the deadline cut short surfaces as the time budget being hit, like a turn that
+ # never started.
+ out_of_time=judgment.stopped_early,
observations_judged=len(judgment.probabilities),
observations_given_up=len(exhausted),
cache_errors=cache_errors,
@@ -286,6 +323,7 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSwe
# Most of a scanner's turn waits on Jev, so scanners take turns JUDGE_CONCURRENCY at a time. The
# teams loop only flag-checks and lists scanners, so it runs ahead and queues them.
turns = asyncio.Semaphore(JUDGE_CONCURRENCY)
+ pacer = _TokenPacer(JUDGE_TOKENS_PER_SECOND)
# 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
@@ -307,7 +345,10 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSwe
# 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)
- outcome = await _sweep_scanner(team_id, scanner_id, mode, window_start)
+ # The deadline passes into the window too: the turn-level check cannot interrupt a
+ # scanner already judging, and a paced window of many chunks could otherwise run long
+ # past the budget toward the activity timeout.
+ outcome = await _sweep_scanner(team_id, scanner_id, mode, window_start, pacer.wait, deadline)
if outcome.rate_limited:
consecutive_rate_limited += 1
paused_until = monotonic() + RATE_LIMIT_PAUSE.total_seconds()
@@ -364,6 +405,7 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSwe
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),
+ pacing_wait_seconds=round(pacer.waited_seconds, 1),
hit_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),
@@ -383,6 +425,7 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSwe
scanners_rate_limited=result.scanners_rate_limited,
scanners_backed_off=result.scanners_backed_off,
input_tokens=result.input_tokens,
+ pacing_wait_seconds=result.pacing_wait_seconds,
hit_team_cap=result.hit_team_cap,
hit_scanner_cap=result.hit_scanner_cap,
hit_time_budget=result.hit_time_budget,
diff --git a/products/replay_vision/backend/temporal/jev_watch_rank/constants.py b/products/replay_vision/backend/temporal/jev_watch_rank/constants.py
index e01f83a74015..5c038311adbc 100644
--- a/products/replay_vision/backend/temporal/jev_watch_rank/constants.py
+++ b/products/replay_vision/backend/temporal/jev_watch_rank/constants.py
@@ -33,17 +33,26 @@ 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
+# Estimated prompt tokens per second one run (one region) may send, enforced across its concurrent
+# turns. The concurrency cap bounds how many requests are in flight, not how fast they go out, so
+# without this the hour's work lands on the decision service in the run's first minutes. About 30%
+# of one L4 host's ~7,000 tokens/s, a peak the service owners asked us to stay under.
+JUDGE_TOKENS_PER_SECOND = 2_000
# 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.
-SWEEP_TIME_BUDGET = timedelta(minutes=30)
+# Judging stops here even under the caps: the wall clock is the binding limit, not the counts, and
+# paced runs are meant to use most of the hour. Capped under the shortest gap between one run and
+# the next (hourly ticks carry up to 10 minutes of jitter, so a late run and an early next tick can
+# sit 50 minutes apart). The activity and workflow timeouts below run past that gap, so a run that
+# pathologically overshoots its budget can make the SKIP overlap policy drop one tick — accepted,
+# because its rows just retry. Scanners cut off by the budget wait for the next hourly run, where
+# already-judged rows cost nothing.
+SWEEP_TIME_BUDGET = timedelta(minutes=45)
-WORKFLOW_EXECUTION_TIMEOUT = timedelta(minutes=45)
-SWEEP_ACTIVITY_TIMEOUT = timedelta(minutes=40)
+WORKFLOW_EXECUTION_TIMEOUT = timedelta(minutes=55)
+SWEEP_ACTIVITY_TIMEOUT = timedelta(minutes=50)
SWEEP_ACTIVITY_HEARTBEAT_TIMEOUT = timedelta(minutes=2)
diff --git a/products/replay_vision/backend/temporal/jev_watch_rank/types.py b/products/replay_vision/backend/temporal/jev_watch_rank/types.py
index 62598edbb90c..e55be35965a5 100644
--- a/products/replay_vision/backend/temporal/jev_watch_rank/types.py
+++ b/products/replay_vision/backend/temporal/jev_watch_rank/types.py
@@ -30,6 +30,9 @@ class JevWatchRankSweepResult(BaseModel, frozen=True):
scanners_rate_limited: int = 0
scanners_backed_off: int = 0
input_tokens: int = 0
+ # Seconds the run's requests spent waiting for their pacing slot, so a run that spends its
+ # budget paced rather than judging is visible without log access.
+ pacing_wait_seconds: float = 0.0
estimated_cost_usd: float = 0.0
hit_team_cap: bool = False
hit_scanner_cap: bool = False
diff --git a/products/replay_vision/backend/tests/test_jev_watch_feed.py b/products/replay_vision/backend/tests/test_jev_watch_feed.py
index a9f133030146..6e42068f4f98 100644
--- a/products/replay_vision/backend/tests/test_jev_watch_feed.py
+++ b/products/replay_vision/backend/tests/test_jev_watch_feed.py
@@ -5,6 +5,7 @@ from time import monotonic
from typing import Any
from uuid import uuid4
+import pytest
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -27,7 +28,11 @@ from products.ml_inference.backend.facade.contracts import (
)
from products.ml_inference.backend.facade.enums import DecisionQuestionType
from products.replay_vision.backend.jev_watch_feed import (
+ _REASON_QUESTION_TOKENS,
+ _WINDOW_QUESTION_TOKENS,
+ REQUEST_TOKEN_TARGET,
WINDOW_CHUNK_SIZE,
+ _entry_tokens,
judge_scanner_window,
load_judged_state,
load_scanner_watch_ranks,
@@ -43,7 +48,11 @@ from products.replay_vision.backend.models.replay_observation import (
ReplayObservation,
)
from products.replay_vision.backend.models.replay_scanner import ReplayScanner, ScannerModel, ScannerType
-from 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.activities import (
+ _judge_watch_ranks,
+ _teams_with_scanners,
+ _TokenPacer,
+)
from products.replay_vision.backend.temporal.jev_watch_rank.constants import (
MAX_JUDGE_ATTEMPTS,
RATE_LIMIT_GIVE_UP_AFTER,
@@ -119,18 +128,19 @@ class TestJudgeScannerWindow(SimpleTestCase):
with patch(_API) as api:
api.decide_when_available.side_effect = _answer_every_question(0.7)
judgment = judge_scanner_window(1, uuid4(), rows)
- # Each chunk is one yes/no request, then one reason request for its watchable rows.
- assert api.decide_when_available.call_count == 4
- assert judgment.chunks == 2
+ # Each chunk is one yes/no request, then one reason request for its watchable rows. How many
+ # rows fit a chunk follows from the token target, so derive the geometry instead of pinning it.
+ assert judgment.chunks >= 2
+ assert api.decide_when_available.call_count == 2 * judgment.chunks
assert judgment.failed_chunks == 0
assert len(judgment.probabilities) == len(rows)
assert judgment.probabilities[str(rows[0]["id"])] == 0.7
- assert judgment.input_tokens == 480
+ assert judgment.input_tokens == 120 * api.decide_when_available.call_count
first_request = api.decide_when_available.call_args_list[0].args[0]
# The chunk travels as shared state with one question per observation, so each judgment is
# relative to its siblings.
- assert len(first_request.state["observations"]) == WINDOW_CHUNK_SIZE
- assert len(first_request.questions) == WINDOW_CHUNK_SIZE
+ assert 1 < len(first_request.state["observations"]) < len(rows)
+ assert len(first_request.questions) == len(first_request.state["observations"])
assert "0" in first_request.questions["watch_0"].instructions
# The state carries recording-derived prose, which must stay out of the internal project.
assert first_request.privacy_mode is True
@@ -150,7 +160,8 @@ class TestJudgeScannerWindow(SimpleTestCase):
api.decide_when_available.side_effect = _first_chunk_fails
judgment = judge_scanner_window(1, uuid4(), rows)
assert judgment.failed_chunks == 1
- assert len(judgment.probabilities) == 6
+ first_request = api.decide_when_available.call_args_list[0].args[0]
+ assert len(judgment.probabilities) == len(rows) - len(first_request.state["observations"])
# An unavailable decision service is not the batch's fault, so no retry budget is charged.
assert judgment.batch_failed_ids == ()
assert judgment.chunk_error_types == {"DecisionsDisabledError": 1}
@@ -279,6 +290,51 @@ class TestJudgeScannerWindow(SimpleTestCase):
assert judgment.rate_limited
assert judgment.batch_failed_ids == ()
+ def test_requests_pack_to_the_token_target(self) -> None:
+ # A full-count chunk of verbose entries must not become a host-filling request. Every row is
+ # watchable here, the worst case: the reason request resends the state with a criteria-bearing
+ # question per row, so it, not the judgment request, is the largest request a chunk produces.
+ rows = [_prose_row(uuid4(), f"entry {index} " + "x" * 1400) for index in range(WINDOW_CHUNK_SIZE)]
+ with patch(_API) as api:
+ api.decide_when_available.side_effect = _answer_every_question(0.7)
+ judgment = judge_scanner_window(1, uuid4(), rows)
+ assert judgment.failed_chunks == 0
+ assert len(judgment.probabilities) == WINDOW_CHUNK_SIZE
+ requests = [call.args[0] for call in api.decide_when_available.call_args_list]
+ # Count-only chunking would fit all of these into one judgment request.
+ assert len(requests) > 2
+ for request in requests:
+ # state["observations"] is a dict keyed by index, so size the entries, not the keys.
+ entry_tokens = sum(_entry_tokens(entry) for entry in request.state["observations"].values())
+ question_tokens = sum(
+ _REASON_QUESTION_TOKENS if question_id.startswith("reason_") else _WINDOW_QUESTION_TOKENS
+ for question_id in request.questions
+ )
+ assert entry_tokens + question_tokens <= REQUEST_TOKEN_TARGET
+
+ def test_each_request_pays_the_pacing_toll_before_it_sends(self) -> None:
+ rows = [_prose_row(uuid4(), f"summary {index}") for index in range(3)]
+ 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)
+ # One judgment request plus one reason request (the rows are watchable), each paced.
+ assert api.decide_when_available.call_count == 2
+ assert len(paid) == 2
+ assert all(tokens > 0 for tokens in 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.
+ rows = [_prose_row(uuid4(), "The user hit an error.") for _ in range(2)]
+ with patch(_API) as api:
+ judgment = judge_scanner_window(1, uuid4(), rows, stop_after=monotonic() - 1)
+ api.decide_when_available.assert_not_called()
+ assert judgment.probabilities == {}
+ assert judgment.batch_failed_ids == ()
+ # The cut-off is visible: no chunk counts as attempted, and the window says it stopped early.
+ assert judgment.stopped_early
+ assert judgment.chunks == 0
+
def test_an_empty_window_makes_no_request(self) -> None:
with patch(_API) as api:
judgment = judge_scanner_window(1, uuid4(), [])
@@ -306,6 +362,34 @@ def _feed_row(
return row
+class TestTokenPacer(SimpleTestCase):
+ # The clock and sleep are patched at the activities module, so these assert the reservation
+ # math deterministically instead of timing real sleeps (which flake on a loaded CI machine).
+ _MOD = "products.replay_vision.backend.temporal.jev_watch_rank.activities"
+
+ def test_a_request_waits_for_the_slot_the_one_before_it_reserved(self) -> None:
+ with (
+ patch(f"{self._MOD}.monotonic", side_effect=[100.0, 100.0, 100.05]),
+ patch(f"{self._MOD}.sleep") as slept,
+ ):
+ pacer = _TokenPacer(tokens_per_second=10_000)
+ pacer.wait(2_000) # sends at once and reserves until 100.2
+ pacer.wait(1)
+ slept.assert_called_once()
+ assert slept.call_args.args[0] == pytest.approx(0.15)
+ assert pacer.waited_seconds == pytest.approx(0.15)
+
+ def test_the_first_request_of_an_idle_run_never_waits(self) -> None:
+ with (
+ patch(f"{self._MOD}.monotonic", side_effect=[100.0, 200.0]),
+ patch(f"{self._MOD}.sleep") as slept,
+ ):
+ pacer = _TokenPacer(tokens_per_second=1) # any backlog at this rate would show instantly
+ pacer.wait(10)
+ slept.assert_not_called()
+ assert pacer.waited_seconds == 0.0
+
+
class TestRankWatchFeedByJev(SimpleTestCase):
def test_watchable_rows_rank_by_probability_and_filler_pads_only_to_the_floor(self) -> None:
# A judged-low row falls to the same recency filler tier as an unjudged one, so a stale low