: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): keep goal drafts from truncating, and name the failure (#95277)
Kim Svatos Duganc94c0a02d0ba
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex 229d2c50ba57..ad30b7d4326d 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -59,6 +59,7 @@ const ERROR_FILTER_ALLOW_LIST = ['loadMonitoringSeries', // The managed warehouse Monitoring tab renders its own partial/error state'loadInstrumentationChecklist', // AI observability hides its checklist entirely rather than accusing a project on data it could not read'loadFullEmail', // Its failure listener shows a retry toast and closes the modal+ 'draftScannerFromGoal', // replayScannerLogic's failure listener toasts and routes back to the goal questions]/*diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex d52ead84ecd2..e1db0febbd66 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -2307,12 +2307,19 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viuser_access_control=self.user_access_control,include_business_context=include_business_context,)- except DraftError:+ except DraftError as e:+ # The 503 below is deliberately uniform, so the reason only survives here.+ logger.warning(+ "replay_vision.scanner_draft.failed",+ team_id=self.team_id,+ reason=e.reason,+ goal_flow=goal_flow,+ )# Report failures too, so model errors don't read as user abandonment.report_user_action(cast(User, request.user),"replay_vision_scanner_drafted",- {**draft_properties, "success": False},+ {**draft_properties, "success": False, "failure_reason": e.reason},team=self.team,request=request,)diff --git a/products/replay_vision/backend/scanner_draft.py b/products/replay_vision/backend/scanner_draft.pyindex e5d62f6ee100..e1bf229125da 100644--- a/products/replay_vision/backend/scanner_draft.py+++ b/products/replay_vision/backend/scanner_draft.py@@ -20,7 +20,7 @@ from django.db.models import Qimport structlogimport posthoganalytics-from google.genai.types import GenerateContentConfig, GenerateContentResponse+from google.genai.types import FinishReason, GenerateContentConfig, GenerateContentResponsefrom posthoganalytics.ai.gemini import genaifrom pydantic import BaseModel, Field@@ -73,8 +73,11 @@ _SCALE_MAX_ALLOWED = 100_SCALE_SPAN_ALLOWED = 100# CoreMemory.text is model-capped at 10k chars; cap lower to keep the one-shot draft prompt lean._MAX_BUSINESS_CONTEXT_CHARS = 5_000-# Well above the largest plausible draft (a full config is a few hundred tokens); only caps runaway output.-_MAX_OUTPUT_TOKENS = 4096+# Thinking tokens are drawn from this same budget, and a vague goal makes the model deliberate far+# longer than it writes: at 4096 the JSON was being cut off mid-object after only ~150 tokens of+# answer. Doubling it clears that while staying well inside `_MODEL_CALL_TIMEOUT_MS` — a budget the+# model cannot exhaust before the request times out just trades a quick failure for a slow one.+_MAX_OUTPUT_TOKENS = 8192# Bounds on assembled context so a scanner-heavy team can't blow up the prompt._MAX_EXISTING_SCANNERS = 15_SCANNER_GIST_CHARS = 200@@ -206,7 +209,16 @@ _GOAL_STOPWORDS = frozenset(class DraftError(Exception):- """Raised when the model call fails or returns nothing usable."""+ """Raised when the model call fails or returns nothing usable.++ `reason` is a stable slug carried into telemetry. The user-facing 503 is deliberately generic,+ so it is the only thing that tells a provider outage apart from a draft the model got wrong.+ """++ def __init__(self, reason: str = "unknown", detail: str = "") -> None:+ super().__init__(f"{reason}: {detail}" if detail else reason)+ self.reason = reason+ self.detail = detailclass _LlmDraft(BaseModel):@@ -516,6 +528,14 @@ def draft_scanner_from_goal(return _finalize(parsed, allowed_screens=taxonomy.screens, allowed_events=taxonomy.events, team_id=team.id)+def _hit_output_cap(response: GenerateContentResponse) -> bool:+ """Whether the model stopped because it ran out of output budget, leaving the JSON unfinished."""+ for candidate in response.candidates or []:+ if candidate.finish_reason == FinishReason.MAX_TOKENS:+ return True+ return False++def _generate(*,user_content: str,@@ -536,7 +556,7 @@ def _generate(except Exception as e:# A missing or malformed API key raises at construction. Wrap it so the API returns# the friendly 503 instead of a 500.- raise DraftError("model client unavailable") from e+ raise DraftError("model_client_unavailable") from econfig = GenerateContentConfig(system_instruction=system_prompt,response_mime_type="application/json",@@ -571,14 +591,19 @@ def _generate(response = call_model()except Exception as e:logger.exception("replay_vision.scanner_draft.generate_failed", team_id=team_id)- raise DraftError("model call failed") from e+ raise DraftError("model_call_failed") from e+ if _hit_output_cap(response):+ # Truncated JSON parses as invalid, but the cause is our budget rather than the model+ # writing nonsense — keep the two apart so a recurrence is recognizable.+ logger.warning("replay_vision.scanner_draft.output_truncated", team_id=team_id, feature=feature)+ raise DraftError("output_truncated")if not response.text:- raise DraftError("empty response")+ raise DraftError("empty_response")try:return response_model.model_validate_json(response.text)except Exception as e:- raise DraftError("invalid response") from e+ raise DraftError("invalid_response") from edef _grounded(proposed: list[str], allowed: Sequence[str], cap: int) -> list[str]:@@ -642,7 +667,7 @@ def _normalized_config(parsed: _LlmDraft) -> dict[str, Any]:# (e.g. a classifier whose tags all slugified away).error = scanner_config_error(ScannerType(parsed.scanner_type), scanner_config)if error:- raise DraftError(f"draft config invalid: {error}")+ raise DraftError("config_invalid", str(error))return scanner_config@@ -656,7 +681,7 @@ def _finalize("""Normalize the model output into a draft the wizard form (and later the create endpoint) will accept."""name = parsed.name.strip()[:_MAX_NAME_LENGTH]if not name or not parsed.prompt.strip():- raise DraftError("draft missing name or prompt")+ raise DraftError("missing_name_or_prompt")scanner_config = _normalized_config(parsed)screens = _grounded(@@ -795,6 +820,10 @@ recordings of the user's product and produces one observation per recording. The- summarizer: writes a free-text summary of the session. Best when the goal is broad ("what are usersdoing?", "give me an overview") and doesn't fit one question, dimension, or vocabulary.+A short or vague goal ("test", "help", "what's going on") is not a puzzle to work out. Draft a summarizer over+the whole product with no filters and move on. The user reviews the draft in the wizard and narrows it+there, so a broad draft is the right answer, not a guess at what they meant.+Pick the single type that best fits the goal, then draft the scanner:- name: short and specific, under 8 words.- description: one sentence saying what the scanner looks for.@@ -1344,7 +1373,7 @@ def _finalize_v2("""Normalize the v2 model output; costing is applied by the caller."""name = parsed.name.strip()[:_MAX_NAME_LENGTH]if not name or not parsed.prompt.strip():- raise DraftError("draft missing name or prompt")+ raise DraftError("missing_name_or_prompt")scanner_config = _normalized_config(parsed) # type: ignore[arg-type]# The briefing shows each page as "/billing (10)" for ranking, but the prompt tells the model todiff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.pyindex 67982c96963d..b4687134f845 100644--- a/products/replay_vision/backend/tests/test_api.py+++ b/products/replay_vision/backend/tests/test_api.py@@ -1131,12 +1131,18 @@ class TestScannerLifecycleTelemetry(_VisionAPITestCase):@parameterized.expand([- ("drafted", None, 200, True),- ("model_failed", DraftError(), 503, False),+ ("drafted", None, 200, True, None),+ ("model_failed", DraftError("model_call_failed"), 503, False, "model_call_failed"),+ ("bad_draft", DraftError("config_invalid", "tags are required"), 503, False, "config_invalid"),])def test_draft_reports_outcome(- self, _name: str, error: Exception | None, expected_status: int, expected_success: bool+ self,+ _name: str,+ error: Exception | None,+ expected_status: int,+ expected_success: bool,+ expected_reason: str | None,) -> None:# A draft that reports nothing would read as user abandonment instead of a model failure.self.organization.is_ai_data_processing_approved = True@@ -1166,6 +1172,8 @@ class TestScannerLifecycleTelemetry(_VisionAPITestCase):properties = drafted_events[0].args[2]self.assertEqual(properties["success"], expected_success)self.assertEqual(properties["goal_length"], len(goal))+ # A uniform 503 can't be triaged, so the failure mode has to reach telemetry.+ self.assertEqual(properties.get("failure_reason"), expected_reason)# The goal is customer text; only its length may ride along.self.assertNotIn("goal", properties)diff --git a/products/replay_vision/backend/tests/test_scanner_draft.py b/products/replay_vision/backend/tests/test_scanner_draft.pyindex c0556c998492..f1d97cd26bf5 100644--- a/products/replay_vision/backend/tests/test_scanner_draft.py+++ b/products/replay_vision/backend/tests/test_scanner_draft.py@@ -3,6 +3,7 @@ from unittest.mock import MagicMock, patchfrom django.utils import timezone+from google.genai.types import FinishReasonfrom rest_framework import statusfrom posthog.schema import RecordingsQuery@@ -420,7 +421,22 @@ class TestGenerate:_generate(user_content="goal", team_id=1, distinct_id="u")- assert generate.call_args.kwargs["config"].max_output_tokens == 4096+ assert generate.call_args.kwargs["config"].max_output_tokens == 8192++ @patch("products.replay_vision.backend.scanner_draft.genai.Client")+ def test_output_cut_off_by_the_token_budget_is_its_own_failure(self, mock_client_cls):+ # Thinking shares the output budget, so a truncated draft is our cap's fault, not a bad+ # model response — the two used to be indistinguishable as "invalid_response".+ truncated = MagicMock(+ text='{"scanner_type": "classifier", "name": "Chec',+ candidates=[MagicMock(finish_reason=FinishReason.MAX_TOKENS)],+ )+ self._mock_client(mock_client_cls, [truncated])++ with pytest.raises(DraftError) as caught:+ _generate(user_content="goal", team_id=1, distinct_id="u")++ assert caught.value.reason == "output_truncated"class TestDraftScannerEndpoint(_VisionAPITestCase):