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): add hourly jev watch-rank sweep (#107092)

Kim Svatos Dugan2eaa94229d5e
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index 89703ac85cb5..17fb729b7100 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -124,6 +124,7 @@ from products.replay_vision.backend.temporal.estimates import create_replay_visi
from products.replay_vision.backend.temporal.gemini_cleanup_sweep import (
create_replay_vision_gemini_cleanup_sweep_schedule,
)
+from products.replay_vision.backend.temporal.jev_watch_rank import create_replay_vision_jev_watch_rank_schedule
from products.replay_vision.backend.temporal.read_meter import create_replay_vision_read_meter_schedule
from products.replay_vision.backend.temporal.reconciler import create_replay_vision_reconciler_schedule
from products.replay_vision.backend.temporal.search_suggestions import create_replay_vision_search_suggestions_schedule
@@ -965,6 +966,7 @@ schedules = [
create_replay_vision_search_suggestions_schedule,
create_vision_alert_check_schedule,
create_replay_vision_read_meter_schedule,
+ create_replay_vision_jev_watch_rank_schedule,
create_github_job_logs_coordinator_schedule,
create_review_hog_finding_outcomes_schedule,
create_ci_signals_coordinator_schedule,
diff --git a/products/ml_inference/backend/facade/api.py b/products/ml_inference/backend/facade/api.py
index f3020a654414..0238f97b89f6 100644
--- a/products/ml_inference/backend/facade/api.py
+++ b/products/ml_inference/backend/facade/api.py
@@ -10,6 +10,12 @@ from ..logic import decisions
from . import contracts
+def decisions_available_here() -> bool:
+ """Whether this region serves decisions at all. A batch caller checks this once before it
+ enumerates work, so a region without the service spends nothing per team."""
+ return decisions.decisions_available_here()
+
+
def decisions_enabled(team_id: int) -> bool:
return decisions.decisions_enabled(team_id)
diff --git a/products/ml_inference/backend/facade/contracts.py b/products/ml_inference/backend/facade/contracts.py
index 73f0d40c49a8..b3a4a8cc6180 100644
--- a/products/ml_inference/backend/facade/contracts.py
+++ b/products/ml_inference/backend/facade/contracts.py
@@ -69,6 +69,9 @@ class DecisionRequest:
properties: dict[str, str] | None = None
# The acting user; unset for background work, which is labelled with the team.
distinct_id: str | None = None
+ # The gateway records the request state and answers into the internal AI observability project
+ # unless asked not to. Set this when the state carries customer content.
+ privacy_mode: bool = False
def __post_init__(self) -> None:
if self.team_id <= 0:
diff --git a/products/ml_inference/backend/logic/decisions.py b/products/ml_inference/backend/logic/decisions.py
index f13aa7f0e9a1..d4c0513c8666 100644
--- a/products/ml_inference/backend/logic/decisions.py
+++ b/products/ml_inference/backend/logic/decisions.py
@@ -107,6 +107,8 @@ def decide(
)
or {}
)
+ if request.privacy_mode:
+ headers["X-PostHog-Privacy-Mode"] = "true"
try:
with httpx.Client(trust_env=False, timeout=timeout_seconds, transport=transport) as client:
response = client.post(decision_url(config.url), json=_wire_body(request), headers=headers)
diff --git a/products/ml_inference/backend/tests/test_logic.py b/products/ml_inference/backend/tests/test_logic.py
index 90a16fea230e..087f1195bd38 100644
--- a/products/ml_inference/backend/tests/test_logic.py
+++ b/products/ml_inference/backend/tests/test_logic.py
@@ -56,6 +56,7 @@ def _request(
trace_id: str | None = None,
properties: dict[str, str] | None = None,
distinct_id: str | None = None,
+ privacy_mode: bool = False,
) -> DecisionRequest:
return DecisionRequest(
team_id=42,
@@ -65,6 +66,7 @@ def _request(
trace_id=trace_id,
properties=properties,
distinct_id=distinct_id,
+ privacy_mode=privacy_mode,
)
@@ -103,14 +105,14 @@ def test_a_question_refuses_more_options_than_the_model_has_letters(criteria: di
class TestDecide:
@pytest.mark.parametrize(
- "gateway_url,state,ai_product",
+ "gateway_url,state,ai_product,privacy_mode",
[
- ("https://gateway.example.com/v1", "ticket text", "ml_inference"),
- ("https://gateway.example.com/v1/", {"policy": "rules", "record": "ticket text"}, "signals"),
+ ("https://gateway.example.com/v1", "ticket text", "ml_inference", False),
+ ("https://gateway.example.com/v1/", {"policy": "rules", "record": "ticket text"}, "signals", True),
],
)
def test_posts_to_the_decision_route_off_the_gateway_origin(
- self, gateway_url: str, state: JsonValue, ai_product: str
+ self, gateway_url: str, state: JsonValue, ai_product: str, privacy_mode: bool
) -> None:
seen: list[httpx.Request] = []
@@ -125,6 +127,7 @@ class TestDecide:
ai_product=ai_product,
trace_id="decision-1",
properties={"signals_decision_id": "decision-1", "ai_stage": "signal_safety"},
+ privacy_mode=privacy_mode,
),
transport=httpx.MockTransport(handler),
)
@@ -141,6 +144,11 @@ class TestDecide:
}
assert request.headers["X-PostHog-Trace-Id"] == "decision-1"
assert request.headers["X-PostHog-Distinct-Id"] == "team-42"
+ # The gateway records the request state unless this header asks it not to.
+ if privacy_mode:
+ assert request.headers["X-PostHog-Privacy-Mode"] == "true"
+ else:
+ assert "X-PostHog-Privacy-Mode" not in request.headers
body = json.loads(request.content)
assert body["model"] == "posthog/hogference/jevk5-fp8-0.2"
assert body["state"] == state
diff --git a/products/replay_vision/backend/jev_watch_feed.py b/products/replay_vision/backend/jev_watch_feed.py
new file mode 100644
index 000000000000..3762e4611728
--- /dev/null
+++ b/products/replay_vision/backend/jev_watch_feed.py
@@ -0,0 +1,528 @@
+"""Jev ranking for the What to watch feed, as an alternative to the weighted score.
+
+The multivariate `vision-watch-feed-ranker` flag selects one of two independent rankers per team:
+
+- `weighted-score` (default): the deterministic blend in `watch_feed.py`, unchanged, no Jev calls.
+- `jev-shadow`: the hourly sweep judges and caches probabilities, but the feed still ranks on the
+ weighted score. This arm exists to collect probabilities and cost data before any feed changes.
+- `jev`: the feed ranks on the cached probabilities alone (`rank_watch_feed_by_jev`).
+
+Jev, the shared decision model behind the ml_inference facade, judges each observation once, in
+company: one request carries a chunk of observations as the state and one yes/no question per
+observation, with already-judged rows padding a short chunk as context, so every judgment sees the
+scanner's own recent sessions rather than standing alone. The hourly Temporal sweep
+(`temporal/jev_watch_rank/`) judges only the rows without a cached probability and merges the
+results into a Redis cache, so coverage accumulates across sweeps at a bounded hourly cost whatever
+the scanner's volume. The cache exists because the feed API is synchronous over up to 1,000 rows
+and must not make model calls, and the scan pipeline must not either. The two rankers share only the
+`WatchFeedEntry` shape and the feed's presentation contract (the filler floor and the notable-reason
+bar), so switching the flag switches the whole ranking, not one component of it.
+"""
+
+import json
+import math
+from collections.abc import Collection
+from datetime import UTC, datetime, timedelta
+from time import perf_counter
+from typing import Any, Literal
+from uuid import UUID, uuid4
+
+from django.conf import settings
+
+import structlog
+from prometheus_client import Counter, Histogram
+
+from posthog.dataclasses import frozen
+from posthog.ph_client import get_feature_flag_or_none
+from posthog.redis import get_client
+
+from products.ml_inference.backend.facade import api as decision_api
+from products.ml_inference.backend.facade.contracts import (
+ MAX_QUESTIONS_PER_REQUEST,
+ DecisionGatewayError,
+ DecisionQuestion,
+ DecisionRequest,
+ JsonValue,
+ NoulAnswer,
+)
+from products.ml_inference.backend.facade.enums import DecisionQuestionType
+from products.replay_vision.backend.watch_feed import NOTABLE_MIN_SCORE, WatchFeedEntry, _trim_filler
+
+logger = structlog.get_logger(__name__)
+
+WATCH_FEED_RANKER_FLAG = "vision-watch-feed-ranker"
+RankerMode = Literal["weighted-score", "jev-shadow", "jev"]
+# The JevK5 build PostHog hosts on the AI gateway, which is the only backend the ml_inference
+# facade reaches. The vendor (typesafe.ai) is not approved for customer data, and observation prose
+# is customer data, so never point this at a vendor model id.
+JEV_MODEL = "posthog/hogference/jevk5-fp8-0.2"
+JEV_INPUT_USD_PER_MILLION = 0.042
+# A chunk request carries up to WINDOW_CHUNK_SIZE questions over a multi-observation state, so it
+# runs far longer than the single-question decisions Signals times out at 3s. Matches the gateway
+# client's own default; the sweep is background work, so latency is cheap and a timeout loses a
+# whole chunk's judgments.
+JEV_TIMEOUT_SECONDS = 30.0
+# 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.
+JEV_SEEN_PENALTY = 0.3
+# Below this probability a judged row carries no evidence: it falls to the same recency filler tier
+# as an unjudged row, so its card never claims the model judged it worth watching, and a judged-low
+# row cannot outrank a fresh observation the sweep has not seen yet. Tier membership uses the raw
+# probability; the seen penalty only orders rows inside the evidence tier.
+JEV_WATCHABLE_MIN = 0.5
+# One incident can put many near-identical watchable sessions on one scanner, and a pure probability
+# sort would fill the top of the feed with them. Hold each scanner to this share of the evidence
+# tier as it is placed (same intent as WATCH_FEED_MAX_SIGNAL_SHARE in the weighted ranker), with a
+# floor so a short feed is not over-constrained; the overflow trails the tier instead of leaving it.
+JEV_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
+# whatever the scanner's configured summary length.
+_MAX_TITLE_CHARS = 300
+_MAX_PROSE_CHARS = 1500
+_MAX_TAGS = 20
+_WATCH_RANK_REDIS_PREFIX = "replay-vision:jev-watch-rank:"
+# Judgments are append-only per observation and the sweep prunes entries that leave the window, so
+# a long lifetime is resilience, not staleness: the cache survives a day of failed sweeps before
+# the feed falls back to the recency filler tier and coverage rebuilds at the judging cap per hour.
+WATCH_RANK_TTL = timedelta(hours=25)
+
+# User text stays in the request state; these instructions refer to it by observation id only, so
+# session prose cannot become an instruction (the rule from posthog/llm/system_one.py). Each
+# question is an independent probability, not a pick, and the instruction says so: without the
+# "every answer may be no" sentence a relative phrasing grades the window on a curve, forcing
+# winners out of an all-routine window and suppressing an all-failures one.
+_WINDOW_INSTRUCTIONS = (
+ "The state holds recent AI scans of recorded product sessions, all from one scanner, keyed by "
+ "id. Judge the scan with id {index} on its own evidence: should a product team spend time "
+ "watching that session's recording in a 'What to watch' feed? "
+ "Sessions worth watching show user friction, failures, confusion, surprising behavior, or an "
+ "outcome unusual for this scanner. "
+ "Use the other scans in the state only as context for what is routine for this scanner; the "
+ "scans do not compete with each other. It is correct to answer no for every scan in the state "
+ "when nothing stands out, and to answer yes for many scans when many sessions show real "
+ "problems. "
+ "A session about a product whose subject matter is errors or debugging is not automatically "
+ "worth watching; only what the recorded user experienced counts."
+)
+
+_CALLS = Counter(
+ "replay_vision_jev_watch_rank_calls",
+ "Jev watch rank chunk requests by outcome.",
+ ["outcome"],
+)
+_LATENCY = Histogram(
+ "replay_vision_jev_watch_rank_latency_seconds",
+ "Jev watch rank chunk request wall-clock latency.",
+ buckets=(0.25, 0.5, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0),
+)
+_INPUT_TOKENS = Counter(
+ "replay_vision_jev_watch_rank_input_tokens",
+ "Jev input tokens reported by the decision gateway.",
+)
+_ESTIMATED_COST = Counter(
+ "replay_vision_jev_watch_rank_estimated_cost_usd",
+ "Jev input-token cost at the gateway catalog price.",
+)
+
+
+def watch_feed_ranker(team_id: int) -> RankerMode:
+ """The team's arm of the watch feed ranker experiment. Any flag failure reads as the default
+ arm, so the sweep and the feed never fail on flag evaluation."""
+ value = get_feature_flag_or_none(
+ WATCH_FEED_RANKER_FLAG,
+ f"team-{team_id}",
+ groups={"project": str(team_id)},
+ group_properties={"project": {"id": team_id}},
+ send_feature_flag_events=False,
+ )
+ if value == "jev-shadow":
+ return "jev-shadow"
+ if value == "jev":
+ return "jev"
+ return "weighted-score"
+
+
+@frozen
+class WindowJudgment:
+ """Jev's judgment of one batch of observations: a probability per observation id (as a string)."""
+
+ probabilities: dict[str, float]
+ # Rows with no prose to judge. The sweep records these as judged, so they settle into the
+ # filler tier once instead of being refetched every sweep; a failed chunk's rows are absent
+ # from `probabilities` and retry next sweep.
+ skipped_no_prose: tuple[str, ...]
+ # Rows from chunks that failed for a reason the batch itself caused (an invalid answer, or a
+ # gateway refusal that is not a rate limit), so a retry will fail the same way. The sweep
+ # charges its retry budget only against these: an outage or a misconfigured gateway fails every
+ # chunk alike and must not park rows as judged-with-no-score.
+ batch_failed_ids: tuple[str, ...]
+ model: str | None
+ chunks: int
+ failed_chunks: int
+ input_tokens: int
+ estimated_cost_usd: float
+
+
+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")
+ output = result.get("model_output") if isinstance(result, dict) else None
+ if not isinstance(output, dict):
+ return None
+ raw_tags = output.get("tags")
+ raw_freeform = output.get("tags_freeform")
+
+ def clipped(value: Any, limit: int) -> Any:
+ return value[:limit] if isinstance(value, str) else value
+
+ entry = {
+ key: value
+ for key, value in {
+ "scanner_type": output.get("scanner_type"),
+ "title": clipped(output.get("title"), _MAX_TITLE_CHARS),
+ "summary": clipped(output.get("summary"), _MAX_PROSE_CHARS),
+ "reasoning": clipped(output.get("reasoning"), _MAX_PROSE_CHARS),
+ "verdict": output.get("verdict"),
+ "score": output.get("score"),
+ "tags": [
+ *(raw_tags if isinstance(raw_tags, list) else []),
+ *(raw_freeform if isinstance(raw_freeform, list) else []),
+ ][:_MAX_TAGS],
+ "notability": output.get("notability"),
+ "signals_count": result.get("signals_count") if isinstance(result, dict) else None,
+ }.items()
+ if value not in (None, "", [])
+ }
+ if not any(isinstance(value := entry.get(key), str) and value.strip() for key in ("title", "summary", "reasoning")):
+ return None
+ return entry
+
+
+def _judge_chunk(
+ team_id: int,
+ trace_id: str,
+ chunk: list[tuple[str, dict[str, Any]]],
+ context: list[dict[str, Any]],
+) -> tuple[dict[str, float], Any]:
+ """One request: questions about `chunk`, with `context` entries in the state as extra siblings.
+ Context pads a small chunk (a quiet hour adds only a few new rows) so its judgments still see
+ what routine looks like for this scanner."""
+ entries = [entry for _, entry in chunk] + context
+ state: JsonValue = {"observations": {str(index): entry for index, entry in enumerate(entries)}}
+ questions = {
+ f"watch_{index}": DecisionQuestion(
+ type=DecisionQuestionType.NOUL, instructions=_WINDOW_INSTRUCTIONS.format(index=index)
+ )
+ for index in range(len(chunk))
+ }
+ result = decision_api.decide_when_available(
+ DecisionRequest(
+ team_id=team_id,
+ state=state,
+ questions=questions,
+ model=JEV_MODEL,
+ ai_product="replay_vision",
+ trace_id=trace_id,
+ # The state holds recording-derived scan prose, which must stay out of the internal
+ # AI observability project — the same rule every other Replay Vision LLM call follows.
+ privacy_mode=True,
+ ),
+ timeout_seconds=JEV_TIMEOUT_SECONDS,
+ )
+ probabilities: dict[str, float] = {}
+ for index, (observation_id, _) in enumerate(chunk):
+ answer = result.answers.get(f"watch_{index}")
+ if (
+ not isinstance(answer, NoulAnswer)
+ or not math.isfinite(answer.probability)
+ or not 0 <= answer.probability <= 1
+ ):
+ raise ValueError("Jev returned an invalid watchability probability")
+ probabilities[observation_id] = answer.probability
+ return probabilities, result
+
+
+def judge_scanner_window(
+ team_id: int, scanner_id: UUID, rows: list[dict[str, Any]], context_rows: list[dict[str, Any]] | None = None
+) -> WindowJudgment:
+ """Ask Jev which of these observations are worth watching, one probability per row.
+
+ `rows` and `context_rows` carry `id` and `scanner_result` (the shape the sweep loads). Context
+ 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.
+ """
+ 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)]
+ # 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] = {}
+ batch_failed_ids: list[str] = []
+ model: str | None = None
+ failed_chunks = 0
+ input_tokens = 0
+ estimated_cost = 0.0
+ for chunk in chunks:
+ started = perf_counter()
+ try:
+ # The state holds at most WINDOW_CHUNK_SIZE entries, so context only pads short chunks.
+ chunk_probabilities, result = _judge_chunk(
+ team_id, trace_id, chunk, context[: WINDOW_CHUNK_SIZE - len(chunk)]
+ )
+ except Exception as error:
+ _LATENCY.observe(perf_counter() - started)
+ _CALLS.labels(type(error).__name__).inc()
+ failed_chunks += 1
+ # An invalid answer or a non-rate-limit gateway refusal is the batch's own fault; an
+ # unreachable, disabled, misconfigured, rate-limited, or erroring gateway is not, and
+ # its rows must retry free.
+ if isinstance(error, ValueError) or (
+ isinstance(error, DecisionGatewayError) and 400 <= error.status_code < 500 and error.status_code != 429
+ ):
+ batch_failed_ids.extend(entry_id for entry_id, _ in chunk)
+ # The gateway error body can echo the state, which holds recording-derived prose, so
+ # only the error type leaves here.
+ logger.warning(
+ "Jev watch rank chunk failed",
+ team_id=team_id,
+ scanner_id=str(scanner_id),
+ error_type=type(error).__name__,
+ )
+ continue
+ _LATENCY.observe(perf_counter() - started)
+ _CALLS.labels("ok").inc()
+ probabilities.update(chunk_probabilities)
+ model = result.model
+ input_tokens += result.input_tokens
+ chunk_cost = result.input_tokens * JEV_INPUT_USD_PER_MILLION / 1_000_000
+ estimated_cost += chunk_cost
+ _INPUT_TOKENS.inc(result.input_tokens)
+ _ESTIMATED_COST.inc(chunk_cost)
+ return WindowJudgment(
+ probabilities=probabilities,
+ skipped_no_prose=skipped_no_prose,
+ batch_failed_ids=tuple(batch_failed_ids),
+ model=model,
+ chunks=len(chunks),
+ failed_chunks=failed_chunks,
+ input_tokens=input_tokens,
+ estimated_cost_usd=estimated_cost,
+ )
+
+
+# The watchable map (probability >= JEV_WATCHABLE_MIN, all the feed reads) lives apart from the
+# judged-id set (everything the sweep has bought, read only by the sweep's skip logic): the feed
+# loads every readable scanner's key on each request, so its keys must stay small however large a
+# scanner's judged window grows.
+def _watchable_key(team_id: int, scanner_id: UUID | str) -> str:
+ return f"{_WATCH_RANK_REDIS_PREFIX}watchable:{team_id}:{scanner_id}"
+
+
+def _judged_key(team_id: int, scanner_id: UUID | str) -> str:
+ return f"{_WATCH_RANK_REDIS_PREFIX}judged:{team_id}:{scanner_id}"
+
+
+def refresh_watch_ranks_ttl(team_id: int, scanner_id: UUID) -> None:
+ client = get_client(settings.REPLAY_VISION_REDIS_URL)
+ client.expire(_watchable_key(team_id, scanner_id), WATCH_RANK_TTL)
+ client.expire(_judged_key(team_id, scanner_id), WATCH_RANK_TTL)
+
+
+def store_watch_ranks(
+ team_id: int,
+ scanner_id: UUID,
+ judged_ids: Collection[str],
+ watchable: dict[str, float],
+ attempts: dict[str, int],
+ model: str | None,
+) -> None:
+ client = get_client(settings.REPLAY_VISION_REDIS_URL)
+ client.setex(
+ _watchable_key(team_id, scanner_id),
+ WATCH_RANK_TTL,
+ json.dumps(
+ {
+ "model": model,
+ "judged_at": datetime.now(UTC).isoformat(),
+ "probabilities": watchable,
+ }
+ ),
+ )
+ # The judged marker is written last on purpose: a partial failure then leaves scores without
+ # the marker, so the batch is re-bought next sweep. The reverse order would mark rows judged
+ # with their scores lost forever. (Not one MULTI: the two keys hash to different slots, so a
+ # transaction would break on a cluster.)
+ client.setex(
+ _judged_key(team_id, scanner_id),
+ WATCH_RANK_TTL,
+ json.dumps({"ids": sorted(judged_ids), "attempts": attempts}),
+ )
+
+
+@frozen
+class JudgedState:
+ """What the sweep already bought for one scanner: the judged observation ids, and how many
+ times each still-unjudged row's judgment has failed."""
+
+ ids: set[str]
+ attempts: dict[str, int]
+
+
+def load_judged_state(team_id: int, scanner_id: UUID) -> JudgedState:
+ """The sweep's judged set and attempt counts for this scanner. A missing key is empty state.
+
+ A Redis read failure raises: an unreadable cache must not read as an empty one, or the sweep
+ re-buys the scanner's judgments and its next write replaces entries it never saw. A stored
+ value that cannot be parsed reads as empty instead, because rewriting it loses nothing.
+ """
+ value = get_client(settings.REPLAY_VISION_REDIS_URL).get(_judged_key(team_id, scanner_id))
+ if not value:
+ return JudgedState(ids=set(), attempts={})
+ try:
+ stored = json.loads(value)
+ except Exception:
+ logger.exception("Jev watch rank judged-set malformed", team_id=team_id)
+ return JudgedState(ids=set(), attempts={})
+ raw_ids = stored.get("ids")
+ raw_attempts = stored.get("attempts")
+ return JudgedState(
+ ids={str(judged_id) for judged_id in raw_ids} if isinstance(raw_ids, list) else set(),
+ attempts=(
+ {
+ str(observation_id): count
+ for observation_id, count in raw_attempts.items()
+ if isinstance(count, int) and not isinstance(count, bool)
+ }
+ if isinstance(raw_attempts, dict)
+ else {}
+ ),
+ )
+
+
+def _parse_watchable(value: Any) -> dict[str, float]:
+ if not value:
+ return {}
+ try:
+ stored = json.loads(value).get("probabilities")
+ except Exception:
+ logger.exception("Jev watch rank cache value malformed")
+ return {}
+ if not isinstance(stored, dict):
+ return {}
+ probabilities: dict[str, float] = {}
+ for observation_id, probability in stored.items():
+ # Clamped like the weighted ranker clamps notability, because a cache can carry anything
+ # (and bool is an int subclass).
+ if isinstance(probability, int | float) and not isinstance(probability, bool):
+ probabilities[str(observation_id)] = min(1.0, max(0.0, float(probability)))
+ return probabilities
+
+
+def load_scanner_watch_ranks(team_id: int, scanner_id: UUID) -> dict[str, float]:
+ """The sweep's read of one scanner's watchable map. Raises on a Redis read failure, because the
+ sweep merges what it loads back into the store, so writing over a map it never saw drops
+ entries. The feed reads through `load_watch_ranks`, which fails soft instead."""
+ return _parse_watchable(get_client(settings.REPLAY_VISION_REDIS_URL).get(_watchable_key(team_id, scanner_id)))
+
+
+def load_watch_ranks(team_id: int, scanner_ids: list[UUID]) -> dict[str, float]:
+ """The cached watchable probabilities for these scanners, keyed by observation id. Fail-soft:
+ any malformed, missing, or unreachable cache entry contributes nothing, so the Jev feed degrades
+ to the recency filler tier rather than failing the request."""
+ if not scanner_ids:
+ return {}
+ probabilities: dict[str, float] = {}
+ try:
+ values = get_client(settings.REPLAY_VISION_REDIS_URL).mget(
+ [_watchable_key(team_id, scanner_id) for scanner_id in scanner_ids]
+ )
+ for value in values:
+ probabilities |= _parse_watchable(value)
+ except Exception:
+ logger.exception("Jev watch rank cache read failed", team_id=team_id)
+ return probabilities
+
+
+def _scan_notability_reason(row: dict[str, Any]) -> str | None:
+ result = row.get("scanner_result")
+ output = result.get("model_output") if isinstance(result, dict) else None
+ if not isinstance(output, dict):
+ return None
+ # The scan writes a notability_reason on every session (including "nothing stands out"), so
+ # only carry it when the scan itself found the session notable — the same bar the weighted
+ # ranker applies. Jev can rate a session watchable relative to a dull window while the scan's
+ # own sentence says the opposite, and that sentence must not lead the card.
+ notability = output.get("notability")
+ if not isinstance(notability, int | float) or isinstance(notability, bool) or notability < NOTABLE_MIN_SCORE:
+ return None
+ reason = output.get("notability_reason")
+ return reason if isinstance(reason, str) and reason.strip() else None
+
+
+def _spread_scanners(ordered: list[tuple[Any, WatchFeedEntry]]) -> list[WatchFeedEntry]:
+ """Hold each scanner to JEV_MAX_SCANNER_SHARE of the evidence tier as it is placed.
+
+ Checked per place rather than over the whole list because the view slices the head: a feed of 5
+ obeys the same share as a feed of 50. Overflow trails the tier in probability order — reordering
+ for breadth is the job here, shortening the feed is not.
+ """
+ placed: list[WatchFeedEntry] = []
+ deferred: list[WatchFeedEntry] = []
+ counts: dict[Any, int] = {}
+ for scanner_id, entry in ordered:
+ allowed = max(_SCANNER_SPREAD_FLOOR, math.ceil(JEV_MAX_SCANNER_SHARE * (len(placed) + 1)))
+ if counts.get(scanner_id, 0) >= allowed:
+ deferred.append(entry)
+ else:
+ counts[scanner_id] = counts.get(scanner_id, 0) + 1
+ placed.append(entry)
+ return placed + deferred
+
+
+def rank_watch_feed_by_jev(rows: list[dict[str, Any]], probabilities: dict[str, float]) -> list[WatchFeedEntry]:
+ """Rank candidate rows (`id`, `scanner_id`, `created_at`, `scanner_result`, `feed_viewed`) on
+ Jev's cached watchability alone: highest probability first, one scanner held to a share of the
+ tier, viewed rows docked, newest as the tiebreak.
+
+ Independent of `rank_watch_feed_candidates` on purpose: the flag picks a whole ranker, so this
+ arm measures Jev's judgment without any component of the weighted score mixed in. Rows without
+ evidence sort below every watchable row by recency, with the same filler reasons the weighted
+ ranker uses: rows the model rated below `JEV_WATCHABLE_MIN`, rows without a cached probability
+ (not yet swept, or the cache went cold), and rows outside the sweep's window. Filler is trimmed
+ to the same floor as the weighted feed, so a cold cache yields 3 newest clips, not a full page
+ of them.
+ """
+ watchable: list[tuple[float, Any, Any, WatchFeedEntry]] = []
+ filler: list[tuple[bool, Any, WatchFeedEntry]] = []
+ for row in rows:
+ probability = probabilities.get(str(row["id"]))
+ viewed = bool(row.get("feed_viewed"))
+ if probability is not None and probability >= JEV_WATCHABLE_MIN:
+ reason: dict[str, Any] = {"kind": "jev_watchable", "jev_probability": probability}
+ # The scan's own sentence, so the card says why the session is worth watching instead
+ # of only that the model said so; the frontend prefers it over kind-derived copy.
+ if notability_reason := _scan_notability_reason(row):
+ reason["notability_reason"] = notability_reason
+ entry = WatchFeedEntry(observation_id=row["id"], reason=reason)
+ watchable.append(
+ (probability - (JEV_SEEN_PENALTY if viewed else 0.0), row["created_at"], row.get("scanner_id"), entry)
+ )
+ else:
+ entry = WatchFeedEntry(observation_id=row["id"], reason={"kind": "recent" if viewed else "unviewed_recent"})
+ filler.append((not viewed, row["created_at"], entry))
+ watchable.sort(key=lambda item: (item[0], item[1]), reverse=True)
+ filler.sort(key=lambda item: (item[0], item[1]), reverse=True)
+ return _trim_filler(
+ _spread_scanners([(scanner_id, entry) for _, _, scanner_id, entry in watchable])
+ + [entry for *_, entry in filler]
+ )
diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.py
index 3fa2048bfa94..f7b308bc4bd1 100644
--- a/products/replay_vision/backend/temporal/__init__.py
+++ b/products/replay_vision/backend/temporal/__init__.py
@@ -65,6 +65,10 @@ from products.replay_vision.backend.temporal.gemini_cleanup_sweep import (
ReplayVisionGeminiCleanupSweepWorkflow,
sweep_gemini_files_activity,
)
+from products.replay_vision.backend.temporal.jev_watch_rank import (
+ ReplayVisionJevWatchRankWorkflow,
+ judge_watch_ranks_activity,
+)
from products.replay_vision.backend.temporal.media_workflow import ObservationMediaWorkflow
from products.replay_vision.backend.temporal.read_meter import MeterScannerReadsWorkflow
from products.replay_vision.backend.temporal.reconciler import ReconcileScannerSchedulesWorkflow
@@ -90,6 +94,7 @@ WORKFLOWS = [
RefreshScannerEstimatesWorkflow,
RefreshSearchSuggestionsWorkflow,
ReplayVisionGeminiCleanupSweepWorkflow,
+ ReplayVisionJevWatchRankWorkflow,
SweepScannerWorkflow,
VisionAlertCheckWorkflow,
]
@@ -142,6 +147,7 @@ ACTIVITIES: list[Callable[..., Any]] = [
reap_childless_inline_scanners_activity,
reap_orphaned_observations_activity,
sweep_gemini_files_activity,
+ judge_watch_ranks_activity,
list_stale_search_suggestions_activity,
refresh_scanner_search_suggestions_activity,
snapshot_benchmark_labels_activity,
diff --git a/products/replay_vision/backend/temporal/jev_watch_rank/__init__.py b/products/replay_vision/backend/temporal/jev_watch_rank/__init__.py
new file mode 100644
index 000000000000..67fe33619049
--- /dev/null
+++ b/products/replay_vision/backend/temporal/jev_watch_rank/__init__.py
@@ -0,0 +1,9 @@
+from products.replay_vision.backend.temporal.jev_watch_rank.activities import judge_watch_ranks_activity
+from products.replay_vision.backend.temporal.jev_watch_rank.schedule import create_replay_vision_jev_watch_rank_schedule
+from products.replay_vision.backend.temporal.jev_watch_rank.workflow import ReplayVisionJevWatchRankWorkflow
+
+__all__ = [
+ "ReplayVisionJevWatchRankWorkflow",
+ "create_replay_vision_jev_watch_rank_schedule",
+ "judge_watch_ranks_activity",
+]
diff --git a/products/replay_vision/backend/temporal/jev_watch_rank/activities.py b/products/replay_vision/backend/temporal/jev_watch_rank/activities.py
new file mode 100644
index 000000000000..c9d3030dd2fc
--- /dev/null
+++ b/products/replay_vision/backend/temporal/jev_watch_rank/activities.py
@@ -0,0 +1,284 @@
+"""The hourly sweep that asks Jev to rank each enrolled scanner's recent window.
+
+Runs outside both hot paths on purpose: the feed API is synchronous and must not make model calls,
+and the scan pipeline must not carry a judgment that can only slow or fail a paid-for scan. Each
+sweep judges only the rows without a cached probability (`judge_scanner_window`, with judged rows
+padding the request as context) and merges the results into the Redis cache the feed reads
+(`load_watch_ranks`), so coverage of a scanner's window accumulates at a bounded hourly cost
+whatever the scanner's volume.
+
+The gates run cheapest-first: region (one settings read), then the per-team flag, then the org's AI
+data-processing consent, then per-team indexed observation queries. The observation table has no
+cross-team index on (status, created_at), so the sweep never queries it without a team_id.
+"""
+
+import asyncio
+from contextlib import suppress
+from datetime import UTC, datetime
+from statistics import fmean
+from time import monotonic
+from typing import Any
+from uuid import UUID
+
+import structlog
+import posthoganalytics
+from asgiref.sync import sync_to_async
+from temporalio import activity
+
+from posthog.temporal.common.heartbeat import Heartbeater
+
+from products.ml_inference.backend.facade import api as decision_api
+from products.replay_vision.backend.consent import is_ai_data_processing_approved
+from products.replay_vision.backend.jev_watch_feed import (
+ JEV_WATCHABLE_MIN,
+ WINDOW_CHUNK_SIZE,
+ judge_scanner_window,
+ load_judged_state,
+ load_scanner_watch_ranks,
+ refresh_watch_ranks_ttl,
+ store_watch_ranks,
+ watch_feed_ranker,
+)
+from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
+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 (
+ MAX_JUDGE_ATTEMPTS,
+ MAX_JUDGED_PER_SCANNER,
+ MAX_SCANNERS_PER_SWEEP,
+ MAX_TEAMS_PER_SWEEP,
+ PINNED_TEAM_IDS,
+ SWEEP_TIME_BUDGET,
+ WATCH_RANK_WINDOW,
+ WINDOW_SCAN_CAP,
+)
+from products.replay_vision.backend.temporal.jev_watch_rank.types import (
+ JevWatchRankSweepInputs,
+ JevWatchRankSweepResult,
+)
+
+logger = structlog.get_logger(__name__)
+
+
+def _teams_with_scanners() -> list[int]:
+ """Teams that own any scanner. The scanner table is small, so this is the cheap universe to
+ flag-check; the huge observation table is only queried per team below, where its indexes hold.
+
+ Ordered, so the team cap cuts deterministically instead of by whatever order Postgres returns —
+ an unordered slice could drop an enrolled team on some runs and not others. Pinned teams go
+ first, so they never fall past the cap at all.
+ """
+ team_ids = ReplayScanner.all_origins.values_list("team_id", flat=True).distinct().order_by("team_id")
+ return [
+ *PINNED_TEAM_IDS,
+ *[team_id for team_id in team_ids[: MAX_TEAMS_PER_SWEEP + 1] if team_id not in PINNED_TEAM_IDS],
+ ]
+
+
+def _team_scanner_ids(team_id: int, window_start: datetime) -> list[UUID]:
+ return list(
+ ReplayObservation.objects.filter(
+ team_id=team_id, status=ObservationStatus.SUCCEEDED, created_at__gte=window_start
+ )
+ .values_list("scanner_id", flat=True)
+ .distinct()
+ )
+
+
+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
+ sweep can tell which rows still lack a judgment and which cached entries left the window."""
+ return list(
+ ReplayObservation.objects.filter(
+ team_id=team_id,
+ scanner_id=scanner_id,
+ status=ObservationStatus.SUCCEEDED,
+ created_at__gte=window_start,
+ )
+ .order_by("-created_at")
+ .values_list("id", flat=True)[:WINDOW_SCAN_CAP]
+ )
+
+
+def _rows_by_id(team_id: int, ids: list[UUID]) -> list[dict[str, Any]]:
+ rows = ReplayObservation.objects.filter(team_id=team_id, id__in=ids).values("id", "scanner_result")
+ by_id = {row["id"]: dict(row) for row in rows}
+ # `id__in` loses the caller's newest-first order.
+ return [by_id[row_id] for row_id in ids if row_id in by_id]
+
+
[email protected](name="replay_vision_judge_watch_ranks_activity")
+@track_activity()
+async def judge_watch_ranks_activity(inputs: JevWatchRankSweepInputs) -> JevWatchRankSweepResult:
+ """Judges every enrolled scanner's window. Per-scanner failures counted, never raised."""
+ # Continuous background heartbeats — a slow Jev fan-out otherwise outlives the heartbeat timeout.
+ async with Heartbeater(factor=4):
+ return await _judge_watch_ranks(inputs)
+
+
+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()
+ window_start = datetime.now(UTC) - WATCH_RANK_WINDOW
+ team_ids = await sync_to_async(_teams_with_scanners)()
+
+ teams_enrolled = 0
+ teams_without_consent = 0
+ scanners_judged = 0
+ scanners_skipped_unchanged = 0
+ observations_judged = 0
+ observations_given_up = 0
+ cache_errors = 0
+ failed_chunks = 0
+ input_tokens = 0
+ estimated_cost = 0.0
+ scanners_seen = 0
+ hit_scanner_cap = False
+ hit_time_budget = False
+ for team_id in team_ids[:MAX_TEAMS_PER_SWEEP]:
+ if monotonic() > deadline:
+ hit_time_budget = True
+ break
+ mode = await asyncio.to_thread(watch_feed_ranker, team_id)
+ if mode == "weighted-score":
+ continue
+ # The scan prose the sweep sends to the model derives from recordings, so a revoked consent
+ # stops the judgments even while the flag stays on.
+ if not await sync_to_async(is_ai_data_processing_approved)(team_id):
+ teams_without_consent += 1
+ continue
+ teams_enrolled += 1
+ scanner_ids = await sync_to_async(_team_scanner_ids)(team_id, window_start)
+ for scanner_id in scanner_ids:
+ if monotonic() > deadline:
+ hit_time_budget = True
+ break
+ if scanners_seen >= MAX_SCANNERS_PER_SWEEP:
+ hit_scanner_cap = True
+ break
+ scanners_seen += 1
+ window_ids = await sync_to_async(_scanner_window_ids)(team_id, scanner_id, window_start)
+ if not window_ids:
+ continue
+ # 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
+ # scanner's volume, and a fully judged window costs nothing.
+ try:
+ judged_state = await asyncio.to_thread(load_judged_state, team_id, scanner_id)
+ cached_watchable = await asyncio.to_thread(load_scanner_watch_ranks, team_id, scanner_id)
+ except Exception:
+ # A cache the sweep cannot read must not be judged over or written: without the
+ # judged set it re-buys rows, and the write would replace entries it never saw.
+ logger.exception(
+ "Jev watch rank cache unreadable, skipping scanner",
+ team_id=team_id,
+ scanner_id=str(scanner_id),
+ )
+ cache_errors += 1
+ continue
+ judged = judged_state.ids
+ 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)
+ scanners_skipped_unchanged += 1
+ continue
+ 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)
+ # 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}
+ watchable = {
+ **{oid: p for oid, p in cached_watchable.items() if oid in window_strs},
+ **{oid: p for oid, p in judgment.probabilities.items() if p >= JEV_WATCHABLE_MIN},
+ }
+ # A row whose judgment failed through its own batch (an invalid answer, a non-rate-limit
+ # gateway refusal) retries on later sweeps, but only MAX_JUDGE_ATTEMPTS times: the
+ # newest-first pick would otherwise retry a deterministically failing batch every hour
+ # and starve older rows. An exhausted row is recorded as judged with no score, so it
+ # settles into the filler tier like a prose-less row. An outage charges nothing — its
+ # rows stay unjudged and retry free next sweep.
+ failed_ids = set(judgment.batch_failed_ids)
+ updated_attempts = {oid: judged_state.attempts.get(oid, 0) + 1 for oid in failed_ids}
+ exhausted = {oid for oid, count in updated_attempts.items() if count >= MAX_JUDGE_ATTEMPTS}
+ attempts = {
+ oid: count
+ for oid, count in judged_state.attempts.items()
+ if oid in window_strs and oid not in failed_ids
+ } | {oid: count for oid, count in updated_attempts.items() if count < MAX_JUDGE_ATTEMPTS}
+ observations_given_up += len(exhausted)
+ all_judged = (
+ (judged & window_strs) | set(judgment.probabilities) | set(judgment.skipped_no_prose) | exhausted
+ )
+ if all_judged or attempts:
+ try:
+ await asyncio.to_thread(
+ store_watch_ranks, team_id, scanner_id, all_judged, watchable, attempts, judgment.model
+ )
+ except Exception:
+ # 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
+ scanners_judged += 1
+ observations_judged += len(judgment.probabilities)
+ failed_chunks += judgment.failed_chunks
+ input_tokens += judgment.input_tokens
+ estimated_cost += judgment.estimated_cost_usd
+ with suppress(Exception):
+ posthoganalytics.capture(
+ event="replay_vision_jev_watch_rank_judged",
+ distinct_id=f"team-{team_id}",
+ properties={
+ "scanner_id": str(scanner_id),
+ "mode": mode,
+ "window_rows": len(rows),
+ "observations_judged": len(judgment.probabilities),
+ "mean_watchability": (
+ fmean(judgment.probabilities.values()) if judgment.probabilities else None
+ ),
+ "chunks": judgment.chunks,
+ "failed_chunks": judgment.failed_chunks,
+ "jev_model": judgment.model,
+ "input_tokens": judgment.input_tokens,
+ "estimated_cost_usd": judgment.estimated_cost_usd,
+ },
+ )
+ if hit_scanner_cap:
+ break
+
+ result = JevWatchRankSweepResult(
+ teams_seen=min(len(team_ids), MAX_TEAMS_PER_SWEEP),
+ teams_enrolled=teams_enrolled,
+ teams_without_consent=teams_without_consent,
+ scanners_judged=scanners_judged,
+ scanners_skipped_unchanged=scanners_skipped_unchanged,
+ observations_judged=observations_judged,
+ observations_given_up=observations_given_up,
+ cache_errors=cache_errors,
+ failed_chunks=failed_chunks,
+ input_tokens=input_tokens,
+ estimated_cost_usd=estimated_cost,
+ hit_team_cap=len(team_ids) > MAX_TEAMS_PER_SWEEP,
+ hit_scanner_cap=hit_scanner_cap,
+ hit_time_budget=hit_time_budget,
+ )
+ logger.info(
+ "replay_vision.jev_watch_rank.cycle_complete",
+ teams_seen=result.teams_seen,
+ teams_enrolled=result.teams_enrolled,
+ teams_without_consent=result.teams_without_consent,
+ scanners_judged=result.scanners_judged,
+ scanners_skipped_unchanged=result.scanners_skipped_unchanged,
+ observations_judged=result.observations_judged,
+ observations_given_up=result.observations_given_up,
+ cache_errors=result.cache_errors,
+ failed_chunks=result.failed_chunks,
+ input_tokens=result.input_tokens,
+ hit_team_cap=result.hit_team_cap,
+ hit_scanner_cap=result.hit_scanner_cap,
+ hit_time_budget=result.hit_time_budget,
+ )
+ return result
diff --git a/products/replay_vision/backend/temporal/jev_watch_rank/constants.py b/products/replay_vision/backend/temporal/jev_watch_rank/constants.py
new file mode 100644
index 000000000000..5fe028ce80dd
--- /dev/null
+++ b/products/replay_vision/backend/temporal/jev_watch_rank/constants.py
@@ -0,0 +1,43 @@
+from datetime import timedelta
+
+SCHEDULE_ID = "replay-vision-jev-watch-rank-schedule"
+WORKFLOW_ID = "replay-vision-jev-watch-rank"
+WORKFLOW_NAME = "replay-vision-jev-watch-rank"
+SCHEDULE_TYPE = "replay-vision-jev-watch-rank"
+
+SCHEDULE_INTERVAL = timedelta(hours=1)
+
+# Matches the feed's default window (`date_from=-7d`), so every row the default feed can show has
+# been offered to Jev.
+WATCH_RANK_WINDOW = timedelta(days=7)
+# Ids listed per scanner per sweep. This bounds the cache size and the id query, and it is the
+# coverage ceiling on a very-high-volume scanner: rows past it stay unjudged filler.
+WINDOW_SCAN_CAP = 1000
+# New rows judged per scanner per sweep. Judgments accumulate in the cache, so this caps the hourly
+# Jev spend, not the coverage: a backlog drains at this rate across later sweeps, newest first.
+MAX_JUDGED_PER_SCANNER = 100
+# The newest-first pick would retry a deterministically failing batch every hour and starve older
+# rows for the whole window. After this many batch-attributable failures (an invalid answer, a
+# gateway refusal that is not a rate limit) a row is recorded as judged with no score, so it
+# settles into the recency filler tier like a prose-less row — for the life of the cache entry,
+# since every sweep over an active scanner refreshes the TTL. Environmental failures (an outage,
+# a rate limit, a misconfigured gateway) charge no attempt, so a bad hour parks nothing.
+MAX_JUDGE_ATTEMPTS = 3
+# TODO: Team 2 is PostHog's own team, pinned first while the jev ranker runs as an internal shadow
+# test, so it can never fall past the team cap. When the experiment opens to other teams: remove the
+# pin, give the caps fair rotation, and make watch_feed_ranker return the default arm where
+# decisions_available_here() is false, so a region without the decision service can never land on
+# the jev arm. Enrollment is team-targeted and US-only until then.
+PINNED_TEAM_IDS = (2,)
+# Bound one sweep. The flag gates per team, so at experiment scale these caps are slack; they exist
+# so a misconfigured flag rollout cannot turn the sweep into an unbounded flag-check or Jev fan-out.
+MAX_TEAMS_PER_SWEEP = 2000
+MAX_SCANNERS_PER_SWEEP = 500
+# 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)
+
+WORKFLOW_EXECUTION_TIMEOUT = timedelta(minutes=45)
+SWEEP_ACTIVITY_TIMEOUT = timedelta(minutes=40)
+SWEEP_ACTIVITY_HEARTBEAT_TIMEOUT = timedelta(minutes=2)
diff --git a/products/replay_vision/backend/temporal/jev_watch_rank/schedule.py b/products/replay_vision/backend/temporal/jev_watch_rank/schedule.py
new file mode 100644
index 000000000000..c20f23117cf9
--- /dev/null
+++ b/products/replay_vision/backend/temporal/jev_watch_rank/schedule.py
@@ -0,0 +1,30 @@
+from temporalio.client import Client
+from temporalio.common import SearchAttributePair, TypedSearchAttributes
+
+from posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_TYPE_KEY
+
+from products.replay_vision.backend.temporal.jev_watch_rank.constants import (
+ SCHEDULE_ID,
+ SCHEDULE_INTERVAL,
+ SCHEDULE_TYPE,
+ WORKFLOW_EXECUTION_TIMEOUT,
+ WORKFLOW_ID,
+ WORKFLOW_NAME,
+)
+from products.replay_vision.backend.temporal.jev_watch_rank.types import JevWatchRankSweepInputs
+from products.replay_vision.backend.temporal.schedule import upsert_interval_schedule
+
+
+async def create_replay_vision_jev_watch_rank_schedule(client: Client) -> None:
+ await upsert_interval_schedule(
+ client,
+ schedule_id=SCHEDULE_ID,
+ workflow_name=WORKFLOW_NAME,
+ workflow_id=WORKFLOW_ID,
+ inputs=JevWatchRankSweepInputs(),
+ interval=SCHEDULE_INTERVAL,
+ execution_timeout=WORKFLOW_EXECUTION_TIMEOUT,
+ search_attributes=TypedSearchAttributes(
+ search_attributes=[SearchAttributePair(key=POSTHOG_SCHEDULE_TYPE_KEY, value=SCHEDULE_TYPE)]
+ ),
+ )
diff --git a/products/replay_vision/backend/temporal/jev_watch_rank/types.py b/products/replay_vision/backend/temporal/jev_watch_rank/types.py
new file mode 100644
index 000000000000..f0ee9d33f884
--- /dev/null
+++ b/products/replay_vision/backend/temporal/jev_watch_rank/types.py
@@ -0,0 +1,29 @@
+from pydantic import BaseModel
+
+
+class JevWatchRankSweepInputs(BaseModel, frozen=True):
+ pass
+
+
+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 = False
+ teams_seen: int = 0
+ teams_enrolled: int = 0
+ # Enrolled in the flag, but the organization has not approved AI data processing.
+ teams_without_consent: int = 0
+ scanners_judged: int = 0
+ # Windows whose every row the judged set already holds, so no Jev call was spent.
+ scanners_skipped_unchanged: int = 0
+ observations_judged: int = 0
+ # Rows abandoned after MAX_JUDGE_ATTEMPTS failed judgments; they settle into the filler tier.
+ observations_given_up: int = 0
+ # Scanners skipped because their cache could not be read (judging over an unseen cache would
+ # overwrite it), plus writes that failed after judging.
+ cache_errors: int = 0
+ failed_chunks: int = 0
+ input_tokens: int = 0
+ estimated_cost_usd: float = 0.0
+ hit_team_cap: bool = False
+ hit_scanner_cap: bool = False
+ hit_time_budget: bool = False
diff --git a/products/replay_vision/backend/temporal/jev_watch_rank/workflow.py b/products/replay_vision/backend/temporal/jev_watch_rank/workflow.py
new file mode 100644
index 000000000000..d243c4b8474e
--- /dev/null
+++ b/products/replay_vision/backend/temporal/jev_watch_rank/workflow.py
@@ -0,0 +1,33 @@
+from typing import Any
+
+from temporalio import workflow
+from temporalio.common import RetryPolicy
+
+from posthog.temporal.common.base import PostHogWorkflow
+
+from products.replay_vision.backend.temporal.jev_watch_rank.constants import (
+ SWEEP_ACTIVITY_HEARTBEAT_TIMEOUT,
+ SWEEP_ACTIVITY_TIMEOUT,
+ WORKFLOW_NAME,
+)
+from products.replay_vision.backend.temporal.jev_watch_rank.types import JevWatchRankSweepInputs
+
+with workflow.unsafe.imports_passed_through():
+ from products.replay_vision.backend.temporal.jev_watch_rank.activities import judge_watch_ranks_activity
+
+
[email protected](name=WORKFLOW_NAME)
+class ReplayVisionJevWatchRankWorkflow(PostHogWorkflow):
+ inputs_cls = JevWatchRankSweepInputs
+ inputs_optional = True
+
+ @workflow.run
+ async def run(self, inputs: JevWatchRankSweepInputs) -> dict[str, Any]:
+ result = await workflow.execute_activity(
+ judge_watch_ranks_activity,
+ inputs,
+ start_to_close_timeout=SWEEP_ACTIVITY_TIMEOUT,
+ heartbeat_timeout=SWEEP_ACTIVITY_HEARTBEAT_TIMEOUT,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+ return result.model_dump()
diff --git a/products/replay_vision/backend/tests/test_jev_watch_feed.py b/products/replay_vision/backend/tests/test_jev_watch_feed.py
new file mode 100644
index 000000000000..670a8c90757f
--- /dev/null
+++ b/products/replay_vision/backend/tests/test_jev_watch_feed.py
@@ -0,0 +1,547 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any
+from uuid import uuid4
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.conf import settings
+from django.test import SimpleTestCase
+from django.utils import timezone
+
+from asgiref.sync import async_to_sync
+from parameterized import parameterized
+
+from posthog.redis import get_client
+
+from products.ml_inference.backend.facade.contracts import (
+ DecisionGatewayError,
+ DecisionRequest,
+ DecisionResult,
+ DecisionsDisabledError,
+ NoulAnswer,
+)
+from products.replay_vision.backend.jev_watch_feed import (
+ WINDOW_CHUNK_SIZE,
+ judge_scanner_window,
+ load_judged_state,
+ load_scanner_watch_ranks,
+ load_watch_ranks,
+ rank_watch_feed_by_jev,
+ store_watch_ranks,
+ watch_feed_ranker,
+)
+from products.replay_vision.backend.models.replay_observation import (
+ ObservationStatus,
+ ObservationTrigger,
+ 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.constants import MAX_JUDGE_ATTEMPTS
+from products.replay_vision.backend.temporal.jev_watch_rank.types import JevWatchRankSweepInputs
+from products.replay_vision.backend.tests.helpers import snapshot_for as _snapshot_for
+
+_FLAG = "products.replay_vision.backend.jev_watch_feed.get_feature_flag_or_none"
+_API = "products.replay_vision.backend.jev_watch_feed.decision_api"
+
+
+def _answer_every_question(probability: float):
+ """A decide_when_available side effect that answers each question in the request with `probability`."""
+
+ def _decide(request: DecisionRequest, **kwargs: Any) -> DecisionResult:
+ return DecisionResult(
+ model="jevk5-fp8-0.2",
+ answers={name: NoulAnswer(probability=probability) for name in request.questions},
+ input_tokens=120,
+ )
+
+ return _decide
+
+
+def _prose_row(observation_id: object, summary: str) -> dict[str, Any]:
+ return {
+ "id": observation_id,
+ "scanner_result": {
+ "model_output": {"scanner_type": "summarizer", "title": "t", "summary": summary, "confidence": 0.9},
+ "signals_count": 0,
+ },
+ }
+
+
+class TestWatchFeedRankerFlag(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("flag_off", None, "weighted-score"),
+ ("boolean_flag", True, "weighted-score"),
+ ("unknown_variant", "something-else", "weighted-score"),
+ ("shadow", "jev-shadow", "jev-shadow"),
+ ("graduated", "jev", "jev"),
+ ]
+ )
+ def test_only_known_variants_leave_the_default_arm(self, _name: str, flag_value: object, expected: str) -> None:
+ with patch(_FLAG, return_value=flag_value):
+ assert watch_feed_ranker(1) == expected
+
+
+class TestJudgeScannerWindow(SimpleTestCase):
+ def test_a_window_larger_than_one_chunk_is_judged_across_requests(self) -> None:
+ 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 = _answer_every_question(0.7)
+ judgment = judge_scanner_window(1, uuid4(), rows)
+ assert api.decide_when_available.call_count == 2
+ assert judgment.chunks == 2
+ assert judgment.failed_chunks == 0
+ assert len(judgment.probabilities) == len(rows)
+ assert judgment.probabilities[str(rows[0]["id"])] == 0.7
+ assert judgment.input_tokens == 240
+ 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 "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
+
+ def test_a_failed_chunk_loses_only_its_own_rows(self) -> None:
+ rows = [_prose_row(uuid4(), f"summary {index}") for index in range(WINDOW_CHUNK_SIZE + 6)]
+ answer = _answer_every_question(0.7)
+ attempts: list[int] = []
+
+ def _first_chunk_fails(request: DecisionRequest, **kwargs: Any) -> DecisionResult:
+ attempts.append(1)
+ if len(attempts) == 1:
+ raise DecisionsDisabledError(1)
+ return answer(request)
+
+ with patch(_API) as api:
+ 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
+ # An unavailable decision service is not the batch's fault, so no retry budget is charged.
+ assert judgment.batch_failed_ids == ()
+
+ def test_an_invalid_probability_fails_the_whole_chunk(self) -> None:
+ rows = [_prose_row(uuid4(), "summary")]
+ with patch(_API) as api:
+ api.decide_when_available.side_effect = _answer_every_question(7.0)
+ judgment = judge_scanner_window(1, uuid4(), rows)
+ assert judgment.probabilities == {}
+ assert judgment.failed_chunks == 1
+ # An invalid answer is the batch's own fault, so its rows are charged a retry attempt.
+ assert judgment.batch_failed_ids == (str(rows[0]["id"]),)
+
+ @parameterized.expand(
+ [
+ ("refusal", 422, True),
+ ("rate_limit", 429, False),
+ ("server_error", 503, False),
+ ]
+ )
+ def test_only_a_batch_attributable_gateway_refusal_charges_the_retry_budget(
+ self, _name: str, status_code: int, charged: bool
+ ) -> None:
+ rows = [_prose_row(uuid4(), "summary")]
+ with patch(_API) as api:
+ api.decide_when_available.side_effect = DecisionGatewayError(status_code, "detail")
+ judgment = judge_scanner_window(1, uuid4(), rows)
+ assert judgment.failed_chunks == 1
+ assert judgment.batch_failed_ids == ((str(rows[0]["id"]),) if charged else ())
+
+ def test_rows_without_prose_are_reported_instead_of_sent(self) -> None:
+ no_output, no_result = uuid4(), uuid4()
+ rows = [
+ _prose_row(uuid4(), "summary"),
+ {"id": no_output, "scanner_result": {"model_output": {}, "signals_count": 0}},
+ {"id": no_result, "scanner_result": None},
+ ]
+ with patch(_API) as api:
+ api.decide_when_available.side_effect = _answer_every_question(0.5)
+ judgment = judge_scanner_window(1, uuid4(), rows)
+ assert len(judgment.probabilities) == 1
+ assert set(judgment.skipped_no_prose) == {str(no_output), str(no_result)}
+
+ def test_context_rows_enter_the_state_without_questions(self) -> None:
+ rows = [_prose_row(uuid4(), f"new {index}") for index in range(3)]
+ context_rows = [_prose_row(uuid4(), f"old {index}") for index in range(40)]
+ with patch(_API) as api:
+ api.decide_when_available.side_effect = _answer_every_question(0.5)
+ judgment = judge_scanner_window(1, uuid4(), rows, context_rows)
+ request = api.decide_when_available.call_args.args[0]
+ # A quiet hour's small batch is still judged against the scanner's routine, and the state
+ # never exceeds one chunk's size.
+ assert len(request.questions) == 3
+ assert len(request.state["observations"]) == WINDOW_CHUNK_SIZE
+ assert len(judgment.probabilities) == 3
+
+ def test_long_prose_is_clipped_before_it_enters_the_request(self) -> None:
+ rows = [_prose_row(uuid4(), "x" * 100_000)]
+ with patch(_API) as api:
+ api.decide_when_available.side_effect = _answer_every_question(0.5)
+ judge_scanner_window(1, uuid4(), rows)
+ request = api.decide_when_available.call_args.args[0]
+ assert len(request.state["observations"]["0"]["summary"]) == 1500
+
+ def test_an_empty_window_makes_no_request(self) -> None:
+ with patch(_API) as api:
+ judgment = judge_scanner_window(1, uuid4(), [])
+ api.decide_when_available.assert_not_called()
+ assert judgment.probabilities == {}
+
+
+def _feed_row(
+ observation_id: str,
+ minutes_ago: int,
+ *,
+ viewed: bool = False,
+ scanner: str = "scanner-a",
+ notability: str | None = None,
+ notability_score: float = 0.9,
+) -> dict[str, Any]:
+ row: dict[str, Any] = {
+ "id": observation_id,
+ "scanner_id": scanner,
+ "created_at": datetime(2026, 9, 25, 12, 0, tzinfo=UTC) - timedelta(minutes=minutes_ago),
+ "feed_viewed": viewed,
+ }
+ if notability is not None:
+ row["scanner_result"] = {"model_output": {"notability_reason": notability, "notability": notability_score}}
+ return row
+
+
+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
+ # judgment never outranks a fresh observation the sweep has not seen yet, and its card never
+ # claims the model judged it worth watching. Filler then pads the findings only up to the
+ # feed's floor, newest first, so the older filler rows drop.
+ ranked = rank_watch_feed_by_jev(
+ [
+ _feed_row("old-unjudged", 50),
+ _feed_row("judged-low", 40),
+ _feed_row("high", 30),
+ _feed_row("higher", 20, notability="The user paid twice for one order."),
+ _feed_row("new-unjudged", 10),
+ ],
+ {"judged-low": 0.2, "high": 0.7, "higher": 0.9},
+ )
+ assert [entry.observation_id for entry in ranked] == ["higher", "high", "new-unjudged"]
+ # The scan's own sentence rides along so the card can explain the pick; a row without one
+ # carries only the kind and probability.
+ assert ranked[0].reason == {
+ "kind": "jev_watchable",
+ "jev_probability": 0.9,
+ "notability_reason": "The user paid twice for one order.",
+ }
+ assert ranked[1].reason == {"kind": "jev_watchable", "jev_probability": 0.7}
+ assert ranked[2].reason == {"kind": "unviewed_recent"}
+
+ def test_a_cold_cache_returns_the_filler_floor_not_a_full_page(self) -> None:
+ # With no cached judgments every row is filler: the feed shows the same 3-row floor as the
+ # weighted ranker, unviewed rows first and newest first, instead of a whole page of "new
+ # since you last looked" cards.
+ rows = [_feed_row(f"row-{index}", index, viewed=index == 0) for index in range(20)]
+ ranked = rank_watch_feed_by_jev(rows, {})
+ assert [entry.observation_id for entry in ranked] == ["row-1", "row-2", "row-3"]
+
+ def test_one_scanner_cannot_flood_the_top_of_the_evidence_tier(self) -> None:
+ # One incident's near-identical sessions must leave room for other scanners' findings, and
+ # the overflow trails the tier instead of dropping out of it.
+ rows = [_feed_row(f"flood-{index}", 10 + index, scanner="flooding") for index in range(6)]
+ rows += [_feed_row("other-0", 30, scanner="quiet"), _feed_row("other-1", 31, scanner="quiet")]
+ probabilities = {f"flood-{index}": 0.96 - index / 100 for index in range(6)} | {
+ "other-0": 0.7,
+ "other-1": 0.69,
+ }
+ ranked = rank_watch_feed_by_jev(rows, probabilities)
+ assert [entry.observation_id for entry in ranked] == [
+ "flood-0",
+ "flood-1",
+ "flood-2",
+ "other-0",
+ "other-1",
+ "flood-3",
+ "flood-4",
+ "flood-5",
+ ]
+
+ def test_a_viewed_row_is_docked_inside_the_watchable_tier_only(self) -> None:
+ ranked = rank_watch_feed_by_jev(
+ [
+ # The scan itself found nothing notable, so its sentence must not lead a card Jev
+ # rated watchable relative to a dull window.
+ _feed_row("viewed-strong", 30, viewed=True, notability="Nothing stands out.", notability_score=0.2),
+ _feed_row("unviewed-mid", 20),
+ # Raw probability decides the tier, so the dock cannot push a watchable row into filler.
+ _feed_row("viewed-borderline", 15, viewed=True),
+ _feed_row("viewed-filler", 5, viewed=True),
+ _feed_row("unviewed-filler", 1),
+ ],
+ {"viewed-strong": 0.95, "unviewed-mid": 0.6, "viewed-borderline": 0.55},
+ )
+ # 0.95 - 0.3 dock = 0.65 still beats 0.6; 0.55 - 0.3 = 0.25 stays watchable, ordered last.
+ # Three findings meet the floor, so no filler row survives the trim.
+ assert [entry.observation_id for entry in ranked] == [
+ "viewed-strong",
+ "unviewed-mid",
+ "viewed-borderline",
+ ]
+ assert ranked[0].reason == {"kind": "jev_watchable", "jev_probability": 0.95}
+ assert ranked[2].reason == {"kind": "jev_watchable", "jev_probability": 0.55}
+
+
+class TestWatchRankCache(SimpleTestCase):
+ def test_stored_ranks_round_trip_and_malformed_values_are_dropped_or_clamped(self) -> None:
+ team_id = 990_001
+ scanner_id, other_scanner_id, missing_scanner_id = uuid4(), uuid4(), uuid4()
+ store_watch_ranks(
+ team_id, scanner_id, {"obs-a", "obs-b", "obs-low"}, {"obs-a": 0.9, "obs-b": 7.0}, {"obs-f": 2}, "jevk5"
+ )
+ store_watch_ranks(team_id, other_scanner_id, {"obs-c"}, {"obs-c": 0.4}, {}, "jevk5")
+ loaded = load_watch_ranks(team_id, [scanner_id, other_scanner_id, missing_scanner_id])
+ assert loaded == {"obs-a": 0.9, "obs-b": 1.0, "obs-c": 0.4}
+ # The feed's per-request keys carry only the watchable map; the judged set remembers every
+ # row the sweep has bought, including the sub-threshold ones the feed never needs, plus the
+ # attempt counts for rows whose judgment keeps failing.
+ judged_state = load_judged_state(team_id, scanner_id)
+ assert judged_state.ids == {"obs-a", "obs-b", "obs-low"}
+ assert judged_state.attempts == {"obs-f": 2}
+ assert load_judged_state(team_id, missing_scanner_id).ids == set()
+ # Another team's cache never leaks in.
+ assert load_watch_ranks(team_id + 1, [scanner_id]) == {}
+
+ def test_a_partial_store_failure_leaves_rows_rejudgeable(self) -> None:
+ # The judged marker is written last: when the watchable write lands and the judged write
+ # fails, the next sweep re-buys the batch. The reverse order would mark the rows judged
+ # with their scores lost forever.
+ team_id = 990_002
+ scanner_id = uuid4()
+ inner = get_client(settings.REPLAY_VISION_REDIS_URL)
+
+ class _JudgedWritesFail:
+ def setex(self, key: str, ttl: Any, value: str) -> None:
+ if ":judged:" in key:
+ raise ConnectionError("redis down")
+ inner.setex(key, ttl, value)
+
+ with patch("products.replay_vision.backend.jev_watch_feed.get_client", return_value=_JudgedWritesFail()):
+ with self.assertRaises(ConnectionError):
+ store_watch_ranks(team_id, scanner_id, {"obs-a"}, {"obs-a": 0.9}, {}, "jevk5")
+ assert load_watch_ranks(team_id, [scanner_id]) == {"obs-a": 0.9}
+ assert load_judged_state(team_id, scanner_id).ids == set()
+
+ def test_a_read_failure_raises_for_the_sweep_and_stays_soft_for_the_feed(self) -> None:
+ # An unreachable cache must not read as an empty one: the sweep would re-buy the scanner's
+ # judgments and its write would replace entries it never saw. The feed only degrades.
+ scanner_id = uuid4()
+ with patch(
+ "products.replay_vision.backend.jev_watch_feed.get_client",
+ side_effect=ConnectionError("redis down"),
+ ):
+ with self.assertRaises(ConnectionError):
+ load_judged_state(1, scanner_id)
+ with self.assertRaises(ConnectionError):
+ load_scanner_watch_ranks(1, scanner_id)
+ assert load_watch_ranks(1, [scanner_id]) == {}
+
+
+class TestJevWatchRankSweep(BaseTest):
+ def _succeeded_observation(self, scanner: ReplayScanner, session_id: str, summary: str) -> ReplayObservation:
+ return ReplayObservation.objects.create(
+ scanner=scanner,
+ session_id=session_id,
+ scanner_snapshot=_snapshot_for(scanner),
+ triggered_by=ObservationTrigger.SCHEDULE,
+ status=ObservationStatus.SUCCEEDED,
+ completed_at=timezone.now(),
+ scanner_result={
+ "model_output": {"scanner_type": "summarizer", "title": "t", "summary": summary, "confidence": 0.9},
+ "signals_count": 0,
+ },
+ )
+
+ def test_the_sweep_gates_judges_and_skips_unchanged_windows(self) -> None:
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save()
+ scanner = ReplayScanner.objects.create(
+ team=self.team,
+ name="s",
+ scanner_type=ScannerType.SUMMARIZER,
+ scanner_config={"prompt": "p", "length": "short"},
+ model=ScannerModel.GEMINI_3_8_FLASH,
+ )
+ first = self._succeeded_observation(scanner, "s1", "The user hit an error at checkout.")
+ second = self._succeeded_observation(scanner, "s2", "The user skimmed the pricing page.")
+
+ activities = "products.replay_vision.backend.temporal.jev_watch_rank.activities"
+ flag = f"{activities}.watch_feed_ranker"
+ region = f"{activities}.decision_api.decisions_available_here"
+
+ with patch(flag, return_value="weighted-score"), patch(region, return_value=True), patch(_API) as api:
+ result = async_to_sync(_judge_watch_ranks)(JevWatchRankSweepInputs())
+ # A team on the default arm costs no Jev calls and gets no cache entry.
+ api.decide_when_available.assert_not_called()
+ assert result.teams_enrolled == 0
+ assert load_watch_ranks(self.team.id, [scanner.id]) == {}
+
+ with (
+ patch(flag, side_effect=self._flag_arm("jev-shadow")),
+ patch(region, return_value=False),
+ patch(_API) as api,
+ ):
+ result = async_to_sync(_judge_watch_ranks)(JevWatchRankSweepInputs())
+ # A region without the decision service does no work at all.
+ api.decide_when_available.assert_not_called()
+ assert result.decisions_unavailable
+
+ self.organization.is_ai_data_processing_approved = False
+ self.organization.save()
+ with (
+ patch(flag, side_effect=self._flag_arm("jev-shadow")),
+ patch(region, return_value=True),
+ patch(_API) as api,
+ ):
+ result = async_to_sync(_judge_watch_ranks)(JevWatchRankSweepInputs())
+ # An enrolled team without AI data-processing consent sends nothing to the model.
+ api.decide_when_available.assert_not_called()
+ assert result.teams_without_consent == 1
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save()
+
+ with (
+ patch(flag, side_effect=self._flag_arm("jev-shadow")),
+ patch(region, return_value=True),
+ patch(_API) as api,
+ patch("posthoganalytics.capture"),
+ ):
+ api.decide_when_available.side_effect = _answer_every_question(0.7)
+ result = async_to_sync(_judge_watch_ranks)(JevWatchRankSweepInputs())
+ assert result.teams_enrolled == 1
+ assert result.scanners_judged == 1
+ assert result.observations_judged == 2
+ assert load_watch_ranks(self.team.id, [scanner.id]) == {str(first.id): 0.7, str(second.id): 0.7}
+
+ with (
+ patch(flag, side_effect=self._flag_arm("jev-shadow")),
+ patch(region, return_value=True),
+ patch(_API) as api,
+ ):
+ result = async_to_sync(_judge_watch_ranks)(JevWatchRankSweepInputs())
+ # 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 load_watch_ranks(self.team.id, [scanner.id]) == {str(first.id): 0.7, str(second.id): 0.7}
+
+ third = self._succeeded_observation(scanner, "s3", "The user deleted the whole workspace.")
+ with (
+ patch(flag, side_effect=self._flag_arm("jev-shadow")),
+ patch(region, return_value=True),
+ patch(_API) as api,
+ patch("posthoganalytics.capture"),
+ ):
+ api.decide_when_available.side_effect = _answer_every_question(0.9)
+ result = async_to_sync(_judge_watch_ranks)(JevWatchRankSweepInputs())
+ # Only the new row is judged, with the already-judged rows in the state as context, and the
+ # earlier judgments survive the merge.
+ request = api.decide_when_available.call_args.args[0]
+ assert len(request.questions) == 1
+ assert len(request.state["observations"]) == 3
+ assert result.observations_judged == 1
+ assert load_watch_ranks(self.team.id, [scanner.id]) == {
+ str(first.id): 0.7,
+ str(second.id): 0.7,
+ str(third.id): 0.9,
+ }
+
+ def test_an_unreadable_cache_skips_the_scanner_without_judging_or_writing(self) -> None:
+ # A transient Redis failure must not read as an empty cache: judging over it would re-buy
+ # rows, and the write would replace the scanner's entries with only the current batch.
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save()
+ scanner = ReplayScanner.objects.create(
+ team=self.team,
+ name="s",
+ scanner_type=ScannerType.SUMMARIZER,
+ scanner_config={"prompt": "p", "length": "short"},
+ model=ScannerModel.GEMINI_3_8_FLASH,
+ )
+ self._succeeded_observation(scanner, "s1", "The user hit an error at checkout.")
+ store_watch_ranks(self.team.id, scanner.id, {"judged-earlier"}, {"judged-earlier": 0.9}, {}, "jevk5")
+
+ 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}.load_judged_state", side_effect=ConnectionError("redis down")),
+ patch(_API) as api,
+ ):
+ result = async_to_sync(_judge_watch_ranks)(JevWatchRankSweepInputs())
+ api.decide_when_available.assert_not_called()
+ assert result.cache_errors == 1
+ assert result.scanners_judged == 0
+ assert load_watch_ranks(self.team.id, [scanner.id]) == {"judged-earlier": 0.9}
+
+ def _flag_arm(self, arm: str):
+ """The experiment arm for self.team only, so the pinned team 2 stays on the default arm."""
+ return lambda team_id: arm if team_id == self.team.id else "weighted-score"
+
+ def test_posthogs_own_team_is_always_swept_first(self) -> None:
+ # While the experiment is internal-only, team 2 must never fall past the team cap,
+ # whatever order the other teams come back in.
+ assert _teams_with_scanners()[0] == 2
+
+ def test_a_batch_that_keeps_failing_is_abandoned_after_max_attempts(self) -> None:
+ # A deterministically failing batch must not stay newest-unjudged forever, re-bought every
+ # hour while older rows starve. After MAX_JUDGE_ATTEMPTS batch-attributable failures it
+ # joins the judged set with no score and the sweep moves on. An outage sweep charges no
+ # attempt, so a bad hour cannot park the rows.
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save()
+ scanner = ReplayScanner.objects.create(
+ team=self.team,
+ name="s",
+ scanner_type=ScannerType.SUMMARIZER,
+ scanner_config={"prompt": "p", "length": "short"},
+ model=ScannerModel.GEMINI_3_8_FLASH,
+ )
+ self._succeeded_observation(scanner, "s1", "The user hit an error at checkout.")
+
+ activities = "products.replay_vision.backend.temporal.jev_watch_rank.activities"
+ # One outage sweep first: it fails the chunk but burns none of the batch's retry budget,
+ # so the batch still takes the full MAX_JUDGE_ATTEMPTS failing sweeps below to give up.
+ 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 = DecisionsDisabledError(self.team.id)
+ result = async_to_sync(_judge_watch_ranks)(JevWatchRankSweepInputs())
+ assert result.failed_chunks == 1
+ assert result.observations_given_up == 0
+
+ for attempt in range(1, MAX_JUDGE_ATTEMPTS + 1):
+ 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 = _answer_every_question(7.0)
+ result = async_to_sync(_judge_watch_ranks)(JevWatchRankSweepInputs())
+ assert result.failed_chunks == 1, attempt
+ assert result.observations_given_up == (1 if attempt == MAX_JUDGE_ATTEMPTS else 0), attempt
+
+ 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,
+ ):
+ result = async_to_sync(_judge_watch_ranks)(JevWatchRankSweepInputs())
+ # The abandoned row is judged with no score: no more Jev spend, filler tier in the feed.
+ api.decide_when_available.assert_not_called()
+ assert result.scanners_skipped_unchanged == 1
+ assert load_watch_ranks(self.team.id, [scanner.id]) == {}
diff --git a/tach.toml b/tach.toml
index 4b99b4aee205..126bc94a8163 100644
--- a/tach.toml
+++ b/tach.toml
@@ -798,6 +798,8 @@ depends_on = [
"products.experiments",
"products.exports",
"products.feature_flags",
+ # Facade-only: the watch feed's hourly Jev sweep calls the shared decision-model client.
+ "products.ml_inference",
"products.notifications",
"products.signals",
"products.tasks", "products.access_control",