: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): show clear summary errors for no-events and out-of-range recordings (#63985)
Tue Haulund3ea3f04aa438
diff --git a/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.test.ts b/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.test.tsindex 8eb740c0d1db..deb5588ec20c 100644--- a/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.test.ts+++ b/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.test.ts@@ -1,7 +1,8 @@import { expectLogic } from 'kea-test-utils'+import { dayjs } from 'lib/dayjs'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'-import { playerMetaLogic } from 'scenes/session-recordings/player/player-meta/playerMetaLogic'+import { hasSummarizableEvents, playerMetaLogic } from 'scenes/session-recordings/player/player-meta/playerMetaLogic'import { sessionRecordingDataCoordinatorLogic } from 'scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic'import { sessionRecordingPlayerLogic } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'@@ -12,6 +13,7 @@ import { SessionRecordingType } from '~/types'import recordingEventsJson from '../../__mocks__/recording_events_query'import { recordingMetaJson } from '../../__mocks__/recording_meta'import { snapshotsAsJSONLines } from '../../__mocks__/recording_snapshots'+import type { InspectorListItemEvent } from '../inspector/playerInspectorLogic'jest.mock('../snapshot-processing/DecompressionWorkerManager')@@ -72,4 +74,43 @@ describe('playerMetaLogic', () => {})})})++ describe('hasSummarizableEvents (gate mirrors backend filters)', () => {+ const start = dayjs('2026-01-01T00:00:00Z')+ const end = start.add(60, 'second')+ const makeEvent = (event: string, timestamp: typeof start): InspectorListItemEvent =>+ ({ type: 'events', timestamp, data: { event } }) as InspectorListItemEvent++ it('true for a normal event within the window', () => {+ expect(hasSummarizableEvents([makeEvent('$pageview', start.add(30, 'second'))], start, end)).toBe(true)+ })+ it('false when the only event is blocklisted ($feature_flag_called)', () => {+ expect(+ hasSummarizableEvents([makeEvent('$feature_flag_called', start.add(30, 'second'))], start, end)+ ).toBe(false)+ })+ it('false when the only event is within the start cutoff', () => {+ expect(hasSummarizableEvents([makeEvent('$pageview', start.add(2, 'second'))], start, end)).toBe(false)+ })+ it('false when the only event is within the end cutoff', () => {+ expect(hasSummarizableEvents([makeEvent('$pageview', end.subtract(2, 'second'))], start, end)).toBe(false)+ })+ it('true when at least one event survives the filters', () => {+ expect(+ hasSummarizableEvents(+ [+ makeEvent('$feature_flag_called', start.add(30, 'second')),+ makeEvent('$pageview', start.add(2, 'second')),+ makeEvent('custom_event', start.add(30, 'second')),+ ],+ start,+ end+ )+ ).toBe(true)+ })+ it('applies the blocklist but skips the timing check when start/end are unknown', () => {+ expect(hasSummarizableEvents([makeEvent('$pageview', start)], null, null)).toBe(true)+ expect(hasSummarizableEvents([makeEvent('$feature_flag_called', start)], null, null)).toBe(false)+ })+ })})diff --git a/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.tsx b/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.tsxindex c8bf06f0c5b6..8da76d8e82b2 100644--- a/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.tsx+++ b/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.tsx@@ -8,6 +8,7 @@ import { IconClock, IconCursorClick, IconHourglass, IconKeyboard, IconWarning }import { PropertyFilterIcon } from 'lib/components/PropertyFilters/components/PropertyFilterIcon'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { Dayjs } from 'lib/dayjs'import {capitalizeFirstLetter,ceilMsToClosestSecond,@@ -30,6 +31,7 @@ import { PersonType, PropertyFilterType, SessionRecordingType } from '~/types'import { sessionRecordingsListPropertiesLogic } from '../../playlist/sessionRecordingsListPropertiesLogic'import { SeekbarSegmentRange } from '../controller/SeekbarSegments'import { playerInspectorLogic } from '../inspector/playerInspectorLogic'+import type { InspectorListItemEvent } from '../inspector/playerInspectorLogic'import type { playerMetaLogicType } from './playerMetaLogicType'import { sessionRecordingPinnedPropertiesLogic } from './sessionRecordingPinnedPropertiesLogic'import { HARDCODED_DISPLAY_LABELS } from './sessionRecordingPinnedPropertiesLogic'@@ -38,6 +40,46 @@ import { SessionSummaryContent, SummarizationProgress } from './types'const recordingPropertyKeys = ['click_count', 'keypress_count', 'console_error_count'] as const+// The summary backend filters these out before summarizing, so mirror them here: the+// "Summarize" button should be disabled when every event would be filtered away (otherwise+// the user triggers a summary that fails with "This recording has no events to summarize").+// Keep in sync with SESSION_SUMMARY_EVENT_BLOCKLIST and SESSION_EVENTS_REPLAY_CUTOFF_MS in+// ee/hogai/session_summaries/constants.py.+const SUMMARY_EVENT_MINI_FILTER_KEYS = [+ 'events-posthog',+ 'events-custom',+ 'events-pageview',+ 'events-autocapture',+ 'events-exceptions',+]+const SUMMARY_EVENT_BLOCKLIST = ['$feature_flag_called']+const SUMMARY_EVENTS_REPLAY_CUTOFF_MS = 5000++/**+ * Whether any event would survive the backend summary filters — i.e. is not blocklisted and+ * does not fall within the replay cutoff of the recording start/end. Mirrors the backend so+ * the Summarize button is only enabled when a summary could actually be produced.+ */+export function hasSummarizableEvents(+ eventItems: InspectorListItemEvent[],+ start: Dayjs | null,+ end: Dayjs | null+): boolean {+ return eventItems.some((item) => {+ if (SUMMARY_EVENT_BLOCKLIST.includes(item.data.event)) {+ return false+ }+ if (start && end) {+ const msSinceStart = item.timestamp.diff(start)+ const msTillEnd = end.diff(item.timestamp)+ if (msSinceStart <= SUMMARY_EVENTS_REPLAY_CUTOFF_MS || msTillEnd <= SUMMARY_EVENTS_REPLAY_CUTOFF_MS) {+ return false+ }+ }+ return true+ })+}+function getAllPersonProperties(sessionPlayerMetaData: SessionRecordingType | null): Record<string, any> {return sessionPlayerMetaData?.person?.properties ?? {}}@@ -191,16 +233,17 @@ export const playerMetaLogic = kea<playerMetaLogicType>([(feedbackBySessionId): boolean => !!feedbackBySessionId[props.sessionRecordingId],],summaryDisabledReason: [- (s) => [s.allItemsByMiniFilterKey],- (allItemsByMiniFilterKey): string | undefined => {- const hasAnyEvents = [- 'events-posthog',- 'events-custom',- 'events-pageview',- 'events-autocapture',- 'events-exceptions',- ].some((key) => allItemsByMiniFilterKey[key]?.length > 0)- return hasAnyEvents ? undefined : 'Session events are not available yet. Try again in a few minutes.'+ (s) => [s.allItemsByMiniFilterKey, s.sessionPlayerData],+ (allItemsByMiniFilterKey, sessionPlayerData): string | undefined => {+ const eventItems = SUMMARY_EVENT_MINI_FILTER_KEYS.flatMap(+ (key) => allItemsByMiniFilterKey[key] ?? []+ ).filter((item): item is InspectorListItemEvent => item.type === 'events')+ if (eventItems.length === 0) {+ return 'Session events are not available yet. Try again in a few minutes.'+ }+ return hasSummarizableEvents(eventItems, sessionPlayerData.start ?? null, sessionPlayerData.end ?? null)+ ? undefined+ : 'This recording has no events to summarize.'},],loading: [diff --git a/posthog/temporal/session_replay/session_summary/workflow.py b/posthog/temporal/session_replay/session_summary/workflow.pyindex 6be841dd6f59..007c3966a2d4 100644--- a/posthog/temporal/session_replay/session_summary/workflow.py+++ b/posthog/temporal/session_replay/session_summary/workflow.py@@ -29,6 +29,7 @@ from posthog.models.team.team import Teamfrom posthog.models.user import Userfrom posthog.redis import get_clientfrom posthog.session_recordings.ai_summary_cap import atomic_check_and_consume, refund+from posthog.session_recordings.queries.session_replay_events import SessionReplayEventsfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.base import PostHogWorkflowfrom posthog.temporal.common.client import async_connect@@ -71,7 +72,12 @@ from posthog.temporal.session_replay.session_summary.types.video import (from products.replay.backend.models.session_summaries import SingleSessionSummary-from ee.hogai.session_summaries.constants import DEFAULT_VIDEO_UNDERSTANDING_MODEL, SESSION_SUMMARIES_MODEL+from ee.hogai.session_summaries.constants import (+ DEFAULT_VIDEO_UNDERSTANDING_MODEL,+ MAX_ACTIVE_SECONDS_FOR_VIDEO_SUMMARY_S,+ MIN_SESSION_DURATION_FOR_VIDEO_SUMMARY_S,+ SESSION_SUMMARIES_MODEL,+)from ee.hogai.session_summaries.session.summarize_session import ExtraSummaryContextfrom ee.hogai.session_summaries.utils import serialize_to_sse_event@@ -82,6 +88,10 @@ SESSION_VIDEO_CHUNK_DURATION_S = 60# How large should the active period be, so we still analyze it (or skip it, if it's smaller)MIN_SESSION_PERIOD_DURATION_S = 1+# Returned by the workflow run() when the session has no events to summarize, so the+# streaming endpoint can surface a specific message instead of the generic error.+SUMMARY_RESULT_NO_EVENTS = "no_events"+# Drives the step counter in the get_progress query so the frontend can render "Step N of M".VIDEO_PHASE_ORDER: tuple[str, ...] = ("fetching_data",@@ -131,7 +141,7 @@ class SummarizeSingleSessionWorkflow(PostHogWorkflow):return cast(SingleSessionProgress, dict(self._progress))@temporalio.workflow.run- async def run(self, inputs: SingleSessionSummaryInputs) -> None:+ async def run(self, inputs: SingleSessionSummaryInputs) -> str | None:start_time = temporalio.workflow.now()progress = self._progress if inputs.video_based else None_set_phase(progress, "fetching_data")@@ -142,7 +152,9 @@ class SummarizeSingleSessionWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=3),)if not session_got_data:- return None+ # The session has no events to summarize — signal the reason so the+ # stream surfaces a clear message rather than a generic failure.+ return SUMMARY_RESULT_NO_EVENTSawait ensure_llm_single_session_summary(inputs, progress=progress)duration_seconds = (temporalio.workflow.now() - start_time).total_seconds()await temporalio.workflow.execute_activity(@@ -161,6 +173,8 @@ class SummarizeSingleSessionWorkflow(PostHogWorkflow):start_to_close_timeout=timedelta(seconds=30),retry_policy=RetryPolicy(maximum_attempts=2),)+ # Success path writes the summary to Postgres; no sentinel to return.+ return Nonedef _validate_period(@@ -827,6 +841,10 @@ async def execute_summarize_session_video_stream(client and workflow handle — both of which hold asyncio-bound state — arereused safely across iterations."""++ def error_event(message: str) -> str:+ return serialize_to_sse_event(event_label="session-summary-error", event_data=message)+# Fast path: if a summary already exists, yield it immediately and skip Temporal entirely.existing_summary = await database_sync_to_async(SingleSessionSummary.objects.get_summary, thread_sensitive=False)(team_id=team.id, session_id=session_id, extra_summary_context=extra_summary_context@@ -843,6 +861,36 @@ async def execute_summarize_session_video_stream()return+ # Length is knowable from cheap metadata, so reject too-short/too-long sessions up front+ # with a clear message rather than starting a doomed workflow. (The no-events case can only+ # be determined after fetching events, so it's signalled from inside the workflow instead.)+ try:+ metadata = await database_sync_to_async(SessionReplayEvents().get_metadata, thread_sensitive=False)(+ session_id=session_id, team=team+ )+ except Exception as e:+ # Don't block summarization on a flaky metadata read; downstream activities still guard length.+ logger.warning(+ "video summary length precheck skipped (metadata read failed)",+ session_id=session_id,+ error=str(e),+ signals_type="session-summaries",+ )+ metadata = None+ if metadata:+ if (metadata.get("duration") or 0) < MIN_SESSION_DURATION_FOR_VIDEO_SUMMARY_S:+ yield error_event(+ f"This recording is too short to summarize — recordings under "+ f"{MIN_SESSION_DURATION_FOR_VIDEO_SUMMARY_S} seconds can't be summarized."+ )+ return+ if (metadata.get("active_seconds") or 0) > MAX_ACTIVE_SECONDS_FOR_VIDEO_SUMMARY_S:+ yield error_event(+ f"This recording is too long to summarize — AI summaries are limited to "+ f"{MAX_ACTIVE_SECONDS_FOR_VIDEO_SUMMARY_S // 60} minutes of activity."+ )+ return+_, _, _, session_input, workflow_id = _prepare_execution(session_id=session_id,user=user,@@ -893,12 +941,9 @@ async def execute_summarize_session_video_stream(},groups=groups(None, team),)- yield serialize_to_sse_event(- event_label="session-summary-error",- event_data=(- "You've reached this team's monthly limit for AI session summaries "- f"({cap_decision.used}/{cap_decision.cap}). Try again next month."- ),+ yield error_event(+ "You've reached this team's monthly limit for AI session summaries "+ f"({cap_decision.used}/{cap_decision.cap}). Try again next month.")return@@ -930,21 +975,21 @@ async def execute_summarize_session_video_stream(while True:try:- status, _final_result = await _check_handle_data(handle)+ status, final_result = await _check_handle_data(handle)if status is None:await asyncio.sleep(VIDEO_PROGRESS_POLL_INTERVAL_S)continueif status == WorkflowExecutionStatus.COMPLETED:+ if final_result == SUMMARY_RESULT_NO_EVENTS:+ yield error_event("This recording has no events to summarize.")+ return# Workflow writes the summary to Postgres, doesn't return it.summary_row = await database_sync_to_async(SingleSessionSummary.objects.get_summary, thread_sensitive=False)(team_id=team.id, session_id=session_id, extra_summary_context=extra_summary_context)if not summary_row:- yield serialize_to_sse_event(- event_label="session-summary-error",- event_data="Something went wrong while generating the summary. Please try again.",- )+ yield error_event("Something went wrong while generating the summary. Please try again.")returnyield serialize_to_sse_event(event_label="session-summary-stream",@@ -964,10 +1009,7 @@ async def execute_summarize_session_video_stream(WorkflowExecutionStatus.TERMINATED: "The summary generation was terminated unexpectedly. Please try again.",WorkflowExecutionStatus.TIMED_OUT: "The summary generation timed out. The recording may be too long or complex. Please try again.",}- yield serialize_to_sse_event(- event_label="session-summary-error",- event_data=status_messages[status],- )+ yield error_event(status_messages[status])returnprogress_payload = await _fetch_summary_progress(client, handle)@@ -990,8 +1032,5 @@ async def execute_summarize_session_video_stream(await asyncio.sleep(VIDEO_PROGRESS_POLL_INTERVAL_S)except Exception as e:capture_exception(e)- yield serialize_to_sse_event(- event_label="session-summary-error",- event_data="Something went wrong while generating the summary. Please try again.",- )+ yield error_event("Something went wrong while generating the summary. Please try again.")returndiff --git a/posthog/temporal/tests/session_replay/session_summary/test_summarize_session.py b/posthog/temporal/tests/session_replay/session_summary/test_summarize_session.pyindex 23bdc6553ed0..dc2289dfe2d2 100644--- a/posthog/temporal/tests/session_replay/session_summary/test_summarize_session.py+++ b/posthog/temporal/tests/session_replay/session_summary/test_summarize_session.py@@ -1,5 +1,7 @@+import reimport jsonfrom collections.abc import AsyncGenerator, Callable, Iterator+from pathlib import Pathfrom types import SimpleNamespacefrom typing import Any@@ -12,6 +14,7 @@ from temporalio.common import WorkflowIDConflictPolicy, WorkflowIDReusePolicyfrom posthog.models import Teamfrom posthog.models.user import User+from posthog.session_recordings.queries.session_replay_events import SessionReplayEventsfrom posthog.temporal.session_replay.session_summary.activities.event_based.fetch_session_data import (fetch_session_data_activity,)@@ -22,6 +25,7 @@ from posthog.temporal.session_replay.session_summary.state import ()from posthog.temporal.session_replay.session_summary.types.inputs import SingleSessionProgressfrom posthog.temporal.session_replay.session_summary.workflow import (+ SUMMARY_RESULT_NO_EVENTS,_execute_single_session_summary_workflow,_set_phase,_start_video_summary_workflow,@@ -32,6 +36,7 @@ from posthog.temporal.tests.session_replay.session_summary.conftest import Asyncfrom products.replay.backend.models.session_summaries import SingleSessionSummary+from ee.hogai.session_summaries.constants import SESSION_EVENTS_REPLAY_CUTOFF_MS, SESSION_SUMMARY_EVENT_BLOCKLISTfrom ee.hogai.session_summaries.session.summarize_session import SingleSessionSummaryLlmInputsfrom ee.hogai.session_summaries.utils import serialize_to_sse_event@@ -54,6 +59,22 @@ def test_set_phase_updates_phase_and_step() -> None:assert progress["step"] == 3+def test_frontend_summary_gate_constants_match_backend() -> None:+ # The Summarize button gate in playerMetaLogic.tsx hardcodes copies of the backend summary+ # event filters. Guard against the two drifting apart (there is no shared source).+ repo_root = Path(__file__).resolve().parents[5]+ ts = (repo_root / "frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.tsx").read_text()++ cutoff_match = re.search(r"SUMMARY_EVENTS_REPLAY_CUTOFF_MS\s*=\s*(\d+)", ts)+ assert cutoff_match, "SUMMARY_EVENTS_REPLAY_CUTOFF_MS not found in playerMetaLogic.tsx"+ assert int(cutoff_match.group(1)) == SESSION_EVENTS_REPLAY_CUTOFF_MS++ blocklist_match = re.search(r"SUMMARY_EVENT_BLOCKLIST\s*=\s*\[(.*?)\]", ts, re.DOTALL)+ assert blocklist_match, "SUMMARY_EVENT_BLOCKLIST not found in playerMetaLogic.tsx"+ frontend_blocklist = set(re.findall(r"""['"]([^'"]+)['"]""", blocklist_match.group(1)))+ assert frontend_blocklist == set(SESSION_SUMMARY_EVENT_BLOCKLIST)++class TestFetchSessionDataActivity:@pytest.mark.asyncioasync def test_fetch_session_data_activity_standalone(@@ -142,6 +163,9 @@ class TestExecuteSummarizeSessionVideoStream:workflow_is_running = AsyncMock(return_value=False)atomic = MagicMock(return_value=MagicMock(allowed=True, used=1, cap=4000))refund = MagicMock(return_value=None)+ # In-range metadata by default so the up-front length precheck is a no-op;+ # length tests override the return value to drive the too-short/too-long paths.+ get_metadata = MagicMock(return_value={"duration": 120, "active_seconds": 60})with (patch("posthog.temporal.session_replay.session_summary.workflow._workflow_is_running",@@ -155,11 +179,13 @@ class TestExecuteSummarizeSessionVideoStream:"posthog.temporal.session_replay.session_summary.workflow.refund",refund,),+ patch.object(SessionReplayEvents, "get_metadata", get_metadata),):yield SimpleNamespace(workflow_is_running=workflow_is_running,atomic=atomic,refund=refund,+ get_metadata=get_metadata,)@staticmethod@@ -484,6 +510,140 @@ class TestExecuteSummarizeSessionVideoStream:event_data="Something went wrong while generating the summary. Please try again.",)+ @pytest.mark.asyncio+ async def test_completed_no_events_yields_specific_error(+ self,+ mock_session_id: str,+ mock_user: MagicMock,+ mock_team: MagicMock,+ ):+ # Workflow completes with the no-events sentinel: surface a clear message, not the generic one.+ handle = self._make_handle([(WorkflowExecutionStatus.COMPLETED, SUMMARY_RESULT_NO_EVENTS)])++ with (+ patch.object(SingleSessionSummary.objects, "get_summary", MagicMock(return_value=None)),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow._prepare_execution",+ return_value=(None, None, None, MagicMock(), "workflow-id"),+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow._start_video_summary_workflow",+ AsyncMock(return_value=handle),+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow.async_connect",+ AsyncMock(return_value=MagicMock()),+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow.asyncio.sleep",+ AsyncMock(),+ ),+ ):+ events = await self._collect(+ execute_summarize_session_video_stream(+ session_id=mock_session_id,+ user=mock_user,+ team=mock_team,+ )+ )++ assert events == [+ serialize_to_sse_event(+ event_label="session-summary-error",+ event_data="This recording has no events to summarize.",+ )+ ]++ @pytest.mark.parametrize(+ "metadata,expected_substring",+ [+ ({"duration": 5, "active_seconds": 5}, "too short"),+ ({"duration": 40000, "active_seconds": 40000}, "too long"),+ ],+ )+ @pytest.mark.asyncio+ async def test_out_of_range_recording_yields_error_without_starting_workflow(+ self,+ metadata: dict,+ expected_substring: str,+ cap_mocks: SimpleNamespace,+ mock_session_id: str,+ mock_user: MagicMock,+ mock_team: MagicMock,+ ):+ cap_mocks.get_metadata.return_value = metadata++ with (+ patch.object(SingleSessionSummary.objects, "get_summary", MagicMock(return_value=None)),+ patch("posthog.temporal.session_replay.session_summary.workflow._prepare_execution") as mock_prepare,+ patch(+ "posthog.temporal.session_replay.session_summary.workflow._start_video_summary_workflow"+ ) as mock_start,+ patch("posthog.temporal.session_replay.session_summary.workflow.async_connect") as mock_connect,+ ):+ events = await self._collect(+ execute_summarize_session_video_stream(+ session_id=mock_session_id,+ user=mock_user,+ team=mock_team,+ )+ )++ assert len(events) == 1+ assert events[0].startswith("event: session-summary-error\n")+ assert expected_substring in events[0]+ mock_prepare.assert_not_called()+ mock_start.assert_not_called()+ mock_connect.assert_not_called()++ @pytest.mark.asyncio+ async def test_length_precheck_fails_open_when_metadata_read_errors(+ self,+ cap_mocks: SimpleNamespace,+ mock_session_id: str,+ mock_user: MagicMock,+ mock_team: MagicMock,+ mock_enriched_llm_json_response: dict[str, Any],+ ):+ # A failing get_metadata read must not block summarization: skip the length+ # precheck and proceed to start the workflow as normal.+ cap_mocks.get_metadata.side_effect = Exception("clickhouse unavailable")+ completed_summary = MagicMock()+ completed_summary.id = "completed-summary-id"+ completed_summary.summary = mock_enriched_llm_json_response+ handle = self._make_handle([(WorkflowExecutionStatus.COMPLETED, None)])++ with (+ patch.object(SingleSessionSummary.objects, "get_summary", MagicMock(side_effect=[None, completed_summary])),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow._prepare_execution",+ return_value=(None, None, None, MagicMock(), "workflow-id"),+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow._start_video_summary_workflow",+ AsyncMock(return_value=handle),+ ) as mock_start,+ patch(+ "posthog.temporal.session_replay.session_summary.workflow.async_connect",+ AsyncMock(return_value=MagicMock()),+ ),+ patch(+ "posthog.temporal.session_replay.session_summary.workflow.asyncio.sleep",+ AsyncMock(),+ ),+ ):+ events = await self._collect(+ execute_summarize_session_video_stream(+ session_id=mock_session_id,+ user=mock_user,+ team=mock_team,+ )+ )++ mock_start.assert_awaited_once()+ assert not any("event: session-summary-error" in event for event in events)+ assert events[-1].startswith("event: session-summary-stream\n")+@pytest.mark.asyncioasync def test_get_progress_query_failure_retries_next_iteration(self,@@ -824,6 +984,14 @@ class TestVideoStreamCapEndToEnd:iteration count, not exercise any new behavior."""+ @pytest.fixture(autouse=True)+ def _stub_metadata(self) -> Iterator[None]:+ # In-range metadata so the up-front length precheck is a no-op (avoids a real ClickHouse read).+ with patch.object(+ SessionReplayEvents, "get_metadata", MagicMock(return_value={"duration": 120, "active_seconds": 60})+ ):+ yield+@pytest.fixture(autouse=True)def _isolate_redis_key(self, mock_team: MagicMock) -> Iterator[None]:from datetime import UTC, datetime