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): keep partially enriched session group summaries (#75076)

Arno Hillend58675c4fbf5
diff --git a/ee/hogai/session_summaries/session_group/patterns.py b/ee/hogai/session_summaries/session_group/patterns.py
index 6109be69c4e1..ba8d6b501553 100644
--- a/ee/hogai/session_summaries/session_group/patterns.py
+++ b/ee/hogai/session_summaries/session_group/patterns.py
@@ -502,6 +502,7 @@ def combine_patterns_with_events_context(
f"Input: {len(patterns.patterns)}"
)
logger.exception(exception_message, user_id=user_id, signals_type="session-summaries")
+ # Retryable: the assignment step regenerates a fresh LLM response each attempt, so a bad one can recover
raise ApplicationError(exception_message)
if failed_patterns_count:
logger.warning(
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 0db16d7e29f0..2d477cd344a4 100644
--- a/ee/hogai/session_summaries/session_group/summarize_session_group.py
+++ b/ee/hogai/session_summaries/session_group/summarize_session_group.py
@@ -123,7 +123,8 @@ def partition_sessions_by_recording_existence(session_ids: list[str], team: Team
"""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.
+ whole batch. See ``find_sessions_timestamps`` for the strict variant (group API flow) and
+ ``find_sessions_timestamps_dropping_missing`` for the lenient one with timestamps (chat group flow).
"""
replay_events = SessionReplayEvents()
sessions_found = replay_events.sessions_found_with_timestamps(session_ids, team).session_ids
@@ -138,6 +139,53 @@ class SessionsTimestampRange:
max_timestamp: datetime
+@dataclass(frozen=True, kw_only=True, slots=True)
+class FoundSessionsWithTimestamps:
+ """Result of the lenient session lookup: the recordings we kept, the ones we dropped, and the batch timestamps."""
+
+ found_session_ids: list[str]
+ missing_session_ids: list[str]
+ min_timestamp: datetime
+ max_timestamp: datetime
+
+
+def find_sessions_timestamps_dropping_missing(session_ids: list[str], team: Team) -> FoundSessionsWithTimestamps:
+ """Lenient variant of ``find_sessions_timestamps``: drops session IDs without a replay row instead of
+ failing the whole batch. Raises ValidationError only when no session in the batch has a recording."""
+ replay_events = SessionReplayEvents()
+ result = replay_events.sessions_found_with_timestamps(session_ids, team)
+ # Dedupe while preserving order: duplicate IDs would otherwise spawn duplicate summarization tasks
+ found = list(dict.fromkeys(sid for sid in session_ids if sid in result.session_ids))
+ missing = list(dict.fromkeys(sid for sid in session_ids if sid not in result.session_ids))
+ if not found:
+ 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)}"
+ )
+ logger.error(msg, team_id=team.id, signals_type="session-summaries")
+ raise exceptions.ValidationError(msg)
+ if result.min_timestamp is None or result.max_timestamp is None:
+ msg = (
+ f"Failed to get min ({result.min_timestamp}) or max ({result.max_timestamp}) "
+ f"timestamps for sessions: {', '.join(found)}"
+ )
+ logger.error(msg, team_id=team.id, signals_type="session-summaries")
+ raise exceptions.ValidationError(msg)
+ if missing:
+ logger.warning(
+ f"Dropping {len(missing)} of {len(session_ids)} sessions without a replay row "
+ f"from group summarization: {', '.join(missing)}",
+ team_id=team.id,
+ signals_type="session-summaries",
+ )
+ return FoundSessionsWithTimestamps(
+ found_session_ids=found,
+ missing_session_ids=missing,
+ min_timestamp=result.min_timestamp,
+ max_timestamp=result.max_timestamp,
+ )
+
+
def find_sessions_timestamps(session_ids: list[str], team: Team) -> SessionsTimestampRange:
"""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()
diff --git a/ee/hogai/session_summaries/tests/test_summarize_session_group.py b/ee/hogai/session_summaries/tests/test_summarize_session_group.py
new file mode 100644
index 000000000000..9649cb938520
--- /dev/null
+++ b/ee/hogai/session_summaries/tests/test_summarize_session_group.py
@@ -0,0 +1,60 @@
+from datetime import UTC, datetime
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from rest_framework import exceptions
+
+from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents, SessionsWithTimestamps
+
+from ee.hogai.session_summaries.session_group.summarize_session_group import find_sessions_timestamps_dropping_missing
+
+MIN_TS = datetime(2026, 7, 29, 8, 0, 0, tzinfo=UTC)
+MAX_TS = datetime(2026, 7, 29, 9, 0, 0, tzinfo=UTC)
+
+
+ "requested,found_in_db,expected_found,expected_missing",
+ [
+ # One recording dropped out between validation reads: keep the rest instead of failing the batch
+ (["s-1", "s-2", "s-3"], {"s-1", "s-3"}, ["s-1", "s-3"], ["s-2"]),
+ (["s-1", "s-2"], {"s-1", "s-2"}, ["s-1", "s-2"], []),
+ # Duplicate requested IDs must not spawn duplicate summarization tasks: dedupe found and missing in order
+ (["s-1", "s-1", "s-2", "s-2", "s-3"], {"s-1"}, ["s-1"], ["s-2", "s-3"]),
+ ],
+)
+def test_find_sessions_timestamps_dropping_missing(
+ requested: list[str],
+ found_in_db: set[str],
+ expected_found: list[str],
+ expected_missing: list[str],
+) -> None:
+ query_result = SessionsWithTimestamps(session_ids=found_in_db, min_timestamp=MIN_TS, max_timestamp=MAX_TS)
+ with patch.object(SessionReplayEvents, "sessions_found_with_timestamps", return_value=query_result):
+ sessions = find_sessions_timestamps_dropping_missing(session_ids=requested, team=MagicMock(id=1))
+ assert sessions.found_session_ids == expected_found
+ assert sessions.missing_session_ids == expected_missing
+ assert sessions.min_timestamp == MIN_TS
+ assert sessions.max_timestamp == MAX_TS
+
+
+ "found_in_db,min_timestamp,max_timestamp,expected_error",
+ [
+ (set(), None, None, "Session recordings not found for the following IDs.*s-1, s-2"),
+ # Recordings were found, so the error has to name the timestamps instead of listing no IDs at all
+ ({"s-1"}, None, MAX_TS, "Failed to get min .* or max .* timestamps for sessions: s-1"),
+ ],
+)
+def test_find_sessions_timestamps_dropping_missing_raises(
+ found_in_db: set[str],
+ min_timestamp: datetime | None,
+ max_timestamp: datetime | None,
+ expected_error: str,
+) -> None:
+ query_result = SessionsWithTimestamps(
+ session_ids=found_in_db, min_timestamp=min_timestamp, max_timestamp=max_timestamp
+ )
+ with patch.object(SessionReplayEvents, "sessions_found_with_timestamps", return_value=query_result):
+ with pytest.raises(exceptions.ValidationError, match=expected_error):
+ find_sessions_timestamps_dropping_missing(session_ids=["s-1", "s-2"], team=MagicMock(id=1))
diff --git a/ee/hogai/tools/replay/summarize_sessions.py b/ee/hogai/tools/replay/summarize_sessions.py
index 8cfa39204b71..6ddc1b34dd58 100644
--- a/ee/hogai/tools/replay/summarize_sessions.py
+++ b/ee/hogai/tools/replay/summarize_sessions.py
@@ -1,6 +1,7 @@
import json
import asyncio
from dataclasses import dataclass
+from datetime import datetime
from textwrap import dedent
from typing import Any, Literal, cast
@@ -30,7 +31,11 @@ from ee.hogai.session_summaries.constants import (
from ee.hogai.session_summaries.session.stringify import SingleSessionSummaryStringifier
from ee.hogai.session_summaries.session_group.patterns import EnrichedSessionGroupSummaryPatternsList
from ee.hogai.session_summaries.session_group.stringify import SessionGroupSummaryStringifier
-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 (
+ SessionRecordingPartition,
+ find_sessions_timestamps_dropping_missing,
+ partition_sessions_by_recording_existence,
+)
from ee.hogai.session_summaries.tracking import (
capture_session_summary_generated,
capture_session_summary_started,
@@ -42,6 +47,15 @@ from ee.hogai.utils.state import prepare_reasoning_progress_message
logger = structlog.get_logger(__name__)
+@dataclass(frozen=True)
+class SessionSummariesResult:
+ """Result of a chat summarization run; summary_id is only set for the group path."""
+
+ content: str
+ summary_id: str | None
+ failed_sessions: list[FailedSessionInfo]
+
+
class SummarizeSessionsToolArgs(BaseModel):
recordings_filters_or_explicit_session_ids: MaxRecordingUniversalFilters | list[str] = Field(
description=dedent(
@@ -68,13 +82,6 @@ class SummarizeSessionsToolArgs(BaseModel):
)
-@dataclass(frozen=True, kw_only=True, slots=True)
-class SessionsSummaryResult:
- summary_text: str
- summary_id: str | None
- failed_sessions: list[FailedSessionInfo]
-
-
class SummarizeSessionsTool(MaxTool):
name: Literal["summarize_sessions"] = "summarize_sessions"
description: str = dedent(
@@ -131,9 +138,11 @@ class SummarizeSessionsTool(MaxTool):
if not llm_provided_session_ids:
return "No sessions were found matching the specified criteria.", None
# Confirm that the sessions provided by the LLM (through filters or explicitly) are true sessions with events (to avoid DB query failures)
- session_ids = await database_sync_to_async(self._validate_specific_session_ids, thread_sensitive=False)(
+ partition = await database_sync_to_async(self._validate_specific_session_ids, thread_sensitive=False)(
llm_provided_session_ids
)
+ session_ids = partition.found_session_ids
+ missing_session_ids = partition.missing_session_ids
# LLM provided session ids, but no actual sessions with events were found
if not session_ids:
llm_provided_input = (
@@ -168,17 +177,15 @@ class SummarizeSessionsTool(MaxTool):
session_ids=session_ids,
summary_title=summary_title,
session_ids_source=llm_provided_session_ids_source,
+ # Recordings that were already missing at validation time still get reported as skipped
+ pre_dropped_session_ids=missing_session_ids,
)
- content: str | None = None
artifact: dict | None = None
if result.summary_id:
- content = result.summary_text
artifact = {
"title": summary_title or "Sessions summary",
"session_group_summary_id": result.summary_id,
}
- else:
- content = result.summary_text
except Exception as err:
capture_session_summary_generated(
user=self._user,
@@ -197,12 +204,14 @@ class SummarizeSessionsTool(MaxTool):
team=self._team,
tracking_id=tracking_id,
summary_source="chat",
- summary_type=summary_type,
+ # A group run can fall back to individual summaries when too few recordings survive validation,
+ # so report the path that actually ran (only the group path produces a summary id)
+ summary_type="group" if result.summary_id else "single",
session_ids=session_ids,
success=True,
failed_session_count=len(result.failed_sessions),
)
- return content, artifact
+ return result.content, artifact
def _stream_progress(self, progress_message: str) -> None:
"""Push summarization progress as reasoning messages"""
@@ -289,11 +298,12 @@ class SummarizeSessionsTool(MaxTool):
"""Get the session ID of the user who triggered the summarization."""
return self._get_session_id(self._config)
- async def _summarize_sessions_individually(self, session_ids: list[str]) -> str:
- """Summarize sessions individually with progress updates."""
+ async def _summarize_sessions_individually(self, session_ids: list[str]) -> tuple[str, list[FailedSessionInfo]]:
+ """Summarize sessions individually with progress updates. Returns (summaries_str, failed_sessions)."""
total = len(session_ids)
completed = 0
trigger_session_id = self._get_trigger_session_id()
+ failed_sessions: list[FailedSessionInfo] = []
async def _summarize(session_id: str) -> dict[str, Any] | None:
nonlocal completed
@@ -317,6 +327,13 @@ class SummarizeSessionsTool(MaxTool):
exc_info=True,
signals_type="session-summaries",
)
+ failed_sessions.append(
+ FailedSessionInfo(
+ session_id=session_id,
+ category="summarization_failed",
+ reason="Failed to generate a summary for this session",
+ )
+ )
return None
# Run all tasks concurrently, with periodic heartbeats to keep the parent activity alive
@@ -333,7 +350,27 @@ class SummarizeSessionsTool(MaxTool):
stringified_summaries.append(stringifier.stringify_session())
# Combine all stringified summaries into a single string
summaries_str = "\n\n".join(stringified_summaries)
- return summaries_str
+ return summaries_str, failed_sessions
+
+ @staticmethod
+ def _missing_recordings_as_failed(session_ids: list[str]) -> list[FailedSessionInfo]:
+ return [
+ FailedSessionInfo(
+ session_id=session_id,
+ category="skipped",
+ reason="Recording not found (it may have expired or been deleted)",
+ )
+ for session_id in session_ids
+ ]
+
+ @staticmethod
+ def _stringify_group_summary(summary: EnrichedSessionGroupSummaryPatternsList) -> str:
+ # An empty report would render as a bare "# Patterns" header, leaving the LLM to improvise
+ if not summary.patterns:
+ return "No recurring patterns or issues were found across the analyzed sessions."
+ # Stringify the summary to "weight" less and apply example limits per pattern, so it won't overload the context
+ stringifier = SessionGroupSummaryStringifier(summary.model_dump(exclude_none=False))
+ return stringifier.stringify_patterns()
@staticmethod
def _format_failed_sessions_note(failed_sessions: list[FailedSessionInfo], total_requested: int) -> str:
@@ -360,24 +397,28 @@ class SummarizeSessionsTool(MaxTool):
self,
session_ids: list[str],
summary_title: str | None,
- ) -> SessionsSummaryResult:
- """Summarize sessions as a group. The result's summary_id is always set on this path."""
+ *,
+ dropped_sessions: list[FailedSessionInfo],
+ min_timestamp: datetime,
+ max_timestamp: datetime,
+ ) -> SessionSummariesResult:
+ """Summarize sessions as a group."""
from ee.hogai.session_summaries.utils import logging_session_ids
- timestamps = await database_sync_to_async(find_sessions_timestamps, thread_sensitive=False)(
- session_ids=session_ids, team=self._team
- )
+ total_requested = len(session_ids) + len(dropped_sessions)
trigger_session_id = self._get_trigger_session_id()
async with Heartbeater():
async for update_type, data in execute_summarize_session_group(
session_ids=session_ids,
user=self._user,
team=self._team,
- min_timestamp=timestamps.min_timestamp,
- max_timestamp=timestamps.max_timestamp,
+ min_timestamp=min_timestamp,
+ max_timestamp=max_timestamp,
summary_title=summary_title,
extra_summary_context=None,
trigger_session_id=trigger_session_id,
+ # Forwarded so the saved summary reports them too, not just the chat response
+ pre_run_failed_sessions=dropped_sessions,
):
# Max "reasoning" text update message
if update_type == SessionSummaryStreamUpdate.UI_STATUS:
@@ -411,15 +452,11 @@ class SummarizeSessionsTool(MaxTool):
)
logger.error(msg, signals_type="session-summaries")
raise ValueError(msg)
- if not summary.patterns:
- summary_str = "No recurring patterns were found across these sessions."
- else:
- # Stringify the summary to "weight" less and apply example limits per pattern, so it won't overload the context
- stringifier = SessionGroupSummaryStringifier(summary.model_dump(exclude_none=False))
- summary_str = stringifier.stringify_patterns()
- note = self._format_failed_sessions_note(failed_sessions, total_requested=len(session_ids))
- return SessionsSummaryResult(
- summary_text=note + summary_str,
+ summary_str = self._stringify_group_summary(summary)
+ # The workflow persists the dropped sessions too, so they come back in `failed_sessions`
+ note = self._format_failed_sessions_note(failed_sessions, total_requested=total_requested)
+ return SessionSummariesResult(
+ content=note + summary_str,
summary_id=session_group_summary_id,
failed_sessions=failed_sessions,
)
@@ -433,10 +470,14 @@ class SummarizeSessionsTool(MaxTool):
raise ValueError(msg)
async def _summarize_sessions(
- self, session_ids: list[str], summary_title: str | None, *, session_ids_source: Literal["filters", "explicit"]
- ) -> SessionsSummaryResult:
- """summary_id and failed_sessions are only populated for the group path; the individual
- path logs per-session errors inline."""
+ self,
+ session_ids: list[str],
+ summary_title: str | None,
+ *,
+ session_ids_source: Literal["filters", "explicit"],
+ pre_dropped_session_ids: list[str] | None = None,
+ ) -> SessionSummariesResult:
+ dropped_sessions = self._missing_recordings_as_failed(pre_dropped_session_ids or [])
# Fetch per-session metadata for the progress widget
metadata = await database_sync_to_async(self._get_session_metadata, thread_sensitive=False)(session_ids)
# Emit sessions_discovered for the frontend progress widget
@@ -458,24 +499,47 @@ class SummarizeSessionsTool(MaxTool):
)
# Process sessions based on count
if len(session_ids) <= GROUP_SUMMARIES_MIN_SESSIONS:
- summaries_content = await self._summarize_sessions_individually(session_ids=session_ids)
- return SessionsSummaryResult(summary_text=summaries_content, summary_id=None, failed_sessions=[])
+ summaries_content, run_failed_sessions = await self._summarize_sessions_individually(
+ session_ids=session_ids
+ )
+ failed_sessions = dropped_sessions + run_failed_sessions
+ note = self._format_failed_sessions_note(
+ failed_sessions, total_requested=len(session_ids) + len(dropped_sessions)
+ )
+ return SessionSummariesResult(
+ content=note + summaries_content, summary_id=None, failed_sessions=failed_sessions
+ )
+ # The group flow needs timestamps, and a recording can drop out between validation reads (still
+ # ingesting, deleted, or a lagging replica), so report it as failed instead of erroring the whole batch
+ sessions = await database_sync_to_async(find_sessions_timestamps_dropping_missing, thread_sensitive=False)(
+ session_ids=session_ids, team=self._team
+ )
+ dropped_sessions += self._missing_recordings_as_failed(sessions.missing_session_ids)
+ total_requested = len(sessions.found_session_ids) + len(dropped_sessions)
+ # Report dropped sessions so the progress widget takes them off the list, as the workflow never sees them
+ for dropped_session_id in sessions.missing_session_ids:
+ self._dispatch_session_progress(dropped_session_id, "skipped", 0, total_requested)
+ # Too few recordings left for pattern extraction, so summarize what's left one by one instead
+ if len(sessions.found_session_ids) <= GROUP_SUMMARIES_MIN_SESSIONS:
+ summaries_content, run_failed_sessions = await self._summarize_sessions_individually(
+ session_ids=sessions.found_session_ids
+ )
+ failed_sessions = dropped_sessions + run_failed_sessions
+ note = self._format_failed_sessions_note(failed_sessions, total_requested=total_requested)
+ return SessionSummariesResult(
+ content=note + summaries_content, summary_id=None, failed_sessions=failed_sessions
+ )
# For large groups, process in detail, searching for patterns
return await self._summarize_sessions_as_group(
- session_ids=session_ids,
+ session_ids=sessions.found_session_ids,
summary_title=summary_title,
+ dropped_sessions=dropped_sessions,
+ min_timestamp=sessions.min_timestamp,
+ max_timestamp=sessions.max_timestamp,
)
- def _validate_specific_session_ids(self, session_ids: list[str]) -> list[str] | None:
- """Validate that specific session IDs exist in the database."""
- from posthog.session_recordings.queries.session_replay_events import SessionReplayEvents
-
- replay_events = SessionReplayEvents()
- sessions_found = replay_events.sessions_found_with_timestamps(
- session_ids=session_ids,
- team=self._team,
- ).session_ids
- if not sessions_found:
- return None
- # Preserve the original order, filtering out invalid sessions
- return [sid for sid in session_ids if sid in sessions_found]
+ def _validate_specific_session_ids(self, session_ids: list[str]) -> SessionRecordingPartition:
+ """Partition the requested session IDs into found/missing, deduped and in the original order."""
+ # Dedupe while preserving order: duplicate IDs would otherwise spawn duplicate summarization tasks
+ deduped_session_ids = list(dict.fromkeys(session_ids))
+ return partition_sessions_by_recording_existence(deduped_session_ids, self._team)
diff --git a/ee/hogai/tools/replay/test/test_summarize_sessions.py b/ee/hogai/tools/replay/test/test_summarize_sessions.py
new file mode 100644
index 000000000000..2811c3f2b5c8
--- /dev/null
+++ b/ee/hogai/tools/replay/test/test_summarize_sessions.py
@@ -0,0 +1,255 @@
+from collections.abc import AsyncIterator
+from datetime import UTC, datetime
+from typing import Any
+
+from posthog.test.base import BaseTest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from langchain_core.runnables import RunnableConfig
+
+from posthog.temporal.session_replay.session_summary_group.types import SessionSummaryStreamUpdate
+
+from ee.hogai.session_summaries.session_group.patterns import EnrichedSessionGroupSummaryPatternsList
+from ee.hogai.session_summaries.session_group.summarize_session_group import (
+ FoundSessionsWithTimestamps,
+ SessionRecordingPartition,
+)
+from ee.hogai.tools.replay.summarize_sessions import SessionSummariesResult, SummarizeSessionsTool
+from ee.hogai.utils.types import AssistantState
+from ee.hogai.utils.types.base import NodePath
+
+MIN_TS = datetime(2026, 7, 29, 8, 0, 0, tzinfo=UTC)
+MAX_TS = datetime(2026, 7, 29, 9, 0, 0, tzinfo=UTC)
+REQUESTED_SESSION_IDS = [f"s-{index}" for index in range(7)]
+
+
+class _NoopHeartbeater:
+ async def __aenter__(self) -> "_NoopHeartbeater":
+ return self
+
+ async def __aexit__(self, *_args: Any) -> bool:
+ return False
+
+
+class TestSummarizeSessionsTool(BaseTest):
+ async def _create_tool(self) -> SummarizeSessionsTool:
+ config: RunnableConfig = RunnableConfig()
+ return await SummarizeSessionsTool.create_tool_class(
+ team=self.team,
+ user=self.user,
+ state=AssistantState(messages=[]),
+ config=config,
+ node_path=(NodePath(name="test_node", tool_call_id="test_tool_call_id", message_id="test"),),
+ )
+
+ @staticmethod
+ def _metadata(session_ids: list[str]) -> dict[str, dict]:
+ return {
+ session_id: {
+ "first_url": "",
+ "active_duration_s": 0,
+ "distinct_id": "",
+ "start_time": None,
+ "snapshot_source": "web",
+ }
+ for session_id in session_ids
+ }
+
+ async def test_group_summary_skips_the_missing_recording_and_reports_it(self) -> None:
+ found_session_ids, dropped_session_ids = REQUESTED_SESSION_IDS[:6], REQUESTED_SESSION_IDS[6:]
+ tool = await self._create_tool()
+ workflow_kwargs: dict[str, Any] = {}
+
+ async def fake_execute_summarize_session_group(
+ **kwargs: Any,
+ ) -> AsyncIterator[tuple[SessionSummaryStreamUpdate, Any]]:
+ workflow_kwargs.update(kwargs)
+ # The workflow persists the sessions dropped before the run, so they come back with the final result
+ yield (
+ SessionSummaryStreamUpdate.FINAL_RESULT,
+ (
+ EnrichedSessionGroupSummaryPatternsList(patterns=[]),
+ "summary-id",
+ list(kwargs["pre_run_failed_sessions"]),
+ ),
+ )
+
+ with (
+ patch.object(
+ SummarizeSessionsTool, "_get_session_metadata", return_value=self._metadata(REQUESTED_SESSION_IDS)
+ ),
+ patch(
+ "ee.hogai.tools.replay.summarize_sessions.find_sessions_timestamps_dropping_missing",
+ return_value=FoundSessionsWithTimestamps(
+ found_session_ids=found_session_ids,
+ missing_session_ids=dropped_session_ids,
+ min_timestamp=MIN_TS,
+ max_timestamp=MAX_TS,
+ ),
+ ),
+ patch("ee.hogai.tools.replay.summarize_sessions.Heartbeater", _NoopHeartbeater),
+ patch(
+ "ee.hogai.tools.replay.summarize_sessions.execute_summarize_session_group",
+ fake_execute_summarize_session_group,
+ ),
+ ):
+ result = await tool._summarize_sessions(
+ session_ids=REQUESTED_SESSION_IDS, summary_title="Test", session_ids_source="explicit"
+ )
+
+ assert workflow_kwargs["session_ids"] == found_session_ids
+ assert result.summary_id == "summary-id"
+ assert [(fs.session_id, fs.category) for fs in result.failed_sessions] == [("s-6", "skipped")]
+ assert "only 6 of 7 sessions were included" in result.content
+
+ async def test_group_summary_falls_back_to_individual_when_too_few_recordings_are_left(self) -> None:
+ found_session_ids, dropped_session_ids = REQUESTED_SESSION_IDS[:5], REQUESTED_SESSION_IDS[5:]
+ tool = await self._create_tool()
+ mock_summarize_session = AsyncMock(return_value={})
+ mock_summarize_session_group = MagicMock()
+
+ with (
+ patch.object(
+ SummarizeSessionsTool, "_get_session_metadata", return_value=self._metadata(REQUESTED_SESSION_IDS)
+ ),
+ patch(
+ "ee.hogai.tools.replay.summarize_sessions.find_sessions_timestamps_dropping_missing",
+ return_value=FoundSessionsWithTimestamps(
+ found_session_ids=found_session_ids,
+ missing_session_ids=dropped_session_ids,
+ min_timestamp=MIN_TS,
+ max_timestamp=MAX_TS,
+ ),
+ ),
+ patch("ee.hogai.tools.replay.summarize_sessions.Heartbeater", _NoopHeartbeater),
+ patch(
+ "ee.hogai.tools.replay.summarize_sessions.execute_summarize_session_group",
+ mock_summarize_session_group,
+ ),
+ patch("ee.hogai.tools.replay.summarize_sessions.execute_summarize_session", mock_summarize_session),
+ patch("ee.hogai.tools.replay.summarize_sessions.SingleSessionSummaryStringifier") as mock_stringifier,
+ ):
+ mock_stringifier.return_value.stringify_session.return_value = "Session summary"
+ result = await tool._summarize_sessions(
+ session_ids=REQUESTED_SESSION_IDS, summary_title="Test", session_ids_source="explicit"
+ )
+
+ mock_summarize_session_group.assert_not_called()
+ assert sorted(call.kwargs["session_id"] for call in mock_summarize_session.await_args_list) == found_session_ids
+ assert result.summary_id is None
+ assert [(fs.session_id, fs.category) for fs in result.failed_sessions] == [
+ ("s-5", "skipped"),
+ ("s-6", "skipped"),
+ ]
+ assert "only 5 of 7 sessions were included" in result.content
+
+ async def test_validate_specific_session_ids_dedupes_and_partitions(self) -> None:
+ tool = await self._create_tool()
+ with patch(
+ "posthog.session_recordings.queries.session_replay_events.SessionReplayEvents.sessions_found_with_timestamps",
+ return_value=MagicMock(session_ids={"s-1", "s-2"}),
+ ):
+ partition = tool._validate_specific_session_ids(["s-1", "s-1", "s-2", "s-3"])
+ assert partition.found_session_ids == ["s-1", "s-2"]
+ assert partition.missing_session_ids == ["s-3"]
+
+ async def test_sessions_missing_at_validation_time_are_reported(self) -> None:
+ # An explicitly selected recording that already expired is reported, not silently dropped
+ tool = await self._create_tool()
+ workflow_kwargs: dict[str, Any] = {}
+
+ async def fake_execute_summarize_session_group(
+ **kwargs: Any,
+ ) -> AsyncIterator[tuple[SessionSummaryStreamUpdate, Any]]:
+ workflow_kwargs.update(kwargs)
+ yield (
+ SessionSummaryStreamUpdate.FINAL_RESULT,
+ (
+ EnrichedSessionGroupSummaryPatternsList(patterns=[]),
+ "summary-id",
+ list(kwargs["pre_run_failed_sessions"]),
+ ),
+ )
+
+ with (
+ patch.object(
+ SummarizeSessionsTool, "_get_session_metadata", return_value=self._metadata(REQUESTED_SESSION_IDS)
+ ),
+ patch(
+ "ee.hogai.tools.replay.summarize_sessions.find_sessions_timestamps_dropping_missing",
+ return_value=FoundSessionsWithTimestamps(
+ found_session_ids=REQUESTED_SESSION_IDS,
+ missing_session_ids=[],
+ min_timestamp=MIN_TS,
+ max_timestamp=MAX_TS,
+ ),
+ ),
+ patch("ee.hogai.tools.replay.summarize_sessions.Heartbeater", _NoopHeartbeater),
+ patch(
+ "ee.hogai.tools.replay.summarize_sessions.execute_summarize_session_group",
+ fake_execute_summarize_session_group,
+ ),
+ ):
+ result = await tool._summarize_sessions(
+ session_ids=REQUESTED_SESSION_IDS,
+ summary_title="Test",
+ session_ids_source="explicit",
+ pre_dropped_session_ids=["s-expired"],
+ )
+
+ assert workflow_kwargs["session_ids"] == REQUESTED_SESSION_IDS
+ assert [(fs.session_id, fs.category) for fs in workflow_kwargs["pre_run_failed_sessions"]] == [
+ ("s-expired", "skipped")
+ ]
+ assert result.summary_id == "summary-id"
+ assert [(fs.session_id, fs.category) for fs in result.failed_sessions] == [("s-expired", "skipped")]
+ assert "only 7 of 8 sessions were included" in result.content
+
+ async def test_individual_summary_failures_are_counted_in_the_note(self) -> None:
+ session_ids = REQUESTED_SESSION_IDS[:3]
+ tool = await self._create_tool()
+
+ async def mock_execute_summarize_session(**kwargs: Any) -> dict:
+ if kwargs["session_id"] == "s-1":
+ raise ValueError("summary generation failed")
+ return {}
+
+ with (
+ patch.object(SummarizeSessionsTool, "_get_session_metadata", return_value=self._metadata(session_ids)),
+ patch("ee.hogai.tools.replay.summarize_sessions.Heartbeater", _NoopHeartbeater),
+ patch("ee.hogai.tools.replay.summarize_sessions.execute_summarize_session", mock_execute_summarize_session),
+ patch("ee.hogai.tools.replay.summarize_sessions.SingleSessionSummaryStringifier") as mock_stringifier,
+ ):
+ mock_stringifier.return_value.stringify_session.return_value = "Session summary"
+ result = await tool._summarize_sessions(
+ session_ids=session_ids, summary_title="Test", session_ids_source="explicit"
+ )
+
+ assert result.summary_id is None
+ assert [(fs.session_id, fs.category) for fs in result.failed_sessions] == [("s-1", "summarization_failed")]
+ assert "only 2 of 3 sessions were included" in result.content
+ assert result.content.count("Session summary") == 2
+
+ async def test_tracking_reports_the_executed_path_after_fallback(self) -> None:
+ # A group request that falls back to individual summaries should not be tracked as a group run
+ tool = await self._create_tool()
+ fallback_result = SessionSummariesResult(content="Session summary", summary_id=None, failed_sessions=[])
+
+ with (
+ patch.object(
+ SummarizeSessionsTool,
+ "_validate_specific_session_ids",
+ return_value=SessionRecordingPartition(found_session_ids=REQUESTED_SESSION_IDS, missing_session_ids=[]),
+ ),
+ patch.object(SummarizeSessionsTool, "_summarize_sessions", AsyncMock(return_value=fallback_result)),
+ patch("ee.hogai.tools.replay.summarize_sessions.capture_session_summary_started") as mock_started,
+ patch("ee.hogai.tools.replay.summarize_sessions.capture_session_summary_generated") as mock_generated,
+ ):
+ content, artifact = await tool._arun_impl(
+ recordings_filters_or_explicit_session_ids=REQUESTED_SESSION_IDS, summary_title="Test"
+ )
+
+ assert content == "Session summary"
+ assert artifact is None
+ assert mock_started.call_args.kwargs["summary_type"] == "group"
+ assert mock_generated.call_args.kwargs["summary_type"] == "single"
diff --git a/posthog/temporal/session_replay/session_summary_group/types.py b/posthog/temporal/session_replay/session_summary_group/types.py
index e8f56196e6fb..a0b51a835f07 100644
--- a/posthog/temporal/session_replay/session_summary_group/types.py
+++ b/posthog/temporal/session_replay/session_summary_group/types.py
@@ -51,6 +51,8 @@ class SessionGroupSummaryInputs:
local_reads_prod: bool = False
video_based: bool = False
trigger_session_id: str | None = None
+ # Sessions the caller dropped before starting the run, so run_metadata covers the whole request
+ pre_run_failed_sessions: list[FailedSessionInfo] = dataclasses.field(default_factory=list)
@dataclasses.dataclass(frozen=True, kw_only=True)
diff --git a/posthog/temporal/session_replay/session_summary_group/workflow.py b/posthog/temporal/session_replay/session_summary_group/workflow.py
index 704bc6df6a9b..056e37d7e39a 100644
--- a/posthog/temporal/session_replay/session_summary_group/workflow.py
+++ b/posthog/temporal/session_replay/session_summary_group/workflow.py
@@ -427,6 +427,8 @@ class SummarizeSessionGroupWorkflow(PostHogWorkflow):
async def run(self, inputs: SessionGroupSummaryInputs) -> str:
start_time = temporalio.workflow.now()
self._total_sessions = len(inputs.session_ids)
+ for pre_run_failed_session in inputs.pre_run_failed_sessions:
+ self._failed_sessions[pre_run_failed_session.session_id] = pre_run_failed_session
# Get events data from the DB (or cache)
self._current_phase = "fetching_data"
self._current_status.append("Fetching session data from the database")
@@ -661,6 +663,7 @@ async def execute_summarize_session_group(
local_reads_prod: bool = False,
video_based: bool = False,
trigger_session_id: str | None = None,
+ pre_run_failed_sessions: list[FailedSessionInfo] | None = None,
) -> AsyncGenerator[
tuple[
SessionSummaryStreamUpdate,
@@ -688,6 +691,7 @@ async def execute_summarize_session_group(
local_reads_prod=local_reads_prod,
video_based=video_based,
trigger_session_id=trigger_session_id,
+ pre_run_failed_sessions=pre_run_failed_sessions or [],
)
# Connect to Temporal and execute the workflow
workflow_id = f"session-summary:group:{user.id}-{team.id}:{shared_id}:{uuid.uuid4()}"
diff --git a/products/session_summaries/frontend/SessionGroupSummaryScene.tsx b/products/session_summaries/frontend/SessionGroupSummaryScene.tsx
index e73bcd6d671c..46a236d48f9f 100644
--- a/products/session_summaries/frontend/SessionGroupSummaryScene.tsx
+++ b/products/session_summaries/frontend/SessionGroupSummaryScene.tsx
@@ -13,6 +13,7 @@ import {
Tooltip,
} from '@posthog/lemon-ui'
+import { EmptyMessage } from 'lib/components/EmptyMessage/EmptyMessage'
import { IconPlayCircle } from 'lib/lemon-ui/icons'
import { LemonMenu } from 'lib/lemon-ui/LemonMenu'
import { debounce } from 'lib/utils/async'
@@ -539,6 +540,8 @@ export function SessionGroupSummary(): JSX.Element {
const analyzedSessionsCount = sessionGroupSummary.session_ids.length
const failedSessions = sessionGroupSummary.run_metadata?.failed_sessions ?? []
const requestedSessionsCount = analyzedSessionsCount + failedSessions.length
+ // A run can legitimately find nothing, and there's nothing to filter or sort in that case
+ const hasPatterns = (summary.patterns?.length ?? 0) > 0
return (
<SceneContent>
<SceneTitleSection
@@ -574,49 +577,60 @@ export function SessionGroupSummary(): JSX.Element {
<span className="hidden sm:inline">·</span>
<span>{new Date(sessionGroupSummary.created_at).toLocaleString()}</span>
</div>
- <LemonMenu
- items={[
- {
- label: 'Sort by severity',
- icon: sortBy === 'severity' ? <IconCheck /> : undefined,
- onClick: () => setSortBy('severity'),
- },
- {
- label: 'Sort by session count',
- icon: sortBy === 'session_count' ? <IconCheck /> : undefined,
- onClick: () => setSortBy('session_count'),
- },
- ]}
- >
- <LemonButton type="secondary" size="small" icon={<IconSort />}>
- {sortBy === 'severity' ? 'Sort by severity' : 'Sort by session count'}
- </LemonButton>
- </LemonMenu>
+ {hasPatterns && (
+ <LemonMenu
+ items={[
+ {
+ label: 'Sort by severity',
+ icon: sortBy === 'severity' ? <IconCheck /> : undefined,
+ onClick: () => setSortBy('severity'),
+ },
+ {
+ label: 'Sort by session count',
+ icon: sortBy === 'session_count' ? <IconCheck /> : undefined,
+ onClick: () => setSortBy('session_count'),
+ },
+ ]}
+ >
+ <LemonButton type="secondary" size="small" icon={<IconSort />}>
+ {sortBy === 'severity' ? 'Sort by severity' : 'Sort by session count'}
+ </LemonButton>
+ </LemonMenu>
+ )}
</div>
<div className="space-y-4">
<PartialResultBanner failedSessions={failedSessions} analyzedSessionCount={analyzedSessionsCount} />
- <FilterBar
- searchValue={searchValue}
- onSearchChange={setSearchValue}
- issueTypeFilters={issueTypeFilters}
- onIssueTypeFilterChange={handleIssueTypeFilterChange}
- filteredCount={filteredIssuesCount}
- totalCount={totalIssuesCount}
- issueTypeCounts={issueTypeCounts}
- />
- <div className="flex flex-col gap-2">
- {sortedPatterns.length === 0 && summary.patterns && summary.patterns.length > 0 ? (
- <p className="text-muted">No patterns match your search</p>
- ) : (
- sortedPatterns.map((pattern) => (
- <PatternCard
- key={pattern.pattern_id}
- pattern={pattern}
- onViewDetails={(event) => handleViewDetails(pattern, event)}
- />
- ))
- )}
- </div>
+ {hasPatterns ? (
+ <>
+ <FilterBar
+ searchValue={searchValue}
+ onSearchChange={setSearchValue}
+ issueTypeFilters={issueTypeFilters}
+ onIssueTypeFilterChange={handleIssueTypeFilterChange}
+ filteredCount={filteredIssuesCount}
+ totalCount={totalIssuesCount}
+ issueTypeCounts={issueTypeCounts}
+ />
+ <div className="flex flex-col gap-2">
+ {sortedPatterns.length === 0 ? (
+ <p className="text-muted">No patterns match your search</p>
+ ) : (
+ sortedPatterns.map((pattern) => (
+ <PatternCard
+ key={pattern.pattern_id}
+ pattern={pattern}
+ onViewDetails={(event) => handleViewDetails(pattern, event)}
+ />
+ ))
+ )}
+ </div>
+ </>
+ ) : (
+ <EmptyMessage
+ title="No patterns found"
+ description={`We didn't find any recurring patterns across the ${analyzedSessionsCount} sessions analyzed. Try summarizing a different set of recordings.`}
+ />
+ )}
</div>
<SessionGroupSummaryDetailsModal