: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): cap each scanner step's output tokens (#102112)
Tue Haulundcc51306940bf
diff --git a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py b/products/replay_vision/backend/temporal/activities/call_scanner_provider.pyindex 475e376bd3d4..05e4f5f103d5 100644--- a/products/replay_vision/backend/temporal/activities/call_scanner_provider.py+++ b/products/replay_vision/backend/temporal/activities/call_scanner_provider.py@@ -893,9 +893,14 @@ async def _run_step(text = (response.text or "").strip()parsed, error = _parse_and_validate(step, text)+ capped = error is not None and _hit_output_cap(response)+ if capped:+ # The cap counts thoughts, so the usual "respond with raw JSON" correction would only re-run the+ # same reasoning into the same wall. Name the cause so the re-prompt asks for less thinking.+ error = "the response ran out of output tokens before the JSON was complete; reason more briefly"record_provider_call(**metric_labels,- outcome="ok" if error is None else "validation_failed",+ outcome="ok" if error is None else "output_cap_hit" if capped else "validation_failed",seconds=time.monotonic() - started,)@@ -915,7 +920,11 @@ async def _run_step(# Keep turn roles alternating on retry: the model's rejected answer is a model turn, then our# correction is the user turn. Without this, a turn that called a tool then returned bad JSON# would leave two consecutive user turns (the tool response and the correction).- convo.append(response.candidates[0].content)+ # Thinking can consume the whole output cap and leave a candidate with no parts, which the API+ # rejects on resend, so only a turn that carries something goes back into the conversation.+ rejected = response.candidates[0].content+ if rejected is not None and rejected.parts:+ convo.append(rejected)convo.append(types.Part(text=(@@ -960,6 +969,11 @@ async def _force_final_answer(*, generate: Any, convo: list[Any], exhausted: Anyreturn await generate(convo)+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_TOKENS++def _step_config(step: MissionStep, cache_name: str | None, *, allow_tools: bool = True, tools: list[types.Tool] | None = None) -> types.GenerateContentConfig:@@ -978,6 +992,7 @@ def _step_config(# Return thought summaries so the model's reasoning is visible in LLM analytics. Answer parsing is# unaffected (`response.text` skips thought parts); models with thinking off just return none."thinking_config": types.ThinkingConfig(include_thoughts=True),+ "max_output_tokens": step.max_output_tokens,}if not allow_tools:return types.GenerateContentConfig(**kwargs) # inline, no tool to call — the model must answer nowdiff --git a/products/replay_vision/backend/temporal/scanners/base.py b/products/replay_vision/backend/temporal/scanners/base.pyindex 34893024b696..02489c0e3223 100644--- a/products/replay_vision/backend/temporal/scanners/base.py+++ b/products/replay_vision/backend/temporal/scanners/base.py@@ -41,6 +41,13 @@ MIN_SIGNAL_CONFIDENCE = 0.4STEP_CORE = "core"STEP_SIGNALS = "signals"+# Ceiling on one step's response, thought tokens included, because Gemini counts thinking against the cap.+# Every response schema is a few hundred tokens of JSON, so this only bounds the tail: a model that thinks+# its way to the provider default (65k) turns a 5-credit observation into a loss. Tight enough to stop that,+# loose enough that dynamic thinking on a long video is not cut off, which would bill the thoughts and force+# a re-prompt that bills them again.+STEP_MAX_OUTPUT_TOKENS = 16_384+class SignalFinding(BaseModel, frozen=True):"""Optional side-mission finding: a bug, crash, or design flaw the recording itself reveals. See the side-mission prompt block."""@@ -119,6 +126,7 @@ class MissionStep:response_model: type[BaseModel]required: bool = Truevalidate: Callable[[BaseModel], str | None] | None = field(default=None)+ max_output_tokens: int = STEP_MAX_OUTPUT_TOKENS_CONFIDENCE_DESCRIPTION = (diff --git a/products/replay_vision/backend/tests/test_call_scanner_provider.py b/products/replay_vision/backend/tests/test_call_scanner_provider.pyindex d8020133251f..b354bbe75b80 100644--- a/products/replay_vision/backend/tests/test_call_scanner_provider.py+++ b/products/replay_vision/backend/tests/test_call_scanner_provider.py@@ -9,6 +9,7 @@ from unittest.mock import AsyncMock, MagicMock, patchfrom django.utils import timezoneimport httpx+from google.genai import typesfrom google.genai.errors import APIErrorfrom pydantic import BaseModelfrom temporalio.testing import ActivityEnvironment@@ -29,7 +30,12 @@ from products.replay_vision.backend.temporal.activities.call_scanner_provider imfrom products.replay_vision.backend.temporal.errors import FailureKind, ScannerFailureErrorfrom products.replay_vision.backend.temporal.events_tool import events_toolfrom products.replay_vision.backend.temporal.metrics import REPLAY_VISION_VERIFICATION_OUTCOMES-from products.replay_vision.backend.temporal.scanners.base import MissionStep, SignalFinding, SignalsResponse+from products.replay_vision.backend.temporal.scanners.base import (+ STEP_MAX_OUTPUT_TOKENS,+ MissionStep,+ SignalFinding,+ SignalsResponse,+)from products.replay_vision.backend.temporal.scanners.monitor import MonitorLlmResponse, MonitorOutput, MonitorScannerfrom products.replay_vision.backend.temporal.types import ScannerSnapshot, VerificationRecordfrom products.replay_vision.backend.temporal.video_clock import VideoClock@@ -55,10 +61,13 @@ class _FakeContent:class _Resp:- """Minimal genai response: `.text` and `.candidates[0].content.parts`."""+ """Minimal genai response: `.text`, `.candidates[0].content.parts`, and an optional finish reason."""- def __init__(self, text: str = "", function_call: Any = None) -> None:- self.candidates = [type("Cand", (), {"content": _FakeContent(function_call)})()]+ def __init__(+ self, text: str = "", function_call: Any = None, finish_reason: Any = None, empty_content: bool = False+ ) -> None:+ content = None if empty_content else _FakeContent(function_call)+ self.candidates = [type("Cand", (), {"content": content, "finish_reason": finish_reason})()]self.text = text@@ -236,6 +245,31 @@ async def test_cached_tool_budget_exhaustion_forces_an_inline_tool_free_answer()assert forced_turn["contents"][1].text == "PRE"[email protected]("empty_content", [False, True])+async def test_output_cap_hit_re_prompts_for_briefer_reasoning(empty_content: bool) -> None:+ # A MAX_TOKENS finish means thinking ate the cap and the JSON never arrived. The generic "raw JSON only"+ # correction would re-run the same reasoning into the same wall, so the re-prompt has to name the cause. When+ # thinking consumed the whole cap the candidate has no content at all; resending that would 400 the retry.+ steps = [MissionStep(name="core", instruction="c", response_model=_Core)]+ responses = [+ _Resp(+ text="" if empty_content else '{"verd',+ finish_reason=types.FinishReason.MAX_TOKENS,+ empty_content=empty_content,+ ),+ _Resp(text='{"verdict":"yes"}'),+ ]+ client = _FakeClient(responses)+ with patch(f"{_MODULE}.record_provider_call") as record:+ out = await _run(client, steps)+ assert out["core"].verdict == "yes"+ retry_contents = client.models.calls[1]["contents"]+ assert "ran out of output tokens" in retry_contents[-1].text+ assert all(item is not None for item in retry_contents)+ assert [call.kwargs["outcome"] for call in record.call_args_list] == ["output_cap_hit", "ok"]++@pytest.mark.asyncioasync def test_step_survives_a_response_with_no_candidates() -> None:# Gemini can return zero candidates (safety filter / content policy); the step must fail cleanly rather than@@ -738,6 +772,7 @@ class TestStepConfig:assert config.cached_content is Noneassert config.response_json_schema is not Noneassert config.thinking_config is not None and config.thinking_config.include_thoughts is True+ assert config.max_output_tokens == STEP_MAX_OUTPUT_TOKENSdef test_cached_path_references_the_cache_and_omits_tools(self) -> None:config = _step_config(@@ -761,6 +796,9 @@ class TestStepConfig:assert config.tool_config is Noneassert config.cached_content is Noneassert config.response_json_schema is not None+ assert (+ config.max_output_tokens == STEP_MAX_OUTPUT_TOKENS+ ) # the one-shot forced answer is the likeliest to overrun@pytest.mark.asyncio