: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
feat(replay): return partial results from group session summaries (#58849)
Hayne Ryuad7535865c6d
diff --git a/ee/api/session_summaries.py b/ee/api/session_summaries.pyindex 94100a202181..00d805c83bb6 100644--- a/ee/api/session_summaries.py+++ b/ee/api/session_summaries.py@@ -35,7 +35,7 @@ from posthog.models.utils import UUIDfrom posthog.rate_limit import ClickHouseBurstRateThrottle, ClickHouseSustainedRateThrottlefrom posthog.renderers import ServerSentEventRendererfrom posthog.temporal.session_replay.session_summary.workflow import execute_summarize_session-from posthog.temporal.session_replay.session_summary_group.types import SessionSummaryStreamUpdate+from posthog.temporal.session_replay.session_summary_group.types import FailedSessionInfo, SessionSummaryStreamUpdatefrom posthog.temporal.session_replay.session_summary_group.workflow import execute_summarize_session_groupfrom posthog.utils import relative_date_parse@@ -200,9 +200,14 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):min_timestamp: datetime,max_timestamp: datetime,extra_summary_context: ExtraSummaryContext | None = None,- ) -> EnrichedSessionGroupSummaryPatternsList:- """Helper function to consume the async generator and return a summary"""- results: list[tuple[SessionSummaryStreamUpdate, tuple[EnrichedSessionGroupSummaryPatternsList, str] | str]] = []+ ) -> tuple[EnrichedSessionGroupSummaryPatternsList, list[FailedSessionInfo]]:+ """Consume the workflow stream and return (patterns, failed_sessions) for the response."""+ results: list[+ tuple[+ SessionSummaryStreamUpdate,+ tuple[EnrichedSessionGroupSummaryPatternsList, str, list[FailedSessionInfo]] | str,+ ]+ ] = []async for update_type, data in execute_summarize_session_group(session_ids=session_ids,user=user,@@ -223,16 +228,16 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):# The last item in the result should be the summary, if not - raise an exceptionlast_result = results[-1]summary_iteration = last_result[-1]- if not isinstance(summary_iteration, tuple) or len(summary_iteration) != 2:+ if not isinstance(summary_iteration, tuple) or len(summary_iteration) != 3:error_message = f"Unexpected result type ({type(summary_iteration)}) when generating summaries (session ids: {logging_session_ids(session_ids)}): {results}"logger.exception(error_message)raise exceptions.APIException(error_message)- summary, _ = summary_iteration+ summary, _, failed_sessions = summary_iterationif not summary or not isinstance(summary, EnrichedSessionGroupSummaryPatternsList):error_message = f"Unexpected result type ({type(summary)}) when generating summaries (session ids: {logging_session_ids(session_ids)}): {results}"logger.exception(error_message)raise exceptions.APIException(error_message)- return summary+ return summary, failed_sessions@extend_schema(operation_id="create_session_summaries",@@ -257,7 +262,7 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):)# Summarize provided sessionstry:- summary = async_to_sync(self._get_summary_from_progress_stream)(+ summary, failed_sessions = async_to_sync(self._get_summary_from_progress_stream)(session_ids=session_ids,user=user,team=self.team,@@ -273,8 +278,14 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):summary_type="group",session_ids=session_ids,success=True,+ failed_session_count=len(failed_sessions),)- return Response(summary.model_dump(exclude_none=True, mode="json"), status=status.HTTP_200_OK)+ # Sibling field rather than a wrapper, to keep existing `patterns` consumers untouched.+ response_body = summary.model_dump(exclude_none=True, mode="json")+ response_body["failed_sessions"] = [+ {"session_id": fs.session_id, "category": fs.category, "reason": fs.reason} for fs in failed_sessions+ ]+ return Response(response_body, status=status.HTTP_200_OK)except Exception as err:logger.exception(f"Failed to generate session group summary for sessions {logging_session_ids(session_ids)} from team {self.team.id} by user {user.id}: {err}",diff --git a/ee/api/test/test_session_summaries.py b/ee/api/test/test_session_summaries.pyindex 7d2732dcd121..f911455bd7c8 100644--- a/ee/api/test/test_session_summaries.py+++ b/ee/api/test/test_session_summaries.py@@ -12,7 +12,7 @@ from django.http import HttpResponsefrom parameterized import parameterizedfrom rest_framework import exceptions-from posthog.temporal.session_replay.session_summary_group.types import SessionSummaryStreamUpdate+from posthog.temporal.session_replay.session_summary_group.types import FailedSessionInfo, SessionSummaryStreamUpdatefrom ee.api.session_summaries import _NO_READY_SUMMARY_ERROR_SUBSTRINGfrom ee.hogai.session_summaries.session_group.patterns import (@@ -28,9 +28,14 @@ class TestSessionSummariesAPI(APIBaseTest):environment_patches: list[Any]async def _create_async_generator(- self, result: tuple[EnrichedSessionGroupSummaryPatternsList, str]+ self,+ result: tuple[EnrichedSessionGroupSummaryPatternsList, str],+ failed_sessions: Optional[list[FailedSessionInfo]] = None,) -> AsyncIterator[- tuple[SessionSummaryStreamUpdate, Union[str, tuple[EnrichedSessionGroupSummaryPatternsList, str]]]+ tuple[+ SessionSummaryStreamUpdate,+ Union[str, tuple[EnrichedSessionGroupSummaryPatternsList, str, list[FailedSessionInfo]]],+ ]]:"""Helper to create an async generator that yields progress updates and final result."""# Yield progress updates in the new tuple format@@ -40,8 +45,8 @@ class TestSessionSummariesAPI(APIBaseTest):)yield (SessionSummaryStreamUpdate.UI_STATUS, "Processing sessions...")yield (SessionSummaryStreamUpdate.UI_STATUS, "Finding patterns...")- # Yield final result- yield (SessionSummaryStreamUpdate.FINAL_RESULT, result)+ patterns, summary_id = result+ yield (SessionSummaryStreamUpdate.FINAL_RESULT, (patterns, summary_id, failed_sessions or []))def _make_api_request(self, session_ids: list[str], focus_area: Optional[str] = None) -> HttpResponse:"""Helper to make API requests with consistent formatting."""@@ -104,7 +109,21 @@ class TestSessionSummariesAPI(APIBaseTest):datetime(2024, 1, 1, 11, 0, 0),)mock_result = self.create_mock_result()- mock_execute.return_value = self._create_async_generator((mock_result, "session-group-summary-id"))+ mock_failed_sessions = [+ FailedSessionInfo(+ session_id="session-skipped-1",+ category="skipped",+ reason="Recording is too short or has no usable events",+ ),+ FailedSessionInfo(+ session_id="session-errored-1",+ category="summarization_failed",+ reason="Couldn't generate a summary for this session",+ ),+ ]+ mock_execute.return_value = self._create_async_generator(+ (mock_result, "session-group-summary-id"), failed_sessions=mock_failed_sessions+ )# Make requestresponse = self._make_api_request(session_ids=["session1", "session2"], focus_area="login process")# Assertions@@ -118,6 +137,17 @@ class TestSessionSummariesAPI(APIBaseTest):self.assertEqual(data["patterns"][0]["pattern_name"], "Login Flow Pattern")self.assertEqual(data["patterns"][0]["severity"], "medium")self.assertEqual(data["patterns"][0]["stats"]["occurences"], 2)+ self.assertIn("failed_sessions", data)+ self.assertEqual(len(data["failed_sessions"]), 2)+ self.assertEqual(+ data["failed_sessions"][0],+ {+ "session_id": "session-skipped-1",+ "category": "skipped",+ "reason": "Recording is too short or has no usable events",+ },+ )+ self.assertEqual(data["failed_sessions"][1]["category"], "summarization_failed")# Verify execute_summarize_session_group was called correctlymock_execute.assert_called_once_with(session_ids=["session1", "session2"],diff --git a/ee/hogai/session_summaries/constants.py b/ee/hogai/session_summaries/constants.pyindex b18adae4354d..7b50e875b2b1 100644--- a/ee/hogai/session_summaries/constants.py+++ b/ee/hogai/session_summaries/constants.py@@ -27,17 +27,17 @@ MAX_ACTIVE_SECONDS_FOR_VIDEO_SUMMARY_S = (# TemporalSESSION_SUMMARIES_DB_DATA_REDIS_TTL = 60 * 60 * 24 # How long to store the DB data in Redis within Temporal jobs-FAILED_SESSION_SUMMARIES_MIN_RATIO = 0.5 # If less than 50% of session group summaries succeed, stop the workflow-FAILED_PATTERNS_ASSIGNMENT_MIN_RATIO = 0.75 # If less than 75% of patterns assignment succeed, stop the workflowSESSION_GROUP_SUMMARIES_WORKFLOW_POLLING_INTERVAL_MS = 2000 # How often to poll for the workflow status+# Fail-fast threshold for the summarization phase. Group patterns aren't meaningful from 1-2 sessions.+# Continue if `successes >= max(min(FLOOR, ceil(total/2)), total * RATIO)` (floor capped at majority of input).+GROUP_SUMMARY_MIN_SUCCESS_FLOOR = 3+GROUP_SUMMARY_MIN_SUCCESS_RATIO = 0.3# PatternsPATTERNS_ASSIGNMENT_CHUNK_SIZE = 10 # How many single-session-summaries to feed at once to assign events to patterns# Maximum tokens allowed for pattern extraction (below o3 model limit and within expected quality range)PATTERNS_EXTRACTION_MAX_TOKENS = 150000SINGLE_ENTITY_MAX_TOKENS = 200000 # General limit to avoid hitting the o3 model limit, used in case of exceptions-FAILED_PATTERNS_EXTRACTION_MIN_RATIO = 0.75 # If less than 75% of pattern extraction chunks succeed-FAILED_PATTERNS_ASSIGNMENT_MIN_RATIO = 0.75 # If less than 75% of patterns assignment succeedFAILED_PATTERNS_ENRICHMENT_MIN_RATIO = 0.75 # If less than 75% of patterns were enriched with the meta# Loggingdiff --git a/ee/hogai/session_summaries/tracking.py b/ee/hogai/session_summaries/tracking.pyindex db53fd36d65d..fef1f6b10342 100644--- a/ee/hogai/session_summaries/tracking.py+++ b/ee/hogai/session_summaries/tracking.py@@ -81,10 +81,13 @@ def capture_session_summary_generated(success: bool | None = None,error_type: str | None = None,error_message: str | None = None,+ failed_session_count: int = 0,) -> None:"""Capture the completion of a session summary generation."""if not user.distinct_id:return+ # Lets dashboards split clean runs from degraded ones.+ is_partial = success is True and failed_session_count > 0properties: dict = {"ai_product": "session_replay","tracking_id": tracking_id,@@ -94,6 +97,8 @@ def capture_session_summary_generated("session_count": len(session_ids),"video_based": video_based,"success": success,+ "partial": is_partial,+ "failed_session_count": failed_session_count,}if error_type is not None:properties["error_type"] = error_typediff --git a/ee/hogai/tools/replay/summarize_sessions.py b/ee/hogai/tools/replay/summarize_sessions.pyindex f2c85f5865f5..d71540a49446 100644--- a/ee/hogai/tools/replay/summarize_sessions.py+++ b/ee/hogai/tools/replay/summarize_sessions.py@@ -14,6 +14,7 @@ from posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.session_replay.count_playlist_items import convert_filters_to_recordings_queryfrom posthog.temporal.session_replay.session_summary.workflow import execute_summarize_sessionfrom posthog.temporal.session_replay.session_summary_group.types import (+ FailedSessionInfo,SessionProgressStreamData,SessionStatusChange,SessionSummaryStreamUpdate,@@ -155,7 +156,7 @@ class SummarizeSessionsTool(MaxTool):)try:# Summarize the sessions- summaries_content, session_group_summary_id = await self._summarize_sessions(+ summaries_content, session_group_summary_id, failed_sessions = await self._summarize_sessions(session_ids=session_ids,summary_title=summary_title,session_ids_source=llm_provided_session_ids_source,@@ -191,6 +192,7 @@ class SummarizeSessionsTool(MaxTool):summary_type=summary_type,session_ids=session_ids,success=True,+ failed_session_count=len(failed_sessions),)return content, artifact@@ -325,12 +327,33 @@ class SummarizeSessionsTool(MaxTool):summaries_str = "\n\n".join(stringified_summaries)return summaries_str+ @staticmethod+ def _format_failed_sessions_note(failed_sessions: list[FailedSessionInfo], total_requested: int) -> str:+ """Short note prepended to the LLM context when the run was partial, bucketed by category."""+ if not failed_sessions:+ return ""+ analyzed = total_requested - len(failed_sessions)+ counts: dict[str, int] = {}+ reasons_by_category: dict[str, str] = {}+ for fs in failed_sessions:+ counts[fs.category] = counts.get(fs.category, 0) + 1+ reasons_by_category.setdefault(fs.category, fs.reason)+ breakdown_parts = [+ f"{counts[category]} {category.replace('_', ' ')} ({reasons_by_category[category]})" for category in counts+ ]+ breakdown = "; ".join(breakdown_parts)+ return (+ f"Note: only {analyzed} of {total_requested} sessions were included in this summary. "+ f"{len(failed_sessions)} sessions were dropped: {breakdown}. "+ f"When responding to the user, mention this so they know the summary is based on a partial set.\n\n"+ )+async def _summarize_sessions_as_group(self,session_ids: list[str],summary_title: str | None,- ) -> tuple[str, str]:- """Summarize sessions as a group (for larger sets). Returns tuple of (summary_str, session_group_summary_id)."""+ ) -> tuple[str, str, list[FailedSessionInfo]]:+ """Summarize sessions as a group. Returns (summary_str, summary_id, failed_sessions)."""from ee.hogai.session_summaries.utils import logging_session_idsmin_timestamp, max_timestamp = await database_sync_to_async(find_sessions_timestamps, thread_sensitive=False)(@@ -365,14 +388,14 @@ class SummarizeSessionsTool(MaxTool):self._dispatch_structured_update(cast(SessionProgressStreamData, data))# Final summary resultelif update_type == SessionSummaryStreamUpdate.FINAL_RESULT:- if not isinstance(data, tuple) or len(data) != 2:+ if not isinstance(data, tuple) or len(data) != 3:msg = (f"Unexpected data type for stream update {SessionSummaryStreamUpdate.FINAL_RESULT}: {type(data)} "- f"(expected: tuple[EnrichedSessionGroupSummaryPatternsList, str])"+ f"(expected: tuple[EnrichedSessionGroupSummaryPatternsList, str, list[FailedSessionInfo]])")logger.error(msg, signals_type="session-summaries")raise ValueError(msg)- summary, session_group_summary_id = data+ summary, session_group_summary_id, failed_sessions = dataif not isinstance(summary, EnrichedSessionGroupSummaryPatternsList):msg = ( # type: ignore[unreachable]f"Unexpected data type for patterns in stream update {SessionSummaryStreamUpdate.FINAL_RESULT}: {type(summary)} "@@ -383,7 +406,8 @@ class SummarizeSessionsTool(MaxTool):# Stringify the summary to "weight" less and apply example limits per pattern, so it won't overload the contextstringifier = SessionGroupSummaryStringifier(summary.model_dump(exclude_none=False))summary_str = stringifier.stringify_patterns()- return summary_str, session_group_summary_id+ note = self._format_failed_sessions_note(failed_sessions, total_requested=len(session_ids))+ return note + summary_str, session_group_summary_id, failed_sessionselse:msg = f"Unexpected update type ({update_type}) in session group summarization (session_ids: {logging_session_ids(session_ids)})." # type: ignore[unreachable]logger.error(msg, signals_type="session-summaries")@@ -395,11 +419,9 @@ class SummarizeSessionsTool(MaxTool):async def _summarize_sessions(self, session_ids: list[str], summary_title: str | None, *, session_ids_source: Literal["filters", "explicit"]- ) -> tuple[str, str | None]:- """- Summarize sessions. Returns tuple of (summary_str, session_group_summary_id).- session_group_summary_id is None for individual summaries, as report is not generated.- """+ ) -> tuple[str, str | None, list[FailedSessionInfo]]:+ """Returns (summary_str, summary_id, failed_sessions). summary_id and failed_sessions are+ only populated for the group path; the individual path logs per-session errors inline."""# Fetch per-session metadata for the progress widgetmetadata = await database_sync_to_async(self._get_session_metadata, thread_sensitive=False)(session_ids)# Emit sessions_discovered for the frontend progress widget@@ -422,13 +444,13 @@ class SummarizeSessionsTool(MaxTool):# Process sessions based on countif len(session_ids) <= GROUP_SUMMARIES_MIN_SESSIONS:summaries_content = await self._summarize_sessions_individually(session_ids=session_ids)- return summaries_content, None+ return summaries_content, None, []# For large groups, process in detail, searching for patterns- summaries_content, session_group_summary_id = await self._summarize_sessions_as_group(+ summaries_content, session_group_summary_id, failed_sessions = await self._summarize_sessions_as_group(session_ids=session_ids,summary_title=summary_title,)- return summaries_content, session_group_summary_id+ return summaries_content, session_group_summary_id, failed_sessionsdef _validate_specific_session_ids(self, session_ids: list[str]) -> list[str] | None:"""Validate that specific session IDs exist in the database."""diff --git a/ee/models/session_summaries.py b/ee/models/session_summaries.pyindex 7f8f00915918..293a7db393d4 100644--- a/ee/models/session_summaries.py+++ b/ee/models/session_summaries.py@@ -1,6 +1,6 @@-from dataclasses import asdict, dataclass+from dataclasses import asdict, dataclass, fieldfrom datetime import datetime-from typing import TYPE_CHECKING, Optional+from typing import TYPE_CHECKING, Literal, Optionalfrom django.contrib.postgres.fields import ArrayFieldfrom django.contrib.postgres.indexes import GinIndex@@ -50,6 +50,18 @@ class SessionSummaryVisualConfirmationResult:)+FailedSessionCategory = Literal["skipped", "summarization_failed", "patterns_failed"]+++@dataclass(frozen=True)+class FailedSessionInfo:+ """A session dropped from the group summary, with a short reason for the UI."""++ session_id: str+ category: FailedSessionCategory+ reason: str++@dataclass(frozen=True)class SessionSummaryRunMeta:"""Metadata about the run of the summary generation"""@@ -57,6 +69,7 @@ class SessionSummaryRunMeta:model_used: strvisual_confirmation: boolvisual_confirmation_results: list[SessionSummaryVisualConfirmationResult] | None = None+ failed_sessions: list[FailedSessionInfo] = field(default_factory=list)@dataclass(frozen=True)diff --git a/ee/models/test/test_session_summaries.py b/ee/models/test/test_session_summaries.pyindex 86c086927acc..4eb4e608c4e5 100644--- a/ee/models/test/test_session_summaries.py+++ b/ee/models/test/test_session_summaries.py@@ -64,7 +64,12 @@ class TestSingleSessionSummary(BaseTest):self.assertEqual(summary.extra_summary_context, {"focus_area": "authentication"})self.assertEqual(summary.run_metadata,- {"model_used": "gpt-4", "visual_confirmation": False, "visual_confirmation_results": None},+ {+ "model_used": "gpt-4",+ "visual_confirmation": False,+ "visual_confirmation_results": None,+ "failed_sessions": [],+ },)self.assertEqual(summary.created_by, self.user)self.assertEqual(summary.team_id, self.team.id)diff --git a/posthog/temporal/session_replay/session_summary_group/activities/group_patterns.py b/posthog/temporal/session_replay/session_summary_group/activities/group_patterns.pyindex 6765aa2d709d..cb57f0153899 100644--- a/posthog/temporal/session_replay/session_summary_group/activities/group_patterns.py+++ b/posthog/temporal/session_replay/session_summary_group/activities/group_patterns.py@@ -1,7 +1,6 @@import jsonimport asynciofrom dataclasses import asdict-from math import ceilfrom typing import castimport structlog@@ -28,7 +27,6 @@ from posthog.temporal.session_replay.session_summary_group.types import ()from ee.hogai.session_summaries.constants import (- FAILED_PATTERNS_ASSIGNMENT_MIN_RATIO,PATTERNS_ASSIGNMENT_CHUNK_SIZE,PATTERNS_EXTRACTION_MAX_TOKENS,SESSION_SUMMARIES_MODEL,@@ -328,17 +326,25 @@ async def _generate_patterns_assignments(res: RawSessionGroupPatternAssignmentsList | Exception = task.result()if isinstance(res, Exception):temporalio.activity.logger.warning(- f"Patterns assignments generation failed for chunk from sessions ({logging_session_ids(session_ids)}) for user {user_id}: {res}",+ f"A pattern-assignment chunk failed for group of {len(session_ids)} "+ f"sessions ({logging_session_ids(session_ids)}) for user {user_id}: {res}",extra={"user_id": user_id, "signals_type": "session-summaries"},)continuepatterns_assignments_list_of_lists.append(res)- # Fail the activity if too many patterns failed to assign session events- if ceil(len(session_summaries_chunks_str) * FAILED_PATTERNS_ASSIGNMENT_MIN_RATIO) > len(- patterns_assignments_list_of_lists- ):+ # Aggregate signal so a partial run is greppable without counting per-chunk warnings.+ failed_chunk_count = len(session_summaries_chunks_str) - len(patterns_assignments_list_of_lists)+ if failed_chunk_count and patterns_assignments_list_of_lists:+ temporalio.activity.logger.warning(+ f"Pattern assignment partially failed: {failed_chunk_count} of "+ f"{len(session_summaries_chunks_str)} chunks failed for group of {len(session_ids)} "+ f"sessions for user {user_id}",+ extra={"user_id": user_id, "signals_type": "session-summaries"},+ )+ # Abort only on total chunk failure; partial assignments still produce a useful patterns report.+ if not patterns_assignments_list_of_lists:exception_message = (- f"Too many patterns failed to assign session events, when summarizing {len(session_ids)} "+ f"All pattern-assignment chunks failed when summarizing {len(session_ids)} "f"sessions ({logging_session_ids(session_ids)}) for user {user_id}")temporalio.activity.logger.error(@@ -455,7 +461,13 @@ async def assign_events_to_patterns_activity(summary=patterns_with_events_context.model_dump_json(exclude_none=True),extra_summary_context=inputs.extra_summary_context,# We don't do visual confirmation on the patterns assignments level, only on single session level- run_metadata=asdict(SessionSummaryRunMeta(model_used=inputs.model_to_use, visual_confirmation=False)),+ run_metadata=asdict(+ SessionSummaryRunMeta(+ model_used=inputs.model_to_use,+ visual_confirmation=False,+ failed_sessions=list(inputs.failed_sessions),+ )+ ),created_by=user,)return str(session_group_summary.id)diff --git a/posthog/temporal/session_replay/session_summary_group/types.py b/posthog/temporal/session_replay/session_summary_group/types.pyindex dd627abed642..dd687de01752 100644--- a/posthog/temporal/session_replay/session_summary_group/types.py+++ b/posthog/temporal/session_replay/session_summary_group/types.py@@ -5,6 +5,23 @@ from typing import Literal, TypedDictfrom posthog.temporal.session_replay.session_summary.types.inputs import SingleSessionSummaryInputsfrom ee.hogai.session_summaries.session.summarize_session import ExtraSummaryContext+from ee.models.session_summaries import FailedSessionCategory, FailedSessionInfo++# Re-exported so consumers don't reach into ee.models directly for these.+__all__ = [+ "ExtraSummaryContext",+ "FailedSessionCategory",+ "FailedSessionInfo",+ "SessionBatchFetchOutput",+ "SessionGroupSummaryInputs",+ "SessionGroupSummaryOfSummariesInputs",+ "SessionGroupSummaryPatternsExtractionChunksInputs",+ "SessionProgressStreamData",+ "SessionStatusChange",+ "SessionSummaryStreamUpdate",+ "SingleSessionSummaryInputs",+ "WorkflowProgress",+]class SessionSummaryStreamUpdate(Enum):@@ -57,6 +74,8 @@ class SessionGroupSummaryOfSummariesInputs:model_to_use: strextra_summary_context: ExtraSummaryContext | None = Nonetrigger_session_id: str | None = None+ # Forwarded so the assign activity can persist them into run_metadata.+ failed_sessions: list[FailedSessionInfo] = dataclasses.field(default_factory=list)class SessionStatusChange(TypedDict):diff --git a/posthog/temporal/session_replay/session_summary_group/workflow.py b/posthog/temporal/session_replay/session_summary_group/workflow.pyindex 6d336890f63c..a65463944b3f 100644--- a/posthog/temporal/session_replay/session_summary_group/workflow.py+++ b/posthog/temporal/session_replay/session_summary_group/workflow.py@@ -40,6 +40,7 @@ from posthog.temporal.session_replay.session_summary_group.activities.group_pattget_patterns_from_redis_outside_workflow,)from posthog.temporal.session_replay.session_summary_group.types import (+ FailedSessionInfo,SessionBatchFetchOutput,SessionGroupSummaryInputs,SessionGroupSummaryOfSummariesInputs,@@ -51,8 +52,8 @@ from posthog.temporal.session_replay.session_summary_group.types import ()from ee.hogai.session_summaries.constants import (- FAILED_PATTERNS_EXTRACTION_MIN_RATIO,- FAILED_SESSION_SUMMARIES_MIN_RATIO,+ GROUP_SUMMARY_MIN_SUCCESS_FLOOR,+ GROUP_SUMMARY_MIN_SUCCESS_RATIO,SESSION_GROUP_SUMMARIES_WORKFLOW_POLLING_INTERVAL_MS,SESSION_SUMMARIES_MODEL,)@@ -84,6 +85,9 @@ class SummarizeSessionGroupWorkflow(PostHogWorkflow):# Structured per-session progress trackingself._session_statuses: dict[str, str] = {}self._current_phase: str = "fetching_data"+ # Sessions dropped during the run, persisted to run_metadata for the result-page banner.+ # Dict-keyed for defensive dedup; phases naturally don't overlap.+ self._failed_sessions: dict[str, FailedSessionInfo] = {}@temporalio.workflow.querydef get_current_status(self) -> list[str]:@@ -162,9 +166,14 @@ class SummarizeSessionGroupWorkflow(PostHogWorkflow):f"(too short or no events): {fetch_result.expected_skip_session_ids}",extra={"team_id": inputs.team_id, "user_id": inputs.user_id, "signals_type": "session-summaries"},)- # Track skipped sessions in structured progress+ # Persist expected skips so the result page can attribute them.for sid in fetch_result.expected_skip_session_ids:self._session_statuses[sid] = "skipped"+ self._failed_sessions[sid] = FailedSessionInfo(+ session_id=sid,+ category="skipped",+ reason="Recording is too short or has no usable events",+ )# Create SingleSessionSummaryInputs for each sessionsession_inputs: list[SingleSessionSummaryInputs] = []for session_id in fetch_result.fetched_session_ids:@@ -184,19 +193,24 @@ class SummarizeSessionGroupWorkflow(PostHogWorkflow):session_inputs.append(single_session_input)# Update total to exclude skipped sessions so progress reflects actual workself._total_sessions = len(session_inputs)- # Fail the workflow if too many sessions failed unexpectedly- # Expected skips (too short, no events) don't count against the failure ratio- summarizable_session_count = len(inputs.session_ids) - len(fetch_result.expected_skip_session_ids)- min_required = ceil(summarizable_session_count * FAILED_SESSION_SUMMARIES_MIN_RATIO)- if summarizable_session_count > 0 and min_required > len(session_inputs):- extracted_session_ids = {s.session_id for s in session_inputs}- all_skipped_ids = set(fetch_result.expected_skip_session_ids)- unexpected_failures = list(set(inputs.session_ids) - extracted_session_ids - all_skipped_ids)+ # Record unexpected fetch failures so the UI shows them; abort below only if everything failed.+ extracted_session_ids = {s.session_id for s in session_inputs}+ all_skipped_ids = set(fetch_result.expected_skip_session_ids)+ unexpected_failures = list(set(inputs.session_ids) - extracted_session_ids - all_skipped_ids)+ for sid in unexpected_failures:+ self._session_statuses[sid] = "failed"+ self._failed_sessions[sid] = FailedSessionInfo(+ session_id=sid,+ category="summarization_failed",+ reason="Couldn't load session events from the database",+ )+ # Only abort when nothing fetched; partial fetches still produce useful summaries.+ if not session_inputs:exception_message = (- f"Too many sessions failed to fetch data unexpectedly, "- f"when summarizing {len(inputs.session_ids)} sessions. "- f"Unexpected failures: {unexpected_failures}; "- f"Expected skips: {fetch_result.expected_skip_session_ids}; "+ f"No sessions could be fetched for group summary "+ f"({len(inputs.session_ids)} requested, "+ f"{len(fetch_result.expected_skip_session_ids)} skipped, "+ f"{len(unexpected_failures)} unexpected failures) "f"for user {inputs.user_id} in team {inputs.team_id}")temporalio.workflow.logger.exception(@@ -260,16 +274,26 @@ class SummarizeSessionGroupWorkflow(PostHogWorkflow):"signals_type": "session-summaries",},)+ # Record per-session failure. Raw exception strings aren't actionable for users.+ self._failed_sessions[session_id] = FailedSessionInfo(+ session_id=session_id,+ category="summarization_failed",+ reason="Couldn't generate a summary for this session",+ )else:# Store only successful generationssuccessful_sessions.append(single_session_input)- # Fail the workflow if too many sessions failed to summarize- if len(successful_sessions) / len(inputs) < FAILED_SESSION_SUMMARIES_MIN_RATIO:+ # Fail fast below the floor to short-circuit expensive pattern extraction over a tiny sample.+ # Cap the floor at ceil(N/2) so a small batch isn't worse off than the ratio alone would require.+ effective_floor = min(GROUP_SUMMARY_MIN_SUCCESS_FLOOR, ceil(len(inputs) / 2))+ min_required = max(effective_floor, ceil(len(inputs) * GROUP_SUMMARY_MIN_SUCCESS_RATIO))+ if len(successful_sessions) < min_required:session_ids = [s.session_id for s in inputs]exception_message = (- f"Too many sessions failed to summarize, when summarizing {len(inputs)} sessions "- f"({logging_session_ids(session_ids)}) "+ f"Only {len(successful_sessions)} of {len(inputs)} sessions summarized successfully "+ f"(need at least {min_required} to build group patterns), "+ f"when summarizing sessions ({logging_session_ids(session_ids)}) "f"for user {inputs[0].user_id} in team {inputs[0].team_id}")temporalio.workflow.logger.error(@@ -362,16 +386,21 @@ class SummarizeSessionGroupWorkflow(PostHogWorkflow):f"Pattern extraction failed for chunk {chunk_redis_key} containing sessions {chunk_session_ids}: {res}",extra={"signals_type": "session-summaries"},)+ # Don't overwrite earlier per-session reasons; those are more precise than "chunk failed".+ for sid in chunk_session_ids:+ if sid not in self._failed_sessions:+ self._failed_sessions[sid] = FailedSessionInfo(+ session_id=sid,+ category="patterns_failed",+ reason="Couldn't extract behavior patterns for this session",+ )continue# Store only chunks of sessions were extracted successfullyredis_keys_of_chunks_to_combine.append(chunk_redis_key)session_ids_with_patterns_extracted.extend(chunk_session_ids)- # Check failure ratio- if ceil(len(chunks) * FAILED_PATTERNS_EXTRACTION_MIN_RATIO) > len(redis_keys_of_chunks_to_combine):- msg = (- f"Too many chunks failed during pattern extraction: "- f"{len(chunks) - len(redis_keys_of_chunks_to_combine)}/{len(chunks)} chunks failed"- )+ # Abort only when every chunk failed; partial successes combine into a usable patterns set.+ if not redis_keys_of_chunks_to_combine:+ msg = f"All {len(chunks)} pattern-extraction chunks failed, nothing to combine"temporalio.workflow.logger.error(msg, extra={"signals_type": "session-summaries"})raise ApplicationError(msg)# If enough chunks succeeded - combine patterns extracted from chunks in a single list@@ -447,6 +476,8 @@ class SummarizeSessionGroupWorkflow(PostHogWorkflow):extra_summary_context=inputs.extra_summary_context,redis_key_base=inputs.redis_key_base,trigger_session_id=inputs.trigger_session_id,+ # Sorted for deterministic run_metadata.+ failed_sessions=sorted(self._failed_sessions.values(), key=lambda fs: fs.session_id),),start_to_close_timeout=timedelta(minutes=30),retry_policy=RetryPolicy(maximum_attempts=3),@@ -483,7 +514,7 @@ async def _start_session_group_summary_workflow() -> AsyncGenerator[tuple[SessionSummaryStreamUpdate,- tuple[EnrichedSessionGroupSummaryPatternsList, str] | str | SessionProgressStreamData,+ tuple[EnrichedSessionGroupSummaryPatternsList, str, list[FailedSessionInfo]] | str | SessionProgressStreamData,],None,]:@@ -528,9 +559,20 @@ async def _start_session_group_summary_workflow(raise ApplicationError(msg)# Parse the summary JSON into EnrichedSessionGroupSummaryPatternsListpatterns = EnrichedSessionGroupSummaryPatternsList.model_validate_json(session_group_summary.summary)+ # Re-read failed_sessions so callers can distinguish partial from clean runs.+ run_metadata_dict = session_group_summary.run_metadata or {}+ failed_sessions_dicts = run_metadata_dict.get("failed_sessions") or []+ failed_sessions = [+ FailedSessionInfo(+ session_id=fs["session_id"],+ category=fs["category"],+ reason=fs["reason"],+ )+ for fs in failed_sessions_dicts+ ]yield (SessionSummaryStreamUpdate.FINAL_RESULT,- (patterns, summary_id),+ (patterns, summary_id, failed_sessions),)break# Workflow failed - raise an exception@@ -622,7 +664,7 @@ async def execute_summarize_session_group() -> AsyncGenerator[tuple[SessionSummaryStreamUpdate,- tuple[EnrichedSessionGroupSummaryPatternsList, str] | str | SessionProgressStreamData,+ tuple[EnrichedSessionGroupSummaryPatternsList, str, list[FailedSessionInfo]] | str | SessionProgressStreamData,],None,]:diff --git a/posthog/temporal/tests/session_replay/session_summary/conftest.py b/posthog/temporal/tests/session_replay/session_summary/conftest.pyindex 49c976dfd46a..69323df2e398 100644--- a/posthog/temporal/tests/session_replay/session_summary/conftest.py+++ b/posthog/temporal/tests/session_replay/session_summary/conftest.py@@ -144,7 +144,7 @@ def mock_patterns_extraction_yaml_response() -> str:@pytest.fixturedef mock_patterns_assignment_yaml_response() -> str:"""Mock YAML response for pattern assignment"""- # All patterns need events assigned to meet the FAILED_PATTERNS_ASSIGNMENT_MIN_RATIO threshold+ # Cover every pattern so combine_patterns_with_events_context sees full assignments.return """patterns:- pattern_id: 1event_ids: ["abcd1234", "defg4567"]diff --git a/posthog/temporal/tests/session_replay/session_summary_group/test_fan_out.py b/posthog/temporal/tests/session_replay/session_summary_group/test_fan_out.pyindex 7a42b2500f3d..58339513ebc2 100644--- a/posthog/temporal/tests/session_replay/session_summary_group/test_fan_out.py+++ b/posthog/temporal/tests/session_replay/session_summary_group/test_fan_out.py@@ -56,13 +56,15 @@ async def test_run_summary_returns_exception_on_failure():@pytest.mark.asyncio-async def test_run_summaries_isolates_per_session_failures_when_above_threshold():+async def test_run_summaries_keeps_partial_results_above_threshold():+ # N=10, threshold=3, 7 successes: well above. Failures get tagged for the banner.workflow = SummarizeSessionGroupWorkflow()- workflow._total_sessions = 4+ workflow._total_sessions = 10- inputs = [_input(f"sess-{i}") for i in range(4)]- # 3 succeed, 1 fails — ratio = 0.75 > FAILED_SESSION_SUMMARIES_MIN_RATIO (0.5)- side_effects = [None, RuntimeError("boom"), None, None]+ inputs = [_input(f"sess-{i}") for i in range(10)]+ side_effects = [None, None, RuntimeError("a"), None, None, RuntimeError("b"), None, None, RuntimeError("c"), None]+ expected_success_ids = {"sess-0", "sess-1", "sess-3", "sess-4", "sess-6", "sess-7", "sess-9"}+ expected_failed_ids = {"sess-2", "sess-5", "sess-8"}with (_patch_workflow_logger(),@@ -73,24 +75,27 @@ async def test_run_summaries_isolates_per_session_failures_when_above_threshold():result = await workflow._run_summaries(inputs)- assert len(result) == 3- assert {r.session_id for r in result} == {"sess-0", "sess-2", "sess-3"}- assert workflow._session_statuses["sess-1"] == "failed"--+ assert {r.session_id for r in result} == expected_success_ids+ for failed_id in expected_failed_ids:+ assert workflow._session_statuses[failed_id] == "failed"+ assert failed_id in workflow._failed_sessions+ assert workflow._failed_sessions[failed_id].category == "summarization_failed"+++ "side_effects",+ [+ [RuntimeError("a"), RuntimeError("b"), RuntimeError("c")],+ [None, RuntimeError("a"), RuntimeError("b"), RuntimeError("c"), RuntimeError("d")],+ [None] + [RuntimeError(f"boom-{i}") for i in range(29)],+ ],+)@pytest.mark.asyncio-async def test_run_summaries_raises_when_too_many_fail():+async def test_run_summaries_aborts_below_threshold(side_effects):workflow = SummarizeSessionGroupWorkflow()- workflow._total_sessions = 4+ workflow._total_sessions = len(side_effects)- inputs = [_input(f"sess-{i}") for i in range(4)]- # 1 succeeds, 3 fail — ratio = 0.25 < FAILED_SESSION_SUMMARIES_MIN_RATIO (0.5)- side_effects = [- None,- RuntimeError("a"),- RuntimeError("b"),- RuntimeError("c"),- ]+ inputs = [_input(f"sess-{i}") for i in range(len(side_effects))]with (_patch_workflow_logger(),@@ -99,7 +104,7 @@ async def test_run_summaries_raises_when_too_many_fail():new=AsyncMock(side_effect=side_effects),),):- with pytest.raises(ApplicationError, match="Too many sessions failed to summarize"):+ with pytest.raises(ApplicationError, match="sessions summarized successfully"):await workflow._run_summaries(inputs)diff --git a/posthog/temporal/tests/session_replay/session_summary_group/test_workflow.py b/posthog/temporal/tests/session_replay/session_summary_group/test_workflow.pyindex e934c080ca0f..f14fbf588fd0 100644--- a/posthog/temporal/tests/session_replay/session_summary_group/test_workflow.py+++ b/posthog/temporal/tests/session_replay/session_summary_group/test_workflow.py@@ -57,6 +57,7 @@ from posthog.temporal.session_replay.session_summary_group.activities.group_pattsplit_session_summaries_into_chunks_for_patterns_extraction_activity,)from posthog.temporal.session_replay.session_summary_group.types import (+ FailedSessionInfo,SessionGroupSummaryOfSummariesInputs,SessionGroupSummaryPatternsExtractionChunksInputs,SessionSummaryStreamUpdate,@@ -273,7 +274,22 @@ async def test_assign_events_to_patterns_activity_standalone(single_session_inputs = [mock_single_session_summary_inputs(session_id, ateam.id, auser.id) for session_id in session_ids]- activity_input = mock_session_group_summary_of_summaries_inputs(single_session_inputs, auser.id, ateam.id)+ mock_failed_sessions = [+ FailedSessionInfo(+ session_id="failed-skipped-1",+ category="skipped",+ reason="Recording is too short or has no usable events",+ ),+ FailedSessionInfo(+ session_id="failed-summarize-1",+ category="summarization_failed",+ reason="Couldn't generate a summary for this session",+ ),+ ]+ activity_input = dataclasses.replace(+ mock_session_group_summary_of_summaries_inputs(single_session_inputs, auser.id, ateam.id),+ failed_sessions=mock_failed_sessions,+ )redis_client = get_async_client()# Store session summaries in DB for each session (following the new approach)@@ -353,6 +369,20 @@ async def test_assign_events_to_patterns_activity_standalone(# Verify the summary contentpatterns = EnrichedSessionGroupSummaryPatternsList.model_validate_json(session_group_summary.summary)assert len(patterns.patterns) >= 1 # Should have at least one pattern+ assert session_group_summary.run_metadata is not None+ persisted_failed = session_group_summary.run_metadata.get("failed_sessions")+ assert persisted_failed == [+ {+ "session_id": "failed-skipped-1",+ "category": "skipped",+ "reason": "Recording is too short or has no usable events",+ },+ {+ "session_id": "failed-summarize-1",+ "category": "summarization_failed",+ "reason": "Couldn't generate a summary for this session",+ },+ ]# Verify LLM was called (for pattern assignment)mock_call_llm.assert_called() # May be called multiple times for chunks# Verify Redis operations:@@ -972,7 +1002,7 @@ class TestSummarizeSessionGroupWorkflow:async def mock_workflow_generator():"""Mock async generator that yields only the final result"""- yield (SessionSummaryStreamUpdate.FINAL_RESULT, (expected_patterns, "session-group-summary-id"))+ yield (SessionSummaryStreamUpdate.FINAL_RESULT, (expected_patterns, "session-group-summary-id", []))with patch("posthog.temporal.session_replay.session_summary_group.workflow._start_session_group_summary_workflow",@@ -993,7 +1023,7 @@ class TestSummarizeSessionGroupWorkflow:assert len(results) == 1assert results[0] == (SessionSummaryStreamUpdate.FINAL_RESULT,- (expected_patterns, "session-group-summary-id"),+ (expected_patterns, "session-group-summary-id", []),)@pytest.mark.asyncio@@ -1066,11 +1096,13 @@ class TestSummarizeSessionGroupWorkflow:update_type, data = results[0]assert update_type == SessionSummaryStreamUpdate.FINAL_RESULTassert isinstance(data, tuple)- patterns, returned_summary_id = data+ patterns, returned_summary_id, failed_sessions = dataassert returned_summary_id == summary_idassert isinstance(patterns, EnrichedSessionGroupSummaryPatternsList)assert len(patterns.patterns) == 1assert patterns.patterns[0].pattern_name == "Mock Pattern from DB"+ # No failed_sessions in run_metadata for this fixture.+ assert failed_sessions == []@pytest.mark.asyncioasync def test_summarize_session_group_workflow(diff --git a/products/session_summaries/frontend/SessionGroupSummaryScene.tsx b/products/session_summaries/frontend/SessionGroupSummaryScene.tsxindex e8d41d93e384..a05b76acb587 100644--- a/products/session_summaries/frontend/SessionGroupSummaryScene.tsx+++ b/products/session_summaries/frontend/SessionGroupSummaryScene.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { useEffect, useMemo, useRef, useState } from 'react'-import { IconCheck, IconSearch, IconShare, IconSort } from '@posthog/icons'+import { IconCheck, IconSearch, IconShare, IconSort, IconSparkles } from '@posthog/icons'import {LemonBanner,LemonButton,@@ -30,11 +30,106 @@ import { SessionGroupSummarySceneLogicProps, sessionGroupSummarySceneLogic } froimport {EnrichedSessionGroupSummaryPattern,EnrichedSessionGroupSummaryPatternsList,+ FailedSessionCategory,+ FailedSessionInfo,PatternAssignedEventSegmentContext,SeverityLevel,} from './types'import { getIssueTags } from './utils'+const FAILED_SESSION_CATEGORY_LABELS: Record<FailedSessionCategory, string> = {+ skipped: 'Skipped',+ summarization_failed: "Couldn't summarize",+ patterns_failed: "Couldn't extract patterns",+}++function PartialResultBanner({+ failedSessions,+ analyzedSessionCount,+}: {+ failedSessions: FailedSessionInfo[]+ analyzedSessionCount: number+}): JSX.Element | null {+ if (failedSessions.length === 0) {+ return null+ }+ const totalSessions = analyzedSessionCount + failedSessions.length+ const grouped = failedSessions.reduce<Record<FailedSessionCategory, FailedSessionInfo[]>>(+ (acc, fs) => {+ acc[fs.category] = acc[fs.category] ?? []+ acc[fs.category].push(fs)+ return acc+ },+ { skipped: [], summarization_failed: [], patterns_failed: [] }+ )+ return (+ <div className="border border-ai bg-ai/08 dark:bg-ai/20 rounded-lg overflow-hidden mb-2">+ <LemonCollapse+ size="small"+ embedded+ panels={[+ {+ key: 'failed-sessions',+ header: (+ <div className="flex items-center gap-2">+ <IconSparkles className="text-ai shrink-0" />+ <span className="text-sm font-medium">+ Analyzed {analyzedSessionCount} of {totalSessions} sessions+ </span>+ <span className="text-xs text-secondary">· {failedSessions.length} not included</span>+ </div>+ ),+ content: (+ <div className="flex flex-col gap-3 pt-1">+ <p className="text-xs text-secondary mb-0">+ The patterns below are based on the {analyzedSessionCount} sessions that succeeded.+ </p>+ {(Object.keys(grouped) as FailedSessionCategory[])+ .filter((category) => grouped[category].length > 0)+ .map((category) => {+ const items = grouped[category]+ const isClickable = category !== 'skipped'+ return (+ <div key={category} className="flex flex-col gap-1.5">+ <p className="text-xs text-secondary mb-0">+ <span className="font-medium">+ {FAILED_SESSION_CATEGORY_LABELS[category]} ({items.length})+ </span>{' '}+ · {items[0].reason}+ </p>+ <div className="flex flex-wrap gap-1.5">+ {items.map((fs) =>+ isClickable ? (+ <Tooltip key={fs.session_id} title="Open in player">+ <LemonButton+ size="xsmall"+ type="secondary"+ icon={<IconPlayCircle />}+ to={urls.replaySingle(fs.session_id)}+ targetBlank+ >+ {fs.session_id}+ </LemonButton>+ </Tooltip>+ ) : (+ <LemonTag key={fs.session_id} size="small" type="muted">+ {fs.session_id}+ </LemonTag>+ )+ )}+ </div>+ </div>+ )+ })}+ </div>+ ),+ },+ ]}+ />+ </div>+ )+}+export const scene: SceneExport<SessionGroupSummarySceneLogicProps> = {component: SessionGroupSummary,logic: sessionGroupSummarySceneLogic,@@ -440,7 +535,10 @@ export function SessionGroupSummary(): JSX.Element {</SceneContent>)}- const totalSessions = sessionGroupSummary.session_ids.length+ // `session_ids` is the analyzed subset; the original request is analyzed + failed.+ const analyzedSessionsCount = sessionGroupSummary.session_ids.length+ const failedSessions = sessionGroupSummary.run_metadata?.failed_sessions ?? []+ const requestedSessionsCount = analyzedSessionsCount + failedSessions.lengthreturn (<SceneContent><SceneTitleSection@@ -468,7 +566,11 @@ export function SessionGroupSummary(): JSX.Element {<div className="flex flex-wrap items-center justify-between gap-3 text-sm text-muted"><div className="flex items-center gap-3"><LemonTag type="warning">BETA</LemonTag>- <span>{totalSessions} sessions analyzed</span>+ <span>+ {failedSessions.length > 0+ ? `${analyzedSessionsCount} of ${requestedSessionsCount} sessions analyzed`+ : `${analyzedSessionsCount} sessions analyzed`}+ </span><span className="hidden sm:inline">·</span><span>{new Date(sessionGroupSummary.created_at).toLocaleString()}</span></div>@@ -492,6 +594,7 @@ export function SessionGroupSummary(): JSX.Element {</LemonMenu></div><div className="space-y-4">+ <PartialResultBanner failedSessions={failedSessions} analyzedSessionCount={analyzedSessionsCount} /><FilterBarsearchValue={searchValue}onSearchChange={setSearchValue}diff --git a/products/session_summaries/frontend/types.ts b/products/session_summaries/frontend/types.tsindex bd2221f5cd56..d813e128556a 100644--- a/products/session_summaries/frontend/types.ts+++ b/products/session_summaries/frontend/types.ts@@ -60,6 +60,24 @@ export interface EnrichedSessionGroupSummaryPatternsList {patterns: EnrichedSessionGroupSummaryPattern[]}+// Matches FailedSessionCategory from ee/models/session_summaries.py+export type FailedSessionCategory = 'skipped' | 'summarization_failed' | 'patterns_failed'++// Matches FailedSessionInfo from ee/models/session_summaries.py+export interface FailedSessionInfo {+ session_id: string+ category: FailedSessionCategory+ reason: string+}++// Matches SessionSummaryRunMeta from ee/models/session_summaries.py.+// Add new fields explicitly; no index signature (kills autocomplete, lets typos pass).+export interface SessionGroupSummaryRunMetadata {+ model_used?: string+ visual_confirmation?: boolean+ failed_sessions?: FailedSessionInfo[]+}+export type SessionGroupSummaryListItemType = {id: stringtitle: string@@ -72,7 +90,7 @@ export type SessionGroupSummaryType = SessionGroupSummaryListItemType & {session_ids: string[]summary: stringextra_summary_context: Record<string, any> | null- run_metadata: Record<string, any> | null+ run_metadata: SessionGroupSummaryRunMetadata | nullteam: number}