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.

fix(replay): surface per-session errors from session-summaries MCP tool (#57728)

Kim Svatos Dugan827c337a1485
diff --git a/ee/api/session_summaries.py b/ee/api/session_summaries.py
index 3ff4f35a13d7..d9bd7e36ef64 100644
--- a/ee/api/session_summaries.py
+++ b/ee/api/session_summaries.py
@@ -37,7 +37,10 @@ from posthog.utils import relative_date_parse
from ee.hogai.session_summaries.session.output_data import SessionSummarySerializer
from ee.hogai.session_summaries.session.summarize_session import ExtraSummaryContext
from ee.hogai.session_summaries.session_group.patterns import EnrichedSessionGroupSummaryPatternsList
-from ee.hogai.session_summaries.session_group.summarize_session_group import find_sessions_timestamps
+from ee.hogai.session_summaries.session_group.summarize_session_group import (
+ find_sessions_timestamps,
+ partition_sessions_by_recording_existence,
+)
from ee.hogai.session_summaries.tracking import (
capture_session_summary_generated,
capture_session_summary_started,
@@ -64,6 +67,12 @@ class SessionSummariesSerializer(serializers.Serializer):
_PRODUCT_CONTEXT_WRAPPER_TAG_RE = re.compile(r"</?\s*product_context\b[^>]*>", re.IGNORECASE)
+# Substring used by ``execute_summarize_session`` (via the Temporal workflow) when the workflow
+# finished successfully but produced no summary row — typically because ``fetch_session_data_activity``
+# returned False (no events / recording too short). Kept here as a module-level constant so the coupling
+# between the workflow's exception text and the API-layer classification is explicit and grep-able.
+_NO_READY_SUMMARY_ERROR_SUBSTRING = "No ready summary found in DB"
+
class SessionSummariesConfigSerializer(serializers.ModelSerializer):
product_context = serializers.CharField(
@@ -105,17 +114,23 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
return user
def _validate_input(self, request: Request) -> tuple[list[str], datetime, datetime, ExtraSummaryContext | None]:
+ """Strict input validation for the group flow — needs all sessions to exist to compute timestamps."""
+ session_ids, extra_summary_context = self._parse_input(request)
+ min_timestamp, max_timestamp = find_sessions_timestamps(session_ids=session_ids, team=self.team)
+ return session_ids, min_timestamp, max_timestamp, extra_summary_context
+
+ def _parse_input(self, request: Request) -> tuple[list[str], ExtraSummaryContext | None]:
+ """Parse and validate request body without checking session existence.
+
+ Used by the individual flow, which surfaces "no recording" as a per-session error rather
+ than failing the whole batch when one ID is bad.
+ """
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
session_ids = serializer.validated_data["session_ids"]
focus_area = serializer.validated_data.get("focus_area")
- # Check that sessions exist and get min/max timestamps for follow-up queries
- min_timestamp, max_timestamp = find_sessions_timestamps(session_ids=session_ids, team=self.team)
- # Prepare extra context, if provided
- extra_summary_context = None
- if focus_area:
- extra_summary_context = ExtraSummaryContext(focus_area=focus_area)
- return session_ids, min_timestamp, max_timestamp, extra_summary_context
+ extra_summary_context = ExtraSummaryContext(focus_area=focus_area) if focus_area else None
+ return session_ids, extra_summary_context
@staticmethod
async def _get_summary_from_progress_stream(
@@ -221,6 +236,24 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
f"Failed to generate session summaries for sessions {logging_session_ids(session_ids)}. Please try again later."
)
+ @staticmethod
+ def _classify_summary_error(err: BaseException) -> tuple[str, str]:
+ """Map an internal exception to a (error_type, error_message) pair returned to the caller.
+
+ We don't surface raw exception strings — they leak internals and aren't actionable. The handful of
+ types below cover the failure modes the API layer can observe today; everything else falls through to
+ a generic ``summary_failed``.
+ """
+ message = str(err)
+ # Raised by execute_summarize_session when the workflow finished but no summary row was written —
+ # in practice that means fetch_session_data_activity returned False (no events / too short).
+ if isinstance(err, ValueError) and _NO_READY_SUMMARY_ERROR_SUBSTRING in message:
+ return (
+ "no_events_or_too_short",
+ "Recording has no usable events to summarize (typically because it is too short).",
+ )
+ return ("summary_failed", "Failed to generate a summary for this session. Please try again later.")
+
@staticmethod
async def _summarize_session(
session_id: str,
@@ -249,6 +282,12 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
team: Team,
extra_summary_context: ExtraSummaryContext | None = None,
) -> dict[str, dict[str, Any]]:
+ """Run per-session summaries concurrently. Returns one entry per requested session.
+
+ Successful entries match the existing summary shape (``segments``, ``key_actions``, etc.). Failed
+ entries return ``{"error": <type>, "error_message": <human-readable>}`` so callers can tell
+ "skipped on purpose" from "tool broke" without re-invoking with singletons.
+ """
tasks = {}
async with asyncio.TaskGroup() as tg:
for session_id in session_ids:
@@ -260,19 +299,21 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
extra_summary_context=extra_summary_context,
)
)
- summaries: dict[str, dict[str, Any]] = {}
+ results: dict[str, dict[str, Any]] = {}
for session_id, task in tasks.items():
res: SessionSummarySerializer | Exception = task.result()
if isinstance(res, Exception):
+ error_type, error_message = self._classify_summary_error(res)
logger.exception(
f"Failed to generate individual session summary for session {session_id} from team {team.pk} by user {user.id}: {res}",
team_id=team.pk,
user_id=user.id,
+ error_type=error_type,
)
+ results[session_id] = {"error": error_type, "error_message": error_message}
else:
- # Return only successful summaries
- summaries[session_id] = res.data
- return summaries
+ results[session_id] = res.data
+ return results
@extend_schema(
operation_id="create_session_summaries_individually",
@@ -283,7 +324,13 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
@action(methods=["POST"], detail=False, required_scopes=["session_recording:read"])
def create_session_summaries_individually(self, request: Request, **kwargs) -> Response:
user = self._validate_user(request)
- session_ids, _, _, extra_summary_context = self._validate_input(request)
+ session_ids, extra_summary_context = self._parse_input(request)
+ # Don't fail the whole batch if some sessions have no recording — partition them out and surface
+ # each missing session as a per-session error in the response (matches the partial-success contract
+ # this endpoint already had for downstream summary failures).
+ found_session_ids, missing_session_ids = partition_sessions_by_recording_existence(
+ session_ids=session_ids, team=self.team
+ )
tracking_id = generate_tracking_id()
capture_session_summary_started(
user=user,
@@ -295,12 +342,24 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
)
# Summarize provided sessions individually
try:
- summaries = async_to_sync(self._get_individual_summaries)(
- session_ids=session_ids,
- user=user,
- team=self.team,
- extra_summary_context=extra_summary_context,
- )
+ summaries: dict[str, dict[str, Any]] = {}
+ if found_session_ids:
+ summaries.update(
+ async_to_sync(self._get_individual_summaries)(
+ session_ids=found_session_ids,
+ user=user,
+ team=self.team,
+ extra_summary_context=extra_summary_context,
+ )
+ )
+ for missing_id in missing_session_ids:
+ summaries[missing_id] = {
+ "error": "recording_not_found",
+ "error_message": (
+ "No recording found for this session ID. The recording may not have been captured, "
+ "may have expired, or may belong to a different team."
+ ),
+ }
capture_session_summary_generated(
user=user,
team=self.team,
diff --git a/ee/api/test/test_session_summaries.py b/ee/api/test/test_session_summaries.py
index a75bd620185e..76c417104dbf 100644
--- a/ee/api/test/test_session_summaries.py
+++ b/ee/api/test/test_session_summaries.py
@@ -8,6 +8,7 @@ from unittest.mock import Mock, patch
from django.http import HttpResponse
+from parameterized import parameterized
from rest_framework import exceptions
from posthog.temporal.session_replay.session_summary_group.types import SessionSummaryStreamUpdate
@@ -211,14 +212,16 @@ class TestSessionSummariesAPI(APIBaseTest):
def test_create_summaries_session_not_found(self, mock_find_sessions: Mock) -> None:
# Mock find_sessions_timestamps to raise validation error for not found sessions
mock_find_sessions.side_effect = exceptions.ValidationError(
- "Sessions not found or do not belong to this team: nonexistent_session"
+ "Session recordings not found for the following IDs (the recording may not have been captured, "
+ "may have expired, or may belong to a different team): nonexistent_session"
)
response = self._make_api_request(session_ids=["nonexistent_session"])
self.assertEqual(response.status_code, 400)
error: dict[str, Any] = response.json() # type: ignore[attr-defined]
- self.assertIn("Sessions not found or do not belong to this team: nonexistent_session", str(error))
+ self.assertIn("Session recordings not found", str(error))
+ self.assertIn("nonexistent_session", str(error))
@patch("ee.api.session_summaries.find_sessions_timestamps")
@patch("ee.api.session_summaries.execute_summarize_session_group")
@@ -256,17 +259,14 @@ class TestSessionSummariesAPI(APIBaseTest):
response = self.client.delete(self.url)
self.assertEqual(response.status_code, 405)
- @patch("ee.api.session_summaries.find_sessions_timestamps")
+ @patch("ee.api.session_summaries.partition_sessions_by_recording_existence")
@patch("ee.api.session_summaries.execute_summarize_session")
def test_create_summaries_individually_success(
self,
mock_execute: Mock,
- mock_find_sessions: Mock,
+ mock_partition: Mock,
) -> None:
- mock_find_sessions.return_value = (
- datetime(2024, 1, 1, 10, 0, 0),
- datetime(2024, 1, 1, 11, 0, 0),
- )
+ mock_partition.return_value = (["session_1", "session_2"], [])
mock_execute.side_effect = lambda session_id, **kwargs: get_mock_enriched_llm_json_response(session_id)
# Make request
url = f"/api/environments/{self.team.id}/session_summaries/create_session_summaries_individually/"
@@ -276,22 +276,20 @@ class TestSessionSummariesAPI(APIBaseTest):
data = response.json()
self.assertEqual(set(data.keys()), {"session_1", "session_2"})
for session_id in ["session_1", "session_2"]:
+ self.assertNotIn("error", data[session_id])
self.assertIn("segments", data[session_id])
self.assertIn("key_actions", data[session_id])
self.assertIn("segment_outcomes", data[session_id])
self.assertIn("session_outcome", data[session_id])
- @patch("ee.api.session_summaries.find_sessions_timestamps")
+ @patch("ee.api.session_summaries.partition_sessions_by_recording_existence")
@patch("ee.api.session_summaries.execute_summarize_session")
def test_create_summaries_individually_partial_failure(
self,
mock_execute: Mock,
- mock_find_sessions: Mock,
+ mock_partition: Mock,
) -> None:
- mock_find_sessions.return_value = (
- datetime(2024, 1, 1, 10, 0, 0),
- datetime(2024, 1, 1, 11, 0, 0),
- )
+ mock_partition.return_value = (["session_1", "session_2"], [])
# Mock execute to succeed for first session, fail for second
def mock_execute_side_effect(session_id: str, **kwargs: Any) -> dict[str, Any]:
@@ -304,11 +302,85 @@ class TestSessionSummariesAPI(APIBaseTest):
# Make request
url = f"/api/environments/{self.team.id}/session_summaries/create_session_summaries_individually/"
response = self.client.post(url, {"session_ids": ["session_1", "session_2"]}, format="json")
- # Check the response - should return one summary
+ # Check the response - should return one summary plus a per-session error for the failure
self.assertEqual(response.status_code, 200)
data = response.json()
- self.assertEqual(set(data.keys()), {"session_1"})
+ self.assertEqual(set(data.keys()), {"session_1", "session_2"})
self.assertIn("segments", data["session_1"])
self.assertIn("key_actions", data["session_1"])
self.assertIn("segment_outcomes", data["session_1"])
self.assertIn("session_outcome", data["session_1"])
+ self.assertEqual(data["session_2"]["error"], "summary_failed")
+ self.assertIn("error_message", data["session_2"])
+
+ @parameterized.expand(
+ [
+ (
+ "no_events_or_too_short_from_value_error",
+ ValueError(
+ "No ready summary found in DB when generating single session summary for session short_session"
+ ),
+ "no_events_or_too_short",
+ "too short",
+ ),
+ (
+ "summary_failed_from_generic_exception",
+ Exception("Failed to summarize session"),
+ "summary_failed",
+ "please try again",
+ ),
+ (
+ "summary_failed_from_unrelated_value_error",
+ ValueError("Some other unrelated failure"),
+ "summary_failed",
+ "please try again",
+ ),
+ ]
+ )
+ @patch("ee.api.session_summaries.partition_sessions_by_recording_existence")
+ @patch("ee.api.session_summaries.execute_summarize_session")
+ def test_create_summaries_individually_classifies_summary_errors(
+ self,
+ _name: str,
+ raised_exception: BaseException,
+ expected_error_type: str,
+ expected_message_substring: str,
+ mock_execute: Mock,
+ mock_partition: Mock,
+ ) -> None:
+ mock_partition.return_value = (["session_x"], [])
+ mock_execute.side_effect = raised_exception
+
+ url = f"/api/environments/{self.team.id}/session_summaries/create_session_summaries_individually/"
+ response = self.client.post(url, {"session_ids": ["session_x"]}, format="json")
+
+ self.assertEqual(response.status_code, 200)
+ data = response.json()
+ self.assertEqual(set(data.keys()), {"session_x"})
+ self.assertEqual(data["session_x"]["error"], expected_error_type)
+ self.assertIn(expected_message_substring, data["session_x"]["error_message"].lower())
+
+ @patch("ee.api.session_summaries.partition_sessions_by_recording_existence")
+ @patch("ee.api.session_summaries.execute_summarize_session")
+ def test_create_summaries_individually_missing_session_does_not_fail_batch(
+ self,
+ mock_execute: Mock,
+ mock_partition: Mock,
+ ) -> None:
+ mock_partition.return_value = (["session_1"], ["missing_session"])
+ mock_execute.side_effect = lambda session_id, **kwargs: get_mock_enriched_llm_json_response(session_id)
+
+ url = f"/api/environments/{self.team.id}/session_summaries/create_session_summaries_individually/"
+ response = self.client.post(url, {"session_ids": ["session_1", "missing_session"]}, format="json")
+
+ self.assertEqual(response.status_code, 200)
+ data = response.json()
+ self.assertEqual(set(data.keys()), {"session_1", "missing_session"})
+ # Successful session retains the existing summary shape
+ self.assertIn("segments", data["session_1"])
+ # Missing session gets a structured error rather than aborting the request
+ self.assertEqual(data["missing_session"]["error"], "recording_not_found")
+ self.assertIn("error_message", data["missing_session"])
+ # And we should not have invoked the workflow for the missing session
+ called_session_ids = {call.kwargs.get("session_id") for call in mock_execute.call_args_list}
+ self.assertEqual(called_session_ids, {"session_1"})
diff --git a/ee/hogai/session_summaries/session_group/summarize_session_group.py b/ee/hogai/session_summaries/session_group/summarize_session_group.py
index 1e9d277dc523..2afaccbd4143 100644
--- a/ee/hogai/session_summaries/session_group/summarize_session_group.py
+++ b/ee/hogai/session_summaries/session_group/summarize_session_group.py
@@ -112,14 +112,32 @@ def generate_session_group_patterns_combination_prompt(
)
+def partition_sessions_by_recording_existence(session_ids: list[str], team: Team) -> tuple[list[str], list[str]]:
+ """Split session_ids into (found, missing) based on whether a replay row exists for the team.
+
+ Used by flows that want to surface per-session "no recording" errors instead of failing the
+ whole batch — see ``find_sessions_timestamps`` for the strict variant used by the group flow.
+ """
+ replay_events = SessionReplayEvents()
+ sessions_found, _, _ = replay_events.sessions_found_with_timestamps(session_ids, team)
+ found = [sid for sid in session_ids if sid in sessions_found]
+ missing = [sid for sid in session_ids if sid not in sessions_found]
+ return found, missing
+
+
def find_sessions_timestamps(session_ids: list[str], team: Team) -> tuple[datetime, datetime]:
"""Validate that all session IDs exist and belong to the team and return min/max timestamps for the entire list of sessions"""
replay_events = SessionReplayEvents()
sessions_found, min_timestamp, max_timestamp = replay_events.sessions_found_with_timestamps(session_ids, team)
- # Check for missing sessions
+ # Check for missing sessions. The replay_events table is the source of truth for "did we capture a recording";
+ # a missing row most commonly means the session never produced a recording or the recording has aged out
+ # of retention, not that the caller is hitting the wrong team.
if len(sessions_found) != len(session_ids):
missing_sessions = set(session_ids) - sessions_found
- msg = f"Sessions not found or do not belong to this team: {', '.join(missing_sessions)}"
+ msg = (
+ "Session recordings not found for the following IDs (the recording may not have been captured, "
+ f"may have expired, or may belong to a different team): {', '.join(missing_sessions)}"
+ )
logger.error(msg, team_id=team.id, signals_type="session-summaries")
raise exceptions.ValidationError(msg)
# Check for missing timestamps
diff --git a/products/replay/mcp/tools.yaml b/products/replay/mcp/tools.yaml
index 32f68fe67225..52d03bd4e603 100644
--- a/products/replay/mcp/tools.yaml
+++ b/products/replay/mcp/tools.yaml
@@ -155,10 +155,13 @@ tools:
journey segments, key actions, segment outcomes, overall session outcome, and sentiment analysis
(frustration score, rage clicks, confusion signals). Use this instead of asking users to watch full
recordings — it provides the key insights in seconds. Accepts up to 300 session IDs and an optional
- focus_area to guide the summary toward a specific aspect (e.g., "checkout flow" or "error handling").
- WARNING: First-time summaries call an AI model and are very slow — expect around 5 minutes on average.
- Previously generated summaries are cached and return instantly. Warn the user about the wait before calling
- this tool.
+ focus_area to guide the summary toward a specific aspect (e.g., "checkout flow" or "error handling"). The
+ response is a dict keyed by session ID. Successful entries contain the summary fields; failed entries
+ contain an `error` (e.g. `recording_not_found`, `no_events_or_too_short`, `summary_failed`) and an
+ `error_message` so callers can distinguish "skipped on purpose" from "tool broke". A bad session ID in the
+ batch is reported as a per-session error and does not fail the whole request. WARNING: First-time summaries
+ call an AI model and are very slow — expect around 5 minutes on average. Previously generated summaries are
+ cached and return instantly. Warn the user about the wait before calling this tool.
DEEP LINKS: Key actions include `session_id` and `milliseconds_since_start`. Build deep links as
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 5caf9520bbed..5f5a0e37b97f 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -3939,7 +3939,7 @@
}
},
"session-recording-summarize": {
- "description": "Generate an AI-powered summary of one or more session recordings. Returns structured analysis including user journey segments, key actions, segment outcomes, overall session outcome, and sentiment analysis (frustration score, rage clicks, confusion signals). Use this instead of asking users to watch full recordings — it provides the key insights in seconds. Accepts up to 300 session IDs and an optional focus_area to guide the summary toward a specific aspect (e.g., \"checkout flow\" or \"error handling\"). WARNING: First-time summaries call an AI model and are very slow — expect around 5 minutes on average. Previously generated summaries are cached and return instantly. Warn the user about the wait before calling this tool.\n\nDEEP LINKS: Key actions include `session_id` and `milliseconds_since_start`. Build deep links as `{posthog_base_url}/replay/{session_id}?t={milliseconds_since_start / 1000}` (the `?t=` parameter is in seconds). Example: 45000ms in session abc123 → `/replay/abc123?t=45`. Always include these links for key actions and frustration signals.",
+ "description": "Generate an AI-powered summary of one or more session recordings. Returns structured analysis including user journey segments, key actions, segment outcomes, overall session outcome, and sentiment analysis (frustration score, rage clicks, confusion signals). Use this instead of asking users to watch full recordings — it provides the key insights in seconds. Accepts up to 300 session IDs and an optional focus_area to guide the summary toward a specific aspect (e.g., \"checkout flow\" or \"error handling\"). The response is a dict keyed by session ID. Successful entries contain the summary fields; failed entries contain an `error` (e.g. `recording_not_found`, `no_events_or_too_short`, `summary_failed`) and an `error_message` so callers can distinguish \"skipped on purpose\" from \"tool broke\". A bad session ID in the batch is reported as a per-session error and does not fail the whole request. WARNING: First-time summaries call an AI model and are very slow — expect around 5 minutes on average. Previously generated summaries are cached and return instantly. Warn the user about the wait before calling this tool.\n\nDEEP LINKS: Key actions include `session_id` and `milliseconds_since_start`. Build deep links as `{posthog_base_url}/replay/{session_id}?t={milliseconds_since_start / 1000}` (the `?t=` parameter is in seconds). Example: 45000ms in session abc123 → `/replay/abc123?t=45`. Always include these links for key actions and frustration signals.",
"category": "Session replays",
"feature": "replay",
"summary": "Summarize session recording",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 347ba4d74e85..fc385895fe1b 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -4373,7 +4373,7 @@
}
},
"session-recording-summarize": {
- "description": "Generate an AI-powered summary of one or more session recordings. Returns structured analysis including user journey segments, key actions, segment outcomes, overall session outcome, and sentiment analysis (frustration score, rage clicks, confusion signals). Use this instead of asking users to watch full recordings — it provides the key insights in seconds. Accepts up to 300 session IDs and an optional focus_area to guide the summary toward a specific aspect (e.g., \"checkout flow\" or \"error handling\"). WARNING: First-time summaries call an AI model and are very slow — expect around 5 minutes on average. Previously generated summaries are cached and return instantly. Warn the user about the wait before calling this tool.\n\nDEEP LINKS: Key actions include `session_id` and `milliseconds_since_start`. Build deep links as `{posthog_base_url}/replay/{session_id}?t={milliseconds_since_start / 1000}` (the `?t=` parameter is in seconds). Example: 45000ms in session abc123 → `/replay/abc123?t=45`. Always include these links for key actions and frustration signals.",
+ "description": "Generate an AI-powered summary of one or more session recordings. Returns structured analysis including user journey segments, key actions, segment outcomes, overall session outcome, and sentiment analysis (frustration score, rage clicks, confusion signals). Use this instead of asking users to watch full recordings — it provides the key insights in seconds. Accepts up to 300 session IDs and an optional focus_area to guide the summary toward a specific aspect (e.g., \"checkout flow\" or \"error handling\"). The response is a dict keyed by session ID. Successful entries contain the summary fields; failed entries contain an `error` (e.g. `recording_not_found`, `no_events_or_too_short`, `summary_failed`) and an `error_message` so callers can distinguish \"skipped on purpose\" from \"tool broke\". A bad session ID in the batch is reported as a per-session error and does not fail the whole request. WARNING: First-time summaries call an AI model and are very slow — expect around 5 minutes on average. Previously generated summaries are cached and return instantly. Warn the user about the wait before calling this tool.\n\nDEEP LINKS: Key actions include `session_id` and `milliseconds_since_start`. Build deep links as `{posthog_base_url}/replay/{session_id}?t={milliseconds_since_start / 1000}` (the `?t=` parameter is in seconds). Example: 45000ms in session abc123 → `/replay/abc123?t=45`. Always include these links for key actions and frustration signals.",
"category": "Session replays",
"feature": "replay",
"summary": "Summarize session recording",