: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): drop event-less sessions in summarization sweep (#57386)
Tue Haulund902053b87b0a
diff --git a/ee/hogai/session_summaries/constants.py b/ee/hogai/session_summaries/constants.pyindex 24547e15f691..b18adae4354d 100644--- a/ee/hogai/session_summaries/constants.py+++ b/ee/hogai/session_summaries/constants.py@@ -6,6 +6,9 @@ SESSION_SUMMARIES_REASONING_EFFORT = "medium"BASE_LLM_CALL_TIMEOUT_S = 600.0# Summarization+# Shared by `get_session_events` (workflow) and `filter_session_ids_with_events` (sweep);+# they must stay in lockstep or recording-only sessions loop on the sweep tick.+SESSION_SUMMARY_EVENT_BLOCKLIST: tuple[str, ...] = ("$feature_flag_called",)MAX_SESSIONS_TO_SUMMARIZE = 100 # Maximum number of sessions to summarize at onceHALLUCINATED_EVENTS_MIN_RATIO = 0.15 # If more than 15% of events in the summary hallucinated, fail the summarization# Minimum number of sessions to use group summary logic (find patterns) instead of summarizing them separatelydiff --git a/ee/hogai/session_summaries/session/input_data.py b/ee/hogai/session_summaries/session/input_data.pyindex ddc76de46027..e549561c32e2 100644--- a/ee/hogai/session_summaries/session/input_data.py+++ b/ee/hogai/session_summaries/session/input_data.py@@ -10,7 +10,7 @@ from posthog.session_recordings.constants import COLUMNS_TO_REMOVE_FROM_LLM_CONTfrom posthog.session_recordings.models.metadata import RecordingMetadatafrom posthog.session_recordings.queries.session_replay_events import SessionReplayEvents-from ee.hogai.session_summaries.constants import SESSION_EVENTS_REPLAY_CUTOFF_MS+from ee.hogai.session_summaries.constants import SESSION_EVENTS_REPLAY_CUTOFF_MS, SESSION_SUMMARY_EVENT_BLOCKLISTfrom ee.hogai.session_summaries.local.input_data import (_get_production_session_events_locally,_get_production_session_metadata_locally,@@ -53,7 +53,7 @@ def get_session_events(Get session events with pagination to handle large sessions.Returns combined results from all pages up to max_pages."""- events_to_ignore = ["$feature_flag_called"]+ events_to_ignore = list(SESSION_SUMMARY_EVENT_BLOCKLIST)extra_fields = EXTRA_SUMMARY_EVENT_FIELDS# Collect all events and columns from all pagesall_events = []diff --git a/posthog/temporal/session_replay/summarization_sweep/activities.py b/posthog/temporal/session_replay/summarization_sweep/activities.pyindex 9441d2506947..a50396420c68 100644--- a/posthog/temporal/session_replay/summarization_sweep/activities.py+++ b/posthog/temporal/session_replay/summarization_sweep/activities.py@@ -14,6 +14,7 @@ from posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_FINGERPRIfrom posthog.temporal.session_replay.rasterize_recording.activities.stuck_counter import read_stuck_session_idsfrom posthog.temporal.session_replay.summarization_sweep.constants import (CH_QUERY_MAX_EXECUTION_SECONDS,+ EVENTS_PREFILTER_QUERY_MAX_EXECUTION_SECONDS,SCHEDULE_ID_PREFIX,SCHEDULE_TYPE,STUCK_RASTERIZE_THRESHOLD,@@ -22,6 +23,7 @@ from posthog.temporal.session_replay.summarization_sweep.constants import (from posthog.temporal.session_replay.summarization_sweep.session_candidates import (coerce_sample_rate,fetch_recent_session_ids,+ filter_session_ids_with_events,)from posthog.temporal.session_replay.summarization_sweep.types import (DeleteTeamScheduleInput,@@ -120,6 +122,15 @@ async def find_sessions_for_team_activity(inputs: FindSessionsInput) -> FindSessextra_summary_context=None,)sessions_to_summarize = [sid for sid in session_ids if not existing_summaries.get(sid)]+ # Recording-only sessions never write a summary row, so summaries_exist can't dedup them.+ if sessions_to_summarize:+ sessions_with_events = await database_sync_to_async_pool(filter_session_ids_with_events)(+ team=team,+ session_ids=sessions_to_summarize,+ lookback_minutes=inputs.lookback_minutes,+ max_execution_time_seconds=EVENTS_PREFILTER_QUERY_MAX_EXECUTION_SECONDS,+ )+ sessions_to_summarize = [sid for sid in sessions_to_summarize if sid in sessions_with_events]stuck = await _stuck_session_ids(inputs.team_id, sessions_to_summarize)sessions_to_summarize = [sid for sid in sessions_to_summarize if sid not in stuck]diff --git a/posthog/temporal/session_replay/summarization_sweep/constants.py b/posthog/temporal/session_replay/summarization_sweep/constants.pyindex 7857fface50b..2263fb5586fb 100644--- a/posthog/temporal/session_replay/summarization_sweep/constants.py+++ b/posthog/temporal/session_replay/summarization_sweep/constants.py@@ -25,6 +25,8 @@ STUCK_RASTERIZE_THRESHOLD = 3STUCK_RASTERIZE_LOOKBACK = timedelta(hours=2)CH_QUERY_MAX_EXECUTION_SECONDS = 180+# Two CH queries fire under FIND_ACTIVITY_TIMEOUT; the second must fit in what's left.+EVENTS_PREFILTER_QUERY_MAX_EXECUTION_SECONDS = 60# Must exceed FIND_ACTIVITY_TIMEOUT + child-start fan-out. Children are# ABANDONED so their execution does not count against this budget.diff --git a/posthog/temporal/session_replay/summarization_sweep/session_candidates.py b/posthog/temporal/session_replay/summarization_sweep/session_candidates.pyindex aeb7168b49af..3bfb5c26751d 100644--- a/posthog/temporal/session_replay/summarization_sweep/session_candidates.py+++ b/posthog/temporal/session_replay/summarization_sweep/session_candidates.py@@ -4,12 +4,14 @@ from django.conf import settingsfrom temporalio.exceptions import ApplicationError-from posthog.schema import PropertyOperator, RecordingPropertyFilter, RecordingsQuery+from posthog.schema import HogQLQuery, PropertyOperator, RecordingPropertyFilter, RecordingsQueryfrom posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettingsfrom posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.exceptions_capture import capture_exception+from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunnerfrom posthog.models.team import Teamfrom posthog.session_recordings.queries.session_recording_list_from_query import SessionRecordingListFromQueryfrom posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME@@ -19,6 +21,7 @@ from posthog.temporal.session_replay.summarization_sweep.constants import DEFAULfrom ee.hogai.session_summaries.constants import (MAX_ACTIVE_SECONDS_FOR_VIDEO_SUMMARY_S,MIN_ACTIVE_SECONDS_FOR_VIDEO_SUMMARY_S,+ SESSION_SUMMARY_EVENT_BLOCKLIST,)MAX_CANDIDATE_SESSIONS = 10_000@@ -137,3 +140,35 @@ def fetch_recent_session_ids().run()return [recording["session_id"] for recording in result.results]+++def filter_session_ids_with_events(+ team: Team,+ session_ids: list[str],+ lookback_minutes: int,+ max_execution_time_seconds: int = HOGQL_INCREASED_MAX_EXECUTION_TIME,+) -> set[str]:+ """Subset of `session_ids` that have at least one summarizable event in their recording window."""+ if not session_ids:+ return set()+ # Covers candidate sessions started within lookback and active up to MAX_ACTIVE_SECONDS_FOR_VIDEO_SUMMARY_S.+ events_window_minutes = lookback_minutes + MAX_ACTIVE_SECONDS_FOR_VIDEO_SUMMARY_S // 60 + 5+ query = HogQLQuery(+ query=(+ "SELECT DISTINCT $session_id FROM events "+ "WHERE timestamp >= now() - toIntervalMinute({events_window_minutes}) "+ "AND $session_id IN {session_ids} "+ "AND event NOT IN {events_to_ignore} "+ "LIMIT {limit}"+ ),+ values={+ "events_window_minutes": events_window_minutes,+ "session_ids": session_ids,+ "events_to_ignore": list(SESSION_SUMMARY_EVENT_BLOCKLIST),+ "limit": len(session_ids),+ },+ )+ hogql_settings = HogQLGlobalSettings(enable_analyzer=True, max_execution_time=max_execution_time_seconds)+ with tags_context(product=Product.SESSION_SUMMARY, feature=Feature.ENRICHMENT):+ result = HogQLQueryRunner(team=team, query=query, settings=hogql_settings).calculate()+ return {row[0] for row in (result.results or []) if row and row[0]}diff --git a/posthog/temporal/tests/session_replay/summarization_sweep/test_activities.py b/posthog/temporal/tests/session_replay/summarization_sweep/test_activities.pyindex a94d645107cd..84af31735a07 100644--- a/posthog/temporal/tests/session_replay/summarization_sweep/test_activities.py+++ b/posthog/temporal/tests/session_replay/summarization_sweep/test_activities.py@@ -72,6 +72,10 @@ async def test_find_sessions_filters_summarized(activity_environment, organizati"ee.models.session_summaries.SingleSessionSummary.objects.summaries_exist",return_value=existing,),+ patch(+ "posthog.temporal.session_replay.summarization_sweep.activities.filter_session_ids_with_events",+ return_value={"s2"},+ ),):result = await activity_environment.run(find_sessions_for_team_activity,@@ -104,6 +108,10 @@ async def test_find_sessions_dispatches_all_unsummarized_candidates(activity_env"ee.models.session_summaries.SingleSessionSummary.objects.summaries_exist",return_value=existing,),+ patch(+ "posthog.temporal.session_replay.summarization_sweep.activities.filter_session_ids_with_events",+ return_value={"s3", "s4", "s5", "s6", "s7"},+ ),):result = await activity_environment.run(find_sessions_for_team_activity,@@ -138,6 +146,10 @@ async def test_find_sessions_passes_sample_rate_to_fetch(activity_environment, o"ee.models.session_summaries.SingleSessionSummary.objects.summaries_exist",return_value={"only-1": False},),+ patch(+ "posthog.temporal.session_replay.summarization_sweep.activities.filter_session_ids_with_events",+ return_value={"only-1"},+ ),):result = await activity_environment.run(find_sessions_for_team_activity,@@ -231,6 +243,10 @@ async def test_find_sessions_prefers_created_by_user(activity_environment, organ"ee.models.session_summaries.SingleSessionSummary.objects.summaries_exist",return_value={"s1": False},),+ patch(+ "posthog.temporal.session_replay.summarization_sweep.activities.filter_session_ids_with_events",+ return_value={"s1"},+ ),):result = await activity_environment.run(find_sessions_for_team_activity,@@ -259,6 +275,10 @@ async def test_find_sessions_falls_back_when_created_by_is_null(activity_environ"ee.models.session_summaries.SingleSessionSummary.objects.summaries_exist",return_value={"s1": False},),+ patch(+ "posthog.temporal.session_replay.summarization_sweep.activities.filter_session_ids_with_events",+ return_value={"s1"},+ ),):result = await activity_environment.run(find_sessions_for_team_activity,@@ -310,6 +330,10 @@ async def test_find_sessions_skips_recordings_with_too_many_failures(activity_en"ee.models.session_summaries.SingleSessionSummary.objects.summaries_exist",return_value={},),+ patch(+ "posthog.temporal.session_replay.summarization_sweep.activities.filter_session_ids_with_events",+ return_value=set(candidate_ids),+ ),patch("posthog.temporal.session_replay.summarization_sweep.activities._stuck_session_ids",return_value={"stuck-2"},@@ -324,6 +348,104 @@ async def test_find_sessions_skips_recordings_with_too_many_failures(activity_enawait sync_to_async(user.delete)()+ "candidate_ids,sessions_with_events,expected_kept",+ [+ (["has-events", "snapshot-only-1", "snapshot-only-2"], {"has-events"}, ["has-events"]),+ (["s1", "s2", "s3"], {"s1", "s2", "s3"}, ["s1", "s2", "s3"]),+ (["s1", "s2", "s3"], set(), []),+ ],+ ids=["mixed", "all_have_events", "none_have_events"],+)[email protected]_db(transaction=True)+async def test_find_sessions_drops_sessions_without_events(+ activity_environment, organization, team, candidate_ids, sessions_with_events, expected_kept+):+ from typing import Any++ from posthog.models.user import User++ await sync_to_async(enable_signal_source)(team)+ user = await sync_to_async(User.objects.create_and_join)(organization, "[email protected]", "pw", "Events")+ try:+ captured: dict[str, Any] = {}++ def _fake_filter(*, team, session_ids, lookback_minutes, max_execution_time_seconds):+ captured["session_ids"] = list(session_ids)+ captured["lookback_minutes"] = lookback_minutes+ captured["max_execution_time_seconds"] = max_execution_time_seconds+ return sessions_with_events++ with (+ patch(+ "posthog.temporal.session_replay.summarization_sweep.activities.fetch_recent_session_ids",+ return_value=candidate_ids,+ ),+ patch(+ "ee.models.session_summaries.SingleSessionSummary.objects.summaries_exist",+ return_value={},+ ),+ patch(+ "posthog.temporal.session_replay.summarization_sweep.activities.filter_session_ids_with_events",+ side_effect=_fake_filter,+ ),+ ):+ result = await activity_environment.run(+ find_sessions_for_team_activity,+ FindSessionsInput(team_id=team.id, lookback_minutes=30),+ )+ from posthog.temporal.session_replay.summarization_sweep.constants import (+ EVENTS_PREFILTER_QUERY_MAX_EXECUTION_SECONDS,+ )++ assert sorted(result.session_ids) == sorted(expected_kept)+ assert sorted(captured["session_ids"]) == sorted(candidate_ids)+ assert captured["lookback_minutes"] == 30+ assert captured["max_execution_time_seconds"] == EVENTS_PREFILTER_QUERY_MAX_EXECUTION_SECONDS+ finally:+ await sync_to_async(user.delete)()++[email protected]_db(transaction=True)+async def test_find_sessions_skips_events_filter_when_all_summarized(activity_environment, organization, team):+ from posthog.models.user import User++ await sync_to_async(enable_signal_source)(team)+ user = await sync_to_async(User.objects.create_and_join)(organization, "[email protected]", "pw", "Skip")+ try:+ candidate_ids = ["s1", "s2"]+ with (+ patch(+ "posthog.temporal.session_replay.summarization_sweep.activities.fetch_recent_session_ids",+ return_value=candidate_ids,+ ),+ patch(+ "ee.models.session_summaries.SingleSessionSummary.objects.summaries_exist",+ return_value={"s1": True, "s2": True},+ ),+ patch(+ "posthog.temporal.session_replay.summarization_sweep.activities.filter_session_ids_with_events",+ ) as mock_filter,+ ):+ result = await activity_environment.run(+ find_sessions_for_team_activity,+ FindSessionsInput(team_id=team.id, lookback_minutes=30),+ )+ assert result.session_ids == []+ mock_filter.assert_not_called()+ finally:+ await sync_to_async(user.delete)()+++async def test_filter_session_ids_with_events_returns_empty_for_empty_input():+ from posthog.temporal.session_replay.summarization_sweep.session_candidates import filter_session_ids_with_events++ assert filter_session_ids_with_events(team=None, session_ids=[], lookback_minutes=30) == set() # type: ignore[arg-type]++@pytest.mark.asyncioasync def test_stuck_session_ids_returns_empty_for_empty_input():from posthog.temporal.session_replay.summarization_sweep.activities import _stuck_session_ids