:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(replay): keep partial group summary patterns instead of failing (#77468)
Arno Hillenc24b7670cb55
diff --git a/ee/hogai/session_summaries/constants.py b/ee/hogai/session_summaries/constants.pyindex 54672ac9b4f3..f29036991e53 100644--- a/ee/hogai/session_summaries/constants.py+++ b/ee/hogai/session_summaries/constants.py@@ -38,7 +38,6 @@ PATTERNS_ASSIGNMENT_CHUNK_SIZE = 10 # How many single-session-summaries to feed# 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_ENRICHMENT_MIN_RATIO = 0.75 # If less than 75% of patterns were enriched with the meta# LoggingMAX_SESSION_IDS_COMBINED_LOGGING_LENGTH = 150 # Maximum string of combined session ids to log in a readable formatdiff --git a/ee/hogai/session_summaries/session_group/patterns.py b/ee/hogai/session_summaries/session_group/patterns.pyindex 04f3e7cb4af6..6109be69c4e1 100644--- a/ee/hogai/session_summaries/session_group/patterns.py+++ b/ee/hogai/session_summaries/session_group/patterns.py@@ -1,6 +1,5 @@import dataclassesfrom enum import Enum-from math import floorfrom typing import Anyimport structlog@@ -14,7 +13,6 @@ from posthog.personhog_client.caller_tag import personhog_caller_tagfrom products.replay.backend.models.session_summaries import SingleSessionSummaryfrom ee.hogai.session_summaries import SummaryValidationError-from ee.hogai.session_summaries.constants import FAILED_PATTERNS_ENRICHMENT_MIN_RATIOfrom ee.hogai.session_summaries.session.output_data import SessionSummaryIssueTypes, SessionSummarySerializerfrom ee.hogai.session_summaries.session.summarize_session import SingleSessionSummaryLlmInputsfrom ee.hogai.session_summaries.utils import logging_session_ids@@ -493,20 +491,26 @@ def combine_patterns_with_events_context(stats=_calculate_pattern_stats(pattern_events, len(session_ids)),)combined_patterns.append(enriched_pattern)- # If not enough patterns were properly enriched - fail the activity- # Using `floor` as for small numbers of patterns - >30% could be filtered as "non-blocking only"- minimum_expected_patterns_count = max(1, floor(len(patterns.patterns) * FAILED_PATTERNS_ENRICHMENT_MIN_RATIO))successful_patterns_count = len(combined_patterns)failed_patterns_count = len(patterns.patterns) - successful_patterns_count- if minimum_expected_patterns_count > successful_patterns_count:+ # Fail only when patterns exist but none could be enriched - a partial report is still useful,+ # while failing the whole group summary over a few dropped patterns leaves the user with nothing+ if patterns.patterns and not combined_patterns:exception_message = (- f"Too many patterns failed to enrich with session meta, when summarizing {len(session_ids)} "+ f"No patterns could be enriched with session meta, when summarizing {len(session_ids)} "f"sessions ({logging_session_ids(session_ids)}) for user {user_id}. "- f"Input: {len(patterns.patterns)}; success: {successful_patterns_count} "- f"(enriched: {len(combined_patterns)}); failure: {failed_patterns_count}"+ f"Input: {len(patterns.patterns)}")logger.exception(exception_message, user_id=user_id, signals_type="session-summaries")raise ApplicationError(exception_message)+ if failed_patterns_count:+ logger.warning(+ f"Some patterns failed to enrich with session meta, when summarizing {len(session_ids)} "+ f"sessions ({logging_session_ids(session_ids)}) for user {user_id}. "+ f"Input: {len(patterns.patterns)}; success: {successful_patterns_count}; failure: {failed_patterns_count}",+ user_id=user_id,+ signals_type="session-summaries",+ )severity_order = {"critical": 0, "high": 1, "medium": 2, "low": 3}combined_patterns.sort(key=lambda p: severity_order.get(p.severity.value, 3))return EnrichedSessionGroupSummaryPatternsList(patterns=combined_patterns)diff --git a/ee/hogai/tools/replay/summarize_sessions.py b/ee/hogai/tools/replay/summarize_sessions.pyindex f6d325cbc911..8cfa39204b71 100644--- a/ee/hogai/tools/replay/summarize_sessions.py+++ b/ee/hogai/tools/replay/summarize_sessions.py@@ -411,9 +411,12 @@ class SummarizeSessionsTool(MaxTool):)logger.error(msg, signals_type="session-summaries")raise ValueError(msg)- # 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()+ 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,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 ca1b7fec788f..f9cd1c980e20 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@@ -41,6 +41,7 @@ from ee.hogai.session_summaries.llm.consume import ()from ee.hogai.session_summaries.session.summarize_session import ExtraSummaryContextfrom ee.hogai.session_summaries.session_group.patterns import (+ EnrichedSessionGroupSummaryPatternsList,RawSessionGroupPatternAssignmentsList,RawSessionGroupSummaryPattern,RawSessionGroupSummaryPatternsList,@@ -368,6 +369,35 @@ async def assign_events_to_patterns_activity(output_label=StateActivitiesEnum.SESSION_GROUP_PATTERNS_ASSIGNMENTS,state_id=generate_state_id_from_session_ids(session_ids),)+ # Get extracted patterns from Redis to be able to assign events to them+ patterns_extraction_raw = await get_data_class_from_redis(+ redis_client=redis_client,+ redis_key=redis_input_key,+ label=StateActivitiesEnum.SESSION_GROUP_EXTRACTED_PATTERNS,+ target_class=RawSessionGroupSummaryPatternsList,+ )+ if patterns_extraction_raw is None:+ # No reason to retry activity, as the data from the previous activity is not in Redis+ raise ApplicationError(+ f"No patterns extraction found for sessions {logging_session_ids(session_ids)} when assigning events to patterns",+ non_retryable=True,+ )+ patterns_extraction = cast(+ RawSessionGroupSummaryPatternsList,+ patterns_extraction_raw,+ )+ # No patterns across the sessions is a valid outcome, not an error, so store an empty summary+ # instead of failing the workflow (retries can't help, as the extraction result is cached)+ if not patterns_extraction.patterns:+ temporalio.activity.logger.info(+ f"No patterns extracted for sessions {logging_session_ids(session_ids)}, storing an empty group summary",+ extra={"user_id": inputs.user_id, "team_id": inputs.team_id, "signals_type": "session-summaries"},+ )+ return await _store_session_group_summary(+ inputs=inputs,+ session_ids=session_ids,+ patterns=EnrichedSessionGroupSummaryPatternsList(patterns=[]),+ )# Get ready session summaries from DB# Disable thread-sensitive as the call is heavy (N summaries through pagination)ready_summaries = await database_sync_to_async(get_ready_summaries_from_db, thread_sensitive=False)(@@ -395,23 +425,6 @@ async def assign_events_to_patterns_activity(intermediate_session_summaries_str[i : i + PATTERNS_ASSIGNMENT_CHUNK_SIZE]for i in range(0, len(intermediate_session_summaries_str), PATTERNS_ASSIGNMENT_CHUNK_SIZE)]- # Get extracted patterns from Redis to be able to assign events to them- patterns_extraction_raw = await get_data_class_from_redis(- redis_client=redis_client,- redis_key=redis_input_key,- label=StateActivitiesEnum.SESSION_GROUP_EXTRACTED_PATTERNS,- target_class=RawSessionGroupSummaryPatternsList,- )- if patterns_extraction_raw is None:- # No reason to retry activity, as the data from the previous activity is not in Redis- raise ApplicationError(- f"No patterns extraction found for sessions {logging_session_ids(session_ids)} when assigning events to patterns",- non_retryable=True,- )- patterns_extraction = cast(- RawSessionGroupSummaryPatternsList,- patterns_extraction_raw,- )# Assign events <> patterns through LLM calls in chunks to keep the content meaningfulpatterns_assignments_list_of_lists = await _generate_patterns_assignments(patterns=patterns_extraction,@@ -448,7 +461,19 @@ async def assign_events_to_patterns_activity(session_ids=session_ids,user_id=inputs.user_id,)- # Store data in DB to be able to display in the UI+ return await _store_session_group_summary(+ inputs=inputs,+ session_ids=session_ids,+ patterns=patterns_with_events_context,+ )+++async def _store_session_group_summary(+ inputs: SessionGroupSummaryOfSummariesInputs,+ session_ids: list[str],+ patterns: EnrichedSessionGroupSummaryPatternsList,+) -> str:+ """Store the group summary in DB to be able to display it in the UI. Returns session_group_summary_id."""try:user = await database_sync_to_async(User.objects.get, thread_sensitive=False)(id=inputs.user_id)except User.DoesNotExist:@@ -459,7 +484,7 @@ async def assign_events_to_patterns_activity(team_id=inputs.team_id,title=inputs.summary_title or "Group summary",session_ids=session_ids,- summary=patterns_with_events_context.model_dump_json(exclude_none=True),+ summary=patterns.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 levelrun_metadata=asdict(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 f5859341c9f3..febac26cde64 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@@ -394,7 +394,7 @@ async def test_assign_events_to_patterns_activity_standalone(@pytest.mark.asyncio-async def test_assign_events_to_patterns_threshold_check(+async def test_assign_events_to_patterns_enrichment_outcomes(mock_session_id: str,mock_session_summary_serializer: SessionSummarySerializer,mock_single_session_summary_inputs: Callable,@@ -403,7 +403,6 @@ async def test_assign_events_to_patterns_threshold_check(auser: User,ateam: Team,):- """Test that assign_events_to_patterns_activity fails when too few patterns get events assigned"""# Prepare input datasession_ids = [f"{mock_session_id}-1", f"{mock_session_id}-2"]single_session_inputs = [@@ -466,7 +465,7 @@ async def test_assign_events_to_patterns_threshold_check()redis_test_setup.keys_to_cleanup.append(patterns_key)- # Test 1: Should fail when only 2 out of 4 patterns get events (50% < 75% threshold)+ # Case 1: only 2 out of 4 patterns get events - the enriched subset is returned instead of failingwith (patch("ee.hogai.session_summaries.llm.consume.call_llm") as mock_call_llm,patch("temporalio.activity.info") as mock_activity_info,@@ -484,20 +483,21 @@ async def test_assign_events_to_patterns_threshold_check(mock_client.get_workflow_handle = MagicMock(return_value=mock_workflow_handle)mock_async_connect.return_value = mock_client# Mock LLM response that only assigns events to 2 patterns- patterns_assignment_fail = """patterns:+ patterns_assignment_partial = """patterns:- pattern_id: 1event_ids: ["abcd1234"]- pattern_id: 2event_ids: ["ghij7890"]"""- mock_llm_response = _build_openai_response(patterns_assignment_fail)+ mock_llm_response = _build_openai_response(patterns_assignment_partial)mock_call_llm.return_value = mock_llm_response- # Should raise ApplicationError due to threshold failure- with pytest.raises(ApplicationError, match="Too many patterns failed to enrich with session meta"):- await assign_events_to_patterns_activity(activity_input)+ summary_id = await assign_events_to_patterns_activity(activity_input)+ session_group_summary = await SessionGroupSummary.objects.aget(id=summary_id)+ result = EnrichedSessionGroupSummaryPatternsList.model_validate_json(session_group_summary.summary)+ assert sorted(pattern.pattern_id for pattern in result.patterns) == [1, 2]- # Test 2: Should succeed when 3 out of 4 patterns get events (75% == 75% threshold)+ # Case 2: no assigned event id resolves to a known event - nothing can be enriched, so the activity failswith (patch("ee.hogai.session_summaries.llm.consume.call_llm") as mock_call_llm,patch("temporalio.activity.info") as mock_activity_info,@@ -514,26 +514,58 @@ async def test_assign_events_to_patterns_threshold_check(mock_client = MagicMock()mock_client.get_workflow_handle = MagicMock(return_value=mock_workflow_handle)mock_async_connect.return_value = mock_client- # Mock LLM response that assigns events to 3 patterns- patterns_assignment_success = """patterns:+ # Mock LLM response that assigns only event ids that don't exist in any session summary+ patterns_assignment_unmappable = """patterns:- pattern_id: 1- event_ids: ["abcd1234"]+ event_ids: ["zzzz0001"]- pattern_id: 2- event_ids: ["ghij7890"]- - pattern_id: 3- event_ids: ["mnop3456"]+ event_ids: ["zzzz0002"]"""- mock_llm_response = _build_openai_response(patterns_assignment_success)+ mock_llm_response = _build_openai_response(patterns_assignment_unmappable)mock_call_llm.return_value = mock_llm_response- # Should succeed - now returns just the summary id+ with pytest.raises(ApplicationError, match="No patterns could be enriched with session meta"):+ await assign_events_to_patterns_activity(activity_input)+++async def test_assign_events_to_patterns_stores_empty_summary_when_no_patterns_extracted(+ mock_session_id: str,+ mock_single_session_summary_inputs: Callable,+ mock_session_group_summary_of_summaries_inputs: Callable,+ redis_test_setup: AsyncRedisTestContext,+ auser: User,+ ateam: Team,+):+ session_ids = [f"{mock_session_id}-1", f"{mock_session_id}-2"]+ 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)+ redis_client = get_async_client()++ # Store an extraction result with no patterns, as the LLM found nothing in common between sessions+ patterns_key = generate_state_key(+ key_base=activity_input.redis_key_base,+ label=StateActivitiesEnum.SESSION_GROUP_EXTRACTED_PATTERNS,+ state_id=generate_state_id_from_session_ids(session_ids),+ )+ await store_data_in_redis(+ redis_client=redis_client,+ redis_key=patterns_key,+ data=RawSessionGroupSummaryPatternsList(patterns=[]).model_dump_json(exclude_none=True),+ label=StateActivitiesEnum.SESSION_GROUP_EXTRACTED_PATTERNS,+ )+ redis_test_setup.keys_to_cleanup.append(patterns_key)++ with patch("ee.hogai.session_summaries.llm.consume.call_llm") as mock_call_llm:summary_id = await assign_events_to_patterns_activity(activity_input)- assert isinstance(summary_id, str)- # Fetch the result from DB- session_group_summary = await SessionGroupSummary.objects.aget(id=summary_id)- result = EnrichedSessionGroupSummaryPatternsList.model_validate_json(session_group_summary.summary)- assert isinstance(result, EnrichedSessionGroupSummaryPatternsList)- assert len(result.patterns) == 3 # Should have 3 patterns with events++ # An empty summary is stored without any LLM calls, instead of failing the activity+ mock_call_llm.assert_not_called()+ session_group_summary = await SessionGroupSummary.objects.aget(id=summary_id)+ result = EnrichedSessionGroupSummaryPatternsList.model_validate_json(session_group_summary.summary)+ assert result.patterns == []@pytest.mark.asyncio