: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): drop the session summary tool from prompt calibration (#79423)
Tue Haulund2bd48276973d
diff --git a/products/replay_vision/backend/prompt_suggestions.py b/products/replay_vision/backend/prompt_suggestions.pyindex 9ea11cc9fdd3..e5156dcabb33 100644--- a/products/replay_vision/backend/prompt_suggestions.py+++ b/products/replay_vision/backend/prompt_suggestions.py@@ -8,7 +8,6 @@ rewrite. Suggestions are persisted so the calibration tab can show the current oimport jsonimport timeimport uuid-import asyncioimport hashlibimport datetime as dtfrom typing import Any@@ -21,7 +20,6 @@ from django.utils import timezoneimport structlogimport posthoganalytics-from asgiref.sync import async_to_syncfrom google.genai import typesfrom google.genai.types import GenerateContentConfigfrom posthoganalytics.ai.gemini import (@@ -29,10 +27,7 @@ from posthoganalytics.ai.gemini import (genai,)-from posthog.models.team import Teamfrom posthog.models.user import User-from posthog.rbac.user_access_control import UserAccessControl-from posthog.session_recordings.models.session_recording import SessionRecordingfrom products.replay_vision.backend.feedback_themes import refresh_feedback_themes_if_stale, theme_linesfrom products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation@@ -59,23 +54,19 @@ _MAX_DISMISSED_PROMPT_CHARS = 600_MAX_BRIEFING_FEEDBACK_CHARS = 600_MAX_TOOL_FEEDBACK_CHARS = 2000_MAX_TOOL_ROUNDS = 6-_MAX_SUMMARIES_PER_RUN = 2_MAX_TOOL_REASONING_CHARS = 4000-# Wall-clock budgets for the agentic loop: once spent, no new tool rounds start (the final structured-# turn still runs). The inline API path stays close to the old single-call bound; the background-# refresh gets room for cold summaries while finishing well inside its Temporal activity timeout.+# Wall-clock budgets for the agentic loop: once spent, no new tool rounds start, though the in-flight+# round and the final structured turn each still run under _MODEL_CALL_TIMEOUT_MS. The inline path is+# sized against a user waiting on an HTTP request; the background refresh trades that for more rounds,+# since nobody is waiting. See REFRESH_PROMPT_SUGGESTION_TIMEOUT (temporal/constants.py) for the cap it+# has to sit under._AGENT_BUDGET_INLINE_S = 60.0_AGENT_BUDGET_BACKGROUND_S = 180.0-# Never start a cold summary with less than this much budget left; the wait is bounded by the remainder.-_COLD_SUMMARY_MIN_BUDGET_S = 60.0_AGENT_SYSTEM_ADDENDUM = """Before answering you may call tools to gather context: pull a rated session's full output, reasoning-and feedback; list rated sessions beyond the sample; or fetch a session's summary (what actually-happened in the recording). Prioritize investigating thumbs-down sessions and any session where the-feedback and the scanner output seem to disagree — the summary tells you what really happened.--Summaries are expensive: request them only where they change your rewrite. When you have enough+and feedback, or list rated sessions beyond the sample. Prioritize investigating thumbs-down sessions+and any session where the feedback and the scanner output seem to disagree. When you have enoughcontext, answer."""@@ -324,41 +315,15 @@ def _agent_tools() -> types.Tool:},),),- types.FunctionDeclaration(- name="get_session_summary",- description=(- "A narrative summary of what actually happened in the session recording — ground truth to "- "check a rating or feedback against. Expensive; budgeted per run."- ),- parameters=types.Schema(- type=types.Type.OBJECT,- properties={- "session_id": types.Schema(type=types.Type.STRING, description="The session id."),- },- required=["session_id"],- ),- ),])-class _AgentToolState:- def __init__(- self, scanner: ReplayScanner, summary_user: User | None, allow_cold_summaries: bool, deadline: float- ) -> None:- self.scanner = scanner- self.summary_user = summary_user- self.allow_cold_summaries = allow_cold_summaries- self.deadline = deadline- self.cold_summaries_used = 0- self.summary_cache: dict[str, str] = {}---def _rated_observation_for_session(state: _AgentToolState, session_id: str) -> ReplayObservation | None:+def _rated_observation_for_session(scanner: ReplayScanner, session_id: str) -> ReplayObservation | None:return (ReplayObservation.objects.filter(- team_id=state.scanner.team_id,- scanner_id=state.scanner.id,+ team_id=scanner.team_id,+ scanner_id=scanner.id,session_id=session_id,status=ObservationStatus.SUCCEEDED,label__isnull=False,@@ -368,8 +333,8 @@ def _rated_observation_for_session(state: _AgentToolState, session_id: str) -> R)-def _tool_get_rated_observation(state: _AgentToolState, session_id: str) -> dict[str, Any]:- observation = _rated_observation_for_session(state, session_id)+def _tool_get_rated_observation(scanner: ReplayScanner, session_id: str) -> dict[str, Any]:+ observation = _rated_observation_for_session(scanner, session_id)if observation is None:return {"error": "no rated observation for that session id on this scanner"}label = _label(observation)@@ -387,10 +352,10 @@ def _tool_get_rated_observation(state: _AgentToolState, session_id: str) -> dict}-def _tool_list_rated_sessions(state: _AgentToolState, offset: int) -> dict[str, Any]:+def _tool_list_rated_sessions(scanner: ReplayScanner, offset: int) -> dict[str, Any]:base = ReplayObservation.objects.filter(- team_id=state.scanner.team_id,- scanner_id=state.scanner.id,+ team_id=scanner.team_id,+ scanner_id=scanner.id,status=ObservationStatus.SUCCEEDED,label__isnull=False,)@@ -411,93 +376,16 @@ def _tool_list_rated_sessions(state: _AgentToolState, offset: int) -> dict[str,}-def _run_cold_summary(state: _AgentToolState, session_id: str, user: User, *, timeout_s: float) -> dict[str, Any]:- """Run the summarization workflow for an unsummarized session, waiting at most the remaining run budget."""- from posthog.temporal.session_replay.session_summary.workflow import ( # noqa: PLC0415 (heavy temporal dep, only loaded on the cold path)- execute_summarize_session,- )-- # Count before executing so a failing cold run still spends budget.- state.cold_summaries_used += 1- team = Team.objects.get(pk=state.scanner.team_id)-- async def _bounded() -> dict[str, Any]:- return await asyncio.wait_for(- execute_summarize_session(- session_id=session_id,- user=user,- team=team,- custom_tags={"ai_product": "replay_vision", "feature": "suggest_scanner_prompt"},- ),- timeout=timeout_s,- )-- return async_to_sync(_bounded)()---def _summary_access_error(state: _AgentToolState, session_id: str) -> dict[str, Any] | None:- """Mirror the session-summary API's recording gate: no summaries for deleted recordings, and reads- require viewer access on the recording as `summary_user` (the requester inline, the scanner's- creator in the background refresh)."""- team = Team.objects.get(pk=state.scanner.team_id)- recording = SessionRecording.get_or_build(session_id=session_id, team=team)- if recording.deleted:- return {"error": "the recording for this session was deleted; decide with the context you have"}- if state.summary_user is None or not UserAccessControl(state.summary_user, team).check_access_level_for_object(- recording, required_level="viewer"- ):- return {"error": "this session's recording is not accessible; decide with the context you have"}- return None---def _tool_get_session_summary(state: _AgentToolState, session_id: str) -> dict[str, Any]:- if session_id in state.summary_cache:- return {"session_id": session_id, "summary": state.summary_cache[session_id]}- if _rated_observation_for_session(state, session_id) is None:- return {"error": "no rated observation for that session id on this scanner"}- denied = _summary_access_error(state, session_id)- if denied is not None:- return denied- # Deferred: heavy modules stay off the API import path. Summaries go through core helpers,- # since replay_vision must not import products.replay internals.- from posthog.temporal.session_replay.session_summary.state import (- get_ready_summaries_from_db, # noqa: PLC0415 (heavy temporal dep, see above)- )-- from ee.hogai.session_summaries.session.stringify import (- SingleSessionSummaryStringifier, # noqa: PLC0415 (heavy ee dep, see above)- )-- cached = get_ready_summaries_from_db([session_id], team_id=state.scanner.team_id, extra_summary_context=None)- summary_json = cached[0].summary if cached else None- if summary_json is None:- # Only cold generation is budgeted; cached summaries above are cheap reads.- summary_user = state.summary_user if state.allow_cold_summaries else None- if summary_user is None:- return {"error": "no summary exists for this session yet and generating one is unavailable here"}- if state.cold_summaries_used >= _MAX_SUMMARIES_PER_RUN:- return {"error": "summary budget for this run is exhausted; decide with the context you have"}- remaining = state.deadline - time.monotonic()- if remaining < _COLD_SUMMARY_MIN_BUDGET_S:- return {"error": "not enough time left in this run to generate a summary; decide with the context you have"}- summary_json = _run_cold_summary(state, session_id, summary_user, timeout_s=remaining)- text = SingleSessionSummaryStringifier(summary_json).stringify_session()- state.summary_cache[session_id] = text- return {"session_id": session_id, "summary": text}---def _dispatch_agent_tool(state: _AgentToolState, call: types.FunctionCall) -> dict[str, Any]:+def _dispatch_agent_tool(scanner: ReplayScanner, call: types.FunctionCall) -> dict[str, Any]:name = call.nameargs = dict(call.args or {})try:if name == "get_rated_observation":- return _tool_get_rated_observation(state, str(args.get("session_id", "")))+ return _tool_get_rated_observation(scanner, str(args.get("session_id", "")))if name == "list_rated_sessions":- return _tool_list_rated_sessions(state, int(args.get("offset", 0) or 0))- if name == "get_session_summary":- return _tool_get_session_summary(state, str(args.get("session_id", "")))+ return _tool_list_rated_sessions(scanner, int(args.get("offset", 0) or 0))except Exception:- logger.exception("replay_vision.prompt_agent.tool_failed", tool=name, scanner_id=str(state.scanner.id))+ logger.exception("replay_vision.prompt_agent.tool_failed", tool=name, scanner_id=str(scanner.id))return {"error": "tool failed; decide with the context you have"}return {"error": f"unknown tool: {name}"}@@ -525,19 +413,15 @@ def _generate_agentic(*,scanner: ReplayScanner,user_content: str,- user: User | None,- allow_cold_summaries: bool,+ budget_s: float,distinct_id: str,system_prompt: str,output_schema: dict[str, Any],) -> dict[str, Any]:- """Tool-loop generation: the model may inspect rated sessions (and their summaries) before rewriting,- then a final tool-free turn forces the structured answer, mirroring the scanner's own tool loop."""+ """Tool-loop generation: the model may inspect rated sessions before rewriting, then a final tool-free+ turn forces the structured answer, mirroring the scanner's own tool loop."""client = _gemini_client()- budget_s = _AGENT_BUDGET_BACKGROUND_S if allow_cold_summaries else _AGENT_BUDGET_INLINE_Sdeadline = time.monotonic() + budget_s- # Summary tools act as the requester (the scanner's creator on the automatic path); attribution stays `user`.- state = _AgentToolState(scanner, user or scanner.created_by, allow_cold_summaries, deadline)agent_system_prompt = system_prompt + _AGENT_SYSTEM_ADDENDUMtool_config = GenerateContentConfig(system_instruction=agent_system_prompt,@@ -554,7 +438,9 @@ def _generate_agentic(for call in response.function_calls:convo.append(types.Part(- function_response=types.FunctionResponse(name=call.name, response=_dispatch_agent_tool(state, call))+ function_response=types.FunctionResponse(+ name=call.name, response=_dispatch_agent_tool(scanner, call)+ )))response = _model_call(client, convo, tool_config, team_id=scanner.team_id, distinct_id=distinct_id)@@ -567,7 +453,7 @@ def _generate_agentic(convo.append(last_content)final_parts.extend(types.Part(- function_response=types.FunctionResponse(name=call.name, response=_dispatch_agent_tool(state, call))+ function_response=types.FunctionResponse(name=call.name, response=_dispatch_agent_tool(scanner, call)))for call in response.function_calls or [])@@ -589,14 +475,16 @@ def _generate_agentic(def generate_prompt_suggestion(- scanner: ReplayScanner, user: User | None = None, *, allow_cold_summaries: bool = False+ scanner: ReplayScanner, user: User | None = None, *, background: bool = False) -> ReplayScannerPromptSuggestion:"""Generate and persist a fresh suggestion; earlier pending ones become history.- `user` is set for explicit (re)generate requests and null for the automatic daily refresh.- The agentic path lets the model inspect rated sessions (and, budget permitting, their summaries)- before rewriting; on any agent failure we fall back to the single-shot generation so a suggestion- still lands. A rewrite matching the current prompt lands as `no_change`: the scanner looks good.+ `user` is set for explicit (re)generate requests and null for the automatic daily refresh, which+ passes `background` to buy the agent a longer wall-clock budget: nobody is waiting on a response, so+ it can afford more tool rounds than a request a person is holding open.+ The agentic path lets the model inspect rated sessions before rewriting; on any agent failure we+ fall back to the single-shot generation so a suggestion still lands. A rewrite matching the current+ prompt lands as `no_change`: the scanner looks good."""observations = _labeled_observations(scanner)if not observations:@@ -614,8 +502,7 @@ def generate_prompt_suggestion(llm_output = _generate_agentic(scanner=scanner,user_content=user_content,- user=user,- allow_cold_summaries=allow_cold_summaries,+ budget_s=_AGENT_BUDGET_BACKGROUND_S if background else _AGENT_BUDGET_INLINE_S,distinct_id=distinct_id,system_prompt=proposer.system_prompt(),output_schema=proposer.output_schema(),@@ -688,8 +575,8 @@ def refresh_prompt_suggestion_if_stale(scanner: ReplayScanner) -> str:if timezone.now() - latest.created_at < PROMPT_SUGGESTION_MIN_AGE:return "refreshed_recently"try:- # user=None keeps automatic suggestions unattributed; cold summaries run as the scanner's creator.- generate_prompt_suggestion(scanner, allow_cold_summaries=True)+ # user=None keeps automatic suggestions unattributed.+ generate_prompt_suggestion(scanner, background=True)except PromptSuggestionError as e:if str(e) == "no rated observations":return "no_ratings"diff --git a/products/replay_vision/backend/temporal/constants.py b/products/replay_vision/backend/temporal/constants.pyindex a4f69462ca18..da286073b544 100644--- a/products/replay_vision/backend/temporal/constants.py+++ b/products/replay_vision/backend/temporal/constants.py@@ -52,9 +52,10 @@ SCANNER_SCHEDULE_INTERVAL = dt.timedelta(minutes=5)# Overlap SKIP means a slow run absorbs later ticks instead of stacking.SWEEP_WORKFLOW_EXECUTION_TIMEOUT = dt.timedelta(minutes=15)-# The agentic refresh may run several tool rounds and up to two cold summaries. Its in-process budget-# (_AGENT_BUDGET_BACKGROUND_S) keeps typical runs well under this, so the activity finishes cleanly and-# a suggestion lands; this cap is the backstop for a hung provider.+# The agentic refresh may run several tool rounds. _AGENT_BUDGET_BACKGROUND_S stops new rounds from+# starting, but the in-flight round and the final structured turn can each add up to _MODEL_CALL_TIMEOUT_MS+# on top, so a pathological run can still reach this cap. That costs one skipped daily refresh (single+# attempt, swallowed by the sweep) rather than a retry, and the next tick picks it up.REFRESH_PROMPT_SUGGESTION_TIMEOUT = dt.timedelta(minutes=5)SCANNER_SCHEDULE_ID_PREFIX = "replay-vision-scanner"diff --git a/products/replay_vision/backend/tests/test_prompt_agent.py b/products/replay_vision/backend/tests/test_prompt_agent.pyindex a711102d9f19..475fd86a99d2 100644--- a/products/replay_vision/backend/tests/test_prompt_agent.py+++ b/products/replay_vision/backend/tests/test_prompt_agent.py@@ -1,5 +1,4 @@import json-import timefrom typing import Anyfrom unittest.mock import patch@@ -9,28 +8,16 @@ from django.utils import timezonefrom google.genai import typesfrom parameterized import parameterized-from posthog.constants import AvailableFeature-from posthog.models import OrganizationMembership, User-from posthog.session_recordings.models.session_recording import SessionRecording-from products.replay_vision.backend.models.replay_observation import (ObservationStatus,ObservationTrigger,ReplayObservation,)from products.replay_vision.backend.models.replay_observation_label import ReplayObservationLabel-from products.replay_vision.backend.prompt_suggestions import (- _MAX_SUMMARIES_PER_RUN,- _MAX_TOOL_ROUNDS,- _AgentToolState,- _dispatch_agent_tool,- _generate_agentic,-)+from products.replay_vision.backend.prompt_suggestions import _MAX_TOOL_ROUNDS, _dispatch_agent_tool, _generate_agenticfrom products.replay_vision.backend.proposers import get_proposerfrom products.replay_vision.backend.tests.test_api import _VisionAPITestCase-from ee.models.rbac.access_control import AccessControl-def _call(name: str, args: dict[str, Any]) -> types.FunctionCall:return types.FunctionCall(name=name, args=args)@@ -74,9 +61,6 @@ class TestPromptAgent(_VisionAPITestCase):# The scanner defaults to monitor; its proposer supplies the system prompt and schema the agent needs.self.proposer = get_proposer("monitor")- def _state(self, *, allow_cold_summaries: bool = False, budget_s: float = 60.0) -> _AgentToolState:- return _AgentToolState(self.scanner, self.user, allow_cold_summaries, time.monotonic() + budget_s)-def test_tool_rounds_run_then_final_structured_answer_parses(self) -> None:answer = json.dumps({"suggested_prompt": "better prompt", "rationale": "grounded in sess-1"})responses = iter(@@ -96,8 +80,7 @@ class TestPromptAgent(_VisionAPITestCase):parsed = _generate_agentic(scanner=self.scanner,user_content="briefing",- user=self.user,- allow_cold_summaries=False,+ budget_s=60.0,distinct_id="test",system_prompt=self.proposer.system_prompt(),output_schema=self.proposer.output_schema(),@@ -123,15 +106,13 @@ class TestPromptAgent(_VisionAPITestCase):return _Response(calls=[_call("get_rated_observation", {"session_id": "sess-1"})])with (- patch("products.replay_vision.backend.prompt_suggestions._AGENT_BUDGET_INLINE_S", budget_s),patch("products.replay_vision.backend.prompt_suggestions.genai"),patch("products.replay_vision.backend.prompt_suggestions._model_call", side_effect=fake_model_call),):parsed = _generate_agentic(scanner=self.scanner,user_content="briefing",- user=self.user,- allow_cold_summaries=False,+ budget_s=budget_s,distinct_id="test",system_prompt=self.proposer.system_prompt(),output_schema=self.proposer.output_schema(),@@ -146,60 +127,39 @@ class TestPromptAgent(_VisionAPITestCase):)self.assertEqual(final_turn.parts[-1].text, "Respond now with the JSON answer.")- def test_observation_tool_returns_full_detail_and_summary_tool_budgets_cold_runs(self) -> None:- state = self._state()+ def test_observation_tools_return_full_detail_and_the_rated_session_listing(self) -> None:- detail = _dispatch_agent_tool(state, _call("get_rated_observation", {"session_id": "sess-1"}))+ detail = _dispatch_agent_tool(self.scanner, _call("get_rated_observation", {"session_id": "sess-1"}))self.assertEqual(detail["rating"], "thumbs_down")self.assertEqual(detail["feedback"], "should be yes")self.assertEqual(detail["reasoning"], "the user closed the tab at payment")- listing = _dispatch_agent_tool(state, _call("list_rated_sessions", {}))+ listing = _dispatch_agent_tool(self.scanner, _call("list_rated_sessions", {}))self.assertEqual(listing["total"], 1)self.assertEqual(listing["sessions"][0]["session_id"], "sess-1")- summary = _dispatch_agent_tool(state, _call("get_session_summary", {"session_id": "sess-1"}))- self.assertIn("error", summary) # no cached summary, cold generation disallowed here-- cold_state = self._state(allow_cold_summaries=True, budget_s=600.0)- cold_state.cold_summaries_used = _MAX_SUMMARIES_PER_RUN- capped = _dispatch_agent_tool(cold_state, _call("get_session_summary", {"session_id": "sess-1"}))- self.assertIn("budget", capped["error"])-- drained = self._state(allow_cold_summaries=True, budget_s=0.0)- timed_out = _dispatch_agent_tool(drained, _call("get_session_summary", {"session_id": "sess-1"}))- self.assertIn("time", timed_out["error"])-- def test_summary_tool_refuses_deleted_and_inaccessible_recordings(self) -> None:- recording = SessionRecording.objects.create(team=self.team, session_id="sess-1", deleted=True)- deleted = _dispatch_agent_tool(self._state(), _call("get_session_summary", {"session_id": "sess-1"}))- self.assertIn("deleted", deleted["error"])-- recording.deleted = False- recording.save()- self.organization.available_product_features = [- {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}- ]- self.organization.save()- denied_user = User.objects.create_and_join(self.organization, "[email protected]", "testtest")- membership = OrganizationMembership.objects.get(user=denied_user, organization=self.organization)- AccessControl.objects.create(+ def test_tools_only_see_the_ratings_of_the_scanner_under_review(self) -> None:+ # The scanner_id filter is the only thing keeping one scanner's rated sessions out of another's+ # calibration briefing, and the rated set is what the rewrite is derived from.+ other_scanner = self._create_scanner(name="other-scanner")+ other = ReplayObservation.objects.create(+ scanner=other_scanner,team=self.team,- resource="session_recording",- resource_id=None,- access_level="none",- organization_member=membership,+ session_id="sess-1",+ status=ObservationStatus.SUCCEEDED,+ completed_at=timezone.now(),+ triggered_by=ObservationTrigger.ON_DEMAND,+ scanner_snapshot={"scanner_version": 1},+ scanner_result={"model_output": {"verdict": "yes", "scanner_type": "monitor"}, "signals_count": 0},)- denied_state = _AgentToolState(self.scanner, denied_user, False, time.monotonic() + 60.0)- denied = _dispatch_agent_tool(denied_state, _call("get_session_summary", {"session_id": "sess-1"}))- self.assertIn("not accessible", denied["error"])+ ReplayObservationLabel.objects.create(observation=other, is_correct=True, feedback="looks right")- # Background refresh with no scanner creator: fail closed rather than serve cached summaries.- userless_state = _AgentToolState(self.scanner, None, True, time.monotonic() + 600.0)- userless = _dispatch_agent_tool(userless_state, _call("get_session_summary", {"session_id": "sess-1"}))- self.assertIn("not accessible", userless["error"])+ self.assertEqual(_dispatch_agent_tool(self.scanner, _call("list_rated_sessions", {}))["total"], 1)+ detail = _dispatch_agent_tool(self.scanner, _call("get_rated_observation", {"session_id": "sess-1"}))+ self.assertEqual(detail["rating"], "thumbs_down") # this scanner's rating, not the other's thumbs updef test_unknown_session_and_unknown_tool_return_errors(self) -> None:- state = self._state()- self.assertIn("error", _dispatch_agent_tool(state, _call("get_rated_observation", {"session_id": "nope"})))- self.assertIn("error", _dispatch_agent_tool(state, _call("hack_the_planet", {})))+ self.assertIn(+ "error", _dispatch_agent_tool(self.scanner, _call("get_rated_observation", {"session_id": "nope"}))+ )+ self.assertIn("error", _dispatch_agent_tool(self.scanner, _call("hack_the_planet", {})))