Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(experiments): remove the summarize recordings button (#88744)

Kim Svatos Dugan29beff7892ec
diff --git a/ee/hogai/core/agent_modes/presets/flags.py b/ee/hogai/core/agent_modes/presets/flags.py
index 5d3a536af03f..f3c233a77f6d 100644
--- a/ee/hogai/core/agent_modes/presets/flags.py
+++ b/ee/hogai/core/agent_modes/presets/flags.py
@@ -2,7 +2,7 @@ from typing import TYPE_CHECKING
from posthog.schema import AgentMode
-from products.experiments.backend.max_tools import CreateExperimentTool, ExperimentSummaryTool, SessionReplaySummaryTool
+from products.experiments.backend.max_tools import CreateExperimentTool, ExperimentSummaryTool
from products.feature_flags.backend.max_tools import CreateFeatureFlagTool
from ee.hogai.chat_agent.executables import ChatAgentPlanExecutable, ChatAgentPlanToolsExecutable
@@ -77,7 +77,7 @@ class FlagsAgentToolkit(AgentToolkit):
@property
def tools(self) -> list[type["MaxTool"]]:
- tools: list[type[MaxTool]] = [CreateFeatureFlagTool, CreateExperimentTool, SessionReplaySummaryTool]
+ tools: list[type[MaxTool]] = [CreateFeatureFlagTool, CreateExperimentTool]
if has_experiment_summary_tool_feature_flag(self._team, self._user):
tools.append(ExperimentSummaryTool)
return tools
@@ -104,13 +104,12 @@ class ReadOnlyFlagsAgentToolkit(AgentToolkit):
@property
def tools(self) -> list[type["MaxTool"]]:
- tools: list[type[MaxTool]] = [SessionReplaySummaryTool]
if has_experiment_summary_tool_feature_flag(self._team, self._user):
- tools.append(ExperimentSummaryTool)
- return tools
+ return [ExperimentSummaryTool]
+ return []
-READ_ONLY_FLAGS_MODE_DESCRIPTION = "Specialized mode for analyzing feature flags and experiments. This mode allows you to analyze experiment results and session replay patterns across experiment variants with statistical summaries."
+READ_ONLY_FLAGS_MODE_DESCRIPTION = "Specialized mode for analyzing feature flags and experiments. This mode allows you to analyze experiment results with statistical summaries."
chat_agent_plan_flags_agent = AgentModeDefinition(
mode=AgentMode.FLAGS,
diff --git a/ee/hogai/core/agent_modes/presets/test/test_flags_preset.py b/ee/hogai/core/agent_modes/presets/test/test_flags_preset.py
index 24e85c22f362..f660aa8d78cf 100644
--- a/ee/hogai/core/agent_modes/presets/test/test_flags_preset.py
+++ b/ee/hogai/core/agent_modes/presets/test/test_flags_preset.py
@@ -2,10 +2,11 @@ from posthog.test.base import BaseTest
from unittest.mock import patch
from langchain_core.runnables import RunnableConfig
+from parameterized import parameterized
from ee.hogai.context import AssistantContextManager
-from ..flags import FlagsAgentToolkit
+from ..flags import FlagsAgentToolkit, ReadOnlyFlagsAgentToolkit
class TestFlagsAgentToolkit(BaseTest):
@@ -27,3 +28,27 @@ class TestFlagsAgentToolkit(BaseTest):
def test_toolkit_has_trajectory_examples(self):
self.assertIsNotNone(FlagsAgentToolkit.POSITIVE_TODO_EXAMPLES)
self.assertGreater(len(FlagsAgentToolkit.POSITIVE_TODO_EXAMPLES), 0)
+
+
+class TestReadOnlyFlagsAgentToolkit(BaseTest):
+ # The readonly toolkit is the whole custom toolset for the plan-only flags mode, and the
+ # experiment summary flag is the only thing that varies it. Asserting the exact list, rather
+ # than membership, keeps a writing tool from being added here unnoticed.
+ @parameterized.expand(
+ [
+ ("flag_enabled", True, ["ExperimentSummaryTool"]),
+ ("flag_disabled", False, []),
+ ]
+ )
+ def test_tools_follow_experiment_summary_flag(self, _name, flag_enabled, expected_tool_names):
+ with patch(
+ "ee.hogai.core.agent_modes.presets.flags.has_experiment_summary_tool_feature_flag",
+ return_value=flag_enabled,
+ ):
+ toolkit = ReadOnlyFlagsAgentToolkit(
+ team=self.team,
+ user=self.user,
+ context_manager=AssistantContextManager(self.team, self.user, RunnableConfig(configurable={})),
+ )
+
+ self.assertEqual([tool_class.__name__ for tool_class in toolkit.tools], expected_tool_names)
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 18dea6c433e4..1b48a005c2a3 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -327,7 +327,6 @@ export const FEATURE_FLAGS = {
EXPERIMENT_FLAG_CLEANUP_PR: 'experiment-flag-cleanup-pr', // owner: @jurajmajerik #team-experiments
EXPERIMENT_METRIC_EVENT_BREAKDOWNS: 'experiment-metric-event-breakdowns', // owner: @rodrigoi #team-experiments
EXPERIMENT_RECORDINGS_TAB: 'experiment-recordings-tab', // owner: @mp-hog #team-experiments
- EXPERIMENT_SESSION_REPLAYS_SKILL: 'experiment-session-replays-skill', // owner: @rodrigoi #team-experiments
EXPERIMENTS_DW_AA_TEST: 'experiments-dw-aa-test', // owner: @rodrigoi #team-experiments
EXPERIMENTS_EXCLUDED_VARIANTS: 'experiments-excluded-variants', // owner: @rodrigoi #team-experiments
EXPERIMENTS_FREEZE_EXPOSURE_AA_TEST: 'experiments-freeze-exposure-aa-test', // owner: @mp-hog #team-experiments multivariate=control,test, dogfood A/A used to validate the freeze-exposure lifecycle action
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index 201415703538..c2a8bbcde65a 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -1339,9 +1339,6 @@ export interface eventUsageLogicActions {
experimentId: ExperimentIdType
teamId: number | null | undefined
}
- reportExperimentSessionReplaySummaryRequested: (experiment: Experiment) => {
- experiment: Experiment
- }
reportExperimentSharedMetricAssigned: (
experimentId: ExperimentIdType,
sharedMetric: SharedMetric
@@ -2711,7 +2708,6 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
metric,
}),
reportExperimentAiSummaryRequested: (experiment: Experiment) => ({ experiment }),
- reportExperimentSessionReplaySummaryRequested: (experiment: Experiment) => ({ experiment }),
reportExperimentTabViewed: (experimentId: ExperimentIdType, tab: string) => ({ experimentId, tab }),
reportExperimentRecordingsTabViewed: (
experimentId: ExperimentIdType,
@@ -3925,11 +3921,6 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
...getEventPropertiesForExperiment(experiment),
})
},
- reportExperimentSessionReplaySummaryRequested: ({ experiment }) => {
- posthog.capture('experiment session replay summary requested', {
- ...getEventPropertiesForExperiment(experiment),
- })
- },
// The recordings-tab events below carry the experiment id alone rather than
// `getEventPropertiesForExperiment`, which serializes every metric definition. These fire on
// tab switches and recording clicks, so that payload would be sent many times per visit.
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 51c33cb61e94..0d1c0c7c11b0 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -4794,7 +4794,6 @@
"search_error_tracking_issues",
"find_error_tracking_impactful_issue_event_list",
"experiment_results_summary",
- "experiment_session_replays_summary",
"create_survey",
"edit_survey",
"analyze_survey_responses",
diff --git a/frontend/src/queries/schema/schema-assistant-messages.ts b/frontend/src/queries/schema/schema-assistant-messages.ts
index 2ca8cd62651e..921c71291041 100644
--- a/frontend/src/queries/schema/schema-assistant-messages.ts
+++ b/frontend/src/queries/schema/schema-assistant-messages.ts
@@ -464,7 +464,6 @@ export type AssistantTool =
| 'search_error_tracking_issues'
| 'find_error_tracking_impactful_issue_event_list'
| 'experiment_results_summary'
- | 'experiment_session_replays_summary'
| 'create_survey'
| 'edit_survey'
| 'analyze_survey_responses'
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
index 3ba90e61e339..af60751f9842 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
@@ -29,7 +29,6 @@ import { Experiment } from '~/types'
import { experimentScannerParams } from 'products/replay_vision/frontend/replay_scanners/experimentTargeting'
import { scannerTypeLabel } from 'products/replay_vision/frontend/replay_scanners/types'
-import { SummarizeSessionReplaysButton } from '../components/SummarizeSessionReplaysButton'
import { isLaunched } from '../experimentStatus'
import { NOT_A_FUNNEL_REASON } from '../utils'
import { ExperimentBehaviorComparison, ExperimentBehaviorComparisonToggle } from './ExperimentBehaviorComparison'
@@ -416,9 +415,6 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):
</DropdownMenu>
)}
<ExperimentBehaviorComparisonToggle experiment={experiment} />
- <div className="ml-auto">
- <SummarizeSessionReplaysButton experiment={experiment} />
- </div>
</div>
{/* The default mode also uses the endpoint for a single multi-source metric, so the
caption follows the request, not the mode. */}
diff --git a/frontend/src/scenes/experiments/components/SummarizeSessionReplaysButton.tsx b/frontend/src/scenes/experiments/components/SummarizeSessionReplaysButton.tsx
deleted file mode 100644
index ae917cb9e85f..000000000000
--- a/frontend/src/scenes/experiments/components/SummarizeSessionReplaysButton.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { IconSparkles } from '@posthog/icons'
-import { LemonTag } from '@posthog/lemon-ui'
-
-import { LemonButton } from 'lib/lemon-ui/LemonButton'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { useOpenAi } from 'scenes/max/useOpenAi'
-
-import { FEATURE_FLAGS } from '~/lib/constants'
-import type { Experiment } from '~/types'
-
-import { experimentLogic } from '../experimentLogic'
-import { useSessionReplaySummaryMaxTool } from '../hooks/useSessionReplaySummaryMaxTool'
-
-type SummarizeSessionReplaysButtonProps = {
- experiment: Experiment
-}
-
-/**
- * Calls the Max tool to summarize session replays for an experiment.
- * When EXPERIMENT_SESSION_REPLAYS_SKILL flag is enabled, opens PostHog AI with a skill-based prompt.
- * Otherwise, uses the legacy MaxTool approach.
- */
-export const SummarizeSessionReplaysButton = ({
- experiment,
-}: SummarizeSessionReplaysButtonProps): JSX.Element | null => {
- const { featureFlags } = useValues(featureFlagLogic)
- const { openMax } = useSessionReplaySummaryMaxTool()
- /**
- * The useOpenAi hook is not using OpenAI directly, but rather using the
- * side panel logic to open the AI in a new tab.
- * I know, it has a terrible name. But the side panel logic is being deprecated.
- */
- const { openAi: openPostHogAI } = useOpenAi()
- const { reportExperimentSessionReplaySummaryRequested } = useActions(experimentLogic)
-
- const useSkill = featureFlags[FEATURE_FLAGS.EXPERIMENT_SESSION_REPLAYS_SKILL]
-
- // openMax is null when the tool isn't available (draft experiment or no results yet).
- // Gate rendering on it for both click paths, so the skill path can't offer an unusable flow.
- if (!openMax) {
- return null
- }
-
- const skillPrompt = `Analyze session replays for experiment "${experiment.name}" (ID: ${experiment.id}). Compare user behavior patterns across all variants.`
-
- return (
- <LemonButton
- size="small"
- onClick={() => {
- reportExperimentSessionReplaySummaryRequested(experiment)
- if (useSkill) {
- // Open PostHog AI in a new tab with skill-based prompt
- openPostHogAI(skillPrompt)
- } else {
- // Use legacy MaxTool approach
- openMax()
- }
- }}
- type="secondary"
- icon={<IconSparkles />}
- tooltip="Use AI to compare session recordings across variants and spot differences in user behavior."
- >
- Summarize recordings
- <LemonTag type="highlight" size="small" className="ml-1">
- Beta
- </LemonTag>
- </LemonButton>
- )
-}
diff --git a/frontend/src/scenes/experiments/experimentLogic.tsx b/frontend/src/scenes/experiments/experimentLogic.tsx
index 1ed46aa8bd90..b3a4a72e8a25 100644
--- a/frontend/src/scenes/experiments/experimentLogic.tsx
+++ b/frontend/src/scenes/experiments/experimentLogic.tsx
@@ -737,9 +737,6 @@ export interface experimentLogicActions {
reportExperimentResultsLoadingTimeout: (experimentId: ExperimentIdType) => {
experimentId: ExperimentIdType
} // eventUsageLogic
- reportExperimentSessionReplaySummaryRequested: (experiment: Experiment) => {
- experiment: Experiment
- } // eventUsageLogic
reportExperimentSharedMetricAssigned: (
experimentId: ExperimentIdType,
sharedMetric: SharedMetric
@@ -1509,7 +1506,6 @@ export const experimentLogic = kea<experimentLogicType>([
'reportExperimentTimeseriesViewed',
'reportExperimentTimeseriesRecalculated',
'reportExperimentAiSummaryRequested',
- 'reportExperimentSessionReplaySummaryRequested',
'reportExperimentMetricsRefreshed',
'reportExperimentAutoRefreshToggled',
'reportExperimentMetricBreakdownAdded',
diff --git a/frontend/src/scenes/experiments/hooks/useSessionReplaySummaryMaxTool.ts b/frontend/src/scenes/experiments/hooks/useSessionReplaySummaryMaxTool.ts
deleted file mode 100644
index ba3f01351ab1..000000000000
--- a/frontend/src/scenes/experiments/hooks/useSessionReplaySummaryMaxTool.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { useValues } from 'kea'
-import posthog from 'posthog-js'
-import { useMemo } from 'react'
-
-import { useMaxTool } from 'scenes/max/useMaxTool'
-
-import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
-
-import { useAttachedContext } from 'products/posthog_ai/frontend/api/logics'
-
-import { experimentLogic } from '../experimentLogic'
-import { isLaunched } from '../experimentsLogic'
-
-/**
- * Minimal context sent to the backend for session replay summarization.
- * The backend fetches recording counts and filters for each variant.
- */
-type MinimalSessionReplaySummaryContext = {
- experiment_id: number | string
- experiment_name: string
-}
-
-export const useSessionReplaySummaryMaxTool = (): ReturnType<typeof useMaxTool> => {
- const { experiment, orderedPrimaryMetricsWithResults } = useValues(experimentLogic)
-
- const maxToolContext = useMemo(
- (): MinimalSessionReplaySummaryContext => ({
- experiment_id: experiment.id,
- experiment_name: experiment.name || 'Unnamed experiment',
- }),
- [experiment.id, experiment.name]
- )
-
- const resultsCount = orderedPrimaryMetricsWithResults.length
- const shouldShowButton = useMemo(() => {
- const hasResults = resultsCount > 0
- const hasStarted = isLaunched(experiment)
- return hasResults && hasStarted
- }, [resultsCount, experiment.status, experiment.start_date, experiment.end_date, experiment])
-
- const maxToolResult = useMaxTool({
- identifier: 'experiment_session_replays_summary',
- context: maxToolContext,
- contextDescription: {
- text: `Session replays for ${maxToolContext.experiment_name}`,
- icon: iconForType('session_replay'),
- },
- active: shouldShowButton,
- initialMaxPrompt: `!Summarize session recordings for experiment "${maxToolContext.experiment_name}"`,
- callback(toolOutput) {
- if (toolOutput?.error) {
- posthog.captureException(
- toolOutput?.error || 'Undefined error when summarizing session replays with Max',
- {
- action: 'max-ai-session-replay-summary-failed',
- experiment_id: experiment.id,
- ...toolOutput,
- }
- )
- } else {
- posthog.capture('experiment session replays analyzed', {
- experiment_id: experiment.id,
- has_recordings: (toolOutput?.total_recordings ?? 0) > 0,
- })
- }
- },
- })
-
- useAttachedContext(
- shouldShowButton
- ? [{ type: 'experiment', key: experiment.id, label: experiment.name || 'Unnamed experiment' }]
- : null
- )
-
- return maxToolResult
-}
diff --git a/frontend/src/scenes/max/max-constants.tsx b/frontend/src/scenes/max/max-constants.tsx
index abff4dab2540..456d9d48f75e 100644
--- a/frontend/src/scenes/max/max-constants.tsx
+++ b/frontend/src/scenes/max/max-constants.tsx
@@ -771,20 +771,6 @@ export const TOOL_DEFINITIONS: Record<AssistantTool, ToolDefinition> = {
return 'Summarizing experiment results...'
},
},
- experiment_session_replays_summary: {
- name: 'Summarize experiment session replays',
- description:
- 'Summarize experiment session replays to analyze user behavior patterns across experiment variants using session recordings',
- product: Scene.Experiment,
- icon: iconForType('session_replay'),
- modes: [AgentMode.Flags],
- displayFormatter: (toolCall) => {
- if (toolCall.status === 'completed') {
- return 'Analyzed session replay patterns'
- }
- return 'Analyzing session replays...'
- },
- },
summarize_replay_vision_summaries: {
name: 'Summarize session summaries',
description: 'Summarize session summaries across a Replay Vision summarizer scanner',
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 5adedf743e04..b1bd38a78a2d 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -445,7 +445,6 @@ class AssistantTool(StrEnum):
SEARCH_ERROR_TRACKING_ISSUES = "search_error_tracking_issues"
FIND_ERROR_TRACKING_IMPACTFUL_ISSUE_EVENT_LIST = "find_error_tracking_impactful_issue_event_list"
EXPERIMENT_RESULTS_SUMMARY = "experiment_results_summary"
- EXPERIMENT_SESSION_REPLAYS_SUMMARY = "experiment_session_replays_summary"
CREATE_SURVEY = "create_survey"
EDIT_SURVEY = "edit_survey"
ANALYZE_SURVEY_RESPONSES = "analyze_survey_responses"
diff --git a/products/experiments/backend/max_tools.py b/products/experiments/backend/max_tools.py
index 610ece975529..71cc94426602 100644
--- a/products/experiments/backend/max_tools.py
+++ b/products/experiments/backend/max_tools.py
@@ -1,4 +1,3 @@
-from datetime import UTC, datetime
from textwrap import dedent
from typing import Any, Literal
@@ -6,10 +5,7 @@ from posthoganalytics import capture_exception
from pydantic import BaseModel, Field
from rest_framework.exceptions import ValidationError
-from posthog.clickhouse.query_tagging import Product, tags_context
from posthog.event_usage import EventSource
-from posthog.session_recordings.session_recording_api import list_recordings_from_query
-from posthog.session_recordings.utils import filter_from_params_to_query
from posthog.sync import database_sync_to_async
from products.experiments.backend.experiment_service import ExperimentService
@@ -311,277 +307,3 @@ class ExperimentSummaryTool(MaxTool):
"variants": variants,
"has_results": bool(primary_metrics or secondary_metrics),
}
-
-
-# Session Replay Summary Tool
-
-
-class SessionReplaySummaryArgs(BaseModel):
- """
- Analyze session replay patterns for an experiment to understand user behavior across variants.
- """
-
- experiment_id: int = Field(description="The ID of the experiment to analyze session replays for")
-
-
-class SessionReplaySummaryOutput(BaseModel):
- """Structured output for session replay summary"""
-
- experiment_id: int = Field(description="ID of the experiment")
- experiment_name: str = Field(default="", description="Name of the experiment")
- behavioral_patterns: list[str] = Field(
- default_factory=list,
- description="Key behavioral patterns observed across experiment variants",
- max_length=20,
- )
- recording_counts: dict[str, int] = Field(
- default_factory=dict, description="Number of recordings available per variant"
- )
- total_recordings: int = Field(default=0, description="Total number of recordings across all variants")
- variants: list[str] = Field(default_factory=list, description="List of variant keys")
- date_range: dict[str, str | None] = Field(default_factory=dict, description="Experiment date range")
- variant_insights: dict[str, list[str]] = Field(default_factory=dict, description="Specific insights per variant")
- warning: str | None = Field(default=None, description="Warning about data quality or availability")
- error: str | None = Field(default=None, description="Error code if something went wrong")
-
-
-SESSION_REPLAY_SUMMARY_TOOL_DESCRIPTION = """
-Use this tool to analyze session replay patterns across experiment variants to understand user behavior differences.
-The tool provides recording counts per variant and context for Max to analyze actual session recordings.
-
-This tool is useful when:
-- Understanding how users interact with different experiment variants
-- Identifying usability issues or confusion in specific variants
-- Comparing user behavior patterns between control and test variants
-- Getting qualitative insights to complement quantitative experiment results
-
-**Important:** This tool provides the context and recording counts. Use the filter_session_recordings tool to actually fetch and analyze the recordings for each variant.
-
-# Examples
-
-<example>
-User: How are users behaving in my experiment?
-Assistant: I'll analyze session replay patterns across your experiment variants.
-*Uses experiment_session_replays_summary tool*
-Assistant: I found 299 total recordings across your variants. Let me analyze them...
-
-<reasoning>
-The assistant used experiment_session_replays_summary to get recording counts and filters for the experiment variants.
-</reasoning>
-</example>
-""".strip()
-
-
-class SessionReplaySummaryTool(MaxTool):
- name: str = "experiment_session_replays_summary"
- description: str = SESSION_REPLAY_SUMMARY_TOOL_DESCRIPTION
- context_prompt_template: str = "Analyzes session replay patterns in experiment variants."
-
- args_schema: type[BaseModel] = SessionReplaySummaryArgs
-
- def get_required_resource_access(self):
- return [("experiment", "viewer")]
-
- async def _arun_impl(
- self,
- experiment_id: int,
- ) -> tuple[str, dict[str, Any]]:
- try:
- # Fetch experiment
- @database_sync_to_async
- def get_experiment():
- try:
- return Experiment.objects.select_related("team", "feature_flag").get(
- id=experiment_id, team=self._team
- )
- except Experiment.DoesNotExist:
- raise ValueError(f"Experiment {experiment_id} not found")
-
- experiment = await get_experiment()
-
- await self.check_object_access(experiment, "viewer", resource="experiment", action="read")
-
- if experiment.is_draft:
- output = SessionReplaySummaryOutput(
- experiment_id=experiment_id,
- experiment_name=experiment.name,
- error="not_started",
- )
- return "❌ Experiment has not started yet. No session replays available.", output.model_dump()
-
- # Get variants from feature flag
- variant_keys = [v["key"] for v in experiment.feature_flag.variants]
-
- if not variant_keys:
- output = SessionReplaySummaryOutput(
- experiment_id=experiment_id,
- experiment_name=experiment.name,
- error="no_variants",
- )
- return "❌ No variants configured for this experiment.", output.model_dump()
-
- # Count recordings per variant
- recording_counts = {}
- for variant_key in variant_keys:
- # Build recording filters for this variant
- filters = self._build_experiment_recording_filters(experiment, variant_key)
-
- # Convert to RecordingsQuery and count
- try:
- query = filter_from_params_to_query(filters)
- query.limit = 100
-
- @database_sync_to_async
- def count_recordings(q):
- with tags_context(
- product=Product.MAX_AI, team_id=self._team.pk, org_id=self._team.organization_id
- ):
- listing_result = list_recordings_from_query(query=q, user=None, team=self._team)
- # If more recordings are available, there are 100+ recordings
- return (
- len(listing_result.recordings) if not listing_result.more_recordings_available else 100
- )
-
- count = await count_recordings(query)
- recording_counts[variant_key] = count
- except Exception as e:
- capture_exception(
- e,
- properties={
- "team_id": self._team.id,
- "experiment_id": experiment_id,
- "variant_key": variant_key,
- },
- )
- recording_counts[variant_key] = 0
-
- total_recordings = sum(recording_counts.values())
-
- if total_recordings == 0:
- output = SessionReplaySummaryOutput(
- experiment_id=experiment_id,
- experiment_name=experiment.name,
- recording_counts=recording_counts,
- variants=variant_keys,
- error="no_recordings",
- )
- return (
- f"❌ No session recordings found for experiment '{experiment.name}'. "
- "Make sure session replay is enabled and users have been exposed to the experiment.",
- output.model_dump(),
- )
-
- # Build response
- behavioral_patterns = [
- f"Experiment '{experiment.name}' has {total_recordings} total session recordings across {len(variant_keys)} variants",
- "To analyze user behavior, use the filter_session_recordings tool with the filters for each variant",
- "Compare behavior patterns between variants to understand the impact of your changes",
- ]
-
- # Add variant-specific guidance
- for variant_key, count in recording_counts.items():
- if count > 0:
- behavioral_patterns.append(f"Variant '{variant_key}': {count} recordings available for analysis")
-
- user_message = self._format_summary_for_user(
- experiment_name=experiment.name,
- recording_counts=recording_counts,
- total_recordings=total_recordings,
- )
-
- output = SessionReplaySummaryOutput(
- experiment_id=experiment_id,
- experiment_name=experiment.name,
- behavioral_patterns=behavioral_patterns,
- recording_counts=recording_counts,
- total_recordings=total_recordings,
- variants=variant_keys,
- date_range={
- "start": experiment.start_date.isoformat() if experiment.start_date else None,
- "end": experiment.end_date.isoformat() if experiment.end_date else None,
- },
- )
-
- return user_message, output.model_dump()
-
- except MaxToolAccessDeniedError:
- raise
- except ValueError as e:
- return f"❌ {str(e)}", {"error": "validation_error", "details": str(e)}
- except Exception as e:
- capture_exception(
- e,
- properties={
- "team_id": self._team.id,
- "user_id": self._user.id,
- "experiment_id": experiment_id,
- },
- )
- return f"❌ Failed to analyze session replays: {str(e)}", {
- "error": "analysis_failed",
- "details": str(e),
- }
-
- def _build_experiment_recording_filters(self, experiment: Experiment, variant_key: str) -> dict[str, Any]:
- """
- Build recording filters for experiment variant.
-
- Replicates frontend getViewRecordingFilters() logic from experiments/utils.ts
- """
- feature_flag_key = experiment.feature_flag.key
-
- # Build filter structure matching RecordingUniversalFilters
- return {
- "date_from": experiment.start_date.isoformat() if experiment.start_date else None,
- "date_to": experiment.end_date.isoformat() if experiment.end_date else datetime.now(UTC).isoformat(),
- "events": [
- {
- "id": "$feature_flag_called",
- "type": "events",
- "properties": [
- {
- "key": "$feature_flag",
- "value": [feature_flag_key],
- "operator": "exact",
- "type": "event",
- },
- {
- "key": f"$feature/{feature_flag_key}",
- "value": [variant_key],
- "operator": "exact",
- "type": "event",
- },
- ],
- }
- ],
- }
-
- def _format_summary_for_user(
- self, experiment_name: str, recording_counts: dict[str, int], total_recordings: int
- ) -> str:
- """Format the session replay summary for user display"""
- lines = [
- f"📹 Session Replay Summary for '{experiment_name}'",
- "",
- f"Total recordings: {total_recordings}",
- "",
- "Recordings by variant:",
- ]
-
- for variant_key, count in recording_counts.items():
- percentage = (count / total_recordings * 100) if total_recordings > 0 else 0
- lines.append(f" • {variant_key}: {count} ({percentage:.1f}%)")
-
- lines.extend(
- [
- "",
- "💡 To analyze user behavior patterns:",
- " 1. I can help you filter and view specific recordings",
- " 2. Compare behavior differences between variants",
- " 3. Identify usability issues or unexpected user journeys",
- "",
- "What would you like to explore?",
- ]
- )
-
- return "\n".join(lines)
diff --git a/products/experiments/backend/test/test_session_replay_summary_tool.py b/products/experiments/backend/test/test_session_replay_summary_tool.py
deleted file mode 100644
index aa535af072ed..000000000000
--- a/products/experiments/backend/test/test_session_replay_summary_tool.py
+++ /dev/null
@@ -1,384 +0,0 @@
-from datetime import datetime, timedelta
-
-from freezegun import freeze_time
-from posthog.test.base import APIBaseTest
-from unittest.mock import patch
-
-from posthog.session_recordings.models.session_recording import SessionRecording
-from posthog.session_recordings.session_recording_api import RecordingsListingResult
-
-from products.experiments.backend.max_tools import SessionReplaySummaryTool
-from products.experiments.backend.models.experiment import Experiment
-from products.feature_flags.backend.models.feature_flag import FeatureFlag
-
-from ee.hogai.tool_errors import MaxToolAccessDeniedError
-from ee.hogai.utils.types import AssistantState
-
-
-def _listing_result(recordings: list, has_more: bool = False) -> RecordingsListingResult:
- return RecordingsListingResult(
- recordings=recordings, more_recordings_available=has_more, timings_header="", next_cursor=None
- )
-
-
-@freeze_time("2025-01-15T12:00:00Z")
-class TestSessionReplaySummaryTool(APIBaseTest):
- """Comprehensive tests for SessionReplaySummaryTool"""
-
- async def acreate_feature_flag(self, key="test-experiment", variant_keys=None):
- """
- Create a feature flag with multivariate variants for experiments.
-
- Args:
- key: Feature flag key
- variant_keys: List of variant keys, defaults to ["control", "test"]
- """
- if variant_keys is None:
- variant_keys = ["control", "test"]
-
- variants = [
- {"key": variant_key, "name": variant_key.title(), "rollout_percentage": 100 // len(variant_keys)}
- for variant_key in variant_keys
- ]
-
- return await FeatureFlag.objects.acreate(
- name=f"Test experiment flag: {key}",
- key=key,
- team=self.team,
- filters={
- "groups": [{"properties": [], "rollout_percentage": None}],
- "multivariate": {"variants": variants},
- },
- created_by=self.user,
- )
-
- async def acreate_experiment(
- self, name="test-experiment", feature_flag=None, started=True, start_days_ago=7, end_days_ahead=7
- ):
- """
- Create an experiment with optional started state.
-
- Args:
- name: Experiment name
- feature_flag: FeatureFlag instance, creates one if None
- started: Whether experiment has started (start_date is set)
- start_days_ago: Days before now for start_date
- end_days_ahead: Days after now for end_date
- """
- if feature_flag is None:
- feature_flag = await self.acreate_feature_flag(name)
-
- return await Experiment.objects.acreate(
- name=name,
- team=self.team,
- feature_flag=feature_flag,
- start_date=(datetime(2025, 1, 15, 12, 0, 0) - timedelta(days=start_days_ago) if started else None),
- end_date=(datetime(2025, 1, 15, 12, 0, 0) + timedelta(days=end_days_ahead) if started else None),
- )
-
- def create_mock_session_recording(self, session_id, distinct_id="user_1"):
- """Create a mock SessionRecording object for testing."""
- recording = SessionRecording(
- session_id=session_id,
- team=self.team,
- distinct_id=distinct_id,
- start_time=datetime(2025, 1, 10, 10, 0, 0),
- duration=300,
- )
- return recording
-
- async def create_tool(self):
- """Create SessionReplaySummaryTool instance for testing."""
- return await SessionReplaySummaryTool.create_tool_class(
- team=self.team,
- user=self.user,
- state=AssistantState(messages=[]),
- )
-
- @patch("products.experiments.backend.max_tools.list_recordings_from_query")
- async def test_experiment_with_recordings_returns_counts(self, mock_list_recordings):
- """Test successful analysis of experiment with recordings for each variant."""
- experiment = await self.acreate_experiment(name="test-experiment")
-
- # Mock recordings for each variant
- mock_recordings_control = [self.create_mock_session_recording(f"session_control_{i}") for i in range(50)]
- mock_recordings_test = [self.create_mock_session_recording(f"session_test_{i}") for i in range(75)]
-
- mock_list_recordings.side_effect = [
- _listing_result(mock_recordings_control),
- _listing_result(mock_recordings_test),
- ]
-
- tool = await self.create_tool()
- result, artifact = await tool._arun_impl(experiment_id=experiment.id)
-
- # Assert result message
- self.assertIn("Session Replay Summary", result)
- self.assertIn("test-experiment", result)
- self.assertIn("Total recordings: 125", result)
- self.assertIn("control: 50", result)
- self.assertIn("test: 75", result)
- self.assertIn("40.0%", result)
- self.assertIn("60.0%", result)
- self.assertIn("What would you like to explore?", result)
-
- # Assert artifact structure
- assert isinstance(artifact, dict)
- self.assertEqual(artifact["experiment_id"], experiment.id)
- self.assertEqual(artifact["experiment_name"], "test-experiment")
- self.assertEqual(artifact["recording_counts"], {"control": 50, "test": 75})
- self.assertEqual(artifact["total_recordings"], 125)
- self.assertEqual(artifact["variants"], ["control", "test"])
- self.assertIn("date_range", artifact)
- self.assertIsNotNone(artifact["date_range"]["start"])
- self.assertIsNotNone(artifact["date_range"]["end"])
-
- self.assertEqual(mock_list_recordings.call_count, 2)
-
- @patch("products.experiments.backend.max_tools.list_recordings_from_query")
- async def test_experiment_with_100_plus_recordings(self, mock_list_recordings):
- """Test that tool correctly handles has_more=True (100+ recordings)."""
- experiment = await self.acreate_experiment()
-
- mock_recordings = [self.create_mock_session_recording(f"session_{i}") for i in range(100)]
-
- mock_list_recordings.side_effect = [
- _listing_result(mock_recordings, has_more=True),
- _listing_result(mock_recordings, has_more=True),
- ]
-
- tool = await self.create_tool()
- result, artifact = await tool._arun_impl(experiment_id=experiment.id)
-
- self.assertEqual(artifact["recording_counts"], {"control": 100, "test": 100})
- self.assertEqual(artifact["total_recordings"], 200)
- self.assertIn("200", result)
-
- @patch("products.experiments.backend.max_tools.list_recordings_from_query")
- async def test_experiment_with_no_recordings(self, mock_list_recordings):
- """Test error message when no recordings found for any variant."""
- experiment = await self.acreate_experiment()
-
- mock_list_recordings.side_effect = [
- _listing_result([]),
- _listing_result([]),
- ]
-
- tool = await self.create_tool()
- result, artifact = await tool._arun_impl(experiment_id=experiment.id)
-
- self.assertIn("No session recordings found", result)
- self.assertIn("test-experiment", result)
- self.assertIn("session replay is enabled", result)
-
- self.assertEqual(artifact["error"], "no_recordings")
- self.assertEqual(artifact["experiment_id"], experiment.id)
- self.assertEqual(artifact["recording_counts"], {"control": 0, "test": 0})
-
- async def test_denies_object_level_restricted_experiment(self):
- experiment = await self.acreate_experiment(name="restricted-replay-test")
- tool = await self.create_tool()
-
- with patch.object(tool, "user_access_control") as mock_uac:
- mock_uac.check_access_level_for_object.return_value = False
- with self.assertRaises(MaxToolAccessDeniedError):
- await tool._arun_impl(experiment_id=experiment.id)
-
- async def test_experiment_not_found(self):
- """Test error when experiment ID doesn't exist."""
- tool = await self.create_tool()
- result, artifact = await tool._arun_impl(experiment_id=99999)
-
- self.assertIn("Experiment 99999 not found", result)
- self.assertEqual(artifact["error"], "validation_error")
- self.assertIn("not found", artifact["details"])
-
- async def test_experiment_not_started(self):
- """Test error when experiment hasn't been started yet."""
- experiment = await self.acreate_experiment(started=False)
-
- tool = await self.create_tool()
- result, artifact = await tool._arun_impl(experiment_id=experiment.id)
-
- self.assertIn("Experiment has not started yet", result)
- self.assertIn("No session replays available", result)
- self.assertEqual(artifact["error"], "not_started")
- self.assertEqual(artifact["experiment_id"], experiment.id)
-
- async def test_experiment_with_no_variants(self):
- """Test error when feature flag has no multivariate variants configured."""
- feature_flag = await FeatureFlag.objects.acreate(
- name="No variants flag",
- key="no-variants",
- team=self.team,
- filters={"groups": [{"properties": [], "rollout_percentage": 100}]},
- created_by=self.user,
- )
-
- experiment = await self.acreate_experiment(name="no-variants-exp", feature_flag=feature_flag, started=True)
-
- tool = await self.create_tool()
- result, artifact = await tool._arun_impl(experiment_id=experiment.id)
-
- self.assertIn("No variants configured", result)
- self.assertEqual(artifact["error"], "no_variants")
- self.assertEqual(artifact["experiment_id"], experiment.id)
-
- @patch("products.experiments.backend.max_tools.capture_exception")
- @patch("products.experiments.backend.max_tools.list_recordings_from_query")
- async def test_recording_query_exception_graceful_handling(self, mock_list_recordings, mock_capture_exception):
- """Test that query exceptions for individual variants are caught and logged."""
- experiment = await self.acreate_experiment()
-
- mock_recordings = [self.create_mock_session_recording(f"session_{i}") for i in range(25)]
- mock_list_recordings.side_effect = [
- _listing_result(mock_recordings),
- Exception("ClickHouse connection failed"),
- ]
-
- tool = await self.create_tool()
- result, artifact = await tool._arun_impl(experiment_id=experiment.id)
-
- self.assertEqual(artifact["recording_counts"], {"control": 25, "test": 0})
- self.assertEqual(artifact["total_recordings"], 25)
-
- self.assertEqual(mock_capture_exception.call_count, 1)
- captured_exception = mock_capture_exception.call_args[0][0]
- self.assertIn("ClickHouse connection failed", str(captured_exception))
-
- @patch("products.experiments.backend.max_tools.list_recordings_from_query")
- async def test_experiment_with_multiple_variants(self, mock_list_recordings):
- """Test experiment with 3+ variants."""
- feature_flag = await self.acreate_feature_flag(
- key="multi-variant", variant_keys=["control", "variant_a", "variant_b"]
- )
- experiment = await self.acreate_experiment(name="multi-variant-exp", feature_flag=feature_flag)
-
- mock_list_recordings.side_effect = [
- _listing_result([self.create_mock_session_recording(f"c_{i}") for i in range(20)]),
- _listing_result([self.create_mock_session_recording(f"a_{i}") for i in range(30)]),
- _listing_result([self.create_mock_session_recording(f"b_{i}") for i in range(50)]),
- ]
-
- tool = await self.create_tool()
- result, artifact = await tool._arun_impl(experiment_id=experiment.id)
-
- self.assertEqual(artifact["variants"], ["control", "variant_a", "variant_b"])
- self.assertEqual(artifact["recording_counts"]["control"], 20)
- self.assertEqual(artifact["recording_counts"]["variant_a"], 30)
- self.assertEqual(artifact["recording_counts"]["variant_b"], 50)
- self.assertEqual(artifact["total_recordings"], 100)
-
- self.assertIn("control: 20 (20.0%)", result)
- self.assertIn("variant_a: 30 (30.0%)", result)
- self.assertIn("variant_b: 50 (50.0%)", result)
-
- async def test_build_experiment_recording_filters(self):
- """Test that recording filters are built correctly for experiment variants."""
- feature_flag = await self.acreate_feature_flag(key="test-flag")
- experiment = await self.acreate_experiment(name="filter-test", feature_flag=feature_flag)
-
- tool = await self.create_tool()
- filters = tool._build_experiment_recording_filters(experiment, "control")
-
- # Verify filter structure
- self.assertIn("date_from", filters)
- self.assertIn("date_to", filters)
- self.assertIn("events", filters)
- self.assertEqual(len(filters["events"]), 1)
-
- # Verify event filter
- event_filter = filters["events"][0]
- self.assertEqual(event_filter["id"], "$feature_flag_called")
- self.assertEqual(event_filter["type"], "events")
-
- # Verify properties
- properties = event_filter["properties"]
- self.assertEqual(len(properties), 2)
-
- self.assertEqual(properties[0]["key"], "$feature_flag")
- self.assertEqual(properties[0]["value"], ["test-flag"])
- self.assertEqual(properties[0]["operator"], "exact")
-
- self.assertEqual(properties[1]["key"], "$feature/test-flag")
- self.assertEqual(properties[1]["value"], ["control"])
- self.assertEqual(properties[1]["operator"], "exact")
-
- @patch("products.experiments.backend.max_tools.list_recordings_from_query")
- async def test_date_range_in_artifact(self, mock_list_recordings):
- """Test that date range is correctly included in artifact."""
- experiment = await self.acreate_experiment(start_days_ago=10, end_days_ahead=5)
-
- mock_list_recordings.side_effect = [
- _listing_result([self.create_mock_session_recording("s1")]),
- _listing_result([self.create_mock_session_recording("s2")]),
- ]
-
- tool = await self.create_tool()
- result, artifact = await tool._arun_impl(experiment_id=experiment.id)
-
- self.assertIn("date_range", artifact)
- # Django adds timezone info, so check if it starts with the expected date
- self.assertTrue(artifact["date_range"]["start"].startswith("2025-01-05T12:00:00"))
- self.assertTrue(artifact["date_range"]["end"].startswith("2025-01-20T12:00:00"))
-
- @patch("products.experiments.backend.max_tools.database_sync_to_async")
- @patch("products.experiments.backend.max_tools.capture_exception")
- async def test_general_exception_handling(self, mock_capture_exception, mock_db_sync):
- """Test that unexpected exceptions in get_experiment are caught and logged."""
- # Make database_sync_to_async raise an exception when fetching experiment
- mock_db_sync.side_effect = RuntimeError("Database connection lost")
-
- tool = await self.create_tool()
- result, artifact = await tool._arun_impl(experiment_id=123)
-
- self.assertIn("Failed to analyze session replays", result)
- self.assertEqual(artifact["error"], "analysis_failed")
- self.assertIn("Database connection lost", artifact["details"])
-
- self.assertEqual(mock_capture_exception.call_count, 1)
- call_kwargs = mock_capture_exception.call_args[1]
- self.assertEqual(call_kwargs["properties"]["team_id"], self.team.id)
- self.assertEqual(call_kwargs["properties"]["user_id"], self.user.id)
- self.assertEqual(call_kwargs["properties"]["experiment_id"], 123)
-
- async def test_format_summary_for_user_structure(self):
- """Test the structure and content of formatted user message."""
- tool = await self.create_tool()
-
- recording_counts = {"control": 100, "test": 150, "variant_c": 50}
- message = tool._format_summary_for_user(
- experiment_name="My Test Experiment", recording_counts=recording_counts, total_recordings=300
- )
-
- self.assertIn("📹 Session Replay Summary for 'My Test Experiment'", message)
- self.assertIn("Total recordings: 300", message)
- self.assertIn("Recordings by variant:", message)
- self.assertIn("control: 100 (33.3%)", message)
- self.assertIn("test: 150 (50.0%)", message)
- self.assertIn("variant_c: 50 (16.7%)", message)
- self.assertIn("To analyze user behavior patterns:", message)
- self.assertIn("filter and view specific recordings", message)
- self.assertIn("Compare behavior differences", message)
- self.assertIn("What would you like to explore?", message)
-
- async def test_experiment_with_empty_multivariate_variants_list(self):
- """Test handling when multivariate.variants is an empty list."""
- feature_flag = await FeatureFlag.objects.acreate(
- name="Empty variants flag",
- key="empty-variants",
- team=self.team,
- filters={
- "groups": [{"properties": [], "rollout_percentage": 100}],
- "multivariate": {"variants": []},
- },
- created_by=self.user,
- )
-
- experiment = await self.acreate_experiment(name="empty-variants-exp", feature_flag=feature_flag, started=True)
-
- tool = await self.create_tool()
- result, artifact = await tool._arun_impl(experiment_id=experiment.id)
-
- self.assertIn("No variants configured", result)
- self.assertEqual(artifact["error"], "no_variants")
diff --git a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
index f6a55dc0a9bd..40cae6b2ee7b 100644
--- a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
+++ b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
@@ -34,7 +34,7 @@
e.`$window_id` AS `$window_id`,
if(equals(e.event, 'user signed up'), 1, 0) AS step_0,
if(equals(e.event, 'user did things'), 1, 0) AS step_1,
- ([replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', '')] AS value) AS prop_basic,
+ ([e__person.properties___fish] AS value) AS prop_basic,
prop_basic AS prop
FROM events AS e
LEFT OUTER JOIN
@@ -44,6 +44,16 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0)), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
@@ -111,7 +121,17 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
+ WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
GROUP BY breakdown
@@ -168,8 +188,8 @@
e.uuid AS uuid,
e.`$session_id` AS `$session_id`,
e.`$window_id` AS `$window_id`,
- if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_0,
- if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_1
+ if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), 1, 0) AS step_0,
+ if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), 1, 0) AS step_1
FROM events AS e
LEFT OUTER JOIN
(SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
@@ -178,6 +198,16 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up'))), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
@@ -294,7 +324,24 @@
(SELECT count() AS total,
toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0)))
GROUP BY day_start)
GROUP BY day_start
ORDER BY day_start ASC)
@@ -326,7 +373,24 @@
(SELECT count() AS total,
toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
+ LEFT JOIN
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0)))
GROUP BY day_start)
GROUP BY day_start
ORDER BY day_start ASC)