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): have jev pick why a session is worth watching (#114045)

Kim Svatos Dugan5ff0fb384460
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index c728b6633c71..b5f2e1a9f9f9 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -97,6 +97,7 @@ from products.replay_vision.backend.impact import (
)
from products.replay_vision.backend.jev_watch_feed import (
JEV_WATCHABLE_MIN,
+ JevWatchReason,
load_watch_ranks,
rank_watch_feed_by_jev,
watch_feed_ranker,
@@ -1734,6 +1735,14 @@ class WatchFeedReasonSerializer(serializers.Serializer):
"copy derived from the reason kind. Absent on observations scanned before notability shipped."
),
)
+ watch_reason = serializers.ChoiceField(
+ choices=JevWatchReason.choices,
+ required=False,
+ help_text=(
+ "Why the decision model rated the session worth watching, picked from a fixed list, for "
+ "`jev_watchable`. Absent when no reason on the list fits, or on sessions judged before reasons shipped."
+ ),
+ )
score = serializers.FloatField(
required=False, allow_null=True, help_text="The observation's score, for `outlier_score`."
)
@@ -2480,7 +2489,8 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
# ranker that ordered it, so the shadow arm reads as weighted-score to the client.
ranker = "jev" if watch_feed_ranker(self.team_id) == "jev" else "weighted-score"
if ranker == "jev":
- probabilities = load_watch_ranks(self.team_id, allowed_ids)
+ ranks = load_watch_ranks(self.team_id, allowed_ids)
+ probabilities = ranks.probabilities
jev_rows = list(candidate_rows)
# The recency slice above holds only each scanner's newest rows, which on a high-volume
# scanner covers minutes. The sweep judged the whole window, so fetch the watchable rows
@@ -2512,7 +2522,7 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, vi
)
jev_rows += fetched
needed -= len(fetched)
- ranked = rank_watch_feed_by_jev(jev_rows, probabilities)[: params["limit"]]
+ ranked = rank_watch_feed_by_jev(jev_rows, probabilities, ranks.reasons)[: params["limit"]]
else:
ranked = rank_watch_feed_candidates(candidate_rows)[: params["limit"]]
reasons_by_id = {entry.observation_id: entry.reason for entry in ranked}
diff --git a/products/replay_vision/backend/jev_watch_feed.py b/products/replay_vision/backend/jev_watch_feed.py
index a58cbcc41c90..e2d07c7cf06c 100644
--- a/products/replay_vision/backend/jev_watch_feed.py
+++ b/products/replay_vision/backend/jev_watch_feed.py
@@ -10,7 +10,9 @@ The multivariate `vision-watch-feed-ranker` flag selects one of two independent
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
+scanner's own recent sessions rather than standing alone. A second request over the same state asks
+one multiple-choice question per watchable row, so the feed can say why Jev picked it
+(`JevWatchReason`). 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
@@ -27,6 +29,8 @@ from time import perf_counter
from typing import Any, Literal
from uuid import UUID, uuid4
+from django.db import models
+
import redis
import structlog
from prometheus_client import Counter, Histogram
@@ -39,6 +43,7 @@ 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,
+ ChoiceAnswer,
DecisionGatewayError,
DecisionQuestion,
DecisionRequest,
@@ -123,6 +128,64 @@ _WINDOW_INSTRUCTIONS = (
"worth watching; only what the recorded user experienced counts."
)
+
+class JevWatchReason(models.TextChoices):
+ """Why Jev rated a session worth watching, picked from a fixed list. The frontend maps each value to
+ the sentence on the row, so a wording change needs no re-judging."""
+
+ VISIBLE_ERROR = "visible_error", "Error on screen"
+ SILENT_FAILURE = "silent_failure", "Action silently failed"
+ UNRESPONSIVE = "unresponsive", "Clicks went nowhere"
+ SLOW_OR_STUCK = "slow_or_stuck", "Slow or stuck"
+ BLOCKED = "blocked", "Blocked"
+ CANT_FIND = "cant_find", "Couldn't find it"
+ CONFUSED = "confused", "Confused"
+ WORKAROUND = "workaround", "Took a workaround"
+ ABANDONED = "abandoned", "Gave up"
+ CHURN_SIGNAL = "churn_signal", "Churn signal"
+ SUCCESS = "success", "Worked well"
+
+
+# Jev picks this option when no reason fits. It never reaches the cache, so the row shows no reason.
+_NO_WATCH_REASON = "nothing_notable"
+_WATCH_REASON_CRITERIA: dict[str, str] = {
+ JevWatchReason.VISIBLE_ERROR.value: "An error message, toast, crash, or failed request is shown to the user.",
+ JevWatchReason.SILENT_FAILURE.value: (
+ "Something the user did did not take effect and nothing told them, such as a save that did not stick "
+ "or an action they had to repeat."
+ ),
+ JevWatchReason.UNRESPONSIVE.value: "Dead clicks or rage clicks: the user clicks something that does not respond.",
+ JevWatchReason.SLOW_OR_STUCK.value: "Long loading, spinners, timeouts, or a screen stuck in one state.",
+ JevWatchReason.BLOCKED.value: (
+ "A hard stop the user cannot get past: access denied, a limit reached, a 404 or dead end, or a feature "
+ "that is not available."
+ ),
+ JevWatchReason.CANT_FIND.value: (
+ "Repeated searching or navigating without finding what the user needs, or empty results."
+ ),
+ JevWatchReason.CONFUSED.value: (
+ "Hesitation, backtracking, trial and error, or misunderstanding how something works."
+ ),
+ JevWatchReason.WORKAROUND.value: (
+ "The user gave up on the intended path and reached the goal another way, such as SQL instead of the UI "
+ "or asking support."
+ ),
+ JevWatchReason.ABANDONED.value: "The user left a task, form, or setup unfinished.",
+ JevWatchReason.CHURN_SIGNAL.value: (
+ "Cancelling, downgrading, asking for a refund, deleting a project, or contacting support in frustration."
+ ),
+ JevWatchReason.SUCCESS.value: ("A smooth, notable success: the user used a feature as intended to reach a goal."),
+ _NO_WATCH_REASON: "A routine session. None of the other reasons fits.",
+}
+# Same rule as _WINDOW_INSTRUCTIONS: user text stays in the state, referred to by id only.
+_REASON_INSTRUCTIONS = (
+ "The state holds recent AI scans of recorded product sessions, all from one scanner, keyed by "
+ "id. The session behind the scan with id {index} was judged worth watching. Pick the one reason "
+ "a product team would most want to watch it for. When several reasons apply, pick the most "
+ "severe one. Use the other scans in the state only as context. Judge only what the recorded "
+ "user experienced."
+)
+
_CALLS = Counter(
"replay_vision_jev_watch_rank_calls",
"Jev watch rank chunk requests by outcome.",
@@ -165,6 +228,10 @@ class WindowJudgment:
"""Jev's judgment of one batch of observations: a probability per observation id (as a string)."""
probabilities: dict[str, float]
+ # The JevWatchReason value Jev picked for each watchable row. A row without a fitting reason, or
+ # from a chunk whose reason request failed, is absent; the row still ranks on its probability.
+ reasons: dict[str, str]
+ failed_reason_chunks: int
# 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.
@@ -220,24 +287,19 @@ def _window_entry(row: dict[str, Any]) -> dict[str, Any] | None:
return entry
-def _judge_chunk(
+def _decide(
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."""
+ questions: dict[str, DecisionQuestion],
+) -> Any:
+ """One request over `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 answers 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(
+ return decision_api.decide_when_available(
DecisionRequest(
team_id=team_id,
state=state,
@@ -251,6 +313,22 @@ def _judge_chunk(
),
timeout_seconds=JEV_TIMEOUT_SECONDS,
)
+
+
+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 yes/no question per observation in `chunk`: is the session worth watching."""
+ questions = {
+ f"watch_{index}": DecisionQuestion(
+ type=DecisionQuestionType.NOUL, instructions=_WINDOW_INSTRUCTIONS.format(index=index)
+ )
+ for index in range(len(chunk))
+ }
+ result = _decide(team_id, trace_id, chunk, context, questions)
probabilities: dict[str, float] = {}
for index, (observation_id, _) in enumerate(chunk):
answer = result.answers.get(f"watch_{index}")
@@ -264,6 +342,36 @@ def _judge_chunk(
return probabilities, result
+def _pick_watch_reasons(
+ team_id: int,
+ trace_id: str,
+ chunk: list[tuple[str, dict[str, Any]]],
+ context: list[dict[str, Any]],
+ watchable_ids: set[str],
+) -> tuple[dict[str, str], Any]:
+ """One multiple-choice question per watchable observation in `chunk`: why it is worth watching.
+
+ Asked only for watchable rows, because the feed shows a reason only on them. The state is the
+ same as the yes/no request's, so the pick sees the same context. An answer outside the list, or
+ no fitting reason, leaves the row without one instead of failing the chunk."""
+ indexes = [index for index, (observation_id, _) in enumerate(chunk) if observation_id in watchable_ids]
+ questions = {
+ f"reason_{index}": DecisionQuestion(
+ type=DecisionQuestionType.CHOICE,
+ instructions=_REASON_INSTRUCTIONS.format(index=index),
+ criteria=_WATCH_REASON_CRITERIA,
+ )
+ for index in indexes
+ }
+ result = _decide(team_id, trace_id, chunk, context, questions)
+ reasons: dict[str, str] = {}
+ for index in indexes:
+ answer = result.answers.get(f"reason_{index}")
+ if isinstance(answer, ChoiceAnswer) and answer.choice in JevWatchReason.values:
+ reasons[chunk[index][0]] = answer.choice
+ return reasons, 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:
@@ -283,19 +391,29 @@ def judge_scanner_window(
# 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] = {}
+ reasons: dict[str, str] = {}
batch_failed_ids: list[str] = []
model: str | None = None
failed_chunks = 0
+ failed_reason_chunks = 0
chunk_error_types: dict[str, int] = {}
input_tokens = 0
estimated_cost = 0.0
+
+ def charge(result: Any) -> None:
+ nonlocal input_tokens, estimated_cost
+ 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)
+
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)]
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)]
- )
+ chunk_probabilities, result = _judge_chunk(team_id, trace_id, chunk, chunk_context)
except Exception as error:
_LATENCY.observe(perf_counter() - started)
error_type = type(error).__name__
@@ -323,13 +441,34 @@ def judge_scanner_window(
_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)
+ charge(result)
+ watchable_ids = {oid for oid, probability in chunk_probabilities.items() if probability >= JEV_WATCHABLE_MIN}
+ if not watchable_ids:
+ continue
+ started = perf_counter()
+ try:
+ chunk_reasons, reason_result = _pick_watch_reasons(team_id, trace_id, chunk, chunk_context, watchable_ids)
+ except Exception as error:
+ # A reason only labels the row, so a failed pick keeps the chunk's probabilities and is
+ # not retried: the rows are judged, and the feed shows them without a reason.
+ _LATENCY.observe(perf_counter() - started)
+ _CALLS.labels(f"reason_{type(error).__name__}").inc()
+ failed_reason_chunks += 1
+ logger.warning(
+ "Jev watch reason chunk failed",
+ team_id=team_id,
+ scanner_id=str(scanner_id),
+ error_type=type(error).__name__,
+ )
+ continue
+ _LATENCY.observe(perf_counter() - started)
+ _CALLS.labels("reason_ok").inc()
+ reasons.update(chunk_reasons)
+ charge(reason_result)
return WindowJudgment(
probabilities=probabilities,
+ reasons=reasons,
+ failed_reason_chunks=failed_reason_chunks,
skipped_no_prose=skipped_no_prose,
batch_failed_ids=tuple(batch_failed_ids),
model=model,
@@ -374,6 +513,7 @@ def store_watch_ranks(
watchable: dict[str, float],
attempts: dict[str, int],
model: str | None,
+ reasons: dict[str, str] | None = None,
) -> None:
client = _watch_rank_client()
client.setex(
@@ -384,6 +524,7 @@ def store_watch_ranks(
"model": model,
"judged_at": datetime.now(UTC).isoformat(),
"probabilities": watchable,
+ "reasons": {oid: reason for oid, reason in (reasons or {}).items() if oid in watchable},
}
),
)
@@ -438,46 +579,71 @@ def load_judged_state(team_id: int, scanner_id: UUID) -> JudgedState:
)
-def _parse_watchable(value: Any) -> dict[str, float]:
+@frozen
+class WatchRanks:
+ """Cached Jev judgments for one or more scanners, keyed by observation id: the watchable
+ probabilities, and the JevWatchReason value for each watchable row that has one."""
+
+ probabilities: dict[str, float]
+ reasons: dict[str, str]
+
+
+def _parse_watchable(value: Any) -> WatchRanks:
if not value:
- return {}
+ return WatchRanks(probabilities={}, reasons={})
try:
- stored = json.loads(value).get("probabilities")
+ stored = json.loads(value)
except Exception:
logger.exception("Jev watch rank cache value malformed")
- return {}
- if not isinstance(stored, dict):
- return {}
+ return WatchRanks(probabilities={}, reasons={})
+ stored_probabilities = stored.get("probabilities") if isinstance(stored, dict) else None
+ if not isinstance(stored_probabilities, dict):
+ return WatchRanks(probabilities={}, reasons={})
probabilities: dict[str, float] = {}
- for observation_id, probability in stored.items():
+ for observation_id, probability in stored_probabilities.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
+ # Entries written before reasons shipped carry none, and a value outside the list never reaches
+ # the API, whose enum would reject it.
+ stored_reasons = stored.get("reasons")
+ reasons = (
+ {
+ str(observation_id): reason
+ for observation_id, reason in stored_reasons.items()
+ if str(observation_id) in probabilities and reason in JevWatchReason.values
+ }
+ if isinstance(stored_reasons, dict)
+ else {}
+ )
+ return WatchRanks(probabilities=probabilities, reasons=reasons)
-def load_scanner_watch_ranks(team_id: int, scanner_id: UUID) -> dict[str, float]:
+def load_scanner_watch_ranks(team_id: int, scanner_id: UUID) -> WatchRanks:
"""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(_watch_rank_client().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 {}
+def load_watch_ranks(team_id: int, scanner_ids: list[UUID]) -> WatchRanks:
+ """The cached watchable probabilities and reasons for these scanners. 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."""
probabilities: dict[str, float] = {}
+ reasons: dict[str, str] = {}
+ if not scanner_ids:
+ return WatchRanks(probabilities=probabilities, reasons=reasons)
try:
values = _watch_rank_client().mget([_watchable_key(team_id, scanner_id) for scanner_id in scanner_ids])
for value in values:
- probabilities |= _parse_watchable(value)
+ ranks = _parse_watchable(value)
+ probabilities |= ranks.probabilities
+ reasons |= ranks.reasons
except Exception:
logger.exception("Jev watch rank cache read failed", team_id=team_id)
- return probabilities
+ return WatchRanks(probabilities=probabilities, reasons=reasons)
def _scan_notability_reason(row: dict[str, Any]) -> str | None:
@@ -516,7 +682,9 @@ def _spread_scanners(ordered: list[tuple[Any, WatchFeedEntry]]) -> list[WatchFee
return placed + deferred
-def rank_watch_feed_by_jev(rows: list[dict[str, Any]], probabilities: dict[str, float]) -> list[WatchFeedEntry]:
+def rank_watch_feed_by_jev(
+ rows: list[dict[str, Any]], probabilities: dict[str, float], reasons: dict[str, str] | None = None
+) -> 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.
@@ -540,6 +708,8 @@ def rank_watch_feed_by_jev(rows: list[dict[str, Any]], probabilities: dict[str,
# 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
+ if watch_reason := (reasons or {}).get(str(row["id"])):
+ reason["watch_reason"] = watch_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)
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 982fef3d4712..8f8651772de4 100644
--- a/products/replay_vision/backend/temporal/jev_watch_rank/activities.py
+++ b/products/replay_vision/backend/temporal/jev_watch_rank/activities.py
@@ -13,6 +13,7 @@ cross-team index on (status, created_at), so the sweep never queries it without
"""
import asyncio
+from collections import Counter
from contextlib import suppress
from datetime import UTC, datetime
from statistics import fmean
@@ -178,7 +179,7 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSwe
# 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)
+ cached = 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.
@@ -203,9 +204,10 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSwe
# 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 cached.probabilities.items() if oid in window_strs},
**{oid: p for oid, p in judgment.probabilities.items() if p >= JEV_WATCHABLE_MIN},
}
+ reasons = {oid: reason for oid, reason in (cached.reasons | judgment.reasons).items() if oid in watchable}
# A row whose judgment failed through its own batch (an invalid answer, a gateway
# refusal the batch caused) retries on later sweeps, but only MAX_JUDGE_ATTEMPTS times: the
# newest-first pick would otherwise retry a deterministically failing batch every hour
@@ -227,7 +229,14 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSwe
if all_judged or attempts:
try:
await asyncio.to_thread(
- store_watch_ranks, team_id, scanner_id, all_judged, watchable, attempts, judgment.model
+ store_watch_ranks,
+ team_id,
+ scanner_id,
+ all_judged,
+ watchable,
+ attempts,
+ judgment.model,
+ reasons,
)
except Exception:
# The batch is re-bought next run, which beats one write failure ending the sweep.
@@ -266,6 +275,8 @@ async def _judge_watch_ranks(inputs: JevWatchRankSweepInputs) -> JevWatchRankSwe
"chunks": judgment.chunks,
"failed_chunks": judgment.failed_chunks,
"chunk_error_types": judgment.chunk_error_types,
+ "watch_reasons": dict(Counter(judgment.reasons.values())),
+ "failed_reason_chunks": judgment.failed_reason_chunks,
"jev_model": judgment.model,
"input_tokens": judgment.input_tokens,
"estimated_cost_usd": judgment.estimated_cost_usd,
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index dbf0b6f6bf5d..751269fcdc89 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -5103,7 +5103,13 @@ class TestWatchFeedAPI(_VisionAPITestCase):
for index in range(100):
self._succeeded_observation(scanner, f"routine-{index}", index + 1, self._monitor_result("no"))
store_watch_ranks(
- self.team.id, scanner.id, {str(old_interesting.id)}, {str(old_interesting.id): 0.9}, {}, "jevk5-fp8-0.2"
+ self.team.id,
+ scanner.id,
+ {str(old_interesting.id)},
+ {str(old_interesting.id): 0.9},
+ {},
+ "jevk5-fp8-0.2",
+ {str(old_interesting.id): "visible_error"},
)
ranker = "products.replay_vision.backend.api.scanners.watch_feed_ranker"
@@ -5115,13 +5121,15 @@ class TestWatchFeedAPI(_VisionAPITestCase):
resp = self.client.get(self.feed_url)
items = resp.json()["results"]
self.assertEqual(items[0]["observation"]["session_id"], "old-interesting")
- # The scan found the session notable, so its own sentence reaches the card's reason.
+ # The scan found the session notable, so its own sentence reaches the card's reason, next to
+ # the reason Jev picked from its fixed list.
self.assertEqual(
items[0]["reason"],
{
"kind": "jev_watchable",
"jev_probability": 0.9,
"notability_reason": "The user paid twice for one order.",
+ "watch_reason": "visible_error",
},
)
# The 100 routine rows are filler: they pad the one finding only to the feed's floor.
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 1939249d13d9..8d762262af01 100644
--- a/products/replay_vision/backend/tests/test_jev_watch_feed.py
+++ b/products/replay_vision/backend/tests/test_jev_watch_feed.py
@@ -15,12 +15,14 @@ from posthog.llm.gateway_client import GatewayNotConfiguredError
from posthog.redis import get_client
from products.ml_inference.backend.facade.contracts import (
+ ChoiceAnswer,
DecisionGatewayError,
DecisionRequest,
DecisionResult,
DecisionsDisabledError,
NoulAnswer,
)
+from products.ml_inference.backend.facade.enums import DecisionQuestionType
from products.replay_vision.backend.jev_watch_feed import (
WINDOW_CHUNK_SIZE,
judge_scanner_window,
@@ -46,13 +48,21 @@ _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 _answer_every_question(probability: float, reason: str = "visible_error"):
+ """A decide_when_available side effect that answers each yes/no question with `probability` and
+ each multiple-choice question with `reason`."""
def _decide(request: DecisionRequest, **kwargs: Any) -> DecisionResult:
return DecisionResult(
model="jevk5-fp8-0.2",
- answers={name: NoulAnswer(probability=probability) for name in request.questions},
+ answers={
+ name: (
+ ChoiceAnswer(choice=reason, confidence=0.8, probabilities={reason: 0.8})
+ if question.type == DecisionQuestionType.CHOICE
+ else NoulAnswer(probability=probability)
+ )
+ for name, question in request.questions.items()
+ },
input_tokens=120,
)
@@ -90,12 +100,13 @@ 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)
- assert api.decide_when_available.call_count == 2
+ # 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
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
+ assert judgment.input_tokens == 480
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.
@@ -201,6 +212,43 @@ class TestJudgeScannerWindow(SimpleTestCase):
request = api.decide_when_available.call_args.args[0]
assert len(request.state["observations"]["0"]["summary"]) == 1500
+ @parameterized.expand(
+ [
+ ("picked", "visible_error", None, {"watchable": "visible_error"}),
+ ("no_reason_fits", "nothing_notable", None, {}),
+ ("off_the_list", "made_up", None, {}),
+ ("request_fails", "visible_error", DecisionGatewayError(503, "detail"), {}),
+ ]
+ )
+ def test_only_watchable_rows_get_a_reason_and_a_failed_pick_keeps_the_scores(
+ self, _name: str, choice: str, reason_error: Exception | None, expected: dict[str, str]
+ ) -> None:
+ rows = [_prose_row("watchable", "The user hit an error."), _prose_row("routine", "The user read docs.")]
+ answer_scores = _answer_every_question(0.7, choice)
+
+ def _decide(request: DecisionRequest, **kwargs: Any) -> DecisionResult:
+ if any(question.type == DecisionQuestionType.CHOICE for question in request.questions.values()):
+ if reason_error:
+ raise reason_error
+ return answer_scores(request)
+ return DecisionResult(
+ model="jevk5-fp8-0.2",
+ answers={"watch_0": NoulAnswer(probability=0.7), "watch_1": NoulAnswer(probability=0.1)},
+ input_tokens=120,
+ )
+
+ with patch(_API) as api:
+ api.decide_when_available.side_effect = _decide
+ judgment = judge_scanner_window(1, uuid4(), rows)
+ reason_request = api.decide_when_available.call_args_list[1].args[0]
+ # The feed shows a reason only on watchable rows, so only they are asked.
+ assert list(reason_request.questions) == ["reason_0"]
+ assert judgment.reasons == expected
+ # A reason only labels the row: a failed pick must not cost the chunk its scores.
+ assert judgment.probabilities == {"watchable": 0.7, "routine": 0.1}
+ assert judgment.failed_chunks == 0
+ assert judgment.failed_reason_chunks == (1 if reason_error else 0)
+
def test_an_empty_window_makes_no_request(self) -> None:
with patch(_API) as api:
judgment = judge_scanner_window(1, uuid4(), [])
@@ -243,6 +291,8 @@ class TestRankWatchFeedByJev(SimpleTestCase):
_feed_row("new-unjudged", 10),
],
{"judged-low": 0.2, "high": 0.7, "higher": 0.9},
+ # A cached reason reaches only a watchable row's card.
+ {"higher": "churn_signal", "judged-low": "blocked"},
)
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
@@ -251,6 +301,7 @@ class TestRankWatchFeedByJev(SimpleTestCase):
"kind": "jev_watchable",
"jev_probability": 0.9,
"notability_reason": "The user paid twice for one order.",
+ "watch_reason": "churn_signal",
}
assert ranked[1].reason == {"kind": "jev_watchable", "jev_probability": 0.7}
assert ranked[2].reason == {"kind": "unviewed_recent"}
@@ -314,11 +365,19 @@ class TestWatchRankCache(SimpleTestCase):
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"
+ team_id,
+ scanner_id,
+ {"obs-a", "obs-b", "obs-low"},
+ {"obs-a": 0.9, "obs-b": 7.0},
+ {"obs-f": 2},
+ "jevk5",
+ # A sub-threshold row's reason is never stored, and an off-list value never loads.
+ {"obs-a": "visible_error", "obs-b": "made_up", "obs-low": "blocked"},
)
- store_watch_ranks(team_id, other_scanner_id, {"obs-c"}, {"obs-c": 0.4}, {}, "jevk5")
+ store_watch_ranks(team_id, other_scanner_id, {"obs-c"}, {"obs-c": 0.4}, {}, "jevk5", {"obs-c": "confused"})
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}
+ assert loaded.probabilities == {"obs-a": 0.9, "obs-b": 1.0, "obs-c": 0.4}
+ assert loaded.reasons == {"obs-a": "visible_error", "obs-c": "confused"}
# 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.
@@ -327,7 +386,7 @@ class TestWatchRankCache(SimpleTestCase):
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]) == {}
+ assert load_watch_ranks(team_id + 1, [scanner_id]).probabilities == {}
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
@@ -346,7 +405,7 @@ class TestWatchRankCache(SimpleTestCase):
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_watch_ranks(team_id, [scanner_id]).probabilities == {"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:
@@ -361,7 +420,7 @@ class TestWatchRankCache(SimpleTestCase):
load_judged_state(1, scanner_id)
with self.assertRaises(ConnectionError):
load_scanner_watch_ranks(1, scanner_id)
- assert load_watch_ranks(1, [scanner_id]) == {}
+ assert load_watch_ranks(1, [scanner_id]).probabilities == {}
class TestJevWatchRankSweep(BaseTest):
@@ -401,7 +460,7 @@ class TestJevWatchRankSweep(BaseTest):
# 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]) == {}
+ assert load_watch_ranks(self.team.id, [scanner.id]).probabilities == {}
with (
patch(flag, side_effect=self._flag_arm("jev-shadow")),
@@ -438,7 +497,7 @@ class TestJevWatchRankSweep(BaseTest):
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}
+ assert load_watch_ranks(self.team.id, [scanner.id]).probabilities == {str(first.id): 0.7, str(second.id): 0.7}
# Sub-threshold scores are cached nowhere, so the judged event must carry the score sample
# the threshold is calibrated from.
judged = [
@@ -449,6 +508,7 @@ class TestJevWatchRankSweep(BaseTest):
assert payload["watchability_max"] == 0.7
assert sorted(entry["id"] for entry in payload["top_scored"]) == sorted([str(first.id), str(second.id)])
assert all(entry["p"] == 0.7 for entry in payload["top_scored"])
+ assert payload["watch_reasons"] == {"visible_error": 2}
with (
patch(flag, side_effect=self._flag_arm("jev-shadow")),
@@ -459,7 +519,7 @@ class TestJevWatchRankSweep(BaseTest):
# Every row is judged already, so the second run keeps the cache without a Jev call.
api.decide_when_available.assert_not_called()
assert result.scanners_skipped_unchanged == 1
- assert load_watch_ranks(self.team.id, [scanner.id]) == {str(first.id): 0.7, str(second.id): 0.7}
+ assert load_watch_ranks(self.team.id, [scanner.id]).probabilities == {str(first.id): 0.7, str(second.id): 0.7}
third = self._succeeded_observation(scanner, "s3", "The user deleted the whole workspace.")
with (
@@ -468,7 +528,7 @@ class TestJevWatchRankSweep(BaseTest):
patch(_API) as api,
patch("posthoganalytics.capture"),
):
- api.decide_when_available.side_effect = _answer_every_question(0.9)
+ api.decide_when_available.side_effect = _answer_every_question(0.9, "churn_signal")
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.
@@ -476,10 +536,13 @@ class TestJevWatchRankSweep(BaseTest):
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,
+ ranks = load_watch_ranks(self.team.id, [scanner.id])
+ assert ranks.probabilities == {str(first.id): 0.7, str(second.id): 0.7, str(third.id): 0.9}
+ # The earlier reasons survive the merge too, so the feed keeps saying why.
+ assert ranks.reasons == {
+ str(first.id): "visible_error",
+ str(second.id): "visible_error",
+ str(third.id): "churn_signal",
}
def test_an_unreadable_cache_skips_the_scanner_without_judging_or_writing(self) -> None:
@@ -508,7 +571,7 @@ class TestJevWatchRankSweep(BaseTest):
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}
+ assert load_watch_ranks(self.team.id, [scanner.id]).probabilities == {"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."""
@@ -576,4 +639,4 @@ class TestJevWatchRankSweep(BaseTest):
# 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]) == {}
+ assert load_watch_ranks(self.team.id, [scanner.id]).probabilities == {}
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 459308fa7df6..e8a7b53f67be 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -2672,6 +2672,35 @@ export interface WatchFeedSignalApi {
headline: string
}
+/**
+ * * `visible_error` - Error on screen
+ * * `silent_failure` - Action silently failed
+ * * `unresponsive` - Clicks went nowhere
+ * * `slow_or_stuck` - Slow or stuck
+ * * `blocked` - Blocked
+ * * `cant_find` - Couldn't find it
+ * * `confused` - Confused
+ * * `workaround` - Took a workaround
+ * * `abandoned` - Gave up
+ * * `churn_signal` - Churn signal
+ * * `success` - Worked well
+ */
+export type JevWatchReasonEnumApi = (typeof JevWatchReasonEnumApi)[keyof typeof JevWatchReasonEnumApi]
+
+export const JevWatchReasonEnumApi = {
+ VisibleError: 'visible_error',
+ SilentFailure: 'silent_failure',
+ Unresponsive: 'unresponsive',
+ SlowOrStuck: 'slow_or_stuck',
+ Blocked: 'blocked',
+ CantFind: 'cant_find',
+ Confused: 'confused',
+ Workaround: 'workaround',
+ Abandoned: 'abandoned',
+ ChurnSignal: 'churn_signal',
+ Success: 'success',
+} as const
+
/**
* Machine-readable reason an observation made the feed; the frontend renders the copy.
*/
@@ -2724,6 +2753,20 @@ export interface WatchFeedReasonApi {
* @nullable
*/
notability_reason?: string | null
+ /** Why the decision model rated the session worth watching, picked from a fixed list, for `jev_watchable`. Absent when no reason on the list fits, or on sessions judged before reasons shipped.
+ *
+ * * `visible_error` - Error on screen
+ * * `silent_failure` - Action silently failed
+ * * `unresponsive` - Clicks went nowhere
+ * * `slow_or_stuck` - Slow or stuck
+ * * `blocked` - Blocked
+ * * `cant_find` - Couldn't find it
+ * * `confused` - Confused
+ * * `workaround` - Took a workaround
+ * * `abandoned` - Gave up
+ * * `churn_signal` - Churn signal
+ * * `success` - Worked well */
+ watch_reason?: JevWatchReasonEnumApi
/**
* The observation's score, for `outlier_score`.
* @nullable
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 042ed5ebe8c6..eb6a701458a8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -59011,6 +59011,36 @@ export namespace Schemas {
recipe_snapshot: IterationTrailWithRecipeRecipeSnapshot;
}
+ /**
+ * * `visible_error` - Error on screen
+ * * `silent_failure` - Action silently failed
+ * * `unresponsive` - Clicks went nowhere
+ * * `slow_or_stuck` - Slow or stuck
+ * * `blocked` - Blocked
+ * * `cant_find` - Couldn't find it
+ * * `confused` - Confused
+ * * `workaround` - Took a workaround
+ * * `abandoned` - Gave up
+ * * `churn_signal` - Churn signal
+ * * `success` - Worked well
+ */
+ export type JevWatchReasonEnum = typeof JevWatchReasonEnum[keyof typeof JevWatchReasonEnum];
+
+
+ export const JevWatchReasonEnum = {
+ VisibleError: 'visible_error',
+ SilentFailure: 'silent_failure',
+ Unresponsive: 'unresponsive',
+ SlowOrStuck: 'slow_or_stuck',
+ Blocked: 'blocked',
+ CantFind: 'cant_find',
+ Confused: 'confused',
+ Workaround: 'workaround',
+ Abandoned: 'abandoned',
+ ChurnSignal: 'churn_signal',
+ Success: 'success',
+ } as const;
+
export interface JiraIssueSignalExtra {
key: string;
url: string | null;
@@ -110005,6 +110035,20 @@ export namespace Schemas {
* @nullable
*/
notability_reason?: string | null;
+ /** Why the decision model rated the session worth watching, picked from a fixed list, for `jev_watchable`. Absent when no reason on the list fits, or on sessions judged before reasons shipped.
+ *
+ * * `visible_error` - Error on screen
+ * * `silent_failure` - Action silently failed
+ * * `unresponsive` - Clicks went nowhere
+ * * `slow_or_stuck` - Slow or stuck
+ * * `blocked` - Blocked
+ * * `cant_find` - Couldn't find it
+ * * `confused` - Confused
+ * * `workaround` - Took a workaround
+ * * `abandoned` - Gave up
+ * * `churn_signal` - Churn signal
+ * * `success` - Worked well */
+ watch_reason?: JevWatchReasonEnum;
/**
* The observation's score, for `outlier_score`.
* @nullable