:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(replay-vision): cut retries from runaway numbers and late signal times (#113439)
Tue Haulundbd1ac36f6ad1
diff --git a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py b/products/replay_vision/backend/temporal/activities/call_scanner_provider.pyindex 2dda2a9c0f86..8b215b8d19f0 100644--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py@@ -80,6 +80,7 @@ from products.replay_vision.backend.temporal.scanners.base import (SignalFinding,SignalsResponse,TextSegment,+ render_signals_instruction,)from products.replay_vision.backend.temporal.scanners.classifier import ClassifierScannerfrom products.replay_vision.backend.temporal.scanners.experiment import ExperimentScanner@@ -656,7 +657,9 @@ async def _run_mission()elif step.name == STEP_SIGNALS:step = replace(- step, validate=functools.partial(_validate_signal_timestamps, duration_seconds=signal_duration_s)+ step,+ instruction=render_signals_instruction(_last_video_second(signal_duration_s)),+ validate=functools.partial(_validate_signal_timestamps, duration_seconds=signal_duration_s),)steps.append(step)@@ -688,6 +691,13 @@ async def _run_mission()+def _last_video_second(duration_seconds: float | None) -> int | None:+ """The largest whole second `_validate_signal_timestamps` accepts, or None when it accepts none."""+ if duration_seconds is None or not math.isfinite(duration_seconds) or duration_seconds <= 0:+ return None+ return math.floor(duration_seconds)++def _validate_signal_timestamps(output: BaseModel, *, duration_seconds: float | None) -> str | None:"""`duration_seconds` is the video's length: signals are reported in video time."""if not isinstance(output, SignalsResponse) or not output.signals:@@ -886,6 +896,19 @@ async def _run_step(started = time.monotonic()try:response = await _generate(convo)+ except ValueError as exc:+ if not _is_runaway_number(exc):+ record_provider_call(**metric_labels, outcome="provider_error", seconds=time.monotonic() - started)+ raise+ # The SDK parses the JSON answer inside `generate_content`, so a number the model never stopped writing+ # raises here instead of reaching validation. It is bad output, so re-prompt rather than re-run inline.+ last_error = "a number in the response had thousands of digits"+ last_was_empty = False+ record_provider_call(**metric_labels, outcome="validation_failed", seconds=time.monotonic() - started)+ logger.warning("replay_vision.call_scanner_provider.runaway_number", step=step.name, attempt=attempt + 1)+ if attempt < _MAX_LLM_ATTEMPTS - 1:+ convo.append(types.Part(text=_RUNAWAY_NUMBER_CORRECTION))+ continueexcept Exception:record_provider_call(**metric_labels, outcome="provider_error", seconds=time.monotonic() - started)raise@@ -951,6 +974,16 @@ async def _run_step(return _StepResult(output=None, provider_refused=last_was_empty)+_RUNAWAY_NUMBER_CORRECTION = (+ "\n\nYour previous answer could not be read: a number in it ran on for thousands of digits. Write every "+ "number as a short value, such as whole seconds of video time. Respond with raw JSON only."+)+++def _is_runaway_number(exc: ValueError) -> bool:+ return "integer string conversion" in str(exc)++def _hit_output_cap(response: Any) -> bool:candidates = getattr(response, "candidates", None) or []return bool(candidates) and getattr(candidates[0], "finish_reason", None) == types.FinishReason.MAX_TOKENSdiff --git a/products/replay_vision/backend/temporal/scanners/base.py b/products/replay_vision/backend/temporal/scanners/base.pyindex 4d9b746eeb2b..f53aeb13f21a 100644--- a/products/replay_vision/backend/temporal/scanners/base.py+++ b/products/replay_vision/backend/temporal/scanners/base.py@@ -142,6 +142,13 @@ class SignalsResponse(BaseModel, frozen=True):return self+def render_signals_instruction(last_video_second: int | None = None) -> str:+ """The signals turn's instruction, naming the last citable video second when the scan knows it."""+ return render_prompt(+ "signals_step.jinja", min_signal_confidence=MIN_SIGNAL_CONFIDENCE, last_video_second=last_video_second+ )++@dataclass(frozen=True)class MissionStep:"""One structured turn in a scanner's conversation: an instruction, the schema the model must answer with,@@ -354,9 +361,10 @@ class BaseScanner(BaseModel, frozen=True):return stepsdef _signals_step(self) -> MissionStep:- instruction = render_prompt("signals_step.jinja", min_signal_confidence=MIN_SIGNAL_CONFIDENCE)# Best-effort: a side-mission failure must not sink the whole scan.- return MissionStep(name=STEP_SIGNALS, instruction=instruction, response_model=SignalsResponse, required=False)+ return MissionStep(+ name=STEP_SIGNALS, instruction=render_signals_instruction(), response_model=SignalsResponse, required=False+ )def _validate_core(self, parsed: BaseModel) -> str | None:"""Run the scanner's semantic checks against a finalized version of the core response."""diff --git a/products/replay_vision/backend/temporal/scanners/prompts/signals_step.jinja b/products/replay_vision/backend/temporal/scanners/prompts/signals_step.jinjaindex 556e2b1b3d47..181ba62945d3 100644--- a/products/replay_vision/backend/temporal/scanners/prompts/signals_step.jinja+++ b/products/replay_vision/backend/temporal/scanners/prompts/signals_step.jinja@@ -11,4 +11,6 @@ Write the `headline` as the shortest line that names the defect — 8 words or fWrite the `description` as plain prose with no timestamp references — no `(t …)` markers, no timestamps, no "at N seconds", no event IDs. The timing belongs in `start_time` and `end_time`, not the text.+Give `start_time` and `end_time` in video time, the same scale you cite moments in and your lookups use. Never read them off the footer's `REC_T`, which counts session time and runs ahead of the video wherever an inactive stretch was cut.{% if last_video_second is not none %} The video ends at second {{ last_video_second }}, so neither value can be larger than {{ last_video_second }}.{% endif %}+One recording can surface more than one distinct defect; list each separately. Don't repeat the earlier turns' conclusions. Skip anything below {{ min_signal_confidence }} confidence.diff --git a/products/replay_vision/backend/tests/test_call_scanner_provider.py b/products/replay_vision/backend/tests/test_call_scanner_provider.pyindex dbb3853928ab..a972070c8e0b 100644--- a/products/replay_vision/backend/tests/test_call_scanner_provider.py+++ b/products/replay_vision/backend/tests/test_call_scanner_provider.py@@ -1,4 +1,4 @@-from collections.abc import Callable+from collections.abc import Callable, Sequencefrom typing import Any, castimport pytest@@ -60,7 +60,7 @@ class _Resp:class _FakeModels:- def __init__(self, responses: list[_Resp]) -> None:+ def __init__(self, responses: Sequence[_Resp | Exception]) -> None:self._it = iter(responses)self.calls: list[dict[str, Any]] = []@@ -68,11 +68,14 @@ class _FakeModels:# Snapshot `contents` — the driver mutates the same list across turns, so a live reference would# show every call the final length.self.calls.append({**kwargs, "contents": list(kwargs["contents"])})- return next(self._it)+ response = next(self._it)+ if isinstance(response, Exception):+ raise response+ return responseclass _FakeClient:- def __init__(self, responses: list[_Resp]) -> None:+ def __init__(self, responses: Sequence[_Resp | Exception]) -> None:self.models = _FakeModels(responses)@@ -243,12 +246,28 @@ async def test_step_survives_a_response_with_no_candidates() -> None:@pytest.mark.asyncio-async def test_step_re_prompts_once_on_invalid_json() -> None:+ "first",+ [+ _Resp(text="not json"),+ ValueError("Exceeds the limit (4300 digits) for integer string conversion: value has 16266 digits"),+ ],+)+async def test_step_re_prompts_once_on_invalid_json(first: _Resp | Exception) -> None:steps = [MissionStep(name="core", instruction="c", response_model=_Core)]- client = _FakeClient([_Resp(text="not json"), _Resp(text='{"verdict":"yes"}')])+ client = _FakeClient([first, _Resp(text='{"verdict":"yes"}')])out = await _run(client, steps)assert out["core"].verdict == "yes"assert len(client.models.calls) == 2 # initial + one re-prompt+ assert "Respond with raw JSON only" in client.models.calls[1]["contents"][-1].text+++async def test_an_unrelated_value_error_still_fails_the_step() -> None:+ steps = [MissionStep(name="core", instruction="c", response_model=_Core)]+ client = _FakeClient([ValueError("bad request config")])+ with pytest.raises(ValueError, match="bad request config"):+ await _run(client, steps)@pytest.mark.asyncio@@ -264,25 +283,40 @@ async def test_non_required_step_failure_is_skipped_not_raised() -> None:assert "side" not in out+# The render cut 10s-40s of the session, so video second 15 shows session second 45.+_CUT_CLOCK = VideoClock(+ spans=(+ ActiveSpan(session_from_s=0, session_to_s=10, video_from_s=0, video_to_s=10),+ ActiveSpan(session_from_s=40, session_to_s=60, video_from_s=10, video_to_s=30),+ )+)++@pytest.mark.asyncio@pytest.mark.parametrize(- "duration_seconds,end_times,expected_end",+ "duration_seconds,clock,end_times,expected_end,limit",[- (10.9, [10], 10),- (10.0, [10], 10),- (0.9, [0], 0),- (10.9, [11, 11], None),- (10.9, [11, 10], 10),- (None, [0, 0], None),- (0.0, [0, 0], None),- (-1.0, [0, 0], None),- (float("nan"), [0, 0], None),- (float("inf"), [0, 0], None),- (None, [None], None),+ (10.9, _IDENTITY_CLOCK, [10], 10, 10),+ (10.0, _IDENTITY_CLOCK, [10], 10, 10),+ (0.9, _IDENTITY_CLOCK, [0], 0, 0),+ (10.9, _IDENTITY_CLOCK, [11, 11], None, 10),+ (10.9, _IDENTITY_CLOCK, [11, 10], 10, 10),+ (None, _IDENTITY_CLOCK, [0, 0], None, None),+ (0.0, _IDENTITY_CLOCK, [0, 0], None, None),+ (-1.0, _IDENTITY_CLOCK, [0, 0], None, None),+ (float("nan"), _IDENTITY_CLOCK, [0, 0], None, None),+ (float("inf"), _IDENTITY_CLOCK, [0, 0], None, None),+ (None, _IDENTITY_CLOCK, [None], None, None),+ # A cut render bounds signals by the video's length, not the longer session's.+ (60.0, _CUT_CLOCK, [45, 30], 30, 30),],)async def test_signal_timestamps_use_recording_duration(- duration_seconds: float | None, end_times: list[int | None], expected_end: int | None+ duration_seconds: float | None,+ clock: VideoClock,+ end_times: list[int | None],+ expected_end: int | None,+ limit: int | None,) -> None:scanner = MonitorScanner(prompt="Did the dialog block input?", emits_signals=True)snapshot = ScannerSnapshot(@@ -328,7 +362,7 @@ async def test_signal_timestamps_use_recording_duration(scanner=scanner,snapshot=snapshot,video_part=_VIDEO,- video_clock=_IDENTITY_CLOCK,+ video_clock=clock,preamble_text="PRE",team_id=1,llm_inputs=MagicMock(metadata=MagicMock(duration_seconds=duration_seconds)),@@ -340,15 +374,8 @@ async def test_signal_timestamps_use_recording_duration(assert outcome.thumbnail_video_s == 7assert outcome.key_moment_video_s == 5assert len(client.models.calls) == 2 + len(end_times)---# The render cut 10s-40s of the session, so video second 15 shows session second 45.-_CUT_CLOCK = VideoClock(- spans=(- ActiveSpan(session_from_s=0, session_to_s=10, video_from_s=0, video_to_s=10),- ActiveSpan(session_from_s=40, session_to_s=60, video_from_s=10, video_to_s=30),- )-)+ signals_instruction = client.models.calls[2]["contents"][-1].text+ assert (f"The video ends at second {limit}," in signals_instruction) is (limit is not None)@pytest.mark.parametrize(