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.

feat(product-analytics): paths v2 combined stack (slices 1-7) (#77085)

Thomas Obermüller880d4f3ba3b8
diff --git a/bin/patch-schema-property-filter-discriminator.py b/bin/patch-schema-property-filter-discriminator.py
index 4e8d1c91cacb..c69273753c50 100644
--- a/bin/patch-schema-property-filter-discriminator.py
+++ b/bin/patch-schema-property-filter-discriminator.py
@@ -72,7 +72,7 @@ EXPECTED_SITE_COUNTS = {
# recursive site, discriminated including the group via its AND/OR -> property_group tag.
"recursive": 1,
# Plain inlined runs: list[<members>], optionally `| PropertyGroupFilter` / `| None`.
- "plain": 63,
+ "plain": 64,
}
diff --git a/ee/hogai/context/insight/test/test_query_executor.py b/ee/hogai/context/insight/test/test_query_executor.py
index e722d09302b3..fd01a86ff73e 100644
--- a/ee/hogai/context/insight/test/test_query_executor.py
+++ b/ee/hogai/context/insight/test/test_query_executor.py
@@ -26,6 +26,8 @@ from posthog.schema import (
LifecycleQuery,
PathsFilter,
PathsQuery,
+ PathsV2Filter,
+ PathsV2Query,
RetentionFilter,
RetentionQuery,
StickinessQuery,
@@ -199,6 +201,31 @@ class TestAssistantQueryExecutor(NonAtomicBaseTest):
# Should NOT capture NotImplementedError
mock_capture.assert_not_called()
+ @patch("ee.hogai.context.insight.query_executor.capture_exception")
+ @patch("ee.hogai.context.insight.query_executor.process_query_dict")
+ async def test_paths_v2_query_degrades_to_json_fallback(self, mock_process_query: Mock, mock_capture: Mock) -> None:
+ # The assistant has no PathsV2Query formatter yet, so a journeys insight must degrade to
+ # the raw-JSON fallback instead of erroring.
+ results = {
+ "steps": [
+ {
+ "stepIndex": 0,
+ "rows": [{"item": {"event": "$pageview", "label": "/home"}, "count": 2}],
+ "otherCount": 0,
+ "dropOffCount": 1,
+ }
+ ],
+ "edges": [],
+ "prefixes": [],
+ }
+ mock_process_query.return_value = {"results": results}
+
+ result = await execute_and_format_query(self.team, PathsV2Query(pathsV2Filter=PathsV2Filter()), user=self.user)
+
+ self.assertIn("stepIndex", result)
+ self.assertIn("/home", result)
+ mock_capture.assert_not_called()
+
@patch("ee.hogai.context.insight.query_executor.process_query_dict")
async def test_run_and_format_query_handles_api_exception(self, mock_process_query):
"""Test handling of APIException"""
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightDetails.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightDetails.tsx
index cd59ec17ee76..93d43ff3a8d8 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightDetails.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightDetails.tsx
@@ -45,6 +45,7 @@ import {
Node,
NodeKind,
PathsQuery,
+ PathsV2Query,
RetentionQuery,
StickinessQuery,
TrendsFormulaNode,
@@ -67,6 +68,7 @@ import {
isInsightVizNode,
isLifecycleQuery,
isPathsQuery,
+ isPathsV2Query,
isRetentionQuery,
isTrendsQuery,
hasBreakdownFilter,
@@ -80,6 +82,8 @@ import {
UserBasicType,
} from '~/types'
+import { journeysSummaryParts } from 'products/product_analytics/frontend/insights/journeys/journeysSummary'
+
import { PropertyKeyInfo } from '../../PropertyKeyInfo'
import { TZLabel } from '../../TZLabel'
import { CompactUniversalFiltersDisplay } from './CompactUniversalFiltersDisplay'
@@ -301,6 +305,25 @@ function PathsSummary({ query }: { query: PathsQuery }): JSX.Element {
)
}
+function PathsV2Summary({ query }: { query: PathsV2Query }): JSX.Element {
+ // Sync format with summarizeJourneys in journeysSummary.ts
+ const { sources, anchor } = journeysSummaryParts(query.pathsV2Filter)
+ return (
+ <div className="SeriesDisplay">
+ <div>
+ <div>
+ Journeys based on <b>{sources}</b>
+ </div>
+ {anchor && (
+ <div>
+ {anchor.verb} at <b>{anchor.label}</b>
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
+
function RetentionSummary({ query }: { query: RetentionQuery }): JSX.Element {
const { aggregationLabel } = useValues(mathsLogic)
@@ -374,6 +397,8 @@ export function SeriesSummary({
{isTrendsQuery(query) && <FormulaSummary query={query} />}
{isPathsQuery(query) ? (
<PathsSummary query={query} />
+ ) : isPathsV2Query(query) ? (
+ <PathsV2Summary query={query} />
) : isRetentionQuery(query) ? (
<RetentionSummary query={query} />
) : isInsightQueryWithSeries(query) ? (
diff --git a/frontend/src/lib/components/PathCleanFilters/PathCleaningControls.tsx b/frontend/src/lib/components/PathCleanFilters/PathCleaningControls.tsx
new file mode 100644
index 000000000000..00dc72f8e273
--- /dev/null
+++ b/frontend/src/lib/components/PathCleanFilters/PathCleaningControls.tsx
@@ -0,0 +1,70 @@
+import { useValues } from 'kea'
+
+import { IconGear } from '@posthog/icons'
+import { LemonButton, LemonSwitch } from '@posthog/lemon-ui'
+
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import { PathCleaningFilter } from '~/types'
+
+import { PathCleanFilters } from './PathCleanFilters'
+
+interface PathCleaningControlsProps {
+ localFilters: PathCleaningFilter[]
+ setLocalFilters: (filters: PathCleaningFilter[]) => void
+ applyGlobal: boolean
+ setApplyGlobal: (apply: boolean) => void
+ 'data-attr'?: string
+}
+
+/** An insight's path cleaning configuration: its local rules plus the switch applying the
+ * project-wide rules, shared between the paths and journeys editors. */
+export function PathCleaningControls({
+ localFilters,
+ setLocalFilters,
+ applyGlobal,
+ setApplyGlobal,
+ 'data-attr': dataAttr,
+}: PathCleaningControlsProps): JSX.Element {
+ const { currentTeam } = useValues(teamLogic)
+ const hasGlobalRules = (currentTeam?.path_cleaning_filters || []).length > 0
+
+ return (
+ <>
+ <PathCleanFilters filters={localFilters} setFilters={setLocalFilters} />
+ <Tooltip
+ title={
+ hasGlobalRules
+ ? 'Apply the path cleaning rules from the project settings.'
+ : 'The project has no path cleaning rules. Configure them via the gear icon.'
+ }
+ >
+ {/* This div is necessary for the tooltip to work. */}
+ <div className="inline-block mt-4 w-full">
+ <LemonSwitch
+ disabled={!hasGlobalRules}
+ checked={hasGlobalRules && applyGlobal}
+ onChange={setApplyGlobal}
+ label={
+ <div className="flex items-center">
+ <span>Apply global path URL cleaning</span>
+ <LemonButton
+ icon={<IconGear />}
+ to={urls.settings('project-product-analytics', 'path-cleaning')}
+ size="small"
+ noPadding
+ className="ml-1"
+ />
+ </div>
+ }
+ fullWidth
+ bordered
+ data-attr={dataAttr}
+ />
+ </div>
+ </Tooltip>
+ </>
+ )
+}
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 1272f6a3437b..a3d3258268b9 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -571,6 +571,7 @@ export const INSIGHT_VISUAL_ORDER = {
funnel: 20,
retention: 30,
paths: 40,
+ journeys: 45,
stickiness: 50,
lifecycle: 60,
calendarHeatmap: 70,
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index b0ada0b63379..cf218965325b 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -1678,6 +1678,15 @@ export const getTreeItemsNew = (): FileSystemImport[] => [
visualOrder: INSIGHT_VISUAL_ORDER.funnel,
sceneKeys: ['Insight'],
},
+ {
+ path: `Insight/Journeys`,
+ type: 'insight',
+ href: urls.insightNew({ type: InsightType.JOURNEYS }),
+ flag: FEATURE_FLAGS.PRODUCT_ANALYTICS_PATHS_V2,
+ iconType: 'insight/paths',
+ visualOrder: INSIGHT_VISUAL_ORDER.journeys,
+ sceneKeys: ['Insight'],
+ },
{
path: `Insight/Lifecycle`,
type: 'insight',
diff --git a/frontend/src/queries/nodes/InsightQuery/defaults.ts b/frontend/src/queries/nodes/InsightQuery/defaults.ts
index 8d4c639f223d..6fedfa05a0b3 100644
--- a/frontend/src/queries/nodes/InsightQuery/defaults.ts
+++ b/frontend/src/queries/nodes/InsightQuery/defaults.ts
@@ -6,6 +6,7 @@ import {
LifecycleQuery,
NodeKind,
PathsQuery,
+ PathsV2Query,
RetentionQuery,
StickinessComputationModes,
StickinessQuery,
@@ -13,6 +14,8 @@ import {
} from '~/queries/schema/schema-general'
import { BaseMathType, ChartDisplayType, FunnelVizType, PathType, RetentionPeriod } from '~/types'
+import { STEP_SOURCE_PRESETS } from 'products/product_analytics/frontend/insights/journeys/stepSourcePresets'
+
function getTrendsQueryDefault(): TrendsQuery {
const defaultEvent = getDefaultEventName()
const defaultLabel = getDefaultEventLabel()
@@ -111,6 +114,16 @@ function getPathsQueryDefault(): PathsQuery {
}
}
+function getPathsV2QueryDefault(): PathsV2Query {
+ const preset = getDefaultEventName() === '$screen' ? STEP_SOURCE_PRESETS.screenViews : STEP_SOURCE_PRESETS.pageViews
+ return {
+ kind: NodeKind.PathsV2Query,
+ pathsV2Filter: {
+ stepSources: preset.stepSources,
+ },
+ }
+}
+
function getStickinessQueryDefault(): StickinessQuery {
const defaultEvent = getDefaultEventName()
const defaultLabel = getDefaultEventLabel()
@@ -162,6 +175,7 @@ export function getNodeKindToDefaultQuery(): Record<ProductAnalyticsInsightNodeK
[NodeKind.FunnelsQuery]: getFunnelsQueryDefault(),
[NodeKind.RetentionQuery]: getRetentionQueryDefault(),
[NodeKind.PathsQuery]: getPathsQueryDefault(),
+ [NodeKind.PathsV2Query]: getPathsV2QueryDefault(),
[NodeKind.StickinessQuery]: getStickinessQueryDefault(),
[NodeKind.LifecycleQuery]: getLifecycleQueryDefault(),
}
diff --git a/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts b/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts
index 0614bfbad575..601d3d026a3e 100644
--- a/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts
+++ b/frontend/src/queries/nodes/InsightQuery/utils/filtersToQueryNode.ts
@@ -80,7 +80,11 @@ import {
import { cleanEntityProperties, cleanGlobalProperties } from './cleanProperties'
const insightTypeToNodeKind: Record<
- Exclude<InsightType, InsightType.JSON | InsightType.SQL | InsightType.HOG | InsightType.WEB_ANALYTICS>,
+ // Journeys insights are query-native and never come from legacy filters
+ Exclude<
+ InsightType,
+ InsightType.JSON | InsightType.SQL | InsightType.HOG | InsightType.WEB_ANALYTICS | InsightType.JOURNEYS
+ >,
ProductAnalyticsInsightNodeKind
> = {
[InsightType.TRENDS]: NodeKind.TrendsQuery,
diff --git a/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.test.ts b/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.test.ts
index 3daa3992b9e8..c1e2a968c6a2 100644
--- a/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.test.ts
+++ b/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.test.ts
@@ -28,6 +28,16 @@ import {
} from '~/types'
describe('queryNodeToFilter', () => {
+ test('maps a paths v2 query to its insight type only, as it has no legacy filter format', () => {
+ const result = queryNodeToFilter({
+ kind: NodeKind.PathsV2Query,
+ dateRange: { date_from: '-7d' },
+ pathsV2Filter: { maxSteps: 4 },
+ })
+
+ expect(result).toEqual({ insight: InsightType.JOURNEYS })
+ })
+
test('converts a query node to a filter', () => {
const query: LifecycleQuery = {
kind: NodeKind.LifecycleQuery,
diff --git a/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.ts b/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.ts
index a9ad404ef63b..415f9d1ea437 100644
--- a/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.ts
+++ b/frontend/src/queries/nodes/InsightQuery/utils/queryNodeToFilter.ts
@@ -28,6 +28,7 @@ import {
isLifecycleDataWarehouseNode,
isLifecycleQuery,
isPathsQuery,
+ isPathsV2Query,
isRetentionQuery,
isStickinessQuery,
isTrendsQuery,
@@ -166,6 +167,7 @@ export const nodeKindToInsightType: Record<ProductAnalyticsInsightNodeKind, Insi
[NodeKind.FunnelsQuery]: InsightType.FUNNELS,
[NodeKind.RetentionQuery]: InsightType.RETENTION,
[NodeKind.PathsQuery]: InsightType.PATHS,
+ [NodeKind.PathsV2Query]: InsightType.JOURNEYS,
[NodeKind.StickinessQuery]: InsightType.STICKINESS,
[NodeKind.LifecycleQuery]: InsightType.LIFECYCLE,
}
@@ -175,6 +177,7 @@ const nodeKindToFilterKey: Record<ProductAnalyticsInsightNodeKind, string> = {
[NodeKind.FunnelsQuery]: 'funnelsFilter',
[NodeKind.RetentionQuery]: 'retentionFilter',
[NodeKind.PathsQuery]: 'pathsFilter',
+ [NodeKind.PathsV2Query]: 'pathsV2Filter',
[NodeKind.StickinessQuery]: 'stickinessFilter',
[NodeKind.LifecycleQuery]: 'lifecycleFilter',
}
@@ -187,6 +190,13 @@ export const queryNodeToFilter = (query: InsightQueryNode): Partial<FilterType>
}
}
+ // Paths v2 queries don't have a legacy filter format either
+ if (isPathsV2Query(query)) {
+ return {
+ insight: InsightType.JOURNEYS,
+ }
+ }
+
const filters: Partial<FilterType> = objectClean({
insight: nodeKindToInsightType[query.kind],
properties: query.properties,
diff --git a/frontend/src/queries/nodes/InsightViz/EditorFilters.tsx b/frontend/src/queries/nodes/InsightViz/EditorFilters.tsx
index 71ce8438b614..f97e65f25c3c 100644
--- a/frontend/src/queries/nodes/InsightViz/EditorFilters.tsx
+++ b/frontend/src/queries/nodes/InsightViz/EditorFilters.tsx
@@ -39,6 +39,10 @@ import {
PathType,
} from '~/types'
+import { JourneysExclusions } from 'products/product_analytics/frontend/insights/journeys/JourneysExclusions'
+import { JourneysSettings } from 'products/product_analytics/frontend/insights/journeys/JourneysSettings'
+import { JourneysStepSourcePicker } from 'products/product_analytics/frontend/insights/journeys/JourneysStepSourcePicker'
+
import { Breakdown } from './Breakdown'
import { CumulativeStickinessFilter } from './CumulativeStickinessFilter'
import { EditorFilterGroup } from './EditorFilterGroup'
@@ -63,11 +67,13 @@ export function EditorFilters({ query, showing, embedded }: EditorFiltersProps):
isFunnels,
isRetention,
isPaths,
+ isPathsV2,
isLifecycle,
isStickiness,
isTrendsLike,
display,
pathsFilter,
+ pathsV2Filter,
querySource,
series,
breakdownFilter,
@@ -117,7 +123,11 @@ export function EditorFilters({ query, showing, embedded }: EditorFiltersProps):
const seriesSummary = getSeriesSummary(series)
const filtersSummary = getFiltersSummary(properties)
const breakdownSummary = getBreakdownSummary(breakdownFilter)
- const exclusionCount = isPaths ? (pathsFilter?.excludeEvents?.length ?? 0) : 0
+ const exclusionCount = isPaths
+ ? (pathsFilter?.excludeEvents?.length ?? 0)
+ : isPathsV2
+ ? (pathsV2Filter?.excludedItems?.length ?? 0)
+ : 0
const exclusionsSummary = exclusionCount > 0 ? pluralize(exclusionCount, 'exclusion') : null
const leftEditorFilterGroups: InsightEditorFilterGroup[] = [
@@ -149,6 +159,18 @@ export function EditorFilters({ query, showing, embedded }: EditorFiltersProps):
editorFilters: visibleFilters([
{ key: 'query-steps', component: FunnelsQuerySteps, show: isFunnels },
{ key: 'event-types', label: 'Event Types', component: PathsEventsTypes, show: isPaths },
+ {
+ key: 'step-source',
+ label: 'Step sources',
+ tooltip: (
+ <>
+ The events that can appear as steps in a journey. Each source is an event, optionally named
+ by a property: page views named by their URL path, for example.
+ </>
+ ),
+ component: JourneysStepSourcePicker,
+ show: isPathsV2,
+ },
{
key: 'hogql',
label: 'SQL Expression',
@@ -192,10 +214,17 @@ export function EditorFilters({ query, showing, embedded }: EditorFiltersProps):
]),
},
{
- title: isFunnels ? 'Funnel settings' : isPaths ? 'Path settings' : 'Advanced options',
+ title: isFunnels
+ ? 'Funnel settings'
+ : isPaths
+ ? 'Path settings'
+ : isPathsV2
+ ? 'Journey settings'
+ : 'Advanced options',
defaultExpanded: false,
editorFilters: visibleFilters([
{ key: 'paths-advanced', component: PathsAdvanced, show: isPaths },
+ { key: 'journeys-settings', component: JourneysSettings, show: isPathsV2 },
{
key: 'funnel-step-configuration',
component: FunnelStepConfiguration,
@@ -350,6 +379,18 @@ export function EditorFilters({ query, showing, embedded }: EditorFiltersProps):
component: PathsExclusions,
show: isPaths,
},
+ {
+ key: 'journeys-exclusions',
+ label: 'Exclusions',
+ tooltip: (
+ <>
+ Exclude specific path items. Their events are ignored entirely, on the chart and in any
+ funnel created from it.
+ </>
+ ),
+ component: JourneysExclusions,
+ show: isPathsV2,
+ },
]),
},
// Hide advanced options for calendar heatmap
diff --git a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
index 88cd0eb1983e..cab2e2c3f577 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
@@ -40,7 +40,6 @@ import { FunnelStepsTable } from 'scenes/insights/views/Funnels/FunnelStepsTable
import { FunnelTimeToConvertTable } from 'scenes/insights/views/Funnels/FunnelTimeToConvertTable'
import { FunnelTrendsTable } from 'scenes/insights/views/Funnels/FunnelTrendsTable'
import { InsightsTable } from 'scenes/insights/views/InsightsTable/InsightsTable'
-import { PathsV2 } from 'scenes/paths-v2/PathsV2'
import { Paths } from 'scenes/paths/Paths'
import { PathCanvasLabel } from 'scenes/paths/PathsLabel'
import { RetentionContainer } from 'scenes/retention/RetentionContainer'
@@ -60,6 +59,8 @@ import {
PropertyMathType,
} from '~/types'
+import { Journeys } from 'products/product_analytics/frontend/insights/journeys/Journeys'
+
import { InsightDisplayConfig } from './InsightDisplayConfig'
import { InsightResultMetadata } from './InsightResultMetadata'
import { ResultCustomizationsModal } from './ResultCustomizationsModal'
@@ -142,8 +143,7 @@ export function InsightVizDisplay({
inSharedMode?: boolean
editMode?: boolean
}): JSX.Element | null {
- const { insightProps, canEditInsight, isUsingPathsV1, isUsingPathsV2, isInDashboardContext } =
- useValues(insightLogic)
+ const { insightProps, canEditInsight, isInDashboardContext } = useValues(insightLogic)
const { activeView } = useValues(insightNavLogic(insightProps))
@@ -381,7 +381,9 @@ export function InsightVizDisplay({
/>
)
case InsightType.PATHS:
- return isUsingPathsV2 ? <PathsV2 /> : <Paths />
+ return <Paths />
+ case InsightType.JOURNEYS:
+ return <Journeys showPersonsModal={!inSharedMode} />
case InsightType.WEB_ANALYTICS:
return <WebAnalyticsInsight context={context} editMode={editMode} />
default:
@@ -525,7 +527,7 @@ export function InsightVizDisplay({
</div>
<div className="flex items-center gap-2">
- {isPaths && isUsingPathsV1 && <PathCanvasLabel />}
+ {isPaths && <PathCanvasLabel />}
{isFunnels && <FunnelCanvasLabel />}
</div>
</div>
diff --git a/frontend/src/queries/nodes/InsightViz/utils.ts b/frontend/src/queries/nodes/InsightViz/utils.ts
index d5b9c03d405a..8d9205354ec8 100644
--- a/frontend/src/queries/nodes/InsightViz/utils.ts
+++ b/frontend/src/queries/nodes/InsightViz/utils.ts
@@ -162,6 +162,8 @@ export const getDefaultQuery = (
return queryFromKind(NodeKind.RetentionQuery, filterTestAccountsDefault)
} else if (insightType === InsightType.PATHS) {
return queryFromKind(NodeKind.PathsQuery, filterTestAccountsDefault)
+ } else if (insightType === InsightType.JOURNEYS) {
+ return queryFromKind(NodeKind.PathsV2Query, filterTestAccountsDefault)
} else if (insightType === InsightType.STICKINESS) {
return queryFromKind(NodeKind.StickinessQuery, filterTestAccountsDefault)
} else if (insightType === InsightType.LIFECYCLE) {
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 5816817fa25c..7bd8cbb2d080 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -530,6 +530,9 @@
{
"$ref": "#/definitions/StickinessActorsQuery"
},
+ {
+ "$ref": "#/definitions/PathsV2ActorsQuery"
+ },
{
"$ref": "#/definitions/HogQLQuery"
}
@@ -10841,6 +10844,103 @@
],
"type": "object"
},
+ "CachedPathsV2QueryResponse": {
+ "additionalProperties": false,
+ "properties": {
+ "cache_key": {
+ "type": "string"
+ },
+ "cache_target_age": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "calculation_trigger": {
+ "description": "What triggered the calculation of the query, leave empty if user/immediate",
+ "type": "string"
+ },
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "is_cached": {
+ "type": "boolean"
+ },
+ "last_refresh": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "next_allowed_client_refresh": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "query_metadata": {
+ "type": "object"
+ },
+ "query_status": {
+ "$ref": "#/definitions/QueryStatus",
+ "description": "Query status indicates whether next to the provided data, a query is still running."
+ },
+ "resolved_compare_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The resolved previous/comparison period date range, when comparing against another period"
+ },
+ "resolved_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The date range used for the query"
+ },
+ "results": {
+ "$ref": "#/definitions/PathsV2Results"
+ },
+ "timezone": {
+ "type": "string"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "used_data_warehouse_sources": {
+ "description": "Connector-synced data warehouse sources referenced by this query, if any.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSourceUsage"
+ },
+ "type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ {
+ "$ref": "#/definitions/AccessControlFilterWarning"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "cache_key",
+ "is_cached",
+ "last_refresh",
+ "next_allowed_client_refresh",
+ "results",
+ "timezone"
+ ],
+ "type": "object"
+ },
"CachedPropertyValuesQueryResponse": {
"additionalProperties": false,
"properties": {
@@ -27550,6 +27650,9 @@
},
{
"$ref": "#/definitions/ExperimentActorsQuery"
+ },
+ {
+ "$ref": "#/definitions/PathsV2ActorsQuery"
}
]
},
@@ -27691,6 +27794,9 @@
{
"$ref": "#/definitions/PathsFilter"
},
+ {
+ "$ref": "#/definitions/PathsV2Filter"
+ },
{
"$ref": "#/definitions/StickinessFilter"
},
@@ -27711,6 +27817,7 @@
"funnelsFilter",
"retentionFilter",
"pathsFilter",
+ "pathsV2Filter",
"stickinessFilter",
"calendarHeatmapFilter",
"lifecycleFilter",
@@ -27724,6 +27831,7 @@
"FunnelsQuery",
"RetentionQuery",
"PathsQuery",
+ "PathsV2Query",
"StickinessQuery",
"LifecycleQuery",
"WebStatsTableQuery",
@@ -27758,6 +27866,9 @@
{
"$ref": "#/definitions/PathsQuery"
},
+ {
+ "$ref": "#/definitions/PathsV2Query"
+ },
{
"$ref": "#/definitions/StickinessQuery"
},
@@ -35310,6 +35421,7 @@
"GroupsQuery",
"FunnelsActorsQuery",
"FunnelCorrelationActorsQuery",
+ "PathsV2ActorsQuery",
"SessionsTimelineQuery",
"RecordingsQuery",
"SessionAttributionExplorerQuery",
@@ -35336,6 +35448,7 @@
"FunnelsQuery",
"RetentionQuery",
"PathsQuery",
+ "PathsV2Query",
"StickinessQuery",
"StickinessActorsQuery",
"LifecycleQuery",
@@ -36080,6 +36193,462 @@
"required": ["results"],
"type": "object"
},
+ "PathsV2ActorsQuery": {
+ "additionalProperties": false,
+ "properties": {
+ "element": {
+ "$ref": "#/definitions/PathsV2ElementSelector"
+ },
+ "includeRecordings": {
+ "type": "boolean"
+ },
+ "kind": {
+ "const": "PathsV2ActorsQuery",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "response": {
+ "$ref": "#/definitions/ActorsQueryResponse"
+ },
+ "source": {
+ "$ref": "#/definitions/PathsV2Query"
+ },
+ "tags": {
+ "$ref": "#/definitions/QueryLogTags"
+ },
+ "version": {
+ "description": "version of the node, used for schema migrations",
+ "type": "number"
+ }
+ },
+ "required": ["element", "kind", "source"],
+ "type": "object"
+ },
+ "PathsV2Anchor": {
+ "additionalProperties": false,
+ "description": "The start or end point an anchored-mode chart is built around.",
+ "properties": {
+ "item": {
+ "$ref": "#/definitions/PathsV2Item",
+ "description": "The path item the chart anchors on. Its event must be one of the step sources."
+ },
+ "type": {
+ "$ref": "#/definitions/PathsV2AnchorType",
+ "description": "`start` runs each actor's single sequence forward from the anchor item; `end` runs it up to the anchor item. Either way the anchor is the grid's single 100% node."
+ }
+ },
+ "required": ["type", "item"],
+ "type": "object"
+ },
+ "PathsV2AnchorType": {
+ "description": "Whether an anchored chart is built around the journeys' start or their end.",
+ "enum": ["start", "end"],
+ "type": "string"
+ },
+ "PathsV2Edge": {
+ "additionalProperties": false,
+ "description": "A displayed transition between path items at adjacent journey grid columns.",
+ "properties": {
+ "anyStepCount": {
+ "description": "Unique actors who transition from source to target at any step of any of their whole journeys, the position-free count behind \"went source → target at any step\". Equals the two-step item-strict funnel's converted count. Only set in open mode on edges between two named items.",
+ "type": "number"
+ },
+ "count": {
+ "description": "Unique actors with a journey that transitions from source to target between these steps.",
+ "type": "number"
+ },
+ "source": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/PathsV2Item"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Source path item, or null for the source column's \"other\" row."
+ },
+ "stepIndex": {
+ "$ref": "#/definitions/integer",
+ "description": "0-based step index of the source column; the target sits at `stepIndex + 1`."
+ },
+ "target": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/PathsV2Item"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Target path item, or null for the target column's \"other\" row."
+ }
+ },
+ "required": ["stepIndex", "source", "target", "count"],
+ "type": "object"
+ },
+ "PathsV2ElementSelector": {
+ "additionalProperties": false,
+ "description": "Selects the journey grid element whose actors a PathsV2ActorsQuery returns. The same journeys that produced the grid produce these actor sets, so each element's modal equals its displayed number by construction.",
+ "properties": {
+ "anyStep": {
+ "description": "Match the source → target transition at any step of any whole journey instead of at one step pair: the position-free set behind an edge's anyStepCount. Requires a named source and target and open mode. Edge elements only.",
+ "type": "boolean"
+ },
+ "chain": {
+ "description": "The chain's path items in order from the anchor. Returns the actors whose anchored sequence begins with exactly these items, the set behind a hover preview's per-chain counts. Chain elements only, anchored mode only. Bounded by the step maximum: a longer chain can never match a displayed card.",
+ "items": {
+ "$ref": "#/definitions/PathsV2Item"
+ },
+ "maxItems": 20,
+ "type": "array"
+ },
+ "elementType": {
+ "$ref": "#/definitions/PathsV2ElementType"
+ },
+ "item": {
+ "$ref": "#/definitions/PathsV2Item",
+ "description": "The node card's path item. Node elements only."
+ },
+ "source": {
+ "$ref": "#/definitions/PathsV2Item",
+ "description": "The edge's source path item; omit for the source column's \"other\" row. Edge elements only."
+ },
+ "stepIndex": {
+ "$ref": "#/definitions/integer",
+ "description": "0-based step index (column) of the element; for an edge, its source column. Required for node, other, dropOff, and positional edge elements."
+ },
+ "target": {
+ "$ref": "#/definitions/PathsV2Item",
+ "description": "The edge's target path item; omit for the target column's \"other\" row. Edge elements only."
+ }
+ },
+ "required": ["elementType"],
+ "type": "object"
+ },
+ "PathsV2ElementType": {
+ "description": "The kind of journey grid element a PathsV2ActorsQuery drills into.",
+ "enum": ["node", "edge", "dropOff", "other", "chain"],
+ "type": "string"
+ },
+ "PathsV2Filter": {
+ "additionalProperties": false,
+ "properties": {
+ "anchor": {
+ "$ref": "#/definitions/PathsV2Anchor",
+ "description": "Anchor selecting anchored mode. When set, each actor contributes exactly one sequence bounded by the conversion window, so every displayed segment equals a plain funnel. Absent selects open mode, which splits an actor's events into journeys on the inactivity gap instead."
+ },
+ "applyTeamPathCleaning": {
+ "default": true,
+ "description": "Apply the team's path cleaning rules to naming property values before they become path items.",
+ "type": "boolean"
+ },
+ "collapseRepeats": {
+ "default": true,
+ "description": "Merge immediate repeats of the same path item within a journey.",
+ "type": "boolean"
+ },
+ "conversionWindowInterval": {
+ "default": 30,
+ "description": "Anchored mode's single conversion window W, anchored at the anchor and reused verbatim as the emitted funnel's window. Bounds per unit are validated server-side against CONVERSION_WINDOW_INTERVAL_BOUNDS, the same funnel conversion window bounds as the gap.",
+ "type": "integer"
+ },
+ "conversionWindowIntervalUnit": {
+ "$ref": "#/definitions/FunnelConversionWindowTimeUnit",
+ "default": "minute"
+ },
+ "excludedItems": {
+ "description": "Path items dropped from the item universe: events deriving to one of these items are ignored as if their event were not a step source, on both the paths side and the \"view as funnel\" side.",
+ "items": {
+ "$ref": "#/definitions/PathsV2Item"
+ },
+ "maxItems": 100,
+ "type": "array"
+ },
+ "gapInterval": {
+ "default": 30,
+ "description": "Inactivity gap that splits an actor's events into journeys. Bounds per unit are validated server-side against CONVERSION_WINDOW_INTERVAL_BOUNDS, the funnel conversion window bounds.",
+ "type": "integer"
+ },
+ "gapIntervalUnit": {
+ "$ref": "#/definitions/FunnelConversionWindowTimeUnit",
+ "default": "minute"
+ },
+ "localPathCleaningFilters": {
+ "description": "Path cleaning rules for this insight only, applied after the team's rules.",
+ "items": {
+ "$ref": "#/definitions/PathCleaningFilter"
+ },
+ "type": "array"
+ },
+ "maxRowsPerStep": {
+ "default": 3,
+ "description": "Number of path item rows per step; items beyond this go into the \"other\" row.",
+ "maximum": 10,
+ "minimum": 1,
+ "type": "integer"
+ },
+ "maxSteps": {
+ "default": 5,
+ "description": "Number of journey steps (columns) shown.",
+ "maximum": 20,
+ "minimum": 2,
+ "type": "integer"
+ },
+ "stepSources": {
+ "description": "Step sources defining which events can become path items. Defaults to the pageviews preset: `$pageview` named by `$pathname`.",
+ "items": {
+ "$ref": "#/definitions/PathsV2StepSource"
+ },
+ "maxItems": 20,
+ "minItems": 1,
+ "type": "array"
+ }
+ },
+ "type": "object"
+ },
+ "PathsV2Item": {
+ "additionalProperties": false,
+ "description": "Identity of a journey grid node: the step source's event plus the label value.",
+ "properties": {
+ "event": {
+ "description": "Event of the step source this item belongs to.",
+ "type": "string"
+ },
+ "label": {
+ "description": "Label value from the source's naming property, after path cleaning. An empty string when the property is missing on the event. Null for sources without a naming property.",
+ "type": ["string", "null"]
+ }
+ },
+ "required": ["event"],
+ "type": "object"
+ },
+ "PathsV2Prefix": {
+ "additionalProperties": false,
+ "description": "A concrete anchored chain from the anchor and the unique actors whose single sequence begins with exactly these path items. Powers the hover funnel preview over the journey grid.",
+ "properties": {
+ "count": {
+ "description": "Unique actors whose anchored sequence begins with exactly these items.",
+ "type": "number"
+ },
+ "items": {
+ "description": "The chain's path items in order, starting at the anchor.",
+ "items": {
+ "$ref": "#/definitions/PathsV2Item"
+ },
+ "type": "array"
+ }
+ },
+ "required": ["items", "count"],
+ "type": "object"
+ },
+ "PathsV2Query": {
+ "additionalProperties": false,
+ "properties": {
+ "dataColorTheme": {
+ "description": "Colors used in the insight's visualization",
+ "type": ["number", "null"]
+ },
+ "dateRange": {
+ "$ref": "#/definitions/DateRange",
+ "description": "Date range for the query"
+ },
+ "filterTestAccounts": {
+ "default": false,
+ "description": "Exclude internal and test users by applying the respective filters",
+ "type": "boolean"
+ },
+ "kind": {
+ "const": "PathsV2Query",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "pathsV2Filter": {
+ "$ref": "#/definitions/PathsV2Filter",
+ "description": "Properties specific to the paths v2 insight"
+ },
+ "properties": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/definitions/AnyPropertyFilter"
+ },
+ "type": "array"
+ },
+ {
+ "$ref": "#/definitions/PropertyGroupFilter"
+ }
+ ],
+ "default": [],
+ "description": "Property filters for all series"
+ },
+ "response": {
+ "$ref": "#/definitions/PathsV2QueryResponse"
+ },
+ "tags": {
+ "$ref": "#/definitions/QueryLogTags",
+ "description": "Tags that will be added to the Query log comment"
+ },
+ "version": {
+ "description": "version of the node, used for schema migrations",
+ "type": "number"
+ }
+ },
+ "required": ["kind"],
+ "type": "object"
+ },
+ "PathsV2QueryResponse": {
+ "additionalProperties": false,
+ "properties": {
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "query_status": {
+ "$ref": "#/definitions/QueryStatus",
+ "description": "Query status indicates whether next to the provided data, a query is still running."
+ },
+ "resolved_compare_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The resolved previous/comparison period date range, when comparing against another period"
+ },
+ "resolved_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The date range used for the query"
+ },
+ "results": {
+ "$ref": "#/definitions/PathsV2Results"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "used_data_warehouse_sources": {
+ "description": "Connector-synced data warehouse sources referenced by this query, if any.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSourceUsage"
+ },
+ "type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ {
+ "$ref": "#/definitions/AccessControlFilterWarning"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": ["results"],
+ "type": "object"
+ },
+ "PathsV2Results": {
+ "additionalProperties": false,
+ "properties": {
+ "edges": {
+ "items": {
+ "$ref": "#/definitions/PathsV2Edge"
+ },
+ "type": "array"
+ },
+ "prefixes": {
+ "description": "Concrete anchored chains with per-chain unique-actor counts, ordered by descending count. Empty in open mode; in anchored mode it carries the counts the hover funnel preview reads per chain. Only chains the grid displays in full are carried: chains through the other bucket are omitted, so the response never exposes labels the chart hides.",
+ "items": {
+ "$ref": "#/definitions/PathsV2Prefix"
+ },
+ "type": "array"
+ },
+ "steps": {
+ "items": {
+ "$ref": "#/definitions/PathsV2Step"
+ },
+ "type": "array"
+ }
+ },
+ "required": ["steps", "edges", "prefixes"],
+ "type": "object"
+ },
+ "PathsV2Row": {
+ "additionalProperties": false,
+ "description": "One row of a journey grid column: a path item and its unique-actor count.",
+ "properties": {
+ "count": {
+ "description": "Unique actors with a journey whose item at this step is this path item.",
+ "type": "number"
+ },
+ "item": {
+ "$ref": "#/definitions/PathsV2Item"
+ }
+ },
+ "required": ["item", "count"],
+ "type": "object"
+ },
+ "PathsV2Step": {
+ "additionalProperties": false,
+ "description": "One journey grid column: the top path items at a step, plus other-row and drop-off counts.",
+ "properties": {
+ "dropOffCount": {
+ "description": "Unique actors whose journey ends at this step.",
+ "type": "number"
+ },
+ "otherCount": {
+ "description": "Unique actors at this step whose path item is beyond the top rows.",
+ "type": "number"
+ },
+ "rows": {
+ "description": "Top path items at this step, ordered by unique-actor count descending.",
+ "items": {
+ "$ref": "#/definitions/PathsV2Row"
+ },
+ "type": "array"
+ },
+ "stepIndex": {
+ "$ref": "#/definitions/integer",
+ "description": "0-based step index (column) in the journey grid."
+ }
+ },
+ "required": ["stepIndex", "rows", "otherCount", "dropOffCount"],
+ "type": "object"
+ },
+ "PathsV2StepSource": {
+ "additionalProperties": false,
+ "description": "A step source defines which events can become path items in a paths v2 query.",
+ "properties": {
+ "event": {
+ "description": "Name of the event this source matches.",
+ "type": "string"
+ },
+ "namingProperty": {
+ "description": "Event property whose value labels the path item, e.g. `$pathname` for pageviews. Team path cleaning rules are applied to the value. Without a naming property, the event itself is the path item.",
+ "type": "string"
+ }
+ },
+ "required": ["event"],
+ "type": "object"
+ },
"PersistedFolder": {
"additionalProperties": false,
"properties": {
@@ -36350,6 +36919,9 @@
{
"$ref": "#/definitions/PathsQuery"
},
+ {
+ "$ref": "#/definitions/PathsV2Query"
+ },
{
"$ref": "#/definitions/StickinessQuery"
},
@@ -41726,6 +42298,68 @@
"required": ["results"],
"type": "object"
},
+ {
+ "additionalProperties": false,
+ "properties": {
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "query_status": {
+ "$ref": "#/definitions/QueryStatus",
+ "description": "Query status indicates whether next to the provided data, a query is still running."
+ },
+ "resolved_compare_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The resolved previous/comparison period date range, when comparing against another period"
+ },
+ "resolved_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The date range used for the query"
+ },
+ "results": {
+ "$ref": "#/definitions/PathsV2Results"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "used_data_warehouse_sources": {
+ "description": "Connector-synced data warehouse sources referenced by this query, if any.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSourceUsage"
+ },
+ "type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ {
+ "$ref": "#/definitions/AccessControlFilterWarning"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": ["results"],
+ "type": "object"
+ },
{
"additionalProperties": false,
"properties": {
@@ -44733,6 +45367,9 @@
{
"$ref": "#/definitions/PathsQuery"
},
+ {
+ "$ref": "#/definitions/PathsV2Query"
+ },
{
"$ref": "#/definitions/StickinessQuery"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index ab1f4ec3acf6..7865793d3cfe 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -40,6 +40,7 @@ import {
LifecycleToggle,
LogEntryPropertyFilter,
MatchedRecordingEvent,
+ PathCleaningFilter,
PathsFilterType,
PersonPropertyFilter,
PropertyGroupFilter,
@@ -95,6 +96,7 @@ export enum NodeKind {
GroupsQuery = 'GroupsQuery',
FunnelsActorsQuery = 'FunnelsActorsQuery',
FunnelCorrelationActorsQuery = 'FunnelCorrelationActorsQuery',
+ PathsV2ActorsQuery = 'PathsV2ActorsQuery',
SessionsTimelineQuery = 'SessionsTimelineQuery',
RecordingsQuery = 'RecordingsQuery',
SessionAttributionExplorerQuery = 'SessionAttributionExplorerQuery',
@@ -124,6 +126,7 @@ export enum NodeKind {
FunnelsQuery = 'FunnelsQuery',
RetentionQuery = 'RetentionQuery',
PathsQuery = 'PathsQuery',
+ PathsV2Query = 'PathsV2Query',
StickinessQuery = 'StickinessQuery',
StickinessActorsQuery = 'StickinessActorsQuery',
LifecycleQuery = 'LifecycleQuery',
@@ -348,6 +351,7 @@ export type QuerySchema =
| FunnelsQuery
| RetentionQuery
| PathsQuery
+ | PathsV2Query
| StickinessQuery
| LifecycleQuery
| FunnelCorrelationQuery
@@ -2035,6 +2039,191 @@ export interface PathsQuery extends InsightsQueryBase<PathsQueryResponse> {
funnelPathsFilter?: FunnelPathsFilter
}
+/** A step source defines which events can become path items in a paths v2 query. */
+export type PathsV2StepSource = {
+ /** Name of the event this source matches. */
+ event: string
+ /**
+ * Event property whose value labels the path item, e.g. `$pathname` for pageviews.
+ * Team path cleaning rules are applied to the value. Without a naming property,
+ * the event itself is the path item.
+ */
+ namingProperty?: string
+}
+
+/** Identity of a journey grid node: the step source's event plus the label value. */
+export type PathsV2Item = {
+ /** Event of the step source this item belongs to. */
+ event: string
+ /**
+ * Label value from the source's naming property, after path cleaning. An empty string when
+ * the property is missing on the event. Null for sources without a naming property.
+ */
+ label?: string | null
+}
+
+/** One row of a journey grid column: a path item and its unique-actor count. */
+export type PathsV2Row = {
+ item: PathsV2Item
+ /** Unique actors with a journey whose item at this step is this path item. */
+ count: number
+}
+
+/** One journey grid column: the top path items at a step, plus other-row and drop-off counts. */
+export type PathsV2Step = {
+ /** 0-based step index (column) in the journey grid. */
+ stepIndex: integer
+ /** Top path items at this step, ordered by unique-actor count descending. */
+ rows: PathsV2Row[]
+ /** Unique actors at this step whose path item is beyond the top rows. */
+ otherCount: number
+ /** Unique actors whose journey ends at this step. */
+ dropOffCount: number
+}
+
+/** A displayed transition between path items at adjacent journey grid columns. */
+export type PathsV2Edge = {
+ /** 0-based step index of the source column; the target sits at `stepIndex + 1`. */
+ stepIndex: integer
+ /** Source path item, or null for the source column's "other" row. */
+ source: PathsV2Item | null
+ /** Target path item, or null for the target column's "other" row. */
+ target: PathsV2Item | null
+ /** Unique actors with a journey that transitions from source to target between these steps. */
+ count: number
+ /**
+ * Unique actors who transition from source to target at any step of any of their whole
+ * journeys, the position-free count behind "went source → target at any step". Equals the
+ * two-step item-strict funnel's converted count. Only set in open mode on edges between two
+ * named items.
+ */
+ anyStepCount?: number
+}
+
+/**
+ * A concrete anchored chain from the anchor and the unique actors whose single sequence begins with
+ * exactly these path items. Powers the hover funnel preview over the journey grid.
+ */
+export type PathsV2Prefix = {
+ /** The chain's path items in order, starting at the anchor. */
+ items: PathsV2Item[]
+ /** Unique actors whose anchored sequence begins with exactly these items. */
+ count: number
+}
+
+export type PathsV2Results = {
+ steps: PathsV2Step[]
+ edges: PathsV2Edge[]
+ /**
+ * Concrete anchored chains with per-chain unique-actor counts, ordered by descending count. Empty
+ * in open mode; in anchored mode it carries the counts the hover funnel preview reads per chain.
+ * Only chains the grid displays in full are carried: chains through the other bucket are omitted,
+ * so the response never exposes labels the chart hides.
+ */
+ prefixes: PathsV2Prefix[]
+}
+
+export interface PathsV2QueryResponse extends AnalyticsQueryResponseBase {
+ results: PathsV2Results
+}
+
+export type CachedPathsV2QueryResponse = CachedQueryResponse<PathsV2QueryResponse>
+
+/** Whether an anchored chart is built around the journeys' start or their end. */
+export enum PathsV2AnchorType {
+ Start = 'start',
+ End = 'end',
+}
+
+/** The start or end point an anchored-mode chart is built around. */
+export type PathsV2Anchor = {
+ /**
+ * `start` runs each actor's single sequence forward from the anchor item; `end` runs it up to the
+ * anchor item. Either way the anchor is the grid's single 100% node.
+ */
+ type: PathsV2AnchorType
+ /** The path item the chart anchors on. Its event must be one of the step sources. */
+ item: PathsV2Item
+}
+
+export type PathsV2Filter = {
+ /**
+ * Step sources defining which events can become path items. Defaults to the pageviews
+ * preset: `$pageview` named by `$pathname`.
+ * @minItems 1
+ * @maxItems 20
+ */
+ stepSources?: PathsV2StepSource[]
+ /**
+ * Anchor selecting anchored mode. When set, each actor contributes exactly one sequence bounded by
+ * the conversion window, so every displayed segment equals a plain funnel. Absent selects open
+ * mode, which splits an actor's events into journeys on the inactivity gap instead.
+ */
+ anchor?: PathsV2Anchor
+ /**
+ * Anchored mode's single conversion window W, anchored at the anchor and reused verbatim as the
+ * emitted funnel's window. Bounds per unit are validated server-side against
+ * CONVERSION_WINDOW_INTERVAL_BOUNDS, the same funnel conversion window bounds as the gap.
+ * @asType integer
+ * @default 30
+ */
+ conversionWindowInterval?: number
+ /** @default minute */
+ conversionWindowIntervalUnit?: FunnelConversionWindowTimeUnit
+ /**
+ * Number of journey steps (columns) shown.
+ * @asType integer
+ * @default 5
+ * @minimum 2
+ * @maximum 20
+ */
+ maxSteps?: number
+ /**
+ * Number of path item rows per step; items beyond this go into the "other" row.
+ * @asType integer
+ * @default 3
+ * @minimum 1
+ * @maximum 10
+ */
+ maxRowsPerStep?: number
+ /**
+ * Inactivity gap that splits an actor's events into journeys. Bounds per unit are validated
+ * server-side against CONVERSION_WINDOW_INTERVAL_BOUNDS, the funnel conversion window bounds.
+ * @asType integer
+ * @default 30
+ */
+ gapInterval?: number
+ /** @default minute */
+ gapIntervalUnit?: FunnelConversionWindowTimeUnit
+ /**
+ * Merge immediate repeats of the same path item within a journey.
+ * @default true
+ */
+ collapseRepeats?: boolean
+ /**
+ * Path items dropped from the item universe: events deriving to one of these items are ignored
+ * as if their event were not a step source, on both the paths side and the "view as funnel" side.
+ * @maxItems 100
+ */
+ excludedItems?: PathsV2Item[]
+ /**
+ * Apply the team's path cleaning rules to naming property values before they become path items.
+ * @default true
+ */
+ applyTeamPathCleaning?: boolean
+ /** Path cleaning rules for this insight only, applied after the team's rules. */
+ localPathCleaningFilters?: PathCleaningFilter[]
+}
+
+export interface PathsV2Query extends Omit<
+ InsightsQueryBase<PathsV2QueryResponse>,
+ 'samplingFactor' | 'aggregation_group_type_index'
+> {
+ kind: NodeKind.PathsV2Query
+ /** Properties specific to the paths v2 insight */
+ pathsV2Filter?: PathsV2Filter
+}
+
/** `StickinessFilterType` minus everything inherited from `FilterType` and persons modal related params */
export type StickinessFilterLegacy = Omit<StickinessFilterType, keyof FilterType | 'stickiness_days' | 'shown_as'>
@@ -2487,6 +2676,7 @@ export interface ActorsQuery extends DataNode<ActorsQueryResponse> {
| FunnelCorrelationActorsQuery
| ExperimentActorsQuery
| StickinessActorsQuery
+ | PathsV2ActorsQuery
| HogQLQuery
select?: HogQLExpression[]
search?: string
@@ -4306,6 +4496,7 @@ export type InsightQueryNode =
| FunnelsQuery
| RetentionQuery
| PathsQuery
+ | PathsV2Query
| StickinessQuery
| LifecycleQuery
| WebStatsTableQuery
@@ -4966,6 +5157,7 @@ export type InsightFilterProperty =
| 'funnelsFilter'
| 'retentionFilter'
| 'pathsFilter'
+ | 'pathsV2Filter'
| 'stickinessFilter'
| 'calendarHeatmapFilter'
| 'lifecycleFilter'
@@ -4976,6 +5168,7 @@ export type InsightFilter =
| FunnelsFilter
| RetentionFilter
| PathsFilter
+ | PathsV2Filter
| StickinessFilter
| LifecycleFilter
| CalendarHeatmapFilter
@@ -5037,6 +5230,55 @@ export interface FunnelCorrelationActorsQuery extends InsightActorsQueryBase {
funnelCorrelationPropertyValues?: AnyPropertyFilter[]
}
+/** The kind of journey grid element a PathsV2ActorsQuery drills into. */
+export enum PathsV2ElementType {
+ Node = 'node',
+ Edge = 'edge',
+ DropOff = 'dropOff',
+ Other = 'other',
+ Chain = 'chain',
+}
+
+/**
+ * Selects the journey grid element whose actors a PathsV2ActorsQuery returns. The same journeys
+ * that produced the grid produce these actor sets, so each element's modal equals its displayed
+ * number by construction.
+ */
+export type PathsV2ElementSelector = {
+ elementType: PathsV2ElementType
+ /**
+ * 0-based step index (column) of the element; for an edge, its source column. Required for
+ * node, other, dropOff, and positional edge elements.
+ */
+ stepIndex?: integer
+ /** The node card's path item. Node elements only. */
+ item?: PathsV2Item
+ /** The edge's source path item; omit for the source column's "other" row. Edge elements only. */
+ source?: PathsV2Item
+ /** The edge's target path item; omit for the target column's "other" row. Edge elements only. */
+ target?: PathsV2Item
+ /**
+ * Match the source → target transition at any step of any whole journey instead of at one step
+ * pair: the position-free set behind an edge's anyStepCount. Requires a named source and
+ * target and open mode. Edge elements only.
+ */
+ anyStep?: boolean
+ /**
+ * The chain's path items in order from the anchor. Returns the actors whose anchored sequence
+ * begins with exactly these items, the set behind a hover preview's per-chain counts. Chain
+ * elements only, anchored mode only. Bounded by the step maximum: a longer chain can never
+ * match a displayed card.
+ * @maxItems 20
+ */
+ chain?: PathsV2Item[]
+}
+
+export interface PathsV2ActorsQuery extends InsightActorsQueryBase {
+ kind: NodeKind.PathsV2ActorsQuery
+ source: PathsV2Query
+ element: PathsV2ElementSelector
+}
+
export interface EventDefinition {
event: string
properties: Record<string, any>
@@ -5145,6 +5387,7 @@ export interface InsightActorsQueryOptions extends Node<InsightActorsQueryOption
| FunnelCorrelationActorsQuery
| StickinessActorsQuery
| ExperimentActorsQuery
+ | PathsV2ActorsQuery
}
export interface DatabaseSchemaSchema {
diff --git a/frontend/src/queries/utils.ts b/frontend/src/queries/utils.ts
index 27196367b3d9..8a4fe2519875 100644
--- a/frontend/src/queries/utils.ts
+++ b/frontend/src/queries/utils.ts
@@ -51,6 +51,7 @@ import {
NodeKind,
NonIntegratedConversionsTableQuery,
PathsQuery,
+ PathsV2Query,
PersonsNode,
ProductAnalyticsInsightQueryNode,
QuerySchema,
@@ -355,6 +356,10 @@ export function isPathsQuery(node?: Record<string, any> | null): node is PathsQu
return node?.kind === NodeKind.PathsQuery
}
+export function isPathsV2Query(node?: Record<string, any> | null): node is PathsV2Query {
+ return node?.kind === NodeKind.PathsV2Query
+}
+
export function isStickinessQuery(node?: Record<string, any> | null): node is StickinessQuery {
return node?.kind === NodeKind.StickinessQuery
}
@@ -429,6 +434,7 @@ export function isInsightQueryNode(node?: Record<string, any> | null): node is I
isFunnelsQuery(node) ||
isRetentionQuery(node) ||
isPathsQuery(node) ||
+ isPathsV2Query(node) ||
isStickinessQuery(node) ||
isLifecycleQuery(node) ||
isWebStatsTableQuery(node) ||
@@ -618,7 +624,7 @@ export const getCompareFilter = (query: InsightQueryNode): CompareFilter | undef
}
export const getAggregationGroupTypeIndex = (query: InsightQueryNode): GroupTypeIndex | null | undefined => {
- if (!isStickinessQuery(query)) {
+ if (!isStickinessQuery(query) && 'aggregation_group_type_index' in query) {
return query.aggregation_group_type_index as GroupTypeIndex | null | undefined
}
return undefined
@@ -769,6 +775,7 @@ export const nodeKindToFilterProperty: Record<ProductAnalyticsInsightNodeKind, I
[NodeKind.FunnelsQuery]: 'funnelsFilter',
[NodeKind.RetentionQuery]: 'retentionFilter',
[NodeKind.PathsQuery]: 'pathsFilter',
+ [NodeKind.PathsV2Query]: 'pathsV2Filter',
[NodeKind.StickinessQuery]: 'stickinessFilter',
[NodeKind.LifecycleQuery]: 'lifecycleFilter',
}
diff --git a/frontend/src/scenes/dashboard/addInsightToDashboardModal/AddInsightToDashboardModal.tsx b/frontend/src/scenes/dashboard/addInsightToDashboardModal/AddInsightToDashboardModal.tsx
index db41eac2d95e..66df6ca3f2e1 100644
--- a/frontend/src/scenes/dashboard/addInsightToDashboardModal/AddInsightToDashboardModal.tsx
+++ b/frontend/src/scenes/dashboard/addInsightToDashboardModal/AddInsightToDashboardModal.tsx
@@ -7,8 +7,10 @@ import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { Popover } from 'lib/lemon-ui/Popover'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { addSavedInsightsModalLogic } from 'scenes/saved-insights/addSavedInsightsModalLogic'
import { AddSavedInsightsToDashboard } from 'scenes/saved-insights/AddSavedInsightsToDashboard'
+import { isInsightTypeCreatable } from 'scenes/saved-insights/insightTypesMetadata'
import { INSIGHT_TYPES_METADATA } from 'scenes/saved-insights/SavedInsights'
import { urls } from 'scenes/urls'
@@ -27,6 +29,7 @@ export function AddInsightToDashboardModal(): JSX.Element {
const { hideAddInsightToDashboardModal, toggleShowMoreInsightTypes } = useActions(addInsightToDashboardLogic)
const { addInsightToDashboardModalVisible, showMoreInsightTypes } = useValues(addInsightToDashboardLogic)
const { dashboard } = useValues(dashboardLogic)
+ const { featureFlags } = useValues(featureFlagLogic)
const handleClose = (): void => {
posthog.capture('insight dashboard modal - closed')
@@ -42,7 +45,7 @@ export function AddInsightToDashboardModal(): JSX.Element {
const additionalTypes = Object.entries(INSIGHT_TYPES_METADATA).filter(
([type, meta]) =>
- meta.inMenu &&
+ isInsightTypeCreatable(meta, featureFlags) &&
type !== InsightType.JSON &&
type !== InsightType.HOG &&
!QUICK_CREATE_TYPES.some((qt) => qt.type === type)
diff --git a/frontend/src/scenes/funnels/funnelCorrelationUsageLogic.ts b/frontend/src/scenes/funnels/funnelCorrelationUsageLogic.ts
index 7cbe258e2bf4..8fbd3c5a9858 100644
--- a/frontend/src/scenes/funnels/funnelCorrelationUsageLogic.ts
+++ b/frontend/src/scenes/funnels/funnelCorrelationUsageLogic.ts
@@ -33,6 +33,7 @@ import type {
WebOverviewQuery,
WebStatsTableQuery,
} from '../../queries/schema/schema-general'
+import type { PathsV2Query } from '../../queries/schema/schema-general'
import type { FunnelCorrelation, FunnelCorrelationType } from '../../types'
import { funnelCorrelationLogic } from './funnelCorrelationLogic'
import { funnelDataLogic } from './funnelDataLogic'
@@ -47,6 +48,7 @@ export interface funnelCorrelationUsageLogicValues {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
diff --git a/frontend/src/scenes/funnels/funnelDataLogic.ts b/frontend/src/scenes/funnels/funnelDataLogic.ts
index 16739d4fa5f3..6d95bd32bd98 100644
--- a/frontend/src/scenes/funnels/funnelDataLogic.ts
+++ b/frontend/src/scenes/funnels/funnelDataLogic.ts
@@ -59,6 +59,7 @@ import type {
WebOverviewQuery,
WebStatsTableQuery,
} from '../../queries/schema/schema-general'
+import type { PathsV2Query } from '../../queries/schema/schema-general'
import type { BreakdownKeyType, FunnelStep, IntervalType, LabelGroupType } from '../../types'
import type { QuerySourceUpdate } from '../insights/insightVizDataLogic'
import {
@@ -201,6 +202,7 @@ export interface funnelDataLogicValues {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -320,6 +322,7 @@ export interface funnelDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -332,6 +335,7 @@ export interface funnelDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -354,6 +358,7 @@ export interface funnelDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -368,6 +373,7 @@ export interface funnelDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
diff --git a/frontend/src/scenes/funnels/funnelUtils.tsx b/frontend/src/scenes/funnels/funnelUtils.tsx
index 491cb806c6c2..d1343e88e436 100644
--- a/frontend/src/scenes/funnels/funnelUtils.tsx
+++ b/frontend/src/scenes/funnels/funnelUtils.tsx
@@ -39,6 +39,8 @@ import {
PropertyOperator,
} from '~/types'
+// Keep in sync with CONVERSION_WINDOW_INTERVAL_BOUNDS in posthog/hogql_queries/insights/funnels/utils.py,
+// which enforces the same bounds server-side for the paths v2 gap.
export const TIME_INTERVAL_BOUNDS: Record<FunnelConversionWindowTimeUnit, number[]> = {
[FunnelConversionWindowTimeUnit.Second]: [1, 3600],
[FunnelConversionWindowTimeUnit.Minute]: [1, 1440],
diff --git a/frontend/src/scenes/insights/EditorFilters/SamplingDeprecationNotice.tsx b/frontend/src/scenes/insights/EditorFilters/SamplingDeprecationNotice.tsx
index d2c3a0643270..b39c1e72521a 100644
--- a/frontend/src/scenes/insights/EditorFilters/SamplingDeprecationNotice.tsx
+++ b/frontend/src/scenes/insights/EditorFilters/SamplingDeprecationNotice.tsx
@@ -11,10 +11,10 @@ interface SamplingDeprecationNoticeProps {
}
export function SamplingDeprecationNotice({ insightProps }: SamplingDeprecationNoticeProps): JSX.Element | null {
- const { querySource } = useValues(insightVizDataLogic(insightProps))
+ const { samplingFactor } = useValues(insightVizDataLogic(insightProps))
const { updateQuerySource } = useActions(insightVizDataLogic(insightProps))
- const hasSampling = querySource?.samplingFactor != null && querySource.samplingFactor < 1
+ const hasSampling = samplingFactor != null && samplingFactor < 1
if (!hasSampling) {
return null
@@ -23,8 +23,8 @@ export function SamplingDeprecationNotice({ insightProps }: SamplingDeprecationN
return (
<LemonBanner type="warning">
<span>
- This insight currently uses {(querySource.samplingFactor! * 100).toFixed(0)}% sampling. Sampling is
- being deprecated and will be removed in a future release.{' '}
+ This insight currently uses {(samplingFactor * 100).toFixed(0)}% sampling. Sampling is being deprecated
+ and will be removed in a future release.{' '}
<button
className="text-link font-semibold"
onClick={() => {
diff --git a/frontend/src/scenes/insights/EditorFilters/goalLinesLogic.ts b/frontend/src/scenes/insights/EditorFilters/goalLinesLogic.ts
index 4acf1d195f9b..3ae3556d5ef7 100644
--- a/frontend/src/scenes/insights/EditorFilters/goalLinesLogic.ts
+++ b/frontend/src/scenes/insights/EditorFilters/goalLinesLogic.ts
@@ -20,6 +20,7 @@ import type {
WebOverviewQuery,
WebStatsTableQuery,
} from '../../../queries/schema/schema-general'
+import type { PathsV2Query } from '../../../queries/schema/schema-general'
import { insightVizDataLogic } from '../insightVizDataLogic'
import type { QuerySourceUpdate } from '../insightVizDataLogic'
@@ -31,6 +32,7 @@ export interface goalLinesLogicValues {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
diff --git a/frontend/src/scenes/insights/EditorFilters/poeFilterLogic.ts b/frontend/src/scenes/insights/EditorFilters/poeFilterLogic.ts
index 6c990aeb40d6..43de09a73e03 100644
--- a/frontend/src/scenes/insights/EditorFilters/poeFilterLogic.ts
+++ b/frontend/src/scenes/insights/EditorFilters/poeFilterLogic.ts
@@ -16,6 +16,7 @@ import type {
WebOverviewQuery,
WebStatsTableQuery,
} from '../../../queries/schema/schema-general'
+import type { PathsV2Query } from '../../../queries/schema/schema-general'
import { insightVizDataLogic } from '../insightVizDataLogic'
import type { QuerySourceUpdate } from '../insightVizDataLogic'
@@ -27,6 +28,7 @@ export interface poeFilterLogicValues {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
diff --git a/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts b/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts
index 267dade8e07b..52192691e9c8 100644
--- a/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts
+++ b/frontend/src/scenes/insights/InsightNav/insightNavLogic.test.ts
@@ -2,6 +2,8 @@ import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
import { expectLogic } from 'kea-test-utils'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
import { insightNavLogic } from 'scenes/insights/InsightNav/insightNavLogic'
@@ -161,6 +163,71 @@ describe('insightNavLogic', () => {
})
})
+ describe('journeys tab visibility', () => {
+ it('hides the journeys tab without the flag', () => {
+ expect(logic.values.tabs.map((tab) => tab.type)).not.toContain(InsightType.JOURNEYS)
+ })
+
+ it('shows the journeys tab with the flag on, between paths and stickiness', () => {
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.PRODUCT_ANALYTICS_PATHS_V2]: true })
+ const tabTypes = logic.values.tabs.map((tab) => tab.type)
+ expect(tabTypes.indexOf(InsightType.JOURNEYS)).toEqual(tabTypes.indexOf(InsightType.PATHS) + 1)
+ expect(tabTypes.indexOf(InsightType.JOURNEYS)).toEqual(tabTypes.indexOf(InsightType.STICKINESS) - 1)
+ })
+
+ it('shows the journeys tab without the flag when viewing a journeys insight, so links never dead-end', () => {
+ const props = {
+ dashboardItemId: 'insight-v2' as InsightShortId,
+ cachedInsight: {
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: { kind: NodeKind.PathsV2Query },
+ } as Node,
+ },
+ }
+ insightLogic(props).mount()
+ const builtLogic = insightNavLogic(props)
+ builtLogic.mount()
+
+ expect(builtLogic.values.activeView).toEqual(InsightType.JOURNEYS)
+ expect(builtLogic.values.tabs.map((tab) => tab.type)).toContain(InsightType.JOURNEYS)
+ })
+
+ it('keeps the journeys filter when switching away and back', async () => {
+ const journeysQuery: InsightVizNode = {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.PathsV2Query,
+ pathsV2Filter: {
+ stepSources: [{ event: '$screen', namingProperty: '$screen_name' }],
+ },
+ },
+ }
+
+ await expectLogic(logic, () => {
+ builtInsightDataLogic.actions.setQuery(journeysQuery)
+ })
+
+ await expectLogic(builtInsightDataLogic, () => {
+ logic.actions.setActiveView(InsightType.TRENDS)
+ }).toFinishAllListeners()
+
+ await expectLogic(builtInsightDataLogic, () => {
+ logic.actions.setActiveView(InsightType.JOURNEYS)
+ }).toFinishAllListeners()
+
+ expect(builtInsightDataLogic.values.query).toMatchObject({
+ kind: 'InsightVizNode',
+ source: {
+ kind: 'PathsV2Query',
+ pathsV2Filter: {
+ stepSources: [{ event: '$screen', namingProperty: '$screen_name' }],
+ },
+ },
+ })
+ })
+ })
+
describe('query cache', () => {
const trendsQuery: InsightVizNode = {
kind: NodeKind.InsightVizNode,
diff --git a/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsx b/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsx
index db721e25b4b6..829077ce5644 100644
--- a/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsx
+++ b/frontend/src/scenes/insights/InsightNav/insightNavLogic.tsx
@@ -2,6 +2,7 @@ import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path,
import { router } from 'kea-router'
import { FEATURE_FLAGS } from 'lib/constants'
+import { LemonTag } from 'lib/lemon-ui/LemonTag'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { identifierToHuman } from 'lib/utils/strings'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
@@ -34,6 +35,7 @@ import {
NodeKind,
PathsFilter,
PathsQuery,
+ PathsV2Query,
ProductAnalyticsInsightQueryNode,
RetentionFilter,
RetentionQuery,
@@ -60,6 +62,7 @@ import {
isLifecycleDataWarehouseNode,
isLifecycleQuery,
isPathsQuery,
+ isPathsV2Query,
isRetentionQuery,
isStickinessQuery,
isTrendsQuery,
@@ -96,6 +99,7 @@ export interface QueryPropertyCache
Omit<Partial<FunnelsQuery>, 'kind' | 'response' | 'series'>,
Omit<Partial<RetentionQuery>, 'kind' | 'response' | 'series'>,
Omit<Partial<PathsQuery>, 'kind' | 'response'>,
+ Omit<Partial<PathsV2Query>, 'kind' | 'response'>,
Omit<Partial<StickinessQuery>, 'kind' | 'response' | 'series'>,
Omit<Partial<LifecycleQuery>, 'kind' | 'response' | 'series'> {
series?: (AnyEntityNode<AnyDataWarehouseNode> | GroupNode)[]
@@ -522,6 +526,22 @@ export const insightNavLogic = kea<insightNavLogicType>([
type: InsightType.PATHS,
dataAttr: 'insight-path-tab',
},
+ ]
+
+ // Visible when flagged or when viewing an existing journeys insight, so links never dead-end
+ if (featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_PATHS_V2] || activeView === InsightType.JOURNEYS) {
+ tabs.push({
+ label: (
+ <>
+ Journeys <LemonTag type="warning">BETA</LemonTag>
+ </>
+ ),
+ type: InsightType.JOURNEYS,
+ dataAttr: 'insight-journeys-tab',
+ })
+ }
+
+ tabs.push(
{
label: 'Stickiness',
type: InsightType.STICKINESS,
@@ -531,8 +551,8 @@ export const insightNavLogic = kea<insightNavLogicType>([
label: 'Lifecycle',
type: InsightType.LIFECYCLE,
dataAttr: 'insight-lifecycle-tab',
- },
- ]
+ }
+ )
if (featureFlags[FEATURE_FLAGS.HOG] || activeView === InsightType.HOG) {
tabs.push({
@@ -725,7 +745,8 @@ const mergeCachedProperties = (query: InsightQueryNode, cache: QueryPropertyCach
...query,
...(cache.dateRange ? { dateRange: cache.dateRange } : {}),
...(cache.properties !== undefined ? { properties: cache.properties } : {}),
- ...(cache.samplingFactor ? { samplingFactor: cache.samplingFactor } : {}),
+ // PathsV2Query has no samplingFactor field, and the backend rejects unknown fields
+ ...(cache.samplingFactor && !isPathsV2Query(query) ? { samplingFactor: cache.samplingFactor } : {}),
...(cache.filterTestAccounts !== undefined ? { filterTestAccounts: cache.filterTestAccounts } : {}),
}
@@ -816,6 +837,9 @@ const buildInsightFilter = (
const vizProps = getCommonVisualizationProperties(query, cache.commonFilter)
return { pathsFilter: { ...query.pathsFilter, ...cache.pathsFilter, ...vizProps } }
}
+ if (isPathsV2Query(query)) {
+ return { pathsV2Filter: { ...query.pathsV2Filter, ...cache.pathsV2Filter } }
+ }
if (isLifecycleQuery(query)) {
const vizProps = getCommonVisualizationProperties(query, cache.commonFilter)
return { lifecycleFilter: { ...query.lifecycleFilter, ...cache.lifecycleFilter, ...vizProps } }
diff --git a/frontend/src/scenes/insights/InsightQuickStart/InsightQuickStart.tsx b/frontend/src/scenes/insights/InsightQuickStart/InsightQuickStart.tsx
index 45c759e8c2b1..0b5c00dce0e7 100644
--- a/frontend/src/scenes/insights/InsightQuickStart/InsightQuickStart.tsx
+++ b/frontend/src/scenes/insights/InsightQuickStart/InsightQuickStart.tsx
@@ -1,5 +1,6 @@
import './InsightQuickStart.scss'
+import { useValues } from 'kea'
import { router } from 'kea-router'
import { useState } from 'react'
@@ -7,7 +8,9 @@ import { IconPlay, IconSparkles } from '@posthog/icons'
import { LemonCard } from 'lib/lemon-ui/LemonCard'
import { Link } from 'lib/lemon-ui/Link'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { INSIGHT_TYPE_URLS } from 'scenes/insights/utils'
+import { isInsightTypeCreatable } from 'scenes/saved-insights/insightTypesMetadata'
import { INSIGHT_TYPES_METADATA } from 'scenes/saved-insights/SavedInsights'
import { SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -147,9 +150,10 @@ function InsightOptionCard({
}
export function InsightQuickStart(): JSX.Element {
+ const { featureFlags } = useValues(featureFlagLogic)
const insightEntries = Object.entries(INSIGHT_TYPES_METADATA).filter(
([insightType, metadata]) =>
- metadata.inMenu &&
+ isInsightTypeCreatable(metadata, featureFlags) &&
insightType !== InsightType.JSON &&
insightType !== InsightType.WEB_ANALYTICS &&
insightType !== InsightType.HOG
diff --git a/frontend/src/scenes/insights/filters/AggregationSelect.tsx b/frontend/src/scenes/insights/filters/AggregationSelect.tsx
index cf0148447287..526272cd5bbb 100644
--- a/frontend/src/scenes/insights/filters/AggregationSelect.tsx
+++ b/frontend/src/scenes/insights/filters/AggregationSelect.tsx
@@ -12,11 +12,11 @@ import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { groupsModel } from '~/models/groupsModel'
import { FunnelsQuery, LifecycleQuery, RetentionQuery } from '~/queries/schema/schema-general'
import {
+ getAggregationGroupTypeIndex,
isFunnelsQuery,
isInsightQueryNode,
isLifecycleQuery,
isRetentionQuery,
- isStickinessQuery,
} from '~/queries/utils'
import { InsightLogicProps } from '~/types'
@@ -78,7 +78,7 @@ export function AggregationSelect({
(isRetentionQuery(querySource) && querySource.retentionFilter?.customAggregationTarget)
? CUSTOM_DATA_WAREHOUSE_ITEMS
: getHogQLValue(
- isStickinessQuery(querySource) ? undefined : querySource.aggregation_group_type_index,
+ getAggregationGroupTypeIndex(querySource),
isFunnelsQuery(querySource) ? querySource.funnelsFilter?.funnelAggregateByHogQL : undefined
)
diff --git a/frontend/src/scenes/insights/filters/PathCleaningFilter.tsx b/frontend/src/scenes/insights/filters/PathCleaningFilter.tsx
index 6bb0e9ed5620..1464e0d58bdb 100644
--- a/frontend/src/scenes/insights/filters/PathCleaningFilter.tsx
+++ b/frontend/src/scenes/insights/filters/PathCleaningFilter.tsx
@@ -1,13 +1,7 @@
import { useActions, useValues } from 'kea'
-import { IconGear } from '@posthog/icons'
-import { LemonButton, LemonSwitch } from '@posthog/lemon-ui'
-
-import { PathCleanFilters } from 'lib/components/PathCleanFilters/PathCleanFilters'
-import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { PathCleaningControls } from 'lib/components/PathCleanFilters/PathCleaningControls'
import { pathsDataLogic } from 'scenes/paths/pathsDataLogic'
-import { teamLogic } from 'scenes/teamLogic'
-import { urls } from 'scenes/urls'
import { EditorFilterProps } from '~/types'
@@ -17,47 +11,12 @@ export function PathCleaningFilter({ insightProps }: EditorFilterProps): JSX.Ele
const { localPathCleaningFilters, pathReplacements } = pathsFilter || {}
- const { currentTeam } = useValues(teamLogic)
- const hasFilters = (currentTeam?.path_cleaning_filters || []).length > 0
-
return (
- <>
- <PathCleanFilters
- filters={localPathCleaningFilters || []}
- setFilters={(filters) => updateInsightFilter({ localPathCleaningFilters: filters })}
- />
- <Tooltip
- title={
- hasFilters
- ? 'Clean paths based using regex replacement.'
- : "You don't have path cleaning filters. Configure via the gear icon."
- }
- >
- {/* This div is necessary for the tooltip to work. */}
- <div className="inline-block mt-4 w-full">
- <LemonSwitch
- disabled={!hasFilters}
- checked={hasFilters && !!pathReplacements}
- onChange={(checked: boolean) => {
- updateInsightFilter({ pathReplacements: checked })
- }}
- label={
- <div className="flex items-center">
- <span>Apply global path URL cleaning</span>
- <LemonButton
- icon={<IconGear />}
- to={urls.settings('project-product-analytics', 'path-cleaning')}
- size="small"
- noPadding
- className="ml-1"
- />
- </div>
- }
- fullWidth
- bordered
- />
- </div>
- </Tooltip>
- </>
+ <PathCleaningControls
+ localFilters={localPathCleaningFilters || []}
+ setLocalFilters={(localPathCleaningFilters) => updateInsightFilter({ localPathCleaningFilters })}
+ applyGlobal={!!pathReplacements}
+ setApplyGlobal={(pathReplacements) => updateInsightFilter({ pathReplacements })}
+ />
)
}
diff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsx
index adc6b6f6c572..1a55b09e537b 100644
--- a/frontend/src/scenes/insights/insightLogic.tsx
+++ b/frontend/src/scenes/insights/insightLogic.tsx
@@ -21,7 +21,6 @@ import { LemonDialog, LemonInput } from '@posthog/lemon-ui'
import { ApiError } from 'lib/api'
import { tryShowMCPHint } from 'lib/components/MCPHint/mcpHintLogic'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
-import { FEATURE_FLAGS } from 'lib/constants'
import { LemonField } from 'lib/lemon-ui/LemonField'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
@@ -130,8 +129,6 @@ export interface insightLogicValues {
isInExperimentContext: boolean
isInViewMode: boolean
isSavingTags: boolean
- isUsingPathsV1: boolean
- isUsingPathsV2: boolean | string | undefined
previousQuery: Node | null
query: Node | null
savedInsight: Partial<QueryBasedInsightModel<Node<Record<string, any>>>>
@@ -503,8 +500,6 @@ export interface insightLogicMeta {
insight: Partial<QueryBasedInsightModel<Node<Record<string, any>>>>,
activeSceneId: string | null
) => boolean | null
- isUsingPathsV1: (featureFlags: FeatureFlagsSet) => boolean
- isUsingPathsV2: (featureFlags: FeatureFlagsSet) => boolean | string | undefined
hasOverrides: (arg: any, arg2: any, arg3: any) => boolean
editingDisabledReason: (hasOverrides: boolean) => 'Discard overrides to edit the insight.' | null
}
@@ -1005,16 +1000,6 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType
Scene.ExperimentsSharedMetrics,
].includes(activeSceneId),
],
- isUsingPathsV1: [
- (s) => [s.featureFlags],
- (featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet) =>
- !featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_PATHS_V2],
- ],
- isUsingPathsV2: [
- (s) => [s.featureFlags],
- (featureFlags: import('lib/logic/featureFlagLogic').FeatureFlagsSet) =>
- featureFlags[FEATURE_FLAGS.PRODUCT_ANALYTICS_PATHS_V2],
- ],
hasOverrides: [
() => [
(_, props) => props.filtersOverride,
diff --git a/frontend/src/scenes/insights/insightVizDataLogic.test.ts b/frontend/src/scenes/insights/insightVizDataLogic.test.ts
index 8dc546e61755..150f20acca5e 100644
--- a/frontend/src/scenes/insights/insightVizDataLogic.test.ts
+++ b/frontend/src/scenes/insights/insightVizDataLogic.test.ts
@@ -8,7 +8,7 @@ import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { useMocks } from '~/mocks/jest'
import { LATEST_VERSIONS } from '~/queries/latest-versions'
import { funnelsQueryDefault, trendsQueryDefault } from '~/queries/nodes/InsightQuery/defaults'
-import { FunnelsQuery, LifecycleQuery, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'
+import { FunnelsQuery, LifecycleQuery, Node, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'
import { setLatestVersionsOnQuery } from '~/queries/utils'
import { initKeaTests } from '~/test/init'
import {
@@ -350,6 +350,20 @@ describe('insightVizDataLogic', () => {
})
describe('updateDateRange', () => {
+ it('does not inject the interval side effect into a paths v2 query, which has no interval field', async () => {
+ builtInsightDataLogic.actions.setQuery({
+ kind: NodeKind.InsightVizNode,
+ source: { kind: NodeKind.PathsV2Query },
+ } as Node)
+
+ await expectLogic(builtInsightDataLogic, () => {
+ builtInsightVizDataLogic.actions.updateDateRange({ date_from: '-7d', date_to: null })
+ }).toFinishAllListeners()
+
+ expect(builtInsightVizDataLogic.values.querySource).not.toHaveProperty('interval')
+ expect(builtInsightVizDataLogic.values.dateRange).toMatchObject({ date_from: '-7d' })
+ })
+
it('updates the date range', async () => {
// when dateRange is empty
await expectLogic(builtInsightDataLogic, () => {
@@ -817,7 +831,7 @@ describe('insightVizDataLogic', () => {
})
it('clears smoothing when switching between intervals', async () => {
- const trendsQuery = { ...trendsQueryDefault, interval: 'minute' }
+ const trendsQuery = { ...trendsQueryDefault, interval: 'minute' as const }
trendsQuery.trendsFilter = { ...trendsQuery.trendsFilter, smoothingIntervals: 2 }
builtInsightVizDataLogic.actions.updateQuerySource(trendsQuery)
diff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.ts
index b76c18a31860..e45e39ad2fa7 100644
--- a/frontend/src/scenes/insights/insightVizDataLogic.ts
+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts
@@ -91,6 +91,7 @@ import {
isLifecycleQuery,
isNodeWithSource,
isPathsQuery,
+ isPathsV2Query,
isRetentionQuery,
isStickinessQuery,
isTrendsQuery,
@@ -133,6 +134,7 @@ import type {
LogsQueryResponse,
MetricsQueryResponse,
PathsFilter,
+ PathsV2Filter,
PathsQuery,
RefreshType,
ResultCustomizationBy,
@@ -146,6 +148,7 @@ import type {
WebOverviewQuery,
WebStatsTableQuery,
} from '../../queries/schema/schema-general'
+import type { PathsV2Query } from '../../queries/schema/schema-general'
import type { AnyPropertyFilter, GroupTypeIndex, PropertyGroupFilter } from '../../types'
const SHOW_TIMEOUT_MESSAGE_AFTER = 5000
@@ -161,7 +164,10 @@ export const DISPLAYS_WITH_IN_CHART_LEGEND = [
ChartDisplayType.ActionsPie,
]
-export type QuerySourceUpdate = Omit<Partial<InsightQueryNode>, 'kind'>
+// Omit must distribute over the query-node union: a plain Omit would collapse the update type
+// to the keys shared by every insight kind, dropping fields like samplingFactor that only some have
+type DistributiveOmit<T, K extends keyof any> = T extends any ? Omit<T, K> : never
+export type QuerySourceUpdate = DistributiveOmit<Partial<InsightQueryNode>, 'kind'>
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface insightVizDataLogicValues {
@@ -207,6 +213,7 @@ export interface insightVizDataLogicValues {
isLifecycle: boolean
isNonTimeSeriesDisplay: boolean
isPaths: boolean
+ isPathsV2: boolean
isRetention: boolean
isSingleSeriesDefinition: boolean
isSingleSeriesOutput: boolean
@@ -223,11 +230,13 @@ export interface insightVizDataLogicValues {
lifecycleFilter: LifecycleFilter | null | undefined
localQuerySource: InsightQueryNode
pathsFilter: PathsFilter | null
+ pathsV2Filter: PathsV2Filter | null | undefined
properties: PropertyGroupFilter | AnyPropertyFilter[] | null | undefined
querySource:
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -442,6 +451,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -453,6 +463,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -466,6 +477,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -478,6 +490,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -490,6 +503,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -502,6 +516,20 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
+ | RetentionQuery
+ | StickinessQuery
+ | TrendsQuery
+ | WebOverviewQuery
+ | WebStatsTableQuery
+ | null
+ ) => boolean
+ isPathsV2: (
+ querySource:
+ | FunnelsQuery
+ | LifecycleQuery
+ | PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -514,6 +542,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -526,6 +555,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -538,6 +568,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -550,6 +581,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -562,6 +594,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -574,6 +607,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -586,6 +620,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -598,6 +633,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -612,6 +648,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -624,6 +661,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -644,6 +682,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -656,6 +695,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -668,6 +708,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -680,6 +721,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -692,6 +734,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -704,6 +747,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -716,6 +760,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -728,6 +773,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -740,6 +786,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -752,6 +799,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -764,6 +812,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -776,6 +825,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -788,6 +838,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -800,6 +851,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -812,6 +864,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -824,6 +877,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -836,6 +890,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -848,6 +903,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -860,6 +916,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -872,6 +929,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -884,6 +942,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -896,6 +955,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -908,6 +968,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -921,6 +982,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -933,6 +995,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -945,6 +1008,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -957,6 +1021,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -969,6 +1034,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -981,6 +1047,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -993,6 +1060,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -1000,11 +1068,25 @@ export interface insightVizDataLogicMeta {
| WebStatsTableQuery
| null
) => PathsFilter | null
+ pathsV2Filter: (
+ querySource:
+ | FunnelsQuery
+ | LifecycleQuery
+ | PathsQuery
+ | PathsV2Query
+ | RetentionQuery
+ | StickinessQuery
+ | TrendsQuery
+ | WebOverviewQuery
+ | WebStatsTableQuery
+ | null
+ ) => PathsV2Filter | null | undefined
stickinessFilter: (
querySource:
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -1017,6 +1099,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -1029,6 +1112,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -1118,6 +1202,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -1132,6 +1217,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -1144,6 +1230,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -1156,6 +1243,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -1168,6 +1256,7 @@ export interface insightVizDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -1359,6 +1448,7 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([
| import('~/queries/schema/schema-general').WebStatsTableQuery
) => isPathsQuery(q),
],
+ isPathsV2: [(s) => [s.querySource], (q: InsightQueryNode | null) => isPathsV2Query(q)],
isStickiness: [
(s) => [s.querySource],
(
@@ -1981,6 +2071,10 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([
| import('~/queries/schema/schema-general').WebStatsTableQuery
) => (isPathsQuery(q) ? q.pathsFilter : null),
],
+ pathsV2Filter: [
+ (s) => [s.querySource],
+ (q: InsightQueryNode | null) => (isPathsV2Query(q) ? q.pathsV2Filter : null),
+ ],
stickinessFilter: [
(s) => [s.querySource],
(
@@ -2803,6 +2897,7 @@ const handleQuerySourceUpdateSideEffects = (
if (
!isRetentionQuery(currentState) &&
!isPathsQuery(currentState) && // TODO: Apply side logic more elegantly
+ !isPathsV2Query(currentState) && // PathsV2Query has no interval field, and the backend rejects unknown fields
update.dateRange &&
update.dateRange.date_from &&
(update.dateRange.date_from !== currentState.dateRange?.date_from ||
diff --git a/frontend/src/scenes/insights/summarizeInsight.test.ts b/frontend/src/scenes/insights/summarizeInsight.test.ts
index a0fb0ad8bb2d..2fdcd74efe5f 100644
--- a/frontend/src/scenes/insights/summarizeInsight.test.ts
+++ b/frontend/src/scenes/insights/summarizeInsight.test.ts
@@ -17,6 +17,8 @@ import {
LifecycleQuery,
NodeKind,
PathsQuery,
+ PathsV2AnchorType,
+ PathsV2Query,
RetentionQuery,
StickinessQuery,
TrendsQuery,
@@ -434,6 +436,49 @@ describe('summarizing insights', () => {
expect(result).toEqual('User paths based on page views starting at /landing-page and ending at /basket')
})
+ it.each([
+ ['absent step sources (runner default)', undefined, 'Journeys based on page views'],
+ [
+ 'a matching preset',
+ { stepSources: [{ event: '$screen', namingProperty: '$screen_name' }] },
+ 'Journeys based on screen views',
+ ],
+ [
+ 'custom step sources',
+ { stepSources: [{ event: '$pageview', namingProperty: '$pathname' }, { event: 'purchase' }] },
+ 'Journeys based on Pageview and purchase',
+ ],
+ [
+ 'a start anchor',
+ {
+ anchor: {
+ type: PathsV2AnchorType.Start,
+ item: { event: '$pageview', label: '/landing-page' },
+ },
+ },
+ 'Journeys based on page views starting at /landing-page',
+ ],
+ [
+ 'an end anchor with an empty label',
+ {
+ anchor: { type: PathsV2AnchorType.End, item: { event: '$pageview', label: '' } },
+ },
+ 'Journeys based on page views ending at (empty)',
+ ],
+ ] as [string, PathsV2Query['pathsV2Filter'], string][])(
+ 'summarizes a Journeys insight with %s',
+ (_name, pathsV2Filter, expected) => {
+ const query: PathsV2Query = { kind: NodeKind.PathsV2Query, pathsV2Filter }
+
+ const result = summarizeInsight(
+ { kind: NodeKind.InsightVizNode, source: query } as InsightVizNode,
+ summaryContext
+ )
+
+ expect(result).toEqual(expected)
+ }
+ )
+
it('summarizes a Stickiness insight with a user-based series and an organization-based one', () => {
const query: StickinessQuery = {
kind: NodeKind.StickinessQuery,
diff --git a/frontend/src/scenes/insights/summarizeInsight.ts b/frontend/src/scenes/insights/summarizeInsight.ts
index 1c838b04dd99..58133ce0c714 100644
--- a/frontend/src/scenes/insights/summarizeInsight.ts
+++ b/frontend/src/scenes/insights/summarizeInsight.ts
@@ -32,6 +32,7 @@ import {
isInsightVizNode,
isLifecycleQuery,
isPathsQuery,
+ isPathsV2Query,
isPersonsNode,
isRetentionQuery,
isStickinessQuery,
@@ -43,6 +44,8 @@ import { getCoreFilterDefinition } from '~/taxonomy/helpers'
import { CORE_FILTER_DEFINITIONS_BY_GROUP } from '~/taxonomy/taxonomy'
import { BreakdownKeyType, BreakdownType, EntityFilter, FilterType, FunnelVizType, StepOrderValue } from '~/types'
+import { summarizeJourneys } from 'products/product_analytics/frontend/insights/journeys/journeysSummary'
+
function summarizeSingularBreakdown(
breakdown: BreakdownKeyType | undefined,
breakdownType: BreakdownType | MultipleBreakdownType | null | undefined,
@@ -220,6 +223,8 @@ export function summarizeInsightQuery(query: InsightQueryNode, context: SummaryC
summary += `${query.pathsFilter?.startPoint ? ' and' : ''} ending at ${query.pathsFilter?.endPoint}`
}
return summary
+ } else if (isPathsV2Query(query)) {
+ return summarizeJourneys(query.pathsV2Filter)
} else if (isStickinessQuery(query)) {
return capitalizeFirstLetter(
query.series
diff --git a/frontend/src/scenes/insights/utils.tsx b/frontend/src/scenes/insights/utils.tsx
index 3f2d642abe72..296a94b36526 100644
--- a/frontend/src/scenes/insights/utils.tsx
+++ b/frontend/src/scenes/insights/utils.tsx
@@ -513,6 +513,7 @@ export const INSIGHT_TYPE_URLS: Record<InsightType | string, string> = {
[InsightType.FUNNELS]: urls.insightNew({ type: InsightType.FUNNELS }),
[InsightType.RETENTION]: urls.insightNew({ type: InsightType.RETENTION }),
[InsightType.PATHS]: urls.insightNew({ type: InsightType.PATHS }),
+ [InsightType.JOURNEYS]: urls.insightNew({ type: InsightType.JOURNEYS }),
[InsightType.WEB_ANALYTICS]: urls.insightNew({ type: InsightType.WEB_ANALYTICS }),
JSON: urls.insightNew({ query: examples.EventsTableFull }),
HOG: urls.insightNew({ query: examples.Hoggonacci }),
diff --git a/frontend/src/scenes/insights/views/BoxPlot/boxPlotChartLogic.tsx b/frontend/src/scenes/insights/views/BoxPlot/boxPlotChartLogic.tsx
index b623c5885500..bcd806551291 100644
--- a/frontend/src/scenes/insights/views/BoxPlot/boxPlotChartLogic.tsx
+++ b/frontend/src/scenes/insights/views/BoxPlot/boxPlotChartLogic.tsx
@@ -16,6 +16,7 @@ import type {
WebOverviewQuery,
WebStatsTableQuery,
} from '../../../../queries/schema/schema-general'
+import type { PathsV2Query } from '../../../../queries/schema/schema-general'
import type { IntervalType } from '../../../../types'
import { keyForInsightLogicProps } from '../../sharedUtils'
@@ -45,6 +46,7 @@ export interface boxPlotChartLogicValues {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
diff --git a/frontend/src/scenes/insights/views/CalendarHeatMap/calendarHeatMapLogic.tsx b/frontend/src/scenes/insights/views/CalendarHeatMap/calendarHeatMapLogic.tsx
index 81199a9fe9d0..81eb1daea9f9 100644
--- a/frontend/src/scenes/insights/views/CalendarHeatMap/calendarHeatMapLogic.tsx
+++ b/frontend/src/scenes/insights/views/CalendarHeatMap/calendarHeatMapLogic.tsx
@@ -22,6 +22,7 @@ import type {
WebOverviewQuery,
WebStatsTableQuery,
} from '../../../../queries/schema/schema-general'
+import type { PathsV2Query } from '../../../../queries/schema/schema-general'
import { keyForInsightLogicProps } from '../../sharedUtils'
import { DaysAbbreviated, HoursAbbreviated } from './utils'
@@ -46,6 +47,7 @@ export interface calendarHeatMapLogicValues {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
diff --git a/frontend/src/scenes/insights/views/RegionMap/regionMapLogic.tsx b/frontend/src/scenes/insights/views/RegionMap/regionMapLogic.tsx
index 5861d2fe17ac..12f8742cd539 100644
--- a/frontend/src/scenes/insights/views/RegionMap/regionMapLogic.tsx
+++ b/frontend/src/scenes/insights/views/RegionMap/regionMapLogic.tsx
@@ -21,6 +21,7 @@ import type {
WebOverviewQuery,
WebStatsTableQuery,
} from '../../../../queries/schema/schema-general'
+import type { PathsV2Query } from '../../../../queries/schema/schema-general'
import { keyForInsightLogicProps } from '../../sharedUtils'
const getTrendResults = (insightData: Record<string, any> | null | undefined): TrendResult[] =>
@@ -37,6 +38,7 @@ export interface regionMapLogicValues {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
diff --git a/frontend/src/scenes/insights/views/WorldMap/worldMapLogic.tsx b/frontend/src/scenes/insights/views/WorldMap/worldMapLogic.tsx
index 2e9bdb1dc5ec..df8d22404396 100644
--- a/frontend/src/scenes/insights/views/WorldMap/worldMapLogic.tsx
+++ b/frontend/src/scenes/insights/views/WorldMap/worldMapLogic.tsx
@@ -21,6 +21,7 @@ import type {
WebOverviewQuery,
WebStatsTableQuery,
} from '../../../../queries/schema/schema-general'
+import type { PathsV2Query } from '../../../../queries/schema/schema-general'
import { keyForInsightLogicProps } from '../../sharedUtils'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -31,6 +32,7 @@ export interface worldMapLogicValues {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
diff --git a/frontend/src/scenes/paths-v2/PathNodeLabel.tsx b/frontend/src/scenes/paths-v2/PathNodeLabel.tsx
deleted file mode 100644
index 64c60ff81ca7..000000000000
--- a/frontend/src/scenes/paths-v2/PathNodeLabel.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-import { useActions, useValues } from 'kea'
-import posthog from 'posthog-js'
-
-import { IconEllipsis } from '@posthog/icons'
-import { LemonButton, LemonMenu, Tooltip } from '@posthog/lemon-ui'
-
-import { IconOpenInNew } from 'lib/lemon-ui/icons'
-import { copyToClipboard } from 'lib/utils/copyToClipboard'
-import { userLogic } from 'scenes/userLogic'
-
-import { AvailableFeature, InsightLogicProps } from '~/types'
-
-import { pathsDataLogic } from './pathsDataLogic'
-import { PathNodeData, pageUrl } from './pathUtils'
-import { NODE_LABEL_HEIGHT, NODE_LABEL_LEFT_OFFSET, NODE_LABEL_TOP_OFFSET, NODE_LABEL_WIDTH } from './renderPaths'
-
-export type PathNodeLabelProps = {
- insightProps: InsightLogicProps
- node: PathNodeData
-}
-
-export function PathNodeLabel({ insightProps, node }: PathNodeLabelProps): JSX.Element | null {
- const { pathsFilter } = useValues(pathsDataLogic(insightProps))
- const { updateInsightFilter, openPersonsModal, viewPathToFunnel } = useActions(pathsDataLogic(insightProps))
-
- const { hasAvailableFeature } = useValues(userLogic)
- const hasAdvancedPaths = hasAvailableFeature(AvailableFeature.PATHS_ADVANCED)
-
- const nodeName = pageUrl(node)
- const isPath = nodeName.includes('/')
-
- const setAsPathStart = (): void => updateInsightFilter({ startPoint: nodeName })
- const setAsPathEnd = (): void => updateInsightFilter({ endPoint: nodeName })
- const excludePathItem = (): void => {
- updateInsightFilter({ excludeEvents: [...(pathsFilter?.excludeEvents || []), pageUrl(node, false)] })
- }
- const viewFunnel = (): void => {
- viewPathToFunnel(node)
- }
- const copyName = (): void => {
- void copyToClipboard(nodeName).catch((e) => posthog.captureException(e))
- }
- const openModal = (): void => openPersonsModal({ path_end_key: node.name })
-
- const isTruncatedPath = node.name.slice(1) === '_...'
-
- return (
- <div
- className="absolute"
- data-attr="path-node-card-button"
- // eslint-disable-next-line react/forbid-dom-props
- style={{
- width: NODE_LABEL_WIDTH,
- height: NODE_LABEL_HEIGHT,
- left: node.x0 + NODE_LABEL_LEFT_OFFSET,
- top: node.y0 + NODE_LABEL_TOP_OFFSET,
- }}
- >
- <div className="flex items-center">
- <Tooltip title={pageUrl(node)} placement="right">
- <div
- className="font-semibold overflow-hidden max-h-16 text-xs break-words"
- data-attr="path-node-name"
- >
- {pageUrl(node, isPath)}
- </div>
- </Tooltip>
- {!isTruncatedPath && (
- <LemonMenu
- items={[
- { label: 'Set as path start', onClick: setAsPathStart },
- ...(hasAdvancedPaths
- ? [
- { label: 'Set as path end', onClick: setAsPathEnd },
- { label: 'Exclude path item', onClick: excludePathItem },
- {
- label: (
- <div className="flex justify-between items-center w-full">
- <span>View funnel</span>
- <IconOpenInNew />
- </div>
- ),
- onClick: viewFunnel,
- },
- ]
- : []),
- { label: 'Copy path item name', onClick: copyName },
- ]}
- >
- <IconEllipsis className="ml-1 cursor-pointer text-muted hover:text-default" />
- </LemonMenu>
- )}
- </div>
-
- <LemonButton size="xsmall" onClick={openModal} noPadding>
- <span className="font-normal" data-attr="path-node-count">
- {node.value}
- </span>
- </LemonButton>
- </div>
- )
-}
diff --git a/frontend/src/scenes/paths-v2/Paths.scss b/frontend/src/scenes/paths-v2/Paths.scss
deleted file mode 100644
index 29a8df3c1eef..000000000000
--- a/frontend/src/scenes/paths-v2/Paths.scss
+++ /dev/null
@@ -1,12 +0,0 @@
-.Paths {
- position: relative;
- width: 100%;
- height: 720px;
- max-height: 100%;
- overflow-y: hidden;
-
- .Paths__canvas {
- width: 100%;
- height: 100% !important;
- }
-}
diff --git a/frontend/src/scenes/paths-v2/PathsV2.tsx b/frontend/src/scenes/paths-v2/PathsV2.tsx
deleted file mode 100644
index 6c649a42abec..000000000000
--- a/frontend/src/scenes/paths-v2/PathsV2.tsx
+++ /dev/null
@@ -1,97 +0,0 @@
-import './Paths.scss'
-
-import { useActions, useValues } from 'kea'
-import { useEffect, useRef, useState } from 'react'
-
-import { useResizeObserver } from 'lib/hooks/useResizeObserver'
-import { lightenDarkenColor } from 'lib/utils/colors'
-import { InsightEmptyState, InsightErrorState } from 'scenes/insights/EmptyStates'
-import { insightDataLogic } from 'scenes/insights/insightDataLogic'
-import { insightLogic } from 'scenes/insights/insightLogic'
-
-import { FunnelPathsFilter } from '~/queries/schema/schema-general'
-import { shouldQueryBeAsync } from '~/queries/utils'
-
-import { PathNodeLabel } from './PathNodeLabel'
-import { pathsDataLogic } from './pathsDataLogic'
-import type { PathNodeData } from './pathUtils'
-import { renderPaths } from './renderPaths'
-
-export function PathsV2(): JSX.Element {
- const canvasRef = useRef<HTMLDivElement>(null)
- const canvasContainerRef = useRef<HTMLDivElement>(null)
- const { width: canvasWidth, height: canvasHeight } = useResizeObserver({ ref: canvasRef })
- const [nodes, setNodes] = useState<PathNodeData[]>([])
-
- const { insightProps } = useValues(insightLogic)
- const { insightQuery, paths, pathsFilter, funnelPathsFilter, insightDataLoading, insightDataError, theme } =
- useValues(pathsDataLogic(insightProps))
- const { openPersonsModal } = useActions(pathsDataLogic(insightProps))
- const { loadData } = useActions(insightDataLogic(insightProps))
-
- useEffect(() => {
- setNodes([])
-
- // Remove the existing SVG canvas(es). The .Paths__canvas selector is crucial, as we have to be sure
- // we're only removing the Paths viz and not, for example, button icons.
- // Only remove canvases within this component's container
- const elements = canvasContainerRef.current?.querySelectorAll(`.Paths__canvas`)
- elements?.forEach((node) => node?.parentNode?.removeChild(node))
-
- renderPaths(
- canvasRef,
- canvasWidth,
- canvasHeight,
- paths,
- pathsFilter || {},
- funnelPathsFilter || ({} as FunnelPathsFilter),
- setNodes,
- openPersonsModal
- )
-
- // Proper cleanup
- return () => {
- const elements = canvasContainerRef.current?.querySelectorAll(`.Paths__canvas`)
- elements?.forEach((node) => node?.parentNode?.removeChild(node))
- }
- }, [paths, insightDataLoading, canvasWidth, canvasHeight, theme, pathsFilter, funnelPathsFilter, openPersonsModal])
-
- if (insightDataError) {
- return (
- <InsightErrorState
- query={insightQuery}
- excludeDetail
- onRetry={() => {
- loadData(shouldQueryBeAsync(insightQuery) ? 'force_async' : 'force_blocking')
- }}
- />
- )
- }
-
- return (
- <div className="h-full w-full overflow-auto" ref={canvasContainerRef}>
- <div
- ref={canvasRef}
- className="Paths"
- data-attr="paths-viz"
- // eslint-disable-next-line react/forbid-dom-props
- style={
- {
- '--paths-node': theme?.['preset-1'] || '#000000',
- '--paths-node-hover': lightenDarkenColor(theme?.['preset-1'] || '#000000', -20),
- '--paths-node-start-or-end': theme?.['preset-2'] || '#000000',
- '--paths-node-start-or-end-hover': lightenDarkenColor(theme?.['preset-2'] || '#000000', -20),
- '--paths-link': theme?.['preset-1'] || '#000000',
- '--paths-link-hover': lightenDarkenColor(theme?.['preset-1'] || '#000000', -20),
- '--paths-dropoff': 'rgba(220,53,69,0.7)',
- } as React.CSSProperties
- }
- >
- {!insightDataLoading && paths && paths.nodes.length === 0 && !insightDataError && <InsightEmptyState />}
- {!insightDataError &&
- nodes &&
- nodes.map((node, idx) => <PathNodeLabel key={idx} node={node} insightProps={insightProps} />)}
- </div>
- </div>
- )
-}
diff --git a/frontend/src/scenes/paths-v2/pathUtils.test.ts b/frontend/src/scenes/paths-v2/pathUtils.test.ts
deleted file mode 100644
index ce716bc65cb3..000000000000
--- a/frontend/src/scenes/paths-v2/pathUtils.test.ts
+++ /dev/null
@@ -1,258 +0,0 @@
-import { RGBColor } from 'd3'
-
-import { PathNodeData, pageUrl } from './pathUtils'
-
-describe('pageUrl', () => {
- it('should correctly process PathNodeData with hash based URL', () => {
- const testData = {
- name: '2_https://example.com/#/auth/login',
- targetLinks: [
- {
- average_conversion_time: 0,
- index: 0,
- value: 0,
- width: 0,
- y0: 0,
- color: { r: 0, g: 0, b: 0 } as RGBColor,
- target: {
- name: '1_https://example.com/',
- targetLinks: [],
- sourceLinks: [],
- depth: 0,
- width: 0,
- height: 0,
- index: 0,
- value: 0,
- x0: 0,
- x1: 0,
- y0: 0,
- y1: 0,
- layer: 0,
- visible: true,
- },
- source: {
- name: '1_https://example.com/',
- targetLinks: [],
- sourceLinks: [],
- depth: 0,
- width: 0,
- height: 0,
- index: 0,
- value: 0,
- x0: 0,
- x1: 0,
- y0: 0,
- y1: 0,
- layer: 0,
- visible: true,
- },
- },
- ],
- sourceLinks: [],
- depth: 0,
- width: 0,
- height: 0,
- index: 0,
- value: 0,
- x0: 0,
- x1: 0,
- y0: 0,
- y1: 0,
- layer: 0,
- visible: true,
- } as unknown as PathNodeData
-
- const result = pageUrl(testData, true)
- expect(result).toBe('/#/auth/login')
- })
-
- it('should correctly process PathNodeData with unrelated hash in URL', () => {
- const testData = {
- name: '2_https://example.com/auth/login#sidepanel=explore',
- targetLinks: [
- {
- average_conversion_time: 0,
- index: 0,
- value: 0,
- width: 0,
- y0: 0,
- color: { r: 0, g: 0, b: 0 } as RGBColor,
- target: {
- name: '1_https://example.com/',
- targetLinks: [],
- sourceLinks: [],
- depth: 0,
- width: 0,
- height: 0,
- index: 0,
- value: 0,
- x0: 0,
- x1: 0,
- y0: 0,
- y1: 0,
- layer: 0,
- visible: true,
- },
- source: {
- name: '1_https://example.com/',
- targetLinks: [],
- sourceLinks: [],
- depth: 0,
- width: 0,
- height: 0,
- index: 0,
- value: 0,
- x0: 0,
- x1: 0,
- y0: 0,
- y1: 0,
- layer: 0,
- visible: true,
- },
- },
- ],
- sourceLinks: [],
- depth: 0,
- width: 0,
- height: 0,
- index: 0,
- value: 0,
- x0: 0,
- x1: 0,
- y0: 0,
- y1: 0,
- layer: 0,
- visible: true,
- } as unknown as PathNodeData
-
- const result = pageUrl(testData, true)
- expect(result).toBe('/auth/login')
- })
-
- it('should correctly process PathNodeData with regular URL', () => {
- const testData = {
- name: '2_https://example.com/path',
- targetLinks: [
- {
- average_conversion_time: 0,
- index: 0,
- value: 0,
- width: 0,
- y0: 0,
- color: { r: 0, g: 0, b: 0 } as RGBColor,
- target: {
- name: '1_https://example.com/',
- targetLinks: [],
- sourceLinks: [],
- depth: 0,
- width: 0,
- height: 0,
- index: 0,
- value: 0,
- x0: 0,
- x1: 0,
- y0: 0,
- y1: 0,
- layer: 0,
- visible: true,
- },
- source: {
- name: '1_https://example.com/',
- targetLinks: [],
- sourceLinks: [],
- depth: 0,
- width: 0,
- height: 0,
- index: 0,
- value: 0,
- x0: 0,
- x1: 0,
- y0: 0,
- y1: 0,
- layer: 0,
- visible: true,
- },
- },
- ],
- sourceLinks: [],
- depth: 0,
- width: 0,
- height: 0,
- index: 0,
- value: 0,
- x0: 0,
- x1: 0,
- y0: 0,
- y1: 0,
- layer: 0,
- visible: true,
- } as unknown as PathNodeData
-
- const result = pageUrl(testData, true)
- expect(result).toBe('/path')
- })
-
- it('should decode URL-encoded characters in path cleaning aliases', () => {
- const testData = {
- name: '2_https://example.com/files/<id>',
- targetLinks: [
- {
- average_conversion_time: 0,
- index: 0,
- value: 0,
- width: 0,
- y0: 0,
- color: { r: 0, g: 0, b: 0 } as RGBColor,
- target: {
- name: '1_https://example.com/',
- targetLinks: [],
- sourceLinks: [],
- depth: 0,
- width: 0,
- height: 0,
- index: 0,
- value: 0,
- x0: 0,
- x1: 0,
- y0: 0,
- y1: 0,
- layer: 0,
- visible: true,
- },
- source: {
- name: '1_https://example.com/',
- targetLinks: [],
- sourceLinks: [],
- depth: 0,
- width: 0,
- height: 0,
- index: 0,
- value: 0,
- x0: 0,
- x1: 0,
- y0: 0,
- y1: 0,
- layer: 0,
- visible: true,
- },
- },
- ],
- sourceLinks: [],
- depth: 0,
- width: 0,
- height: 0,
- index: 0,
- value: 0,
- x0: 0,
- x1: 0,
- y0: 0,
- y1: 0,
- layer: 0,
- visible: true,
- } as unknown as PathNodeData
-
- // The URL API encodes < and > to %3C and %3E, but we should decode them back
- const result = pageUrl(testData, true)
- expect(result).toBe('/files/<id>')
- })
-})
diff --git a/frontend/src/scenes/paths-v2/pathUtils.ts b/frontend/src/scenes/paths-v2/pathUtils.ts
deleted file mode 100644
index 52c8572f0845..000000000000
--- a/frontend/src/scenes/paths-v2/pathUtils.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-import { RGBColor } from 'd3'
-
-import { tryDecodeURIComponent } from 'lib/utils/url'
-
-import { FunnelPathsFilter, PathsFilter } from '~/queries/schema/schema-general'
-import { FunnelPathType } from '~/types'
-
-export interface PathTargetLink {
- average_conversion_time: number
- index: number
- source: PathNodeData
- target: PathNodeData
- value: number
- width: number
- y0: number
- color: RGBColor
-}
-
-export interface PathNodeData {
- name: string
- targetLinks: PathTargetLink[]
- sourceLinks: PathTargetLink[]
- depth: number
- width: number
- height: number
- index: number
- value: number
- x0: number
- x1: number
- y0: number
- y1: number
- layer: number
- source: PathNodeData
- target: PathNodeData
-}
-
-export function roundedRect(
- x: number,
- y: number,
- w: number,
- h: number,
- r: number,
- tl: boolean,
- tr: boolean,
- bl: boolean,
- br: boolean
-): string {
- let retval: string
- retval = 'M' + (x + r) + ',' + y
- retval += 'h' + (w - 2 * r)
- if (tr) {
- retval += 'a' + r + ',' + r + ' 0 0 1 ' + r + ',' + r
- } else {
- retval += 'h' + r
- retval += 'v' + r
- }
- retval += 'v' + (h - 2 * r)
- if (br) {
- retval += 'a' + r + ',' + r + ' 0 0 1 ' + -r + ',' + r
- } else {
- retval += 'v' + r
- retval += 'h' + -r
- }
- retval += 'h' + (2 * r - w)
- if (bl) {
- retval += 'a' + r + ',' + r + ' 0 0 1 ' + -r + ',' + -r
- } else {
- retval += 'h' + -r
- retval += 'v' + -r
- }
- retval += 'v' + (2 * r - h)
- if (tl) {
- retval += 'a' + r + ',' + r + ' 0 0 1 ' + r + ',' + -r
- } else {
- retval += 'v' + -r
- retval += 'h' + r
- }
- retval += 'z'
- return retval
-}
-
-export function pageUrl(d: PathNodeData, display?: boolean): string {
- const incomingUrls = d.targetLinks
- .map((l) => l?.source?.name?.replace(/(^[0-9]+_)/, ''))
- .filter((a) => {
- try {
- new URL(a)
- } catch {
- return false
- }
- return a
- })
- .map((a) => new URL(a))
- const incomingDomains = Array.from(new Set(incomingUrls.map((url) => url.origin)))
-
- let name = d.name.replace(/(^[0-9]+_)/, '')
-
- if (!display) {
- return name
- }
-
- try {
- const url = new URL(name)
- name = incomingDomains.length !== 1 ? url.href.replace(/(^\w+:|^)\/\//, '') : url.pathname + url.search
- if (url.hash?.includes('/')) {
- name += url.hash
- }
- // Decode URL-encoded characters (e.g., %3C becomes <) to display path cleaning aliases correctly
- name = tryDecodeURIComponent(name)
- } catch {
- // discard if invalid url
- }
- return name.length > 30
- ? name.substring(0, 21) + '...' + name.slice(-8)
- : name.length < 4 && d.name.length < 25
- ? d.name.replace(/(^[0-9]+_)/, '')
- : name
-}
-
-export const isSelectedPathStartOrEnd = (
- pathsFilter: PathsFilter,
- funnelPathsFilter: FunnelPathsFilter,
- pathItemCard: PathNodeData
-): boolean => {
- const cardName = pageUrl(pathItemCard)
- const isPathStart = pathItemCard.targetLinks.length === 0
- const isPathEnd = pathItemCard.sourceLinks.length === 0
- const { startPoint, endPoint } = pathsFilter
- const { funnelPathType, funnelSource, funnelStep } = funnelPathsFilter || {}
-
- return (
- (startPoint === cardName && isPathStart) ||
- (endPoint === cardName && isPathEnd) ||
- (funnelPathType === FunnelPathType.between &&
- ((cardName === funnelSource?.series[funnelStep! - 1].name && isPathEnd) ||
- (cardName === funnelSource?.series[funnelStep! - 2].name && isPathStart)))
- )
-}
diff --git a/frontend/src/scenes/paths-v2/pathsDataLogic.test.ts b/frontend/src/scenes/paths-v2/pathsDataLogic.test.ts
deleted file mode 100644
index 02d60e17538d..000000000000
--- a/frontend/src/scenes/paths-v2/pathsDataLogic.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { expectLogic } from 'kea-test-utils'
-
-import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import { pathsDataLogic } from 'scenes/paths-v2/pathsDataLogic'
-import { teamLogic } from 'scenes/teamLogic'
-
-import { examples } from '~/queries/examples'
-import { InsightVizNode, NodeKind } from '~/queries/schema/schema-general'
-import { initKeaTests } from '~/test/init'
-import { InsightLogicProps, PathType } from '~/types'
-
-let logic: ReturnType<typeof pathsDataLogic.build>
-
-const insightProps: InsightLogicProps = {
- dashboardItemId: undefined,
- cachedInsight: {
- query: { kind: NodeKind.InsightVizNode, source: examples.InsightPathsQuery } as InsightVizNode,
- },
-}
-
-async function initPathsDataLogic(): Promise<void> {
- logic = pathsDataLogic(insightProps)
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
-}
-
-describe('pathsDataLogic', () => {
- beforeEach(async () => {
- initKeaTests(false)
- teamLogic.mount()
- await initPathsDataLogic()
- })
-
- it('selects taxonomicGroupTypes from pathsFilter', async () => {
- await expectLogic(logic, () => {
- logic.actions.updateInsightFilter({
- includeEventTypes: [PathType.PageView, PathType.Screen, PathType.CustomEvent],
- })
- })
- .toFinishAllListeners()
- .toMatchValues(logic, {
- taxonomicGroupTypes: [
- TaxonomicFilterGroupType.PageviewUrls,
- TaxonomicFilterGroupType.Screens,
- TaxonomicFilterGroupType.CustomEvents,
- TaxonomicFilterGroupType.Wildcards,
- ],
- })
- })
-})
diff --git a/frontend/src/scenes/paths-v2/pathsDataLogic.ts b/frontend/src/scenes/paths-v2/pathsDataLogic.ts
deleted file mode 100644
index 812d73de8a4c..000000000000
--- a/frontend/src/scenes/paths-v2/pathsDataLogic.ts
+++ /dev/null
@@ -1,238 +0,0 @@
-import { MakeLogicType, actions, connect, kea, key, listeners, path, props, selectors } from 'kea'
-import { router } from 'kea-router'
-
-import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
-import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
-import { MathAvailability } from 'scenes/insights/filters/ActionFilter/ActionFilterRow/ActionFilterRow'
-import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
-import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'
-import { buildFunnelEventsFromPathNode } from 'scenes/paths/pathsDataLogic'
-import { pathsTitle } from 'scenes/trends/persons-modal/persons-modal-utils'
-import { OpenPersonsModalProps, openPersonsModal } from 'scenes/trends/persons-modal/PersonsModal'
-import { urls } from 'scenes/urls'
-
-import { actionsAndEventsToSeries } from '~/queries/nodes/InsightQuery/utils/filtersToQueryNode'
-import { InsightActorsQuery, InsightVizNode, NodeKind, PathsLink, PathsQuery } from '~/queries/schema/schema-general'
-import { isPathsQuery } from '~/queries/utils'
-import { InsightLogicProps, PathType } from '~/types'
-
-import type { DataColorTheme } from '../../lib/colors'
-import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
-import type {
- DataNode,
- DateRange,
- FunnelPathsFilter,
- FunnelsQuery,
- InsightFilter,
- LifecycleQuery,
- PathsFilter,
- RetentionQuery,
- StickinessQuery,
- TrendsQuery,
- WebOverviewQuery,
- WebStatsTableQuery,
-} from '../../queries/schema/schema-general'
-import type { QuerySourceUpdate } from '../insights/insightVizDataLogic'
-import { PathNodeData } from './pathUtils'
-import { Paths, PathsNode } from './types'
-
-export const DEFAULT_STEP_LIMIT = 5
-
-const DEFAULT_PATH_LOGIC_KEY = 'default_path_key'
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface pathsDataLogicValues {
- featureFlags: FeatureFlagsSet // featureFlagLogic
- dateRange: DateRange | null | undefined // insightVizDataLogic
- funnelPathsFilter: FunnelPathsFilter | null | undefined // insightVizDataLogic
- insightData: Record<string, any> // insightVizDataLogic
- insightDataError: Record<string, any> | null // insightVizDataLogic
- insightDataLoading: boolean // insightVizDataLogic
- insightQuery: DataNode<Record<string, any>> // insightVizDataLogic
- pathsFilter: PathsFilter | null // insightVizDataLogic
- theme: DataColorTheme | null // insightVizDataLogic
- vizQuerySource:
- | FunnelsQuery
- | LifecycleQuery
- | PathsQuery
- | RetentionQuery
- | StickinessQuery
- | TrendsQuery
- | WebOverviewQuery
- | WebStatsTableQuery
- | null // insightVizDataLogic
- paths: Paths
- results: PathsLink[]
- taxonomicGroupTypes: TaxonomicFilterGroupType[]
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface pathsDataLogicActions {
- updateInsightFilter: (insightFilter: InsightFilter) => {
- insightFilter: InsightFilter
- } // insightVizDataLogic
- updateQuerySource: (querySource: QuerySourceUpdate) => {
- querySource: QuerySourceUpdate
- } // insightVizDataLogic
- openPersonsModal: (props: { path_dropoff_key?: string; path_end_key?: string; path_start_key?: string }) => {
- path_dropoff_key?: string | undefined
- path_end_key?: string | undefined
- path_start_key?: string | undefined
- }
- viewPathToFunnel: (pathItemCard: PathNodeData) => {
- pathItemCard: PathNodeData
- }
-}
-
-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
-export interface pathsDataLogicMeta {
- key: string
- __keaTypeGenInternalSelectorTypes: {
- results: (insightQuery: DataNode<Record<string, any>>, insightData: Record<string, any>) => PathsLink[]
- paths: (results: PathsLink[]) => Paths
- taxonomicGroupTypes: (pathsFilter: PathsFilter | null) => TaxonomicFilterGroupType[]
- }
-}
-
-export type pathsDataLogicType = MakeLogicType<
- pathsDataLogicValues,
- pathsDataLogicActions,
- InsightLogicProps,
- pathsDataLogicMeta
->
-
-export const pathsDataLogic = kea<pathsDataLogicType>([
- path((key) => ['scenes', 'paths', 'pathsDataLogic', key]),
- props({} as InsightLogicProps),
- key(keyForInsightLogicProps(DEFAULT_PATH_LOGIC_KEY)),
-
- connect((props: InsightLogicProps) => ({
- values: [
- insightVizDataLogic(props),
- [
- 'querySource as vizQuerySource',
- 'insightQuery',
- 'insightData',
- 'insightDataLoading',
- 'insightDataError',
- 'pathsFilter',
- 'funnelPathsFilter',
- 'dateRange',
- 'theme',
- ],
- featureFlagLogic,
- ['featureFlags'],
- ],
- actions: [insightVizDataLogic(props), ['updateInsightFilter', 'updateQuerySource']],
- })),
-
- actions({
- openPersonsModal: (props: { path_start_key?: string; path_end_key?: string; path_dropoff_key?: string }) =>
- props,
- viewPathToFunnel: (pathItemCard: PathNodeData) => ({ pathItemCard }),
- }),
-
- selectors({
- results: [
- (s) => [s.insightQuery, s.insightData],
- (
- insightQuery: import('~/queries/schema/schema-general').DataNode<Record<string, any>>,
- insightData: Record<string, any>
- ): PathsLink[] => {
- return isPathsQuery(insightQuery) ? (insightData?.result ?? []) : []
- },
- ],
- paths: [
- (s) => [s.results],
- (results: PathsLink[]): Paths => {
- const nodes: Record<string, PathsNode> = {}
- for (const path of results) {
- if (!nodes[path.source]) {
- nodes[path.source] = { name: path.source }
- }
- if (!nodes[path.target]) {
- nodes[path.target] = { name: path.target }
- }
- }
-
- return {
- nodes: Object.values(nodes),
- links: results,
- }
- },
- ],
- taxonomicGroupTypes: [
- (s) => [s.pathsFilter],
- (pathsFilter: null | import('~/queries/schema/schema-general').PathsFilter) => {
- const taxonomicGroupTypes: TaxonomicFilterGroupType[] = []
- if (pathsFilter?.includeEventTypes) {
- if (pathsFilter.includeEventTypes.includes(PathType.PageView)) {
- taxonomicGroupTypes.push(TaxonomicFilterGroupType.PageviewUrls)
- }
- if (pathsFilter.includeEventTypes.includes(PathType.Screen)) {
- taxonomicGroupTypes.push(TaxonomicFilterGroupType.Screens)
- }
- if (pathsFilter.includeEventTypes.includes(PathType.CustomEvent)) {
- taxonomicGroupTypes.push(TaxonomicFilterGroupType.CustomEvents)
- }
- }
- taxonomicGroupTypes.push(TaxonomicFilterGroupType.Wildcards)
- return taxonomicGroupTypes
- },
- ],
- }),
-
- listeners(({ values }) => ({
- openPersonsModal: ({ path_start_key, path_end_key, path_dropoff_key }) => {
- const query: InsightActorsQuery = {
- kind: NodeKind.InsightActorsQuery,
- source: {
- ...values.vizQuerySource,
- pathsFilter: {
- ...(values.vizQuerySource as PathsQuery)?.pathsFilter,
- pathStartKey: path_start_key,
- pathEndKey: path_end_key,
- pathDropoffKey: path_dropoff_key,
- },
- } as PathsQuery,
- }
- const modalProps: OpenPersonsModalProps = {
- title: pathsTitle({
- label: path_dropoff_key || path_start_key || path_end_key || 'Pageview',
- mode: path_dropoff_key ? 'dropOff' : path_start_key ? 'continue' : 'completion',
- }),
- query,
- additionalSelect: {
- value_at_data_point: 'event_count',
- matched_recordings: 'matched_recordings',
- },
- orderBy: ['event_count DESC, actor_id DESC'],
- }
- openPersonsModal(modalProps)
- },
- viewPathToFunnel: ({ pathItemCard }) => {
- const events = buildFunnelEventsFromPathNode(pathItemCard)
- if (events.length === 0) {
- return
- }
-
- const query: InsightVizNode = {
- kind: NodeKind.InsightVizNode,
- source: {
- kind: NodeKind.FunnelsQuery,
- series: actionsAndEventsToSeries(
- { events },
- true,
- MathAvailability.None,
- NodeKind.FunnelsDataWarehouseNode
- ),
- dateRange: {
- date_from: values.dateRange?.date_from,
- },
- },
- }
-
- router.actions.push(urls.insightNew({ query }))
- },
- })),
-])
diff --git a/frontend/src/scenes/paths-v2/renderPaths.ts b/frontend/src/scenes/paths-v2/renderPaths.ts
deleted file mode 100644
index d903b586e25b..000000000000
--- a/frontend/src/scenes/paths-v2/renderPaths.ts
+++ /dev/null
@@ -1,224 +0,0 @@
-import * as d3 from 'd3'
-import { Dispatch, RefObject, SetStateAction } from 'react'
-
-import { D3Selector } from 'lib/hooks/useD3'
-
-import { FunnelPathsFilter, PathsFilter } from '~/queries/schema/schema-general'
-import sankey, { sankeyLeft, sankeyLinkHorizontal, SankeyLink, type SankeyLayout } from '~/vendor/d3/sankey'
-
-import { PathNodeData, PathTargetLink, isSelectedPathStartOrEnd } from './pathUtils'
-import { Paths } from './types'
-
-/*
- * Canvas
- */
-
-const FALLBACK_CANVAS_WIDTH = 1000
-const FALLBACK_CANVAS_HEIGHT = 0
-const CANVAS_PADDING_HORIZONTAL = 12
-const CANVAS_PADDING_VERTICAL = 12
-
-/*
- * Node
- */
-
-// We want the border radius to overlap the links. For this we subtract the border radius of both
-// sides from the node width, and add it back to the svg element that is moved left by the border radius.
-//
-// We also expand the canvas margin by the border radius on both sides to make sure the nodes are not cut off.
-const NODE_BORDER_RADIUS = 4
-const NODE_WIDTH = 48 - 2 * NODE_BORDER_RADIUS
-const NODE_MIN_HEIGHT = 3
-
-/*
- * Node label
- */
-
-export const NODE_LABEL_WIDTH = 240
-export const NODE_LABEL_HEIGHT = 44
-const NODE_LABEL_MARGIN_TOP = 20
-const NODE_LABEL_MARGIN_BOTTOM = 10
-export const NODE_LABEL_TOP_OFFSET = -(NODE_LABEL_HEIGHT + NODE_LABEL_MARGIN_BOTTOM)
-export const NODE_LABEL_LEFT_OFFSET = 0 - NODE_BORDER_RADIUS
-
-/** Space between two nodes, should fit the node label and it's vertical margins. */
-const NODE_PADDING = NODE_LABEL_MARGIN_TOP + NODE_LABEL_HEIGHT + NODE_LABEL_MARGIN_BOTTOM
-
-/*
- * Node links
- */
-const LINK_OPACITY = 0.1
-const LINK_OPACITY_EMPHASIZED = 0.25
-const LINK_OPACITY_DEEMPHASIZED = 0.05
-
-const createCanvas = (canvasRef: RefObject<HTMLDivElement>, width: number, height: number): D3Selector => {
- return d3
- .select(canvasRef.current)
- .append('svg')
- .classed('Paths__canvas', true)
- .style('background', 'var(--item-background)')
- .style('width', `${width}px`)
- .style('height', `${height}px`)
-}
-
-const createSankeyGenerator = (width: number, height: number): SankeyLayout<PathNodeData, {}> => {
- /** **Left canvas margin**
- * - Expanded by the border radius to make sure the nodes are not cut off.
- */
- const marginLeft = CANVAS_PADDING_HORIZONTAL + NODE_BORDER_RADIUS
-
- /** **Top canvas margin**
- * - Expanded by the node label height and it's bottom margin, so that the
- * first label fits into the canvas.
- */
- const marginTop = NODE_LABEL_HEIGHT + NODE_LABEL_MARGIN_BOTTOM + CANVAS_PADDING_VERTICAL
-
- /** **Right canvas margin**
- * - Expanded by the border radius to make sure the nodes are not cut off.
- * - Expanded by the width of the node label, minus the already existing
- * node width to make sure the node label fits into the canvas.
- */
- const marginRight = CANVAS_PADDING_HORIZONTAL + NODE_BORDER_RADIUS + NODE_LABEL_WIDTH - NODE_WIDTH
-
- /** **Bottom canvas margin** */
- const marginBottom = CANVAS_PADDING_VERTICAL
-
- return sankey<PathNodeData, {}>()
- .nodeId((d) => d.name)
- .nodeAlign(sankeyLeft)
- .nodeSort(null)
- .nodeWidth(NODE_WIDTH)
- .nodePadding(NODE_PADDING)
- .size([width, height])
- .extent([
- [marginLeft, marginTop], // top-left coordinates
- [width - marginRight, height - marginBottom], // bottom-right coordinates
- ])
-}
-
-const appendNodes = (
- svg: D3Selector,
- nodes: PathNodeData[],
- pathsFilter: PathsFilter,
- funnelPathsFilter: FunnelPathsFilter,
- openPersonsModal: (props: { path_dropoff_key?: string; path_end_key?: string; path_start_key?: string }) => void
-): void => {
- svg.append('g')
- .selectAll('rect')
- .data(nodes)
- .join('rect')
- .attr('x', (node: PathNodeData) => node.x0 - NODE_BORDER_RADIUS)
- .attr('y', (node: PathNodeData) => node.y0)
- .attr('rx', NODE_BORDER_RADIUS)
- .attr('height', (node: PathNodeData) => Math.max(node.y1 - node.y0, NODE_MIN_HEIGHT))
- .attr('width', (node: PathNodeData) => node.x1 - node.x0 + 2 * NODE_BORDER_RADIUS)
- .attr('fill', (node: PathNodeData) => {
- if (isSelectedPathStartOrEnd(pathsFilter, funnelPathsFilter, node)) {
- return 'var(--paths-node-start-or-end)'
- }
- return 'var(--paths-node)'
- })
- .attr('id', (node: PathNodeData) => `node-${node.index}`)
- .on('click', (_event: MouseEvent, node: PathNodeData) => {
- openPersonsModal({ path_end_key: node.name })
- })
- .style('cursor', 'pointer')
- .on('mouseover', (_event: MouseEvent, node: PathNodeData) => {
- svg.selectAll('path').attr('opacity', LINK_OPACITY_DEEMPHASIZED)
-
- // apply effect to hovered node
- const isStartOrEndNode = isSelectedPathStartOrEnd(pathsFilter, funnelPathsFilter, node)
- const nodeColor = isStartOrEndNode ? 'var(--paths-node-start-or-end-hover)' : 'var(--paths-node-hover)'
- svg.select(`#node-${node.index}`).attr('fill', nodeColor)
-
- // recursively apply effect to incoming links
- const sourceNodes = [node]
- while (sourceNodes.length > 0) {
- const _node = sourceNodes.pop()
- _node?.targetLinks.forEach((link: PathTargetLink) => {
- svg.select(`#link-${link.index}`).attr('opacity', LINK_OPACITY_EMPHASIZED)
- sourceNodes.push(link.source) // add source node to recursion
- })
- }
-
- // recursively apply effect to outgoing links
- const targetNodes = [node]
- while (targetNodes.length > 0) {
- const node = targetNodes.pop()
- node?.sourceLinks.forEach((link: PathTargetLink) => {
- svg.select(`#link-${link.index}`).attr('opacity', LINK_OPACITY_EMPHASIZED)
- targetNodes.push(link.target) // add target node to recursion
- })
- }
- })
- .on('mouseleave', (_event: MouseEvent, node: PathNodeData) => {
- // reset hovered node
- const isStartOrEndNode = isSelectedPathStartOrEnd(pathsFilter, funnelPathsFilter, node)
- const nodeColor = isStartOrEndNode ? 'var(--paths-node-start-or-end)' : 'var(--paths-node)'
- svg.select(`#node-${node.index}`).attr('fill', nodeColor)
-
- // reset all links
- svg.selectAll('path').attr('opacity', LINK_OPACITY)
- })
-}
-
-const appendLinks = (svg: D3Selector, links: SankeyLink<PathNodeData, {}>[]): void => {
- svg.selectAll('path')
- .data(links)
- .join('path')
- .attr('d', sankeyLinkHorizontal())
- .attr('id', (link) => `link-${link.index}`)
- .attr('fill', 'none')
- .attr('stroke', 'var(--paths-link)')
- .attr('stroke-width', (link) => Math.max(1, link.width))
- .attr('opacity', LINK_OPACITY)
- .on('mouseover', (_event: MouseEvent, link) => {
- // apply effect to hovered link
- svg.select(`#link-${link.index}`).attr('opacity', LINK_OPACITY_EMPHASIZED)
- })
- .on('mouseleave', (_event: MouseEvent, link) => {
- // reset hovered link
- svg.select(`#link-${link.index}`).attr('opacity', LINK_OPACITY)
- })
-}
-
-export function renderPaths(
- canvasRef: RefObject<HTMLDivElement>,
- _canvasWidth: number | undefined,
- _canvasHeight: number | undefined,
- paths: Paths,
- pathsFilter: PathsFilter,
- funnelPathsFilter: FunnelPathsFilter,
- setNodes: Dispatch<SetStateAction<PathNodeData[]>>,
- openPersonsModal: (props: { path_dropoff_key?: string; path_end_key?: string; path_start_key?: string }) => void
-): void {
- const canvasWidth = _canvasWidth || FALLBACK_CANVAS_WIDTH
- const canvasHeight = _canvasHeight || FALLBACK_CANVAS_HEIGHT
-
- if (!paths || paths.nodes.length === 0) {
- return
- }
-
- const maxLayer = paths.links.reduce((prev, curr) => {
- return Math.max(prev, Number(curr.target.match(/[^_]*/)))
- }, 0)
-
- const minWidth = canvasWidth > FALLBACK_CANVAS_WIDTH || maxLayer < 3 ? canvasWidth : FALLBACK_CANVAS_WIDTH
-
- const width = maxLayer > 5 && canvasWidth ? (minWidth / 5) * maxLayer : minWidth
- const height = canvasHeight
-
- const svg = createCanvas(canvasRef, width, height)
- const sankey = createSankeyGenerator(width, height)
-
- // :TRICKY: clone the paths, as d3 mutates data in place.
- const clonedPaths = structuredClone(paths)
- const { nodes, links } = sankey(clonedPaths)
-
- appendLinks(svg, links)
- appendNodes(svg, nodes, pathsFilter, funnelPathsFilter, openPersonsModal)
-
- // :TRICKY: this needs to come last, as d3 mutates data in place and otherwise
- // we won't have node positions.
- setNodes(nodes)
-}
diff --git a/frontend/src/scenes/paths-v2/types.ts b/frontend/src/scenes/paths-v2/types.ts
deleted file mode 100644
index d5357689a9ad..000000000000
--- a/frontend/src/scenes/paths-v2/types.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { PathsLink } from '~/queries/schema/schema-general'
-
-export type PathsNode = { name: string }
-
-export type Paths = {
- nodes: PathsNode[]
- links: PathsLink[]
-}
diff --git a/frontend/src/scenes/paths/pathsDataLogic.ts b/frontend/src/scenes/paths/pathsDataLogic.ts
index 056161905190..d1bd0a20b0ff 100644
--- a/frontend/src/scenes/paths/pathsDataLogic.ts
+++ b/frontend/src/scenes/paths/pathsDataLogic.ts
@@ -31,6 +31,7 @@ import type {
WebOverviewQuery,
WebStatsTableQuery,
} from '../../queries/schema/schema-general'
+import type { PathsV2Query } from '../../queries/schema/schema-general'
import type { QuerySourceUpdate } from '../insights/insightVizDataLogic'
import { PathNodeData } from './pathUtils'
import { Paths, PathsNode } from './types'
@@ -81,6 +82,7 @@ export interface pathsDataLogicValues {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
diff --git a/frontend/src/scenes/retention/retentionGraphLogic.ts b/frontend/src/scenes/retention/retentionGraphLogic.ts
index a94c9f06b881..997909325edb 100644
--- a/frontend/src/scenes/retention/retentionGraphLogic.ts
+++ b/frontend/src/scenes/retention/retentionGraphLogic.ts
@@ -19,6 +19,7 @@ import type {
WebOverviewQuery,
WebStatsTableQuery,
} from '../../queries/schema/schema-general'
+import type { PathsV2Query } from '../../queries/schema/schema-general'
import type { LabelGroupType } from '../../types'
import { dateOptionToTimeIntervalMap } from './constants'
import { MeanRetentionValue, retentionLogic } from './retentionLogic'
@@ -34,6 +35,7 @@ export interface retentionGraphLogicValues {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -83,6 +85,7 @@ export interface retentionGraphLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
diff --git a/frontend/src/scenes/retention/retentionLogic.ts b/frontend/src/scenes/retention/retentionLogic.ts
index a6b97d1f04d5..fa383b85008b 100644
--- a/frontend/src/scenes/retention/retentionLogic.ts
+++ b/frontend/src/scenes/retention/retentionLogic.ts
@@ -36,6 +36,7 @@ import type {
WebOverviewQuery,
WebStatsTableQuery,
} from '../../queries/schema/schema-general'
+import type { PathsV2Query } from '../../queries/schema/schema-general'
import type { QuerySourceUpdate } from '../insights/insightVizDataLogic'
const DEFAULT_RETENTION_LOGIC_KEY = 'default_retention_key'
@@ -69,6 +70,7 @@ export interface retentionLogicValues {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -171,12 +173,13 @@ export interface retentionLogicMeta {
cohortsById: Partial<Record<number | string, CohortType>>
) => Record<string, string>
getRetentionColorToken: (
- getTheme: (themeId: number | string | null | undefined) => DataColorTheme | null, // insightVizDataLogic
+ getTheme: (themeId: number | string | null | undefined) => DataColorTheme | null,
breakdownFilter: BreakdownFilter | null | undefined,
querySource:
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
diff --git a/frontend/src/scenes/retention/retentionModalLogic.ts b/frontend/src/scenes/retention/retentionModalLogic.ts
index edafd00ba78f..be30a1ceb8dc 100644
--- a/frontend/src/scenes/retention/retentionModalLogic.ts
+++ b/frontend/src/scenes/retention/retentionModalLogic.ts
@@ -34,6 +34,7 @@ import type {
WebOverviewQuery,
WebStatsTableQuery,
} from '../../queries/schema/schema-general'
+import type { PathsV2Query } from '../../queries/schema/schema-general'
import { retentionPeopleLogic } from './retentionPeopleLogic'
const DEFAULT_RETENTION_LOGIC_KEY = 'default_retention_key'
@@ -46,6 +47,7 @@ export interface retentionModalLogicValues {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -102,6 +104,7 @@ export interface retentionModalLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -115,6 +118,7 @@ export interface retentionModalLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
diff --git a/frontend/src/scenes/retention/retentionPeopleLogic.ts b/frontend/src/scenes/retention/retentionPeopleLogic.ts
index 78e30219b399..91dac214e146 100644
--- a/frontend/src/scenes/retention/retentionPeopleLogic.ts
+++ b/frontend/src/scenes/retention/retentionPeopleLogic.ts
@@ -34,6 +34,7 @@ import type {
WebOverviewQuery,
WebStatsTableQuery,
} from '../../queries/schema/schema-general'
+import type { PathsV2Query } from '../../queries/schema/schema-general'
import type { FilterType } from '../../types'
const DEFAULT_RETENTION_LOGIC_KEY = 'default_retention_key'
@@ -44,6 +45,7 @@ export interface retentionPeopleLogicValues {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -158,6 +160,7 @@ export interface retentionPeopleLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
diff --git a/frontend/src/scenes/saved-insights/NewInsightMenu.tsx b/frontend/src/scenes/saved-insights/NewInsightMenu.tsx
index 30debc5a2030..ece0008c3b1f 100644
--- a/frontend/src/scenes/saved-insights/NewInsightMenu.tsx
+++ b/frontend/src/scenes/saved-insights/NewInsightMenu.tsx
@@ -5,7 +5,6 @@ import { IconPlusSmall, IconSparkles } from '@posthog/icons'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { Shortcut } from 'lib/components/Shortcuts/Shortcut'
import { keyBinds } from 'lib/components/Shortcuts/shortcuts'
-import { FEATURE_FLAGS } from 'lib/constants'
import { IconInsightNumber, IconInsightPie, IconInsightTable, IconInsightWorldMap } from 'lib/lemon-ui/icons'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
@@ -15,7 +14,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { cn } from 'lib/utils/css-classes'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { INSIGHT_TYPE_URLS } from 'scenes/insights/utils'
-import { INSIGHT_TYPES_METADATA } from 'scenes/saved-insights/insightTypesMetadata'
+import { INSIGHT_TYPES_METADATA, isInsightTypeCreatable } from 'scenes/saved-insights/insightTypesMetadata'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -162,11 +161,7 @@ function useNewInsightCards(): {
const byType: Partial<Record<InsightType, NewInsightCardSpec>> = {}
for (const [insightType, metadata] of Object.entries(INSIGHT_TYPES_METADATA)) {
- if (
- !metadata.inMenu ||
- insightType === InsightType.JSON ||
- (!featureFlags[FEATURE_FLAGS.HOG] && insightType === InsightType.HOG)
- ) {
+ if (!isInsightTypeCreatable(metadata, featureFlags) || insightType === InsightType.JSON) {
continue
}
const spec: NewInsightCardSpec = {
@@ -232,6 +227,7 @@ const SHORT_CARD_DESCRIPTIONS: Record<string, string> = {
[InsightType.FUNNELS]: 'Conversion through a sequence of steps.',
[InsightType.RETENTION]: 'How many users come back later.',
[InsightType.PATHS]: 'The routes users take through your product.',
+ [InsightType.JOURNEYS]: 'The steps users take and where they stop.',
[InsightType.SQL]: 'Query your data with SQL.',
[InsightType.HOG]: 'Query your data with Hog.',
ai: 'Describe an insight and let AI build it.',
@@ -264,7 +260,12 @@ function useQuestionSections(): QuestionSection[] {
{
title: 'How do users behave?',
description: 'Funnels, retention, and journeys through your product.',
- cards: [byType[InsightType.FUNNELS], byType[InsightType.RETENTION], byType[InsightType.PATHS]],
+ cards: [
+ byType[InsightType.FUNNELS],
+ byType[InsightType.RETENTION],
+ byType[InsightType.PATHS],
+ byType[InsightType.JOURNEYS],
+ ],
},
{
title: 'Build your own',
diff --git a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
index 6625214d8245..a00db1f97b0f 100644
--- a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
+++ b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
@@ -18,6 +18,7 @@ import {
} from '@posthog/icons'
import { LemonSelectOptions } from '@posthog/lemon-ui'
+import { FEATURE_FLAGS, FeatureFlagKey } from 'lib/constants'
import {
IconAction,
IconBracketsChart,
@@ -30,6 +31,7 @@ import {
IconInsightUserPaths,
IconTableChart,
} from 'lib/lemon-ui/icons'
+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import { NodeKind } from '~/queries/schema/schema-general'
import { InsightType } from '~/types'
@@ -41,9 +43,16 @@ export interface InsightTypeMetadata {
tooltipDescription?: string
icon: React.ComponentType<any>
inMenu: boolean
+ /** Creation surfaces only offer this insight type when the flag is enabled for the viewer. */
+ flag?: FeatureFlagKey
tooltipDocLink?: string
}
+/** Whether creation surfaces should offer this insight type to the current user. */
+export function isInsightTypeCreatable(metadata: InsightTypeMetadata, featureFlags: FeatureFlagsSet): boolean {
+ return metadata.inMenu && (!metadata.flag || !!featureFlags[metadata.flag])
+}
+
export const QUERY_TYPES_METADATA: Record<NodeKind, InsightTypeMetadata> = {
[NodeKind.CalendarHeatmapQuery]: {
name: 'Calendar heatmap (BETA)',
@@ -80,6 +89,13 @@ export const QUERY_TYPES_METADATA: Record<NodeKind, InsightTypeMetadata> = {
inMenu: true,
tooltipDocLink: 'https://posthog.com/docs/product-analytics/paths',
},
+ [NodeKind.PathsV2Query]: {
+ name: 'Journeys',
+ description: 'Follow the steps users take through your product and where they stop.',
+ icon: IconInsightUserPaths,
+ inMenu: true,
+ flag: FEATURE_FLAGS.PRODUCT_ANALYTICS_PATHS_V2,
+ },
[NodeKind.StickinessQuery]: {
name: 'Stickiness',
description: 'See what keeps users coming back by viewing the interval between repeated actions.',
@@ -197,6 +213,12 @@ export const QUERY_TYPES_METADATA: Record<NodeKind, InsightTypeMetadata> = {
icon: IconPerson,
inMenu: false,
},
+ [NodeKind.PathsV2ActorsQuery]: {
+ name: 'Persons',
+ description: 'List of persons behind a journey grid element, derived from an insight.',
+ icon: IconPerson,
+ inMenu: false,
+ },
[NodeKind.GroupsQuery]: {
name: 'Groups',
description: 'List and explore groups.',
@@ -656,6 +678,7 @@ export const INSIGHT_TYPES_METADATA: Record<InsightType, InsightTypeMetadata> =
[InsightType.FUNNELS]: QUERY_TYPES_METADATA[NodeKind.FunnelsQuery],
[InsightType.RETENTION]: QUERY_TYPES_METADATA[NodeKind.RetentionQuery],
[InsightType.PATHS]: QUERY_TYPES_METADATA[NodeKind.PathsQuery],
+ [InsightType.JOURNEYS]: QUERY_TYPES_METADATA[NodeKind.PathsV2Query],
[InsightType.STICKINESS]: QUERY_TYPES_METADATA[NodeKind.StickinessQuery],
[InsightType.LIFECYCLE]: QUERY_TYPES_METADATA[NodeKind.LifecycleQuery],
[InsightType.SQL]: {
@@ -676,6 +699,7 @@ export const INSIGHT_TYPES_METADATA: Record<InsightType, InsightTypeMetadata> =
description: 'Use Hog to query your data.',
icon: IconHogQL,
inMenu: false,
+ flag: FEATURE_FLAGS.HOG,
},
[InsightType.WEB_ANALYTICS]: {
name: 'Web Analytics',
diff --git a/frontend/src/scenes/trends/persons-modal/personsModalLogic.ts b/frontend/src/scenes/trends/persons-modal/personsModalLogic.ts
index c12309f837d9..d105c8a6e3e5 100644
--- a/frontend/src/scenes/trends/persons-modal/personsModalLogic.ts
+++ b/frontend/src/scenes/trends/persons-modal/personsModalLogic.ts
@@ -38,6 +38,7 @@ import {
InsightActorsQueryOptions,
InsightActorsQueryOptionsResponse,
NodeKind,
+ PathsV2ActorsQuery,
TrendsQuery,
insightActorsQueryOptionsResponseKeys,
} from '~/queries/schema/schema-general'
@@ -141,7 +142,13 @@ function buildFunnelBreakdownFilter(source: ActorsQuery['source'] | null): Unive
}
export interface PersonModalLogicProps {
- query?: InsightActorsQuery | FunnelsActorsQuery | FunnelCorrelationActorsQuery | ExperimentActorsQuery | null
+ query?:
+ | InsightActorsQuery
+ | FunnelsActorsQuery
+ | FunnelCorrelationActorsQuery
+ | ExperimentActorsQuery
+ | PathsV2ActorsQuery
+ | null
url?: string | null
additionalSelect?: Partial<Record<keyof CommonActorType, string>>
orderBy?: string[]
diff --git a/frontend/src/scenes/trends/trendsDataLogic.ts b/frontend/src/scenes/trends/trendsDataLogic.ts
index 1d7c7263b049..b63488391529 100644
--- a/frontend/src/scenes/trends/trendsDataLogic.ts
+++ b/frontend/src/scenes/trends/trendsDataLogic.ts
@@ -82,6 +82,7 @@ import type {
WebOverviewQuery,
WebStatsTableQuery,
} from '../../queries/schema/schema-general'
+import type { PathsV2Query } from '../../queries/schema/schema-general'
import { IndexedTrendResult } from './types'
export const RESULT_CUSTOMIZATION_DEFAULT = ResultCustomizationBy.Value
@@ -136,6 +137,7 @@ export interface trendsDataLogicValues {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -270,6 +272,7 @@ export interface trendsDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -287,6 +290,7 @@ export interface trendsDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -308,6 +312,7 @@ export interface trendsDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -328,6 +333,7 @@ export interface trendsDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
@@ -381,6 +387,7 @@ export interface trendsDataLogicMeta {
| FunnelsQuery
| LifecycleQuery
| PathsQuery
+ | PathsV2Query
| RetentionQuery
| StickinessQuery
| TrendsQuery
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index fd78d19abb0b..863a01e1b044 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -3030,6 +3030,7 @@ export enum InsightType {
FUNNELS = 'FUNNELS',
RETENTION = 'RETENTION',
PATHS = 'PATHS',
+ JOURNEYS = 'JOURNEYS',
JSON = 'JSON',
SQL = 'SQL',
HOG = 'HOG',
diff --git a/posthog/api/query.py b/posthog/api/query.py
index 45f007c0852e..159e384f3393 100644
--- a/posthog/api/query.py
+++ b/posthog/api/query.py
@@ -475,7 +475,7 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMi
tag_queries(client_query_id=query_id)
@extend_schema(operation_id="query_create_with_kind")
- @action(methods=["POST"], detail=False, url_path=r"(?P<query_kind>[A-Z][A-Za-z]*)")
+ @action(methods=["POST"], detail=False, url_path=r"(?P<query_kind>[A-Z][A-Za-z0-9]*)")
def create_with_kind(self, request: Request, *args, **kwargs) -> Response:
return self.create(request, *args, **kwargs)
diff --git a/posthog/api/test/test_query_kind_endpoint.py b/posthog/api/test/test_query_kind_endpoint.py
index 173ad32483be..2ab586226746 100644
--- a/posthog/api/test/test_query_kind_endpoint.py
+++ b/posthog/api/test/test_query_kind_endpoint.py
@@ -23,6 +23,8 @@ class TestQueryKindEndpoint(APIBaseTest):
[
("environment", "/api/environments/{team_id}/query/HogQLQuery/"),
("project", "/api/projects/{team_id}/query/HogQLQuery/"),
+ # digit-containing kind — the route regex used to reject these with a 405
+ ("environment_digit_kind", "/api/environments/{team_id}/query/PathsV2Query/"),
]
)
def test_query_kind_endpoint_rejects_mismatch(self, _name: str, url_template: str) -> None:
diff --git a/posthog/api/utils.py b/posthog/api/utils.py
index 3cc8791b9e12..308483dc8f3c 100644
--- a/posthog/api/utils.py
+++ b/posthog/api/utils.py
@@ -333,6 +333,7 @@ INSIGHT_KINDS = {
"FunnelCorrelationQuery",
"RetentionQuery",
"PathsQuery",
+ "PathsV2Query",
"StickinessQuery",
"LifecycleQuery",
}
@@ -356,6 +357,7 @@ INSIGHT_ACTORS_KINDS = {
"FunnelsActorsQuery",
"FunnelCorrelationActorsQuery",
"StickinessActorsQuery",
+ "PathsV2ActorsQuery",
}
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index e60d999ed533..24b798176433 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -186,6 +186,7 @@ def kind_fallback_tags(kind: NodeKind) -> FallbackTags | None:
| NodeKind.FUNNELS_QUERY
| NodeKind.RETENTION_QUERY
| NodeKind.PATHS_QUERY
+ | NodeKind.PATHS_V2_QUERY
| NodeKind.STICKINESS_QUERY
| NodeKind.LIFECYCLE_QUERY
| NodeKind.EVENTS_QUERY
@@ -304,6 +305,7 @@ def kind_fallback_tags(kind: NodeKind) -> FallbackTags | None:
| NodeKind.FUNNELS_ACTORS_QUERY
| NodeKind.FUNNEL_CORRELATION_QUERY
| NodeKind.FUNNEL_CORRELATION_ACTORS_QUERY
+ | NodeKind.PATHS_V2_ACTORS_QUERY
# data-source nodes, not full queries
| NodeKind.EVENTS_NODE
| NodeKind.GROUP_NODE
diff --git a/posthog/hogql_queries/insights/funnels/utils.py b/posthog/hogql_queries/insights/funnels/utils.py
index 0947e6f0fa08..cdc409816d45 100644
--- a/posthog/hogql_queries/insights/funnels/utils.py
+++ b/posthog/hogql_queries/insights/funnels/utils.py
@@ -19,9 +19,30 @@ from posthog.constants import FUNNEL_WINDOW_INTERVAL_TYPES
from posthog.hogql_queries.insights.utils.breakdowns import ALL_USERS_COHORT_ID, NOT_IN_COHORT_ID
from posthog.models.team.team import Team
from posthog.types import FunnelEntityNode, FunnelExclusionEntityNode
+from posthog.utils import DATERANGE_MAP
from products.cohorts.backend.models.cohort import Cohort
+# Server-side mirror of TIME_INTERVAL_BOUNDS in frontend/src/scenes/funnels/funnelUtils.tsx;
+# keep both in sync. Inclusive (min, max) per unit, shared by funnel conversion windows and
+# the paths v2 gap so the two can never drift apart.
+CONVERSION_WINDOW_INTERVAL_BOUNDS: dict[FunnelConversionWindowTimeUnit, tuple[int, int]] = {
+ FunnelConversionWindowTimeUnit.SECOND: (1, 3600),
+ FunnelConversionWindowTimeUnit.MINUTE: (1, 1440),
+ FunnelConversionWindowTimeUnit.HOUR: (1, 24),
+ FunnelConversionWindowTimeUnit.DAY: (1, 365),
+ FunnelConversionWindowTimeUnit.WEEK: (1, 53),
+ FunnelConversionWindowTimeUnit.MONTH: (1, 12),
+}
+
+
+def conversion_window_to_seconds(interval: int, unit: FunnelConversionWindowTimeUnit) -> int:
+ """The funnel engine's conversion window realization: fixed seconds per unit, with month
+ meaning 31 days, never calendar arithmetic. Keep in sync with
+ FunnelUDF.conversion_window_limit; paths v2 uses this for gap G so a journey's gap and the
+ emitted funnel's window can never diverge on calendar-length units."""
+ return int(interval * DATERANGE_MAP[unit].total_seconds())
+
def funnel_window_interval_unit_to_sql(
funnelWindowIntervalUnit: FunnelConversionWindowTimeUnit | None,
diff --git a/posthog/hogql_queries/insights/insight_actors_query_runner.py b/posthog/hogql_queries/insights/insight_actors_query_runner.py
index 76442479bd55..4947bbfbcf7a 100644
--- a/posthog/hogql_queries/insights/insight_actors_query_runner.py
+++ b/posthog/hogql_queries/insights/insight_actors_query_runner.py
@@ -12,6 +12,7 @@ from posthog.schema import (
HogQLQueryResponse,
InsightActorsQuery,
LifecycleQuery,
+ PathsV2ActorsQuery,
StickinessActorsQuery,
StickinessQuery,
TrendsQuery,
@@ -35,6 +36,7 @@ from posthog.types import InsightActorsQueryNode
from products.experiments.backend.hogql_queries.experiment_query_runner import ExperimentQueryRunner
from products.product_analytics.backend.hogql_queries.paths.paths_query_runner import PathsQueryRunner
+from products.product_analytics.backend.hogql_queries.paths_v2.paths_v2_query_runner import PathsV2QueryRunner
from products.product_analytics.backend.hogql_queries.stickiness.stickiness_query_runner import StickinessQueryRunner
@@ -102,6 +104,10 @@ class InsightActorsQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
elif isinstance(self.source_runner, PathsQueryRunner):
paths_runner = cast(PathsQueryRunner, self.source_runner)
return paths_runner.to_actors_query()
+ elif isinstance(self.source_runner, PathsV2QueryRunner):
+ paths_v2_runner = cast(PathsV2QueryRunner, self.source_runner)
+ paths_v2_actors_query = cast(PathsV2ActorsQuery, self.query)
+ return paths_v2_runner.to_actors_query(paths_v2_actors_query.element)
elif isinstance(self.source_runner, StickinessQueryRunner):
stickiness_runner = cast(StickinessQueryRunner, self.source_runner)
stickiness_actors_query = cast(StickinessActorsQuery, self.query)
diff --git a/posthog/hogql_queries/query_metadata.py b/posthog/hogql_queries/query_metadata.py
index 1b2d4b5630e4..a9c021bd6d4f 100644
--- a/posthog/hogql_queries/query_metadata.py
+++ b/posthog/hogql_queries/query_metadata.py
@@ -28,6 +28,8 @@ from posthog.schema import (
InsightVizNode,
LifecycleQuery,
PathsQuery,
+ PathsV2ActorsQuery,
+ PathsV2Query,
PathType,
RetentionEntity,
RetentionQuery,
@@ -101,6 +103,8 @@ class QueryEventsExtractor:
events = self.extract_events(self._ensure_model_instance(query, FunnelCorrelationActorsQuery).source)
elif kind == "StickinessActorsQuery":
events = self.extract_events(self._ensure_model_instance(query, StickinessActorsQuery).source)
+ elif kind == "PathsV2ActorsQuery":
+ events = self.extract_events(self._ensure_model_instance(query, PathsV2ActorsQuery).source)
elif kind == "TrendsQuery":
events = self._extract_events_from_series(self._ensure_model_instance(query, TrendsQuery).series)
@@ -128,6 +132,9 @@ class QueryEventsExtractor:
elif kind == "PathsQuery":
events = self._extract_events_from_paths_query(self._ensure_model_instance(query, PathsQuery))
+ elif kind == "PathsV2Query":
+ events = self._extract_events_from_paths_v2_query(self._ensure_model_instance(query, PathsV2Query))
+
elif kind == "EventsNode":
events = self._get_series_events(self._ensure_model_instance(query, EventsNode))
@@ -184,6 +191,11 @@ class QueryEventsExtractor:
return list(set(included_events + excluded_events))
+ def _extract_events_from_paths_v2_query(self, query: PathsV2Query) -> list[str]:
+ if query.pathsV2Filter is None or query.pathsV2Filter.stepSources is None:
+ return ["$pageview"]
+ return list({source.event for source in query.pathsV2Filter.stepSources})
+
def _extract_events_from_funnels_correlation_query(self, query: FunnelCorrelationQuery) -> list[str]:
events = self.extract_events(query.source)
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index 45f144f40132..e3be86acecd6 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -62,6 +62,7 @@ from posthog.schema import (
MetricsQuery,
NodeKind,
PathsQuery,
+ PathsV2Query,
PropertyGroupFilter,
PropertyGroupFilterValue,
QueryStatus,
@@ -341,6 +342,7 @@ RunnableQueryNode = Union[
FunnelsQuery,
RetentionQuery,
PathsQuery,
+ PathsV2Query,
StickinessQuery,
LifecycleQuery,
ActorsQuery,
@@ -496,6 +498,17 @@ def get_query_runner(
user=user,
)
+ if kind == "PathsV2Query":
+ from products.product_analytics.backend.hogql_queries.paths_v2.paths_v2_query_runner import PathsV2QueryRunner
+
+ return PathsV2QueryRunner(
+ query=cast(PathsV2Query | dict[str, Any], query),
+ team=team,
+ timings=timings,
+ limit_context=limit_context,
+ modifiers=modifiers,
+ user=user,
+ )
if kind == "CalendarHeatmapQuery":
from .insights.trends.calendar_heatmap_query_runner import CalendarHeatmapQueryRunner
@@ -605,6 +618,7 @@ def get_query_runner(
"FunnelCorrelationActorsQuery",
"ExperimentActorsQuery",
"StickinessActorsQuery",
+ "PathsV2ActorsQuery",
):
from .insights.insight_actors_query_runner import InsightActorsQueryRunner
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 259c010a05a4..caf16b1f69bb 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -1326,40 +1326,51 @@ def is_read_only_impersonation(request: HttpRequest) -> bool:
# HTTP methods that are considered idempotent/safe and allowed during impersonation
IMPERSONATION_SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "TRACE"})
-# Paths that are allowed for non-idempotent requests during read-only impersonation.
-# These should be paths that are safe or necessary for the impersonated session to function.
-# Supports both prefix strings and compiled regex patterns.
-READ_ONLY_IMPERSONATION_ALLOWLISTED_PATHS: list[str | re.Pattern] = [
- # These endpoints use POST but are read-only:
- # /query/[A-Z][A-Za-z]* matches query-kind segments, while the schema-upgrade POST action
- # /query/upgrade/ needs an explicit "|upgrade" branch as that starts with a lowercase letter
- re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/query(?:/[A-Za-z]+)?/?$"),
- re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/insights/viewed/?$"),
- re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/metalytics/?$"),
- re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/endpoints/[^/]+/run/?$"),
- re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/endpoints/[^/]+/materialization_preview/?$"),
- re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/endpoints/last_execution_times/?$"),
- re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/persons/batch_by_distinct_ids/?$"),
+# Requests allowed despite using a non-idempotent method during read-only impersonation,
+# as (method, path) pairs. These should be requests that are safe or necessary for the
+# impersonated session to function. Each entry permits a single method so a path match
+# can't authorize other mutating methods on overlapping routes (e.g. DELETE
+# /api/.../query/<id>/ cancels a query and must stay blocked).
+# Paths support both prefix strings and compiled regex patterns.
+READ_ONLY_IMPERSONATION_ALLOWLISTED_PATHS: list[tuple[str, str | re.Pattern]] = [
+ # These endpoints use POST but are read-only: the optional segment matches the
+ # schema-upgrade action /query/upgrade/ and query-kind paths, which start uppercase
+ # and may contain digits (e.g. PathsV2Query), mirroring the route in posthog/api/query.py
+ (
+ "POST",
+ re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/query(?:/(?:upgrade|[A-Z][A-Za-z0-9]*))?/?$"),
+ ),
+ ("POST", re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/insights/viewed/?$")),
+ ("POST", re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/metalytics/?$")),
+ ("POST", re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/endpoints/[^/]+/run/?$")),
+ ("POST", re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/endpoints/[^/]+/materialization_preview/?$")),
+ ("POST", re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/endpoints/last_execution_times/?$")),
+ ("POST", re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/persons/batch_by_distinct_ids/?$")),
# POST but read-only: loads stack frame records (source context) for error tracking UI
- re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/error_tracking/stack_frames/batch_get/?$"),
+ ("POST", re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/error_tracking/stack_frames/batch_get/?$")),
# POST but read-only: returns metadata about available incremental fields / columns
# for a data warehouse schema. Validates external credentials and lists schemas
# against the customer's source — no PostHog-side mutations.
- re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/external_data_schemas/[^/]+/incremental_fields/?$"),
+ (
+ "POST",
+ re.compile(
+ r"^/api/(environments|projects)/([0-9]+|@current)/external_data_schemas/[^/]+/incremental_fields/?$"
+ ),
+ ),
# POST but read-only: kicks off insight/dashboard/session replay export renders (e.g. MP4)
- re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/exports/?$"),
+ ("POST", re.compile(r"^/api/(environments|projects)/([0-9]+|@current)/exports/?$")),
# Allow upgrading from read-only to read-write impersonation
- "/admin/impersonation/upgrade/",
+ ("POST", "/admin/impersonation/upgrade/"),
# Logout is POST in Django 5; the frontend submits to `/logout` (no trailing slash),
# while Django's URL config accepts both via opt_slash_path — match both forms.
- re.compile(r"^/logout/?$"),
+ ("POST", re.compile(r"^/logout/?$")),
# OAuth consent submission and token exchange. Both run as POST during the OAuth flow.
# Scopes minted while read-only impersonation is active are filtered through
# `posthog.scopes.downgrade_scopes_to_read_only` in `OAuthAuthorizationView` so the
# resulting tokens can't grant write access. Tokens minted here are also tagged with
# the impersonator and revoked when impersonation ends.
- re.compile(r"^/oauth/authorize/?$"),
- re.compile(r"^/oauth/token/?$"),
+ ("POST", re.compile(r"^/oauth/authorize/?$")),
+ ("POST", re.compile(r"^/oauth/token/?$")),
]
@@ -1390,7 +1401,7 @@ class ImpersonationReadOnlyMiddleware:
if request.method in IMPERSONATION_SAFE_METHODS:
return self.get_response(request)
- if self._is_path_allowlisted(request.path):
+ if self._is_request_allowlisted(request):
return self.get_response(request)
if self._is_allowed_users_request(request):
@@ -1405,12 +1416,14 @@ class ImpersonationReadOnlyMiddleware:
status=403,
)
- def _is_path_allowlisted(self, path: str) -> bool:
- for allowed_path in READ_ONLY_IMPERSONATION_ALLOWLISTED_PATHS:
+ def _is_request_allowlisted(self, request: HttpRequest) -> bool:
+ for allowed_method, allowed_path in READ_ONLY_IMPERSONATION_ALLOWLISTED_PATHS:
+ if request.method != allowed_method:
+ continue
if isinstance(allowed_path, re.Pattern):
- if allowed_path.match(path):
+ if allowed_path.match(request.path):
return True
- elif path.startswith(allowed_path):
+ elif request.path.startswith(allowed_path):
return True
return False
diff --git a/posthog/schema.py b/posthog/schema.py
index bf539389fd8f..c74f1b32b846 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -198,6 +198,8 @@ from posthog.schema_enums import (
OrderDirection1 as OrderDirection1,
OrderDirection2 as OrderDirection2,
ParserMode as ParserMode,
+ PathsV2AnchorType as PathsV2AnchorType,
+ PathsV2ElementType as PathsV2ElementType,
PathType as PathType,
PersonsArgMaxVersion as PersonsArgMaxVersion,
PersonsJoinMode as PersonsJoinMode,
@@ -2202,6 +2204,58 @@ class PathsLink(BaseModel):
value: float
+class PathsV2Item(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ event: str = Field(..., description="Event of the step source this item belongs to.")
+ label: str | None = Field(
+ default=None,
+ description=(
+ "Label value from the source's naming property, after path cleaning. An"
+ " empty string when the property is missing on the event. Null for sources"
+ " without a naming property."
+ ),
+ )
+
+
+class PathsV2Prefix(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ count: float = Field(
+ ...,
+ description=("Unique actors whose anchored sequence begins with exactly these items."),
+ )
+ items: list[PathsV2Item] = Field(..., description="The chain's path items in order, starting at the anchor.")
+
+
+class PathsV2Row(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ count: float = Field(
+ ...,
+ description=("Unique actors with a journey whose item at this step is this path item."),
+ )
+ item: PathsV2Item
+
+
+class PathsV2StepSource(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ event: str = Field(..., description="Name of the event this source matches.")
+ namingProperty: str | None = Field(
+ default=None,
+ description=(
+ "Event property whose value labels the path item, e.g. `$pathname` for"
+ " pageviews. Team path cleaning rules are applied to the value. Without a"
+ " naming property, the event itself is the path item."
+ ),
+ )
+
+
class PersistedFolder(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -2295,7 +2349,7 @@ class QueryResponseAlternative7(BaseModel):
stdout: str | None = None
-class QueryResponseAlternative75(BaseModel):
+class QueryResponseAlternative76(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -5791,6 +5845,183 @@ class PathsFilter(BaseModel):
stepLimit: int | None = 5
+class PathsV2Anchor(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ item: PathsV2Item = Field(
+ ...,
+ description=("The path item the chart anchors on. Its event must be one of the step sources."),
+ )
+ type: PathsV2AnchorType = Field(
+ ...,
+ description=(
+ "`start` runs each actor's single sequence forward from the anchor item;"
+ " `end` runs it up to the anchor item. Either way the anchor is the grid's"
+ " single 100% node."
+ ),
+ )
+
+
+class PathsV2Edge(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ anyStepCount: float | None = Field(
+ default=None,
+ description=(
+ "Unique actors who transition from source to target at any step of any of"
+ ' their whole journeys, the position-free count behind "went source →'
+ " target at any step\". Equals the two-step item-strict funnel's converted"
+ " count. Only set in open mode on edges between two named items."
+ ),
+ )
+ count: float = Field(
+ ...,
+ description=("Unique actors with a journey that transitions from source to target between these steps."),
+ )
+ source: PathsV2Item | None = Field(
+ ...,
+ description='Source path item, or null for the source column\'s "other" row.',
+ )
+ stepIndex: int = Field(
+ ...,
+ description=("0-based step index of the source column; the target sits at `stepIndex + 1`."),
+ )
+ target: PathsV2Item | None = Field(
+ ...,
+ description='Target path item, or null for the target column\'s "other" row.',
+ )
+
+
+class PathsV2ElementSelector(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ anyStep: bool | None = Field(
+ default=None,
+ description=(
+ "Match the source → target transition at any step of any whole journey"
+ " instead of at one step pair: the position-free set behind an edge's"
+ " anyStepCount. Requires a named source and target and open mode. Edge"
+ " elements only."
+ ),
+ )
+ chain: list[PathsV2Item] | None = Field(
+ default=None,
+ description=(
+ "The chain's path items in order from the anchor. Returns the actors whose"
+ " anchored sequence begins with exactly these items, the set behind a hover"
+ " preview's per-chain counts. Chain elements only, anchored mode only."
+ " Bounded by the step maximum: a longer chain can never match a displayed"
+ " card."
+ ),
+ max_length=20,
+ )
+ elementType: PathsV2ElementType
+ item: PathsV2Item | None = Field(default=None, description="The node card's path item. Node elements only.")
+ source: PathsV2Item | None = Field(
+ default=None,
+ description=("The edge's source path item; omit for the source column's \"other\" row. Edge elements only."),
+ )
+ stepIndex: int | None = Field(
+ default=None,
+ description=(
+ "0-based step index (column) of the element; for an edge, its source"
+ " column. Required for node, other, dropOff, and positional edge elements."
+ ),
+ )
+ target: PathsV2Item | None = Field(
+ default=None,
+ description=("The edge's target path item; omit for the target column's \"other\" row. Edge elements only."),
+ )
+
+
+class PathsV2Filter(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ anchor: PathsV2Anchor | None = Field(
+ default=None,
+ description=(
+ "Anchor selecting anchored mode. When set, each actor contributes exactly"
+ " one sequence bounded by the conversion window, so every displayed segment"
+ " equals a plain funnel. Absent selects open mode, which splits an actor's"
+ " events into journeys on the inactivity gap instead."
+ ),
+ )
+ applyTeamPathCleaning: bool | None = Field(
+ default=True,
+ description=("Apply the team's path cleaning rules to naming property values before they become path items."),
+ )
+ collapseRepeats: bool | None = Field(
+ default=True,
+ description="Merge immediate repeats of the same path item within a journey.",
+ )
+ conversionWindowInterval: int | None = Field(
+ default=30,
+ description=(
+ "Anchored mode's single conversion window W, anchored at the anchor and"
+ " reused verbatim as the emitted funnel's window. Bounds per unit are"
+ " validated server-side against CONVERSION_WINDOW_INTERVAL_BOUNDS, the same"
+ " funnel conversion window bounds as the gap."
+ ),
+ )
+ conversionWindowIntervalUnit: FunnelConversionWindowTimeUnit | None = FunnelConversionWindowTimeUnit.MINUTE
+ excludedItems: list[PathsV2Item] | None = Field(
+ default=None,
+ description=(
+ "Path items dropped from the item universe: events deriving to one of these"
+ " items are ignored as if their event were not a step source, on both the"
+ ' paths side and the "view as funnel" side.'
+ ),
+ max_length=100,
+ )
+ gapInterval: int | None = Field(
+ default=30,
+ description=(
+ "Inactivity gap that splits an actor's events into journeys. Bounds per"
+ " unit are validated server-side against CONVERSION_WINDOW_INTERVAL_BOUNDS,"
+ " the funnel conversion window bounds."
+ ),
+ )
+ gapIntervalUnit: FunnelConversionWindowTimeUnit | None = FunnelConversionWindowTimeUnit.MINUTE
+ localPathCleaningFilters: list[PathCleaningFilter] | None = Field(
+ default=None,
+ description=("Path cleaning rules for this insight only, applied after the team's rules."),
+ )
+ maxRowsPerStep: conint(ge=1, le=10) | None = Field(
+ default=3,
+ description=('Number of path item rows per step; items beyond this go into the "other" row.'),
+ )
+ maxSteps: conint(ge=2, le=20) | None = Field(default=5, description="Number of journey steps (columns) shown.")
+ stepSources: list[PathsV2StepSource] | None = Field(
+ default=None,
+ description=(
+ "Step sources defining which events can become path items. Defaults to the"
+ " pageviews preset: `$pageview` named by `$pathname`."
+ ),
+ max_length=20,
+ min_length=1,
+ )
+
+
+class PathsV2Step(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ dropOffCount: float = Field(..., description="Unique actors whose journey ends at this step.")
+ otherCount: float = Field(
+ ...,
+ description=("Unique actors at this step whose path item is beyond the top rows."),
+ )
+ rows: list[PathsV2Row] = Field(
+ ...,
+ description=("Top path items at this step, ordered by unique-actor count descending."),
+ )
+ stepIndex: int = Field(..., description="0-based step index (column) in the journey grid.")
+
+
class PersonMetadataPropertyFilter(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -5921,7 +6152,7 @@ class QueryResponseAlternative28(BaseModel):
status: ExternalQueryStatus
-class QueryResponseAlternative82(BaseModel):
+class QueryResponseAlternative83(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -18144,6 +18375,24 @@ class PathsQueryResponse(BaseModel):
)
+class PathsV2Results(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ edges: list[PathsV2Edge]
+ prefixes: list[PathsV2Prefix] = Field(
+ ...,
+ description=(
+ "Concrete anchored chains with per-chain unique-actor counts, ordered by"
+ " descending count. Empty in open mode; in anchored mode it carries the"
+ " counts the hover funnel preview reads per chain. Only chains the grid"
+ " displays in full are carried: chains through the other bucket are"
+ " omitted, so the response never exposes labels the chart hides."
+ ),
+ )
+ steps: list[PathsV2Step]
+
+
class PersonsNode(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -20746,6 +20995,53 @@ class QueryResponseAlternative61(BaseModel):
class QueryResponseAlternative62(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None,
+ description=("The resolved previous/comparison period date range, when comparing against another period"),
+ )
+ resolved_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None, description="The date range used for the query"
+ )
+ results: PathsV2Results
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(
+ default=None,
+ description=("Connector-synced data warehouse sources referenced by this query, if any."),
+ )
+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose"
+ " latest sync failed, is paused, hit a billing limit, or is otherwise"
+ " stale. Results may not reflect current source data. Accumulated"
+ " across every HogQL execution that contributes to this response — so"
+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"
+ " the same warnings as raw HogQL queries. Also carries access control"
+ " warnings when a system-table query filters out objects the user can't"
+ " access."
+ ),
+ )
+
+
+class QueryResponseAlternative63(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20792,7 +21088,7 @@ class QueryResponseAlternative62(BaseModel):
)
-class QueryResponseAlternative64(BaseModel):
+class QueryResponseAlternative65(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20844,7 +21140,7 @@ class QueryResponseAlternative64(BaseModel):
)
-class QueryResponseAlternative66(BaseModel):
+class QueryResponseAlternative67(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20896,7 +21192,7 @@ class QueryResponseAlternative66(BaseModel):
)
-class QueryResponseAlternative67(BaseModel):
+class QueryResponseAlternative68(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20948,7 +21244,7 @@ class QueryResponseAlternative67(BaseModel):
)
-class QueryResponseAlternative68(BaseModel):
+class QueryResponseAlternative69(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -20996,7 +21292,7 @@ class QueryResponseAlternative68(BaseModel):
)
-class QueryResponseAlternative69(BaseModel):
+class QueryResponseAlternative70(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21043,7 +21339,7 @@ class QueryResponseAlternative69(BaseModel):
)
-class QueryResponseAlternative70(BaseModel):
+class QueryResponseAlternative71(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21090,7 +21386,7 @@ class QueryResponseAlternative70(BaseModel):
)
-class QueryResponseAlternative71(BaseModel):
+class QueryResponseAlternative72(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21141,7 +21437,7 @@ class QueryResponseAlternative71(BaseModel):
)
-class QueryResponseAlternative72(BaseModel):
+class QueryResponseAlternative73(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21192,7 +21488,7 @@ class QueryResponseAlternative72(BaseModel):
)
-class QueryResponseAlternative73(BaseModel):
+class QueryResponseAlternative74(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21243,7 +21539,7 @@ class QueryResponseAlternative73(BaseModel):
)
-class QueryResponseAlternative74(BaseModel):
+class QueryResponseAlternative75(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21294,7 +21590,7 @@ class QueryResponseAlternative74(BaseModel):
)
-class QueryResponseAlternative76(BaseModel):
+class QueryResponseAlternative77(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21344,7 +21640,7 @@ class QueryResponseAlternative76(BaseModel):
)
-class QueryResponseAlternative77(BaseModel):
+class QueryResponseAlternative78(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21394,7 +21690,7 @@ class QueryResponseAlternative77(BaseModel):
)
-class QueryResponseAlternative78(BaseModel):
+class QueryResponseAlternative79(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21441,7 +21737,7 @@ class QueryResponseAlternative78(BaseModel):
)
-class QueryResponseAlternative79(BaseModel):
+class QueryResponseAlternative80(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21492,7 +21788,7 @@ class QueryResponseAlternative79(BaseModel):
)
-class QueryResponseAlternative83(BaseModel):
+class QueryResponseAlternative84(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21539,7 +21835,7 @@ class QueryResponseAlternative83(BaseModel):
)
-class QueryResponseAlternative84(BaseModel):
+class QueryResponseAlternative85(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21586,7 +21882,7 @@ class QueryResponseAlternative84(BaseModel):
)
-class QueryResponseAlternative85(BaseModel):
+class QueryResponseAlternative86(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21643,7 +21939,7 @@ class QueryResponseAlternative85(BaseModel):
)
-class QueryResponseAlternative86(BaseModel):
+class QueryResponseAlternative87(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21690,7 +21986,7 @@ class QueryResponseAlternative86(BaseModel):
)
-class QueryResponseAlternative87(BaseModel):
+class QueryResponseAlternative88(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21742,7 +22038,7 @@ class QueryResponseAlternative87(BaseModel):
)
-class QueryResponseAlternative88(BaseModel):
+class QueryResponseAlternative89(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21789,7 +22085,7 @@ class QueryResponseAlternative88(BaseModel):
)
-class QueryResponseAlternative89(BaseModel):
+class QueryResponseAlternative90(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21836,7 +22132,7 @@ class QueryResponseAlternative89(BaseModel):
)
-class QueryResponseAlternative90(BaseModel):
+class QueryResponseAlternative91(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21883,7 +22179,7 @@ class QueryResponseAlternative90(BaseModel):
)
-class QueryResponseAlternative91(BaseModel):
+class QueryResponseAlternative92(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21930,7 +22226,7 @@ class QueryResponseAlternative91(BaseModel):
)
-class QueryResponseAlternative92(BaseModel):
+class QueryResponseAlternative93(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -21977,7 +22273,7 @@ class QueryResponseAlternative92(BaseModel):
)
-class QueryResponseAlternative93(BaseModel):
+class QueryResponseAlternative94(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22024,7 +22320,7 @@ class QueryResponseAlternative93(BaseModel):
)
-class QueryResponseAlternative94(BaseModel):
+class QueryResponseAlternative95(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22071,7 +22367,7 @@ class QueryResponseAlternative94(BaseModel):
)
-class QueryResponseAlternative95(BaseModel):
+class QueryResponseAlternative96(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22121,7 +22417,7 @@ class QueryResponseAlternative95(BaseModel):
)
-class QueryResponseAlternative96(BaseModel):
+class QueryResponseAlternative97(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22168,7 +22464,7 @@ class QueryResponseAlternative96(BaseModel):
)
-class QueryResponseAlternative97(BaseModel):
+class QueryResponseAlternative98(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22215,7 +22511,7 @@ class QueryResponseAlternative97(BaseModel):
)
-class QueryResponseAlternative98(BaseModel):
+class QueryResponseAlternative99(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22262,7 +22558,7 @@ class QueryResponseAlternative98(BaseModel):
)
-class QueryResponseAlternative99(BaseModel):
+class QueryResponseAlternative100(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22309,7 +22605,7 @@ class QueryResponseAlternative99(BaseModel):
)
-class QueryResponseAlternative100(BaseModel):
+class QueryResponseAlternative101(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22356,7 +22652,7 @@ class QueryResponseAlternative100(BaseModel):
)
-class QueryResponseAlternative101(BaseModel):
+class QueryResponseAlternative102(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22403,7 +22699,7 @@ class QueryResponseAlternative101(BaseModel):
)
-class QueryResponseAlternative102(BaseModel):
+class QueryResponseAlternative103(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22450,7 +22746,7 @@ class QueryResponseAlternative102(BaseModel):
)
-class QueryResponseAlternative103(BaseModel):
+class QueryResponseAlternative104(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22497,7 +22793,7 @@ class QueryResponseAlternative103(BaseModel):
)
-class QueryResponseAlternative104(BaseModel):
+class QueryResponseAlternative105(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -24056,6 +24352,64 @@ class CachedNewExperimentQueryResponse(BaseModel):
)
+class CachedPathsV2QueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ cache_key: str
+ cache_target_age: AwareDatetime | None = None
+ calculation_trigger: str | None = Field(
+ default=None,
+ description=("What triggered the calculation of the query, leave empty if user/immediate"),
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ is_cached: bool
+ last_refresh: AwareDatetime
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ next_allowed_client_refresh: AwareDatetime
+ query_metadata: dict[str, Any] | None = None
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None,
+ description=("The resolved previous/comparison period date range, when comparing against another period"),
+ )
+ resolved_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None, description="The date range used for the query"
+ )
+ results: PathsV2Results
+ timezone: str
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(
+ default=None,
+ description=("Connector-synced data warehouse sources referenced by this query, if any."),
+ )
+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose"
+ " latest sync failed, is paused, hit a billing limit, or is otherwise"
+ " stale. Results may not reflect current source data. Accumulated"
+ " across every HogQL execution that contributes to this response — so"
+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"
+ " the same warnings as raw HogQL queries. Also carries access control"
+ " warnings when a system-table query filters out objects the user can't"
+ " access."
+ ),
+ )
+
+
class CachedWebVitalsQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -24646,6 +25000,7 @@ class InsightFilter(
| FunnelsFilter
| RetentionFilter
| PathsFilter
+ | PathsV2Filter
| StickinessFilter
| LifecycleFilter
| CalendarHeatmapFilter
@@ -24657,6 +25012,7 @@ class InsightFilter(
| FunnelsFilter
| RetentionFilter
| PathsFilter
+ | PathsV2Filter
| StickinessFilter
| LifecycleFilter
| CalendarHeatmapFilter
@@ -25320,6 +25676,53 @@ class NonIntegratedConversionsTableQuery(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+class PathsV2QueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None,
+ description=("The resolved previous/comparison period date range, when comparing against another period"),
+ )
+ resolved_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None, description="The date range used for the query"
+ )
+ results: PathsV2Results
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(
+ default=None,
+ description=("Connector-synced data warehouse sources referenced by this query, if any."),
+ )
+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose"
+ " latest sync failed, is paused, hit a billing limit, or is otherwise"
+ " stale. Results may not reflect current source data. Accumulated"
+ " across every HogQL execution that contributes to this response — so"
+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"
+ " the same warnings as raw HogQL queries. Also carries access control"
+ " warnings when a system-table query filters out objects the user can't"
+ " access."
+ ),
+ )
+
+
class PropertyGroupFilter(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -26396,6 +26799,27 @@ class LogsQuery(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+class PathsV2Query(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ dataColorTheme: float | None = Field(default=None, description="Colors used in the insight's visualization")
+ dateRange: DateRange | None = Field(default=None, description="Date range for the query")
+ filterTestAccounts: bool | None = Field(
+ default=False,
+ description=("Exclude internal and test users by applying the respective filters"),
+ )
+ kind: Literal["PathsV2Query"] = "PathsV2Query"
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ pathsV2Filter: PathsV2Filter | None = Field(default=None, description="Properties specific to the paths v2 insight")
+ properties: list[AnyPropertyFilterDiscriminated] | PropertyGroupFilter | None = Field(
+ default=[], description="Property filters for all series"
+ )
+ response: PathsV2QueryResponse | None = None
+ tags: QueryLogTags | None = Field(default=None, description="Tags that will be added to the Query log comment")
+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+
+
class SessionsQuery(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -26627,7 +27051,21 @@ class LifecycleQuery(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
-class QueryResponseAlternative65(BaseModel):
+class PathsV2ActorsQuery(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ element: PathsV2ElementSelector
+ includeRecordings: bool | None = None
+ kind: Literal["PathsV2ActorsQuery"] = "PathsV2ActorsQuery"
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ response: ActorsQueryResponse | None = None
+ source: PathsV2Query
+ tags: QueryLogTags | None = None
+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+
+
+class QueryResponseAlternative66(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -27327,7 +27765,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative60
| QueryResponseAlternative61
| QueryResponseAlternative62
- | QueryResponseAlternative64
+ | QueryResponseAlternative63
| QueryResponseAlternative65
| QueryResponseAlternative66
| QueryResponseAlternative67
@@ -27343,7 +27781,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative77
| QueryResponseAlternative78
| QueryResponseAlternative79
- | QueryResponseAlternative82
+ | QueryResponseAlternative80
| QueryResponseAlternative83
| QueryResponseAlternative84
| QueryResponseAlternative85
@@ -27366,6 +27804,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative102
| QueryResponseAlternative103
| QueryResponseAlternative104
+ | QueryResponseAlternative105
]
):
root: (
@@ -27431,7 +27870,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative60
| QueryResponseAlternative61
| QueryResponseAlternative62
- | QueryResponseAlternative64
+ | QueryResponseAlternative63
| QueryResponseAlternative65
| QueryResponseAlternative66
| QueryResponseAlternative67
@@ -27447,7 +27886,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative77
| QueryResponseAlternative78
| QueryResponseAlternative79
- | QueryResponseAlternative82
+ | QueryResponseAlternative80
| QueryResponseAlternative83
| QueryResponseAlternative84
| QueryResponseAlternative85
@@ -27470,6 +27909,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative102
| QueryResponseAlternative103
| QueryResponseAlternative104
+ | QueryResponseAlternative105
)
@@ -27683,9 +28123,11 @@ class PathsQuery(BaseModel):
class ProductAnalyticsInsightQueryNode(
- RootModel[TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery]
+ RootModel[
+ TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery
+ ]
):
- root: TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery
+ root: TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery
class VisualizationBlock(BaseModel):
@@ -27828,6 +28270,7 @@ class InsightVizNode(BaseModel):
| FunnelsQuery
| RetentionQuery
| PathsQuery
+ | PathsV2Query
| StickinessQuery
| LifecycleQuery
| WebStatsTableQuery
@@ -27900,6 +28343,7 @@ class WebVitalsQuery(BaseModel):
| FunnelsQuery
| RetentionQuery
| PathsQuery
+ | PathsV2Query
| StickinessQuery
| LifecycleQuery
| WebStatsTableQuery
@@ -27969,6 +28413,7 @@ class InsightActorsQuery(BaseModel):
| FunnelsQuery
| RetentionQuery
| PathsQuery
+ | PathsV2Query
| StickinessQuery
| LifecycleQuery
| WebStatsTableQuery
@@ -27991,6 +28436,7 @@ class InsightActorsQueryOptions(BaseModel):
| FunnelCorrelationActorsQuery
| StickinessActorsQuery
| ExperimentActorsQuery
+ | PathsV2ActorsQuery
)
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
@@ -28108,6 +28554,7 @@ class ActorsQuery(BaseModel):
| FunnelCorrelationActorsQuery
| ExperimentActorsQuery
| StickinessActorsQuery
+ | PathsV2ActorsQuery
| HogQLQuery
| None
) = None
@@ -28633,6 +29080,7 @@ class MaxInsightContext(BaseModel):
| FunnelsQuery
| RetentionQuery
| PathsQuery
+ | PathsV2Query
| StickinessQuery
| LifecycleQuery
| FunnelCorrelationQuery
@@ -28767,6 +29215,7 @@ class QueryRequest(BaseModel):
| FunnelsQuery
| RetentionQuery
| PathsQuery
+ | PathsV2Query
| StickinessQuery
| LifecycleQuery
| FunnelCorrelationQuery
@@ -28893,6 +29342,7 @@ class QuerySchemaRoot(
| FunnelsQuery
| RetentionQuery
| PathsQuery
+ | PathsV2Query
| StickinessQuery
| LifecycleQuery
| FunnelCorrelationQuery
@@ -28989,6 +29439,7 @@ class QuerySchemaRoot(
| FunnelsQuery
| RetentionQuery
| PathsQuery
+ | PathsV2Query
| StickinessQuery
| LifecycleQuery
| FunnelCorrelationQuery
@@ -29090,6 +29541,7 @@ class QueryUpgradeRequest(BaseModel):
| FunnelsQuery
| RetentionQuery
| PathsQuery
+ | PathsV2Query
| StickinessQuery
| LifecycleQuery
| FunnelCorrelationQuery
@@ -29191,6 +29643,7 @@ class QueryUpgradeResponse(BaseModel):
| FunnelsQuery
| RetentionQuery
| PathsQuery
+ | PathsV2Query
| StickinessQuery
| LifecycleQuery
| FunnelCorrelationQuery
@@ -29474,6 +29927,7 @@ class VisualizationArtifactContent(BaseModel):
| FunnelsQuery
| RetentionQuery
| PathsQuery
+ | PathsV2Query
| StickinessQuery
| LifecycleQuery
| FunnelCorrelationQuery
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index f57ab862d47f..09b7ddf430a4 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -2810,6 +2810,7 @@ class InsightFilterProperty(StrEnum):
FUNNELS_FILTER = "funnelsFilter"
RETENTION_FILTER = "retentionFilter"
PATHS_FILTER = "pathsFilter"
+ PATHS_V2_FILTER = "pathsV2Filter"
STICKINESS_FILTER = "stickinessFilter"
CALENDAR_HEATMAP_FILTER = "calendarHeatmapFilter"
LIFECYCLE_FILTER = "lifecycleFilter"
@@ -2821,6 +2822,7 @@ class InsightNodeKind(StrEnum):
FUNNELS_QUERY = "FunnelsQuery"
RETENTION_QUERY = "RetentionQuery"
PATHS_QUERY = "PathsQuery"
+ PATHS_V2_QUERY = "PathsV2Query"
STICKINESS_QUERY = "StickinessQuery"
LIFECYCLE_QUERY = "LifecycleQuery"
WEB_STATS_TABLE_QUERY = "WebStatsTableQuery"
@@ -3190,6 +3192,7 @@ class NodeKind(StrEnum):
GROUPS_QUERY = "GroupsQuery"
FUNNELS_ACTORS_QUERY = "FunnelsActorsQuery"
FUNNEL_CORRELATION_ACTORS_QUERY = "FunnelCorrelationActorsQuery"
+ PATHS_V2_ACTORS_QUERY = "PathsV2ActorsQuery"
SESSIONS_TIMELINE_QUERY = "SessionsTimelineQuery"
RECORDINGS_QUERY = "RecordingsQuery"
SESSION_ATTRIBUTION_EXPLORER_QUERY = "SessionAttributionExplorerQuery"
@@ -3216,6 +3219,7 @@ class NodeKind(StrEnum):
FUNNELS_QUERY = "FunnelsQuery"
RETENTION_QUERY = "RetentionQuery"
PATHS_QUERY = "PathsQuery"
+ PATHS_V2_QUERY = "PathsV2Query"
STICKINESS_QUERY = "StickinessQuery"
STICKINESS_ACTORS_QUERY = "StickinessActorsQuery"
LIFECYCLE_QUERY = "LifecycleQuery"
@@ -3291,6 +3295,19 @@ class PathType(StrEnum):
HOGQL = "hogql"
+class PathsV2AnchorType(StrEnum):
+ START = "start"
+ END = "end"
+
+
+class PathsV2ElementType(StrEnum):
+ NODE = "node"
+ EDGE = "edge"
+ DROP_OFF = "dropOff"
+ OTHER = "other"
+ CHAIN = "chain"
+
+
class SliceContent(StrEnum):
LABELS = "labels"
VALUES = "values"
diff --git a/posthog/schema_helpers.py b/posthog/schema_helpers.py
index e501ef3c7009..772f4ce06cfd 100644
--- a/posthog/schema_helpers.py
+++ b/posthog/schema_helpers.py
@@ -8,6 +8,7 @@ from posthog.schema import (
FunnelsQuery,
LifecycleQuery,
PathsQuery,
+ PathsV2Query,
RetentionQuery,
StickinessQuery,
TrendsQuery,
@@ -47,7 +48,7 @@ def to_dict(query: BaseModel) -> dict:
if isinstance(
query,
- (TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery),
+ (TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery),
):
insightFilterKey = filter_key_for_query(query)
@@ -153,6 +154,8 @@ def filter_key_for_query(node: InsightQueryNode) -> str:
return "retentionFilter"
elif isinstance(node, PathsQuery):
return "pathsFilter"
+ elif isinstance(node, PathsV2Query):
+ return "pathsV2Filter"
elif isinstance(node, StickinessQuery):
return "stickinessFilter"
elif isinstance(node, LifecycleQuery):
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index 785cee01aa8f..c8c19b079a9a 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -859,6 +859,9 @@ class TestImpersonationReadOnlyMiddleware(APIBaseTest):
[
("query", "query/", {"query": {"kind": "EventsQuery", "select": ["event"]}}),
("query_kind", "query/HogQLQuery/", {"query": {"kind": "HogQLQuery", "query": "select 1"}}),
+ # digit-containing kind — the allowlist regex used to miss these
+ ("query_kind_digit", "query/PathsV2Query/", {"query": {"kind": "PathsV2Query"}}),
+ ("query_upgrade", "query/upgrade/", {"query": {"kind": "EventsQuery", "select": ["event"]}}),
("endpoint_materialization_preview", "endpoints/some_endpoint/materialization_preview/", {}),
(
"external_data_schemas_incremental_fields",
@@ -885,6 +888,18 @@ class TestImpersonationReadOnlyMiddleware(APIBaseTest):
assert response.status_code != 403 or response.json().get("code") != "impersonation_read_only"
+ def test_read_only_impersonation_blocks_query_cancellation(self):
+ self.login_as_other_user_read_only()
+
+ assert self.client.get("/api/users/@me").json()["email"] == "[email protected]"
+
+ # DELETE /query/<id>/ cancels a query. The ID below matches the allowlisted query
+ # path pattern, so only the method check keeps this blocked.
+ response = self.client.delete(f"/api/projects/{self.team.id}/query/SomeQueryId123/")
+
+ assert response.status_code == 403
+ assert response.json()["code"] == "impersonation_read_only"
+
def test_regular_impersonation_allows_write(self):
"""Verify regular (non-read-only) impersonation can still write."""
dashboard = Dashboard.objects.create(team=self.team, name="Test Dashboard")
diff --git a/posthog/types.py b/posthog/types.py
index c40ffb52c7b4..96e6abcd0f4d 100644
--- a/posthog/types.py
+++ b/posthog/types.py
@@ -32,6 +32,8 @@ from posthog.schema import (
LogPropertyFilter,
MetricPropertyFilter,
PathsQuery,
+ PathsV2ActorsQuery,
+ PathsV2Query,
PersonMetadataPropertyFilter,
PersonPropertyFilter,
RecordingPropertyFilter,
@@ -53,10 +55,17 @@ from posthog.models.filters.stickiness_filter import StickinessFilter
type FilterType = Union[Filter, PathFilter, RetentionFilter, StickinessFilter]
"""Legacy insight filters."""
-type InsightQueryNode = Union[TrendsQuery, FunnelsQuery, RetentionQuery, PathsQuery, StickinessQuery, LifecycleQuery]
+type InsightQueryNode = Union[
+ TrendsQuery, FunnelsQuery, RetentionQuery, PathsQuery, PathsV2Query, StickinessQuery, LifecycleQuery
+]
type InsightActorsQueryNode = Union[
- InsightActorsQuery, FunnelsActorsQuery, FunnelCorrelationActorsQuery, StickinessActorsQuery, ExperimentActorsQuery
+ InsightActorsQuery,
+ FunnelsActorsQuery,
+ FunnelCorrelationActorsQuery,
+ StickinessActorsQuery,
+ ExperimentActorsQuery,
+ PathsV2ActorsQuery,
]
type AnyPropertyFilter = Union[
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 6c7ef00538ed..83ef56dcf30c 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -3346,6 +3346,173 @@ export interface PathsQueryApi {
version?: number | null
}
+export interface PathsV2ItemApi {
+ /** Event of the step source this item belongs to. */
+ event: string
+ /** Label value from the source's naming property, after path cleaning. An empty string when the property is missing on the event. Null for sources without a naming property. */
+ label?: string | null
+}
+
+export type PathsV2AnchorTypeApi = (typeof PathsV2AnchorTypeApi)[keyof typeof PathsV2AnchorTypeApi]
+
+export const PathsV2AnchorTypeApi = {
+ Start: 'start',
+ End: 'end',
+} as const
+
+export interface PathsV2AnchorApi {
+ /** The path item the chart anchors on. Its event must be one of the step sources. */
+ item: PathsV2ItemApi
+ /** `start` runs each actor's single sequence forward from the anchor item; `end` runs it up to the anchor item. Either way the anchor is the grid's single 100% node. */
+ type: PathsV2AnchorTypeApi
+}
+
+export interface PathsV2StepSourceApi {
+ /** Name of the event this source matches. */
+ event: string
+ /** Event property whose value labels the path item, e.g. `$pathname` for pageviews. Team path cleaning rules are applied to the value. Without a naming property, the event itself is the path item. */
+ namingProperty?: string | null
+}
+
+export interface PathsV2FilterApi {
+ /** Anchor selecting anchored mode. When set, each actor contributes exactly one sequence bounded by the conversion window, so every displayed segment equals a plain funnel. Absent selects open mode, which splits an actor's events into journeys on the inactivity gap instead. */
+ anchor?: PathsV2AnchorApi | null
+ /** Apply the team's path cleaning rules to naming property values before they become path items. */
+ applyTeamPathCleaning?: boolean | null
+ /** Merge immediate repeats of the same path item within a journey. */
+ collapseRepeats?: boolean | null
+ /** Anchored mode's single conversion window W, anchored at the anchor and reused verbatim as the emitted funnel's window. Bounds per unit are validated server-side against CONVERSION_WINDOW_INTERVAL_BOUNDS, the same funnel conversion window bounds as the gap. */
+ conversionWindowInterval?: number | null
+ conversionWindowIntervalUnit?: FunnelConversionWindowTimeUnitApi | null
+ /** Path items dropped from the item universe: events deriving to one of these items are ignored as if their event were not a step source, on both the paths side and the "view as funnel" side. */
+ excludedItems?: PathsV2ItemApi[] | null
+ /** Inactivity gap that splits an actor's events into journeys. Bounds per unit are validated server-side against CONVERSION_WINDOW_INTERVAL_BOUNDS, the funnel conversion window bounds. */
+ gapInterval?: number | null
+ gapIntervalUnit?: FunnelConversionWindowTimeUnitApi | null
+ /** Path cleaning rules for this insight only, applied after the team's rules. */
+ localPathCleaningFilters?: PathCleaningFilterApi[] | null
+ /** Number of path item rows per step; items beyond this go into the "other" row. */
+ maxRowsPerStep?: number | null
+ /** Number of journey steps (columns) shown. */
+ maxSteps?: number | null
+ /** Step sources defining which events can become path items. Defaults to the pageviews preset: `$pageview` named by `$pathname`. */
+ stepSources?: PathsV2StepSourceApi[] | null
+}
+
+export interface PathsV2EdgeApi {
+ /** Unique actors who transition from source to target at any step of any of their whole journeys, the position-free count behind "went source → target at any step". Equals the two-step item-strict funnel's converted count. Only set in open mode on edges between two named items. */
+ anyStepCount?: number | null
+ /** Unique actors with a journey that transitions from source to target between these steps. */
+ count: number
+ /** Source path item, or null for the source column's "other" row. */
+ source: PathsV2ItemApi | null
+ /** 0-based step index of the source column; the target sits at `stepIndex + 1`. */
+ stepIndex: number
+ /** Target path item, or null for the target column's "other" row. */
+ target: PathsV2ItemApi | null
+}
+
+export interface PathsV2PrefixApi {
+ /** Unique actors whose anchored sequence begins with exactly these items. */
+ count: number
+ /** The chain's path items in order, starting at the anchor. */
+ items: PathsV2ItemApi[]
+}
+
+export interface PathsV2RowApi {
+ /** Unique actors with a journey whose item at this step is this path item. */
+ count: number
+ item: PathsV2ItemApi
+}
+
+export interface PathsV2StepApi {
+ /** Unique actors whose journey ends at this step. */
+ dropOffCount: number
+ /** Unique actors at this step whose path item is beyond the top rows. */
+ otherCount: number
+ /** Top path items at this step, ordered by unique-actor count descending. */
+ rows: PathsV2RowApi[]
+ /** 0-based step index (column) in the journey grid. */
+ stepIndex: number
+}
+
+export interface PathsV2ResultsApi {
+ edges: PathsV2EdgeApi[]
+ /** Concrete anchored chains with per-chain unique-actor counts, ordered by descending count. Empty in open mode; in anchored mode it carries the counts the hover funnel preview reads per chain. Only chains the grid displays in full are carried: chains through the other bucket are omitted, so the response never exposes labels the chart hides. */
+ prefixes: PathsV2PrefixApi[]
+ steps: PathsV2StepApi[]
+}
+
+export interface PathsV2QueryResponseApi {
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null
+ /** Generated HogQL query. */
+ hogql?: string | null
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiersApi | null
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatusApi | null
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponseApi | null
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponseApi | null
+ results: PathsV2ResultsApi
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTimingApi[] | null
+ /** Connector-synced data warehouse sources referenced by this query, if any. */
+ used_data_warehouse_sources?: DataWarehouseSourceUsageApi[] | null
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
+ warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null
+}
+
+export interface PathsV2QueryApi {
+ /** Colors used in the insight's visualization */
+ dataColorTheme?: number | null
+ /** Date range for the query */
+ dateRange?: DateRangeApi | null
+ /** Exclude internal and test users by applying the respective filters */
+ filterTestAccounts?: boolean | null
+ kind?: 'PathsV2Query'
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiersApi | null
+ /** Properties specific to the paths v2 insight */
+ pathsV2Filter?: PathsV2FilterApi | null
+ /** Property filters for all series */
+ properties?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ )[]
+ | PropertyGroupFilterApi
+ | null
+ response?: PathsV2QueryResponseApi | null
+ /** Tags that will be added to the Query log comment */
+ tags?: QueryLogTagsApi | null
+ /** version of the node, used for schema migrations */
+ version?: number | null
+}
+
export type StickinessQueryResponseApiResultsItem = { [key: string]: unknown }
export interface StickinessQueryResponseApi {
@@ -3940,6 +4107,7 @@ export interface InsightVizNodeApi {
| FunnelsQueryApi
| RetentionQueryApi
| PathsQueryApi
+ | PathsV2QueryApi
| StickinessQueryApi
| LifecycleQueryApi
| WebStatsTableQueryApi
@@ -5085,6 +5253,7 @@ export interface InsightActorsQueryApi {
| FunnelsQueryApi
| RetentionQueryApi
| PathsQueryApi
+ | PathsV2QueryApi
| StickinessQueryApi
| LifecycleQueryApi
| WebStatsTableQueryApi
@@ -5830,6 +5999,45 @@ export interface StickinessActorsQueryApi {
version?: number | null
}
+export type PathsV2ElementTypeApi = (typeof PathsV2ElementTypeApi)[keyof typeof PathsV2ElementTypeApi]
+
+export const PathsV2ElementTypeApi = {
+ Node: 'node',
+ Edge: 'edge',
+ DropOff: 'dropOff',
+ Other: 'other',
+ Chain: 'chain',
+} as const
+
+export interface PathsV2ElementSelectorApi {
+ /** Match the source → target transition at any step of any whole journey instead of at one step pair: the position-free set behind an edge's anyStepCount. Requires a named source and target and open mode. Edge elements only. */
+ anyStep?: boolean | null
+ /** The chain's path items in order from the anchor. Returns the actors whose anchored sequence begins with exactly these items, the set behind a hover preview's per-chain counts. Chain elements only, anchored mode only. Bounded by the step maximum: a longer chain can never match a displayed card. */
+ chain?: PathsV2ItemApi[] | null
+ elementType: PathsV2ElementTypeApi
+ /** The node card's path item. Node elements only. */
+ item?: PathsV2ItemApi | null
+ /** The edge's source path item; omit for the source column's "other" row. Edge elements only. */
+ source?: PathsV2ItemApi | null
+ /** 0-based step index (column) of the element; for an edge, its source column. Required for node, other, dropOff, and positional edge elements. */
+ stepIndex?: number | null
+ /** The edge's target path item; omit for the target column's "other" row. Edge elements only. */
+ target?: PathsV2ItemApi | null
+}
+
+export interface PathsV2ActorsQueryApi {
+ element: PathsV2ElementSelectorApi
+ includeRecordings?: boolean | null
+ kind?: 'PathsV2ActorsQuery'
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiersApi | null
+ response?: ActorsQueryResponseApi | null
+ source: PathsV2QueryApi
+ tags?: QueryLogTagsApi | null
+ /** version of the node, used for schema migrations */
+ version?: number | null
+}
+
export interface HogQLFiltersApi {
dateRange?: DateRangeApi | null
filterTestAccounts?: boolean | null
@@ -5978,6 +6186,7 @@ export interface ActorsQueryApi {
| FunnelCorrelationActorsQueryApi
| ExperimentActorsQueryApi
| StickinessActorsQueryApi
+ | PathsV2ActorsQueryApi
| HogQLQueryApi
| null
tags?: QueryLogTagsApi | null
@@ -6259,6 +6468,7 @@ export interface WebVitalsQueryApi {
| FunnelsQueryApi
| RetentionQueryApi
| PathsQueryApi
+ | PathsV2QueryApi
| StickinessQueryApi
| LifecycleQueryApi
| WebStatsTableQueryApi
diff --git a/products/endpoints/frontend/InsightPickerEndpointModal.tsx b/products/endpoints/frontend/InsightPickerEndpointModal.tsx
index bb695db7270e..078aa97987d3 100644
--- a/products/endpoints/frontend/InsightPickerEndpointModal.tsx
+++ b/products/endpoints/frontend/InsightPickerEndpointModal.tsx
@@ -23,12 +23,18 @@ import { insightPickerEndpointModalLogic } from './insightPickerEndpointModalLog
const UNSUPPORTED_INSIGHT_TYPES = new Set([
InsightType.FUNNELS,
InsightType.PATHS,
+ InsightType.JOURNEYS,
InsightType.STICKINESS,
InsightType.JSON,
InsightType.HOG,
])
-const UNSUPPORTED_QUERY_KINDS = new Set([NodeKind.FunnelsQuery, NodeKind.PathsQuery, NodeKind.StickinessQuery])
+const UNSUPPORTED_QUERY_KINDS = new Set([
+ NodeKind.FunnelsQuery,
+ NodeKind.PathsQuery,
+ NodeKind.PathsV2Query,
+ NodeKind.StickinessQuery,
+])
function isInsightSupported(insight: QueryBasedInsightModel): boolean {
const query = insight.query
diff --git a/products/notebooks/backend/query_validation.py b/products/notebooks/backend/query_validation.py
index fe21b217bfac..4f14206a7155 100644
--- a/products/notebooks/backend/query_validation.py
+++ b/products/notebooks/backend/query_validation.py
@@ -2,6 +2,8 @@ from typing import Any
import structlog
+from posthog.schema_enums import InsightNodeKind
+
logger = structlog.get_logger(__name__)
@@ -20,20 +22,12 @@ _VALID_TOP_LEVEL_QUERY_KINDS = frozenset(
}
)
-# Source kinds that an InsightVizNode is actually allowed to wrap (matches the Pydantic
-# schema at posthog/schema.py — InsightVizNode.source).
-_VALID_INSIGHT_VIZ_SOURCE_KINDS = frozenset(
- {
- "TrendsQuery",
- "FunnelsQuery",
- "RetentionQuery",
- "PathsQuery",
- "StickinessQuery",
- "LifecycleQuery",
- "WebStatsTableQuery",
- "WebOverviewQuery",
- }
-)
+
+# InsightNodeKind is generated from the same schema union as InsightVizNode.source, so new
+# insight kinds are accepted here the moment they join the union instead of drifting behind a
+# hardcoded copy.
+_VALID_INSIGHT_VIZ_SOURCE_KINDS = frozenset(kind.value for kind in InsightNodeKind)
+_INSIGHT_VIZ_SOURCE_KINDS_SENTENCE = ", ".join(sorted(_VALID_INSIGHT_VIZ_SOURCE_KINDS))
class InvalidNotebookQueryError(ValueError):
@@ -108,8 +102,7 @@ def _normalize_insight_viz_node(query: dict[str, Any]) -> dict[str, Any]:
if not isinstance(source, dict):
raise InvalidNotebookQueryError(
"ph-query node has an InsightVizNode without a `source`. "
- "InsightVizNode.source must be a TrendsQuery, FunnelsQuery, RetentionQuery, "
- "PathsQuery, StickinessQuery, LifecycleQuery, WebStatsTableQuery, or WebOverviewQuery."
+ f"InsightVizNode.source must be one of: {_INSIGHT_VIZ_SOURCE_KINDS_SENTENCE}."
)
source_kind = source.get("kind")
@@ -136,8 +129,7 @@ def _normalize_insight_viz_node(query: dict[str, Any]) -> dict[str, Any]:
if source_kind not in _VALID_INSIGHT_VIZ_SOURCE_KINDS:
raise InvalidNotebookQueryError(
f"ph-query node has an InsightVizNode wrapping `{source_kind}`, which is not "
- "a valid insight source. InsightVizNode.source must be one of: "
- f"{', '.join(sorted(_VALID_INSIGHT_VIZ_SOURCE_KINDS))}."
+ f"a valid insight source. InsightVizNode.source must be one of: {_INSIGHT_VIZ_SOURCE_KINDS_SENTENCE}."
)
return query
diff --git a/products/notebooks/backend/test/test_query_validation.py b/products/notebooks/backend/test/test_query_validation.py
index 8f17f7e4435b..20fd61baf5e3 100644
--- a/products/notebooks/backend/test/test_query_validation.py
+++ b/products/notebooks/backend/test/test_query_validation.py
@@ -50,9 +50,17 @@ class TestNormalizeNotebookQueryNodes:
doc = _wrap(VALID_DATA_VIZ)
assert _extract_query(normalize_notebook_query_nodes(doc)) == VALID_DATA_VIZ
- def test_passes_through_valid_insight_viz_node(self) -> None:
- doc = _wrap(VALID_INSIGHT_VIZ)
- assert _extract_query(normalize_notebook_query_nodes(doc)) == VALID_INSIGHT_VIZ
+ @parameterized.expand(
+ [
+ ("trends", VALID_INSIGHT_VIZ),
+ # The accepted kinds are derived from the schema, so a source kind newer than this
+ # file (PathsV2Query) must pass without an allowlist edit.
+ ("paths_v2", {"kind": "InsightVizNode", "source": {"kind": "PathsV2Query", "pathsV2Filter": {}}}),
+ ]
+ )
+ def test_passes_through_valid_insight_viz_node(self, _name: str, query: dict[str, Any]) -> None:
+ doc = _wrap(query)
+ assert _extract_query(normalize_notebook_query_nodes(doc)) == query
def test_unwraps_insight_viz_node_wrapping_data_visualization_node(self) -> None:
# The exact bug observed in notebook wUll: AI agent wrapped a SQL chart in an
diff --git a/products/product_analytics/backend/api/insight.py b/products/product_analytics/backend/api/insight.py
index c3486d0ce5d0..d5f9bf380e6e 100644
--- a/products/product_analytics/backend/api/insight.py
+++ b/products/product_analytics/backend/api/insight.py
@@ -1644,7 +1644,7 @@ Background calculation can be tracked using the `query_status` response field.""
),
OpenApiParameter(
name="insight",
- enum=["TRENDS", "FUNNELS", "RETENTION", "PATHS", "STICKINESS", "LIFECYCLE", "JSON", "SQL"],
+ enum=["TRENDS", "FUNNELS", "RETENTION", "PATHS", "JOURNEYS", "STICKINESS", "LIFECYCLE", "JSON", "SQL"],
description="Restrict to a single insight type. `JSON` matches non-wrapper query insights; `SQL` matches HogQL queries.",
),
OpenApiParameter(
@@ -2079,6 +2079,7 @@ class InsightViewSet(
"FUNNELS": schema.NodeKind.FUNNELS_QUERY,
"RETENTION": schema.NodeKind.RETENTION_QUERY,
"PATHS": schema.NodeKind.PATHS_QUERY,
+ "JOURNEYS": schema.NodeKind.PATHS_V2_QUERY,
"STICKINESS": schema.NodeKind.STICKINESS_QUERY,
"LIFECYCLE": schema.NodeKind.LIFECYCLE_QUERY,
}
diff --git a/products/product_analytics/backend/api/paths_v2.py b/products/product_analytics/backend/api/paths_v2.py
new file mode 100644
index 000000000000..6e21a3e961d2
--- /dev/null
+++ b/products/product_analytics/backend/api/paths_v2.py
@@ -0,0 +1,144 @@
+from drf_spectacular.utils import OpenApiResponse
+from pydantic import ValidationError as PydanticValidationError
+from rest_framework import serializers, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import ValidationError
+from rest_framework.response import Response
+
+from posthog.schema import PathsV2AnchorType, PathsV2Item, PathsV2Query
+
+from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.routing import TeamAndOrgViewSetMixin
+
+from products.product_analytics.backend.hogql_queries.paths_v2.funnel_converter import (
+ anchored_segment_to_funnels_query,
+ edge_to_funnels_query,
+)
+from products.product_analytics.backend.hogql_queries.paths_v2.path_item import (
+ item_label,
+ resolve_step_sources,
+ step_source_for_event,
+)
+
+# Matches the PathsV2Filter maxSteps upper bound: a displayed segment can never be longer.
+_MAX_SEGMENT_ITEMS = 20
+
+
+class PathsV2SegmentItemSerializer(serializers.Serializer):
+ event = serializers.CharField(
+ help_text="Event of the step source this path item belongs to.",
+ )
+ label = serializers.CharField( # type: ignore[assignment]
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ default=None,
+ help_text=(
+ "Label value from the source's naming property, after path cleaning. "
+ "Null or omitted for sources without a naming property; an empty string means "
+ "the property was missing on the event."
+ ),
+ )
+
+
+class PathsV2SegmentToFunnelRequestSerializer(serializers.Serializer):
+ query = serializers.JSONField(
+ help_text=(
+ "The PathsV2Query the segment is displayed under (JSON object with kind `PathsV2Query`). "
+ "Step sources, path cleaning, excluded items, date range, and the gap or conversion "
+ "window are read from it, so the emitted funnel counts exactly what the chart shows."
+ ),
+ )
+ # min_length/max_length are ListSerializer kwargs many=True forwards at runtime
+ # (LIST_SERIALIZER_KWARGS); the DRF stubs don't know them.
+ items = PathsV2SegmentItemSerializer( # type: ignore[call-arg]
+ many=True,
+ min_length=2,
+ max_length=_MAX_SEGMENT_ITEMS,
+ help_text=(
+ "The segment's path items in displayed order. In open mode exactly two items - a "
+ "single edge, source then target. In anchored mode the concrete chain as shown, "
+ "starting at the anchor."
+ ),
+ )
+
+
+class PathsV2SegmentToFunnelResponseSerializer(serializers.Serializer):
+ funnels_query = serializers.JSONField(
+ help_text=(
+ "The FunnelsQuery (JSON object with kind `FunnelsQuery`) that reproduces the "
+ "segment's displayed unique-actor count exactly. Wrap it in an InsightVizNode to "
+ "open it as a funnel insight."
+ ),
+ )
+
+
+class PathsV2ViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ scope_object = "insight"
+ scope_object_read_actions = ["segment_to_funnel"]
+ scope_object_write_actions: list[str] = []
+
+ @validated_request(
+ request_serializer=PathsV2SegmentToFunnelRequestSerializer,
+ responses={
+ 200: OpenApiResponse(
+ response=PathsV2SegmentToFunnelResponseSerializer,
+ description="The funnel that reproduces the segment's displayed count exactly.",
+ ),
+ 400: OpenApiResponse(
+ description=(
+ "The query is not a valid PathsV2Query, or the segment has no exact funnel "
+ "equivalent (an other-row endpoint, a multi-hop open-mode segment, or an "
+ "anchored segment that does not start at the anchor)."
+ ),
+ ),
+ },
+ summary="Convert a journey segment to a funnel",
+ description=(
+ "Converts a displayed journeys segment into the funnel query that reproduces its "
+ "unique-actor count exactly. In open mode only a single edge converts (a two-step "
+ "funnel with the inactivity gap as conversion window); in anchored mode any "
+ "anchor-rooted chain converts (window W). The funnel is returned as JSON and is not "
+ "executed or persisted here."
+ ),
+ )
+ @action(methods=["POST"], detail=False, required_scopes=["insight:read"])
+ def segment_to_funnel(self, request: ValidatedRequest, **kwargs) -> Response:
+ try:
+ query = PathsV2Query.model_validate(request.validated_data["query"])
+ except PydanticValidationError as error:
+ raise ValidationError({"query": f"Not a valid PathsV2Query: {error}"})
+
+ items = [PathsV2Item(event=item["event"], label=item["label"]) for item in request.validated_data["items"]]
+ anchor = query.pathsV2Filter.anchor if query.pathsV2Filter else None
+
+ try:
+ if anchor is None:
+ if len(items) != 2:
+ raise ValidationError(
+ {"items": "In open mode only a single edge has an exact funnel; send exactly two items."}
+ )
+ funnels_query = edge_to_funnels_query(query, self.team, items[0], items[1])
+ else:
+ if not self._starts_at_anchor(query, items[0], anchor.item):
+ raise ValidationError(
+ {"items": "An anchored segment has an exact funnel only when it starts at the anchor."}
+ )
+ # End-anchored chains are displayed anchor-first, i.e. backward in time;
+ # the funnel wants forward-time order.
+ ordered = list(reversed(items)) if anchor.type == PathsV2AnchorType.END else items
+ funnels_query = anchored_segment_to_funnels_query(query, self.team, list(ordered))
+ except ValueError as error:
+ raise ValidationError({"items": str(error)})
+
+ return Response({"funnels_query": funnels_query.model_dump(exclude_none=True)})
+
+ @staticmethod
+ def _starts_at_anchor(query: PathsV2Query, first: PathsV2Item, anchor_item: PathsV2Item) -> bool:
+ """Compare `(event, label)` identities the way the converter does — `item_label` normalizes
+ a missing label to "" for sources without a naming property — so the guard cannot diverge
+ from the converter over a null-vs-empty label."""
+ if first.event != anchor_item.event:
+ return False
+ source = step_source_for_event(resolve_step_sources(query), anchor_item.event)
+ return item_label(first, source) == item_label(anchor_item, source)
diff --git a/products/product_analytics/backend/api/test/test_insight.py b/products/product_analytics/backend/api/test/test_insight.py
index 72f93cb64ca5..04de6cbeae5a 100644
--- a/products/product_analytics/backend/api/test/test_insight.py
+++ b/products/product_analytics/backend/api/test/test_insight.py
@@ -1208,6 +1208,20 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(len(response.json()["results"]), 2)
+ def test_listing_insights_by_journeys_type(self) -> None:
+ journeys_insight_id, _ = self.dashboard_api.create_insight(
+ data={"query": {"kind": "InsightVizNode", "source": {"kind": "PathsV2Query"}}}
+ )
+ paths_insight_id, _ = self.dashboard_api.create_insight(
+ data={"filters": {"insight": "PATHS", "events": [{"id": "$pageview"}]}}
+ )
+
+ journeys_response = self.client.get(f"/api/environments/{self.team.pk}/insights/?insight=JOURNEYS")
+ assert [insight["id"] for insight in journeys_response.json()["results"]] == [journeys_insight_id]
+
+ paths_response = self.client.get(f"/api/environments/{self.team.pk}/insights/?insight=PATHS")
+ assert [insight["id"] for insight in paths_response.json()["results"]] == [paths_insight_id]
+
def test_can_list_insights_by_which_dashboards_they_are_in(self) -> None:
insight_one_id, _ = self.dashboard_api.create_insight(
{"name": "insight 1", "filters": {"events": [{"id": "$pageview"}]}}
diff --git a/products/product_analytics/backend/api/test/test_paths_v2.py b/products/product_analytics/backend/api/test/test_paths_v2.py
new file mode 100644
index 000000000000..64b3dfad4390
--- /dev/null
+++ b/products/product_analytics/backend/api/test/test_paths_v2.py
@@ -0,0 +1,150 @@
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from rest_framework import status
+
+from posthog.schema import (
+ DateRange,
+ PathsV2Anchor,
+ PathsV2AnchorType,
+ PathsV2Filter,
+ PathsV2Item,
+ PathsV2Query,
+ PathsV2StepSource,
+)
+
+from products.product_analytics.backend.api.paths_v2 import PathsV2SegmentToFunnelRequestSerializer
+from products.product_analytics.backend.hogql_queries.paths_v2.funnel_converter import (
+ anchored_segment_to_funnels_query,
+ edge_to_funnels_query,
+)
+from products.product_analytics.backend.hogql_queries.paths_v2.path_item import PATHS_V2_OTHER
+
+DATE_RANGE = DateRange(date_from="2023-03-01", date_to="2023-03-31")
+
+
+def _query(**filter_overrides: Any) -> dict:
+ filter_kwargs: dict[str, Any] = {
+ "stepSources": [PathsV2StepSource(event=event) for event in ("a", "b", "c")],
+ **filter_overrides,
+ }
+ return PathsV2Query(dateRange=DATE_RANGE, pathsV2Filter=PathsV2Filter(**filter_kwargs)).model_dump(
+ exclude_none=True
+ )
+
+
+def _items(*events: str) -> list[dict]:
+ return [{"event": event} for event in events]
+
+
+class TestSegmentToFunnelRequestValidation(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("single_item", _items("a")),
+ ("too_many_items", _items(*(["a"] * 21))),
+ ("item_without_event", [{"event": "a"}, {"label": "no event"}]),
+ ("missing_query", None),
+ ]
+ )
+ def test_rejects_invalid_bodies(self, _name: str, items: list[dict] | None) -> None:
+ data: dict[str, Any] = {"query": {"kind": "PathsV2Query"}}
+ if items is not None:
+ data["items"] = items
+ else:
+ data = {"items": _items("a", "b")}
+ serializer = PathsV2SegmentToFunnelRequestSerializer(data=data)
+ self.assertFalse(serializer.is_valid())
+
+ def test_accepts_null_and_blank_labels(self) -> None:
+ serializer = PathsV2SegmentToFunnelRequestSerializer(
+ data={
+ "query": {"kind": "PathsV2Query"},
+ "items": [{"event": "a", "label": None}, {"event": "b", "label": ""}],
+ }
+ )
+ self.assertTrue(serializer.is_valid(), serializer.errors)
+
+
+class TestSegmentToFunnelAPI(APIBaseTest):
+ def _post(self, query: dict, items: list[dict]):
+ return self.client.post(
+ f"/api/projects/{self.team.pk}/paths_v2/segment_to_funnel/",
+ {"query": query, "items": items},
+ format="json",
+ )
+
+ def test_open_mode_edge_matches_the_converter(self) -> None:
+ response = self._post(_query(), _items("a", "b"))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ expected = edge_to_funnels_query(
+ PathsV2Query.model_validate(_query()), self.team, PathsV2Item(event="a"), PathsV2Item(event="b")
+ )
+ self.assertEqual(response.json()["funnels_query"], expected.model_dump(exclude_none=True, mode="json"))
+
+ def test_open_mode_rejects_multi_hop_segments(self) -> None:
+ response = self._post(_query(), _items("a", "b", "c"))
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("single edge", response.json()["detail"])
+
+ def test_anchored_chain_matches_the_converter(self) -> None:
+ query = _query(anchor=PathsV2Anchor(item=PathsV2Item(event="a"), type=PathsV2AnchorType.START))
+
+ response = self._post(query, _items("a", "b", "c"))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ expected = anchored_segment_to_funnels_query(
+ PathsV2Query.model_validate(query),
+ self.team,
+ [PathsV2Item(event=event) for event in ("a", "b", "c")],
+ )
+ self.assertEqual(response.json()["funnels_query"], expected.model_dump(exclude_none=True, mode="json"))
+
+ def test_end_anchored_chain_converts_in_forward_time_order(self) -> None:
+ # An end-anchored chain arrives anchor-first, i.e. backward in time; the emitted
+ # funnel must run forward, ending at the anchor.
+ query = _query(anchor=PathsV2Anchor(item=PathsV2Item(event="c"), type=PathsV2AnchorType.END))
+
+ response = self._post(query, _items("c", "b", "a"))
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ series_events = [node["event"] for node in response.json()["funnels_query"]["series"]]
+ self.assertEqual(series_events, ["a", "b", "c"])
+
+ def test_anchored_segment_must_start_at_the_anchor(self) -> None:
+ query = _query(anchor=PathsV2Anchor(item=PathsV2Item(event="a"), type=PathsV2AnchorType.START))
+
+ response = self._post(query, _items("b", "c"))
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertIn("anchor", response.json()["detail"])
+
+ def test_anchor_guard_normalizes_null_and_empty_labels(self) -> None:
+ # For a source without a naming property the converter ignores labels entirely, so a
+ # ""-labelled first item must still match a null-labelled anchor.
+ query = _query(anchor=PathsV2Anchor(item=PathsV2Item(event="a"), type=PathsV2AnchorType.START))
+
+ response = self._post(query, [{"event": "a", "label": ""}, {"event": "b"}])
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+
+ @parameterized.expand(
+ [
+ ("other_row_item", _items("a", PATHS_V2_OTHER)),
+ ("event_without_step_source", _items("a", "unknown-event")),
+ ]
+ )
+ def test_inconvertible_items_return_400(self, _name: str, items: list[dict]) -> None:
+ response = self._post(_query(), items)
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_invalid_paths_query_returns_400(self) -> None:
+ response = self._post({"kind": "TrendsQuery", "series": []}, _items("a", "b"))
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
diff --git a/products/product_analytics/backend/hogql_queries/paths_v2/__init__.py b/products/product_analytics/backend/hogql_queries/paths_v2/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/product_analytics/backend/hogql_queries/paths_v2/funnel_converter.py b/products/product_analytics/backend/hogql_queries/paths_v2/funnel_converter.py
new file mode 100644
index 000000000000..6b57a18decaa
--- /dev/null
+++ b/products/product_analytics/backend/hogql_queries/paths_v2/funnel_converter.py
@@ -0,0 +1,159 @@
+from posthog.schema import (
+ EventsNode,
+ FunnelConversionWindowTimeUnit,
+ FunnelExclusionEventsNode,
+ FunnelsFilter,
+ FunnelsQuery,
+ HogQLPropertyFilter,
+ PathsV2Filter,
+ PathsV2Item,
+ PathsV2Query,
+ PathsV2StepSource,
+ StepOrderValue,
+)
+
+from posthog.hogql import ast
+
+from posthog.models.team.team import Team
+
+from products.product_analytics.backend.hogql_queries.paths_v2.path_item import (
+ DEFAULT_CONVERSION_WINDOW_INTERVAL,
+ DEFAULT_CONVERSION_WINDOW_INTERVAL_UNIT,
+ DEFAULT_GAP_INTERVAL,
+ DEFAULT_GAP_INTERVAL_UNIT,
+ PATHS_V2_OTHER,
+ item_label,
+ item_tuple_expr,
+ item_universe_filter_expr,
+ path_item_expr,
+ resolve_cleaning_rules,
+ resolve_step_sources,
+ source_label_expr,
+ step_source_for_event,
+)
+
+
+def _step_node(item: PathsV2Item, source: PathsV2StepSource, cleaning_rules: list[tuple[str, str]]) -> EventsNode:
+ """A funnel step matching exactly the events that derive into this path item."""
+ if source.namingProperty is None:
+ return EventsNode(event=item.event)
+ label_matches = ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=source_label_expr(source, cleaning_rules),
+ right=ast.Constant(value=item_label(item, source)),
+ )
+ return EventsNode(event=item.event, properties=[HogQLPropertyFilter(key=label_matches.to_hogql())])
+
+
+def _item_strict_exclusion(
+ query: PathsV2Query,
+ sources: list[PathsV2StepSource],
+ segment_item_exprs: list[ast.Expr],
+ cleaning_rules: list[tuple[str, str]],
+ to_step: int,
+) -> FunnelExclusionEventsNode:
+ """The item-strict universe as one all-events exclusion spanning the whole segment: an event
+ breaks the funnel iff it is part of the item universe (a step source's event, not an excluded
+ item) and its derived item is not one of the segment's own items. Events outside the universe
+ stay invisible, exactly as in the paths runner. Active from the first step through `to_step`
+ (the last), so any intervening included item between any two consecutive segment steps
+ disqualifies that attempt."""
+ item_expr = path_item_expr(sources, cleaning_rules)
+ not_a_segment_item = ast.CompareOperation(
+ op=ast.CompareOperationOp.NotIn,
+ left=item_expr,
+ right=ast.Tuple(exprs=segment_item_exprs),
+ )
+ universe = ast.And(exprs=[item_universe_filter_expr(sources, query.pathsV2Filter, item_expr), not_a_segment_item])
+ return FunnelExclusionEventsNode(
+ event=None,
+ funnelFromStep=0,
+ funnelToStep=to_step,
+ properties=[HogQLPropertyFilter(key=universe.to_hogql())],
+ )
+
+
+def _ensure_convertible(item: PathsV2Item | None, endpoint: str) -> PathsV2Item:
+ if item is None or item.event == PATHS_V2_OTHER:
+ raise ValueError(
+ f"The edge {endpoint} is not a named path item; the other row and drop-offs have no funnel equivalent."
+ )
+ return item
+
+
+def segment_to_funnels_query(
+ query: PathsV2Query,
+ team: Team,
+ items: list[PathsV2Item | None],
+ window_interval: int,
+ window_interval_unit: FunnelConversionWindowTimeUnit,
+) -> FunnelsQuery:
+ """Convert a displayed segment of named path items into the funnel that reproduces its
+ unique-actor count exactly: an ordered funnel over the same date range and properties, with the
+ given conversion window and the item-strict universe as one all-events exclusion spanning every
+ step. The items are in funnel (forward-time) order; anchored segments pass window W, open-mode
+ single edges pass gap G."""
+ if len(items) < 2:
+ raise ValueError("A segment needs at least two path items to convert to a funnel.")
+
+ convertible = [_ensure_convertible(item, f"step {index}") for index, item in enumerate(items)]
+ sources = resolve_step_sources(query)
+ cleaning_rules = resolve_cleaning_rules(query.pathsV2Filter, team)
+ item_sources = [step_source_for_event(sources, item.event) for item in convertible]
+
+ seen: set[tuple[str, str]] = set()
+ segment_item_exprs: list[ast.Expr] = []
+ for item, source in zip(convertible, item_sources):
+ key = (item.event, item_label(item, source))
+ if key not in seen:
+ seen.add(key)
+ segment_item_exprs.append(item_tuple_expr(item, source))
+
+ return FunnelsQuery(
+ series=[_step_node(item, source, cleaning_rules) for item, source in zip(convertible, item_sources)],
+ funnelsFilter=FunnelsFilter(
+ exclusions=[
+ _item_strict_exclusion(query, sources, segment_item_exprs, cleaning_rules, to_step=len(convertible) - 1)
+ ],
+ funnelOrderType=StepOrderValue.ORDERED,
+ funnelWindowInterval=window_interval,
+ funnelWindowIntervalUnit=window_interval_unit,
+ ),
+ dateRange=query.dateRange,
+ properties=query.properties,
+ filterTestAccounts=query.filterTestAccounts,
+ )
+
+
+def edge_to_funnels_query(
+ query: PathsV2Query,
+ team: Team,
+ source_item: PathsV2Item | None,
+ target_item: PathsV2Item | None,
+) -> FunnelsQuery:
+ """Convert an open-mode edge between two named path items into the funnel that reproduces its
+ position-free unique-actor count: an ordered two-step funnel with the gap G as conversion window
+ and the item-strict universe as an all-events exclusion between the steps."""
+ paths_filter = query.pathsV2Filter or PathsV2Filter()
+ gap_interval = paths_filter.gapInterval if paths_filter.gapInterval is not None else DEFAULT_GAP_INTERVAL
+ gap_interval_unit: FunnelConversionWindowTimeUnit = (
+ paths_filter.gapIntervalUnit if paths_filter.gapIntervalUnit is not None else DEFAULT_GAP_INTERVAL_UNIT
+ )
+ return segment_to_funnels_query(query, team, [source_item, target_item], gap_interval, gap_interval_unit)
+
+
+def anchored_segment_to_funnels_query(query: PathsV2Query, team: Team, items: list[PathsV2Item | None]) -> FunnelsQuery:
+ """Convert an anchored-mode segment (any depth) into its funnel, reading window W from the query.
+ Anchored mode's promise: every displayed segment equals this plain funnel with window W."""
+ paths_filter = query.pathsV2Filter or PathsV2Filter()
+ window_interval = (
+ paths_filter.conversionWindowInterval
+ if paths_filter.conversionWindowInterval is not None
+ else DEFAULT_CONVERSION_WINDOW_INTERVAL
+ )
+ window_interval_unit: FunnelConversionWindowTimeUnit = (
+ paths_filter.conversionWindowIntervalUnit
+ if paths_filter.conversionWindowIntervalUnit is not None
+ else DEFAULT_CONVERSION_WINDOW_INTERVAL_UNIT
+ )
+ return segment_to_funnels_query(query, team, items, window_interval, window_interval_unit)
diff --git a/products/product_analytics/backend/hogql_queries/paths_v2/path_item.py b/products/product_analytics/backend/hogql_queries/paths_v2/path_item.py
new file mode 100644
index 000000000000..073ff856a002
--- /dev/null
+++ b/products/product_analytics/backend/hogql_queries/paths_v2/path_item.py
@@ -0,0 +1,160 @@
+from rest_framework.exceptions import ValidationError
+
+from posthog.schema import FunnelConversionWindowTimeUnit, PathsV2Filter, PathsV2Item, PathsV2Query, PathsV2StepSource
+
+from posthog.hogql import ast
+
+from posthog.models.team.team import Team
+
+# Sentinel event marking a per-step "other" bucket row; never a real event name.
+PATHS_V2_OTHER = "$$__posthog_other__$$"
+
+# Must match the @default annotations on PathsV2Filter in
+# frontend/src/queries/schema/schema-general.ts; test_defaults pins them to the generated schema.
+DEFAULT_MAX_STEPS = 5
+DEFAULT_MAX_ROWS_PER_STEP = 3
+DEFAULT_GAP_INTERVAL = 30
+DEFAULT_GAP_INTERVAL_UNIT = FunnelConversionWindowTimeUnit.MINUTE
+DEFAULT_COLLAPSE_REPEATS = True
+DEFAULT_CONVERSION_WINDOW_INTERVAL = 30
+DEFAULT_CONVERSION_WINDOW_INTERVAL_UNIT = FunnelConversionWindowTimeUnit.MINUTE
+DEFAULT_APPLY_TEAM_PATH_CLEANING = True
+
+
+def default_step_sources() -> list[PathsV2StepSource]:
+ """The pageviews preset: `$pageview` named by the cleaned URL path."""
+ return [PathsV2StepSource(event="$pageview", namingProperty="$pathname")]
+
+
+def resolve_step_sources(query: PathsV2Query) -> list[PathsV2StepSource]:
+ if query.pathsV2Filter is None or query.pathsV2Filter.stepSources is None:
+ return default_step_sources()
+ return query.pathsV2Filter.stepSources
+
+
+def step_source_for_event(sources: list[PathsV2StepSource], event: str) -> PathsV2StepSource:
+ for source in sources:
+ if source.event == event:
+ return source
+ raise ValidationError(f"No step source is defined for event {event!r}.")
+
+
+def resolve_cleaning_rules(paths_filter: PathsV2Filter | None, team: Team) -> list[tuple[str, str]]:
+ """The path cleaning rules in application order: the team's rules (unless disabled), then the
+ insight-local rules. The runner and the funnel converter both resolve rules through here, so a
+ displayed item and its funnel steps always clean labels identically. Rules without a regex have
+ nothing to match and are skipped; a missing alias strips the match."""
+ paths_filter = paths_filter or PathsV2Filter()
+ apply_team = paths_filter.applyTeamPathCleaning
+ if apply_team is None:
+ apply_team = DEFAULT_APPLY_TEAM_PATH_CLEANING
+ # team.path_cleaning_filters is a nullable JSONField; path_cleaning_filter_models() iterates it
+ # unguarded, so the truthiness check doubles as the None guard.
+ team_rules = team.path_cleaning_filter_models() if apply_team and team.path_cleaning_filters else []
+ local_rules = paths_filter.localPathCleaningFilters or []
+ return [(rule.regex, rule.alias or "") for rule in [*team_rules, *local_rules] if rule.regex]
+
+
+def _raw_source_label_expr(source: PathsV2StepSource) -> ast.Expr:
+ """A source's label before cleaning: the naming property as a string, NULL both when the
+ property is missing and for sources without a naming property."""
+ if source.namingProperty is None:
+ return ast.Constant(value=None)
+ return ast.Call(name="toString", args=[ast.Field(chain=["properties", source.namingProperty])])
+
+
+def _cleaned_label_expr(raw_label: ast.Expr, cleaning_rules: list[tuple[str, str]]) -> ast.Expr:
+ """Apply the cleaning rules to a raw label and coalesce to ''. A NULL raw label stays NULL
+ through every replaceRegexpAll, so cleaning cannot invent a label where none exists."""
+ label = raw_label
+ for regex, alias in cleaning_rules:
+ label = ast.Call(name="replaceRegexpAll", args=[label, ast.Constant(value=regex), ast.Constant(value=alias)])
+ return ast.Call(name="ifNull", args=[label, ast.Constant(value="")])
+
+
+def source_label_expr(source: PathsV2StepSource, cleaning_rules: list[tuple[str, str]]) -> ast.Expr:
+ """Label of a path item produced by this source: the naming property value after path cleaning,
+ coalesced to '' when the property is missing. Constant '' for sources without a naming property,
+ where the event alone identifies the item."""
+ if source.namingProperty is None:
+ return ast.Constant(value="")
+ return _cleaned_label_expr(_raw_source_label_expr(source), cleaning_rules)
+
+
+def path_item_expr(sources: list[PathsV2StepSource], cleaning_rules: list[tuple[str, str]]) -> ast.Expr:
+ """Identity of the path item an event produces: tuple(event, label).
+
+ The runner groups journeys by this expression and the funnel converter reuses it verbatim in
+ step filters and the item-strict exclusion, so both sides derive identical items by construction.
+ The cleaning chain applies once to the multiIf-selected raw label, so the expression grows with
+ sources plus rules rather than sources times rules.
+ """
+ label_args: list[ast.Expr] = []
+ for source in sources:
+ label_args.append(
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.Eq,
+ left=ast.Field(chain=["event"]),
+ right=ast.Constant(value=source.event),
+ )
+ )
+ label_args.append(_raw_source_label_expr(source))
+ label_args.append(ast.Constant(value=None))
+ raw_label = ast.Call(name="multiIf", args=label_args)
+ return ast.Tuple(exprs=[ast.Field(chain=["event"]), _cleaned_label_expr(raw_label, cleaning_rules)])
+
+
+def source_events_filter_expr(sources: list[PathsV2StepSource]) -> ast.Expr:
+ """`event IN (...)`: whether an event can become a path item at all."""
+ return ast.CompareOperation(
+ op=ast.CompareOperationOp.In,
+ left=ast.Field(chain=["event"]),
+ right=ast.Constant(value=[source.event for source in sources]),
+ )
+
+
+def item_label(item: PathsV2Item, source: PathsV2StepSource) -> str:
+ """The label an item contributes to its `(event, label)` identity: the empty string for a source
+ without a naming property (the event alone identifies the item), otherwise the item's label,
+ which must be present."""
+ if source.namingProperty is None:
+ return ""
+ if item.label is None:
+ raise ValidationError(f"Path item for event {item.event!r} needs a label, as its source has a naming property.")
+ return item.label
+
+
+def item_tuple_expr(item: PathsV2Item, source: PathsV2StepSource) -> ast.Expr:
+ """Constant `(event, label)` identity of a concrete path item, matching `path_item_expr`'s shape
+ so the runner can compare a derived item against a chosen anchor and the converter can name it."""
+ return ast.Tuple(exprs=[ast.Constant(value=item.event), ast.Constant(value=item_label(item, source))])
+
+
+def excluded_item_tuples(paths_filter: PathsV2Filter | None) -> list[tuple[str, str]]:
+ """The `(event, label)` identities of the excluded items. A missing label means '' here, which
+ for a source without a naming property is the item itself, and for a source with one is the item
+ whose naming property is missing. Tuples no derivable item can equal are inert."""
+ if paths_filter is None or not paths_filter.excludedItems:
+ return []
+ return [(item.event, item.label or "") for item in paths_filter.excludedItems]
+
+
+def item_universe_filter_expr(
+ sources: list[PathsV2StepSource], paths_filter: PathsV2Filter | None, item_expr: ast.Expr
+) -> ast.Expr:
+ """Whether an event is part of the item universe: its event matches a step source and its
+ derived item is not excluded. The runner's event base and the converter's item-strict exclusion
+ universe both come from here, so an excluded item is invisible to both sides by construction,
+ exactly like an event outside the step sources."""
+ universe: ast.Expr = source_events_filter_expr(sources)
+ excluded = excluded_item_tuples(paths_filter)
+ if not excluded:
+ return universe
+ not_excluded = ast.CompareOperation(
+ op=ast.CompareOperationOp.NotIn,
+ left=item_expr,
+ right=ast.Tuple(
+ exprs=[ast.Tuple(exprs=[ast.Constant(value=event), ast.Constant(value=label)]) for event, label in excluded]
+ ),
+ )
+ return ast.And(exprs=[universe, not_excluded])
diff --git a/products/product_analytics/backend/hogql_queries/paths_v2/paths_v2_query_runner.py b/products/product_analytics/backend/hogql_queries/paths_v2/paths_v2_query_runner.py
new file mode 100644
index 000000000000..91fa768a7ff9
--- /dev/null
+++ b/products/product_analytics/backend/hogql_queries/paths_v2/paths_v2_query_runner.py
@@ -0,0 +1,942 @@
+from datetime import datetime
+from functools import cached_property
+from typing import Any
+
+from rest_framework.exceptions import ValidationError
+
+from posthog.schema import (
+ CachedPathsV2QueryResponse,
+ FunnelConversionWindowTimeUnit,
+ PathsV2Anchor,
+ PathsV2AnchorType,
+ PathsV2Edge,
+ PathsV2ElementSelector,
+ PathsV2ElementType,
+ PathsV2Filter,
+ PathsV2Item,
+ PathsV2Prefix,
+ PathsV2Query,
+ PathsV2QueryResponse,
+ PathsV2Results,
+ PathsV2Row,
+ PathsV2Step,
+ PathsV2StepSource,
+ ResolvedDateRangeResponse,
+)
+
+from posthog.hogql import ast
+from posthog.hogql.constants import MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY, HogQLGlobalSettings
+from posthog.hogql.parser import parse_expr, parse_select
+from posthog.hogql.printer import to_printed_hogql
+from posthog.hogql.property import property_to_expr
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.hogql_queries.insights.funnels.utils import CONVERSION_WINDOW_INTERVAL_BOUNDS, conversion_window_to_seconds
+from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
+from posthog.hogql_queries.utils.query_date_range import QueryDateRange
+from posthog.hogql_queries.validation.validation import QueryValidationContext, QueryValidationRule
+
+from products.product_analytics.backend.hogql_queries.paths_v2.path_item import (
+ DEFAULT_COLLAPSE_REPEATS,
+ DEFAULT_CONVERSION_WINDOW_INTERVAL,
+ DEFAULT_CONVERSION_WINDOW_INTERVAL_UNIT,
+ DEFAULT_GAP_INTERVAL,
+ DEFAULT_GAP_INTERVAL_UNIT,
+ DEFAULT_MAX_ROWS_PER_STEP,
+ DEFAULT_MAX_STEPS,
+ PATHS_V2_OTHER,
+ excluded_item_tuples,
+ item_label,
+ item_tuple_expr,
+ item_universe_filter_expr,
+ path_item_expr,
+ resolve_cleaning_rules,
+ resolve_step_sources,
+ step_source_for_event,
+)
+
+ELEMENT_KIND_NODE = "node"
+ELEMENT_KIND_EDGE = "edge"
+ELEMENT_KIND_DROP_OFF = "dropoff"
+
+# Anchored mode carries per-chain prefix counts for the hover funnel preview. This caps how many rows
+# the prefix query returns, keeping the aggregation bounded on large teams; the most common chains
+# (which include every visible top-item chain) survive the descending-count ordering, so the cap only
+# ever costs long-tail hover data, never grid or persons-modal counts. Chains through items the grid
+# buckets into the other row are then removed from the response entirely (_displayed_prefixes).
+MAX_PREFIX_ROWS = 10_000
+
+
+class ValidateGapBounds:
+ """Reject gaps outside the shared funnel conversion window bounds; never clamp."""
+
+ code = "paths_v2_gap_out_of_bounds"
+
+ def validate(self, context: QueryValidationContext[PathsV2Query]) -> None:
+ paths_filter = context.query.pathsV2Filter
+ if paths_filter is None or paths_filter.gapInterval is None:
+ return
+ unit = paths_filter.gapIntervalUnit or DEFAULT_GAP_INTERVAL_UNIT
+ lower, upper = CONVERSION_WINDOW_INTERVAL_BOUNDS[unit]
+ if not lower <= paths_filter.gapInterval <= upper:
+ raise ValidationError(
+ f"gapInterval must be between {lower} and {upper} for unit {unit.value!r}.",
+ code=self.code,
+ )
+
+
+class ValidateStepSources:
+ """Step sources must name distinct, non-empty events, as each event maps to one item derivation."""
+
+ code = "paths_v2_step_sources_invalid"
+
+ def validate(self, context: QueryValidationContext[PathsV2Query]) -> None:
+ paths_filter = context.query.pathsV2Filter
+ if paths_filter is None or paths_filter.stepSources is None:
+ return
+ events = [source.event for source in paths_filter.stepSources]
+ if any(event == "" for event in events):
+ raise ValidationError("stepSources must not contain an empty event name.", code=self.code)
+ if len(set(events)) != len(events):
+ raise ValidationError("stepSources must not contain duplicate events.", code=self.code)
+
+
+class ValidateWindowBounds:
+ """Reject anchored windows outside the shared funnel conversion window bounds; never clamp. The
+ window is reused verbatim as the emitted funnel's conversion window, so it must stay in bounds."""
+
+ code = "paths_v2_window_out_of_bounds"
+
+ def validate(self, context: QueryValidationContext[PathsV2Query]) -> None:
+ paths_filter = context.query.pathsV2Filter
+ if paths_filter is None or paths_filter.conversionWindowInterval is None:
+ return
+ unit = paths_filter.conversionWindowIntervalUnit or DEFAULT_CONVERSION_WINDOW_INTERVAL_UNIT
+ lower, upper = CONVERSION_WINDOW_INTERVAL_BOUNDS[unit]
+ if not lower <= paths_filter.conversionWindowInterval <= upper:
+ raise ValidationError(
+ f"conversionWindowInterval must be between {lower} and {upper} for unit {unit.value!r}.",
+ code=self.code,
+ )
+
+
+class ValidateAnchor:
+ """An anchor's event must be one of the step sources, otherwise no event could ever derive it and
+ the chart would be empty for a reason the config does not reveal. When that source names its items
+ by a property, the anchor must carry the label that pins which item it is."""
+
+ code = "paths_v2_anchor_invalid"
+
+ def validate(self, context: QueryValidationContext[PathsV2Query]) -> None:
+ paths_filter = context.query.pathsV2Filter
+ if paths_filter is None or paths_filter.anchor is None:
+ return
+ anchor_item = paths_filter.anchor.item
+ source = next((s for s in resolve_step_sources(context.query) if s.event == anchor_item.event), None)
+ if source is None:
+ raise ValidationError(
+ f"The anchor event {anchor_item.event!r} must be one of the step sources.",
+ code=self.code,
+ )
+ if source.namingProperty is not None and anchor_item.label is None:
+ raise ValidationError(
+ f"The anchor item for event {anchor_item.event!r} needs a label, as its source has a naming property.",
+ code=self.code,
+ )
+
+
+class ValidateExcludedItems:
+ """Excluding the anchor would empty the chart for a reason the config does not reveal. Everything
+ else on the exclude list is permitted: an exclusion pins the concrete item (event, label or ''),
+ and exclusions no derivable item can equal are inert, so editing step sources never invalidates a
+ saved exclude list."""
+
+ code = "paths_v2_excluded_items_invalid"
+
+ def validate(self, context: QueryValidationContext[PathsV2Query]) -> None:
+ paths_filter = context.query.pathsV2Filter
+ if paths_filter is None or not paths_filter.excludedItems or paths_filter.anchor is None:
+ return
+ anchor_item = paths_filter.anchor.item
+ source = next((s for s in resolve_step_sources(context.query) if s.event == anchor_item.event), None)
+ if source is None or (source.namingProperty is not None and anchor_item.label is None):
+ # ValidateAnchor rejects these configurations with the more precise message.
+ return
+ # item_label, not the raw label: a spurious label on a source without a naming property must
+ # not hide that the query anchors on (event, ''), which may be the excluded item.
+ if (anchor_item.event, item_label(anchor_item, source)) in excluded_item_tuples(paths_filter):
+ raise ValidationError(
+ "The anchor cannot be an excluded item, as no journey could ever reach it.",
+ code=self.code,
+ )
+
+
+class PathsV2QueryRunner(AnalyticsQueryRunner[PathsV2QueryResponse]):
+ query: PathsV2Query
+ cached_response: CachedPathsV2QueryResponse
+
+ def validators(self) -> tuple[QueryValidationRule[PathsV2Query], ...]:
+ return (
+ ValidateGapBounds(),
+ ValidateWindowBounds(),
+ ValidateStepSources(),
+ ValidateAnchor(),
+ ValidateExcludedItems(),
+ )
+
+ @cached_property
+ def paths_v2_filter(self) -> PathsV2Filter:
+ return self.query.pathsV2Filter or PathsV2Filter()
+
+ @cached_property
+ def step_sources(self) -> list[PathsV2StepSource]:
+ return resolve_step_sources(self.query)
+
+ @cached_property
+ def cleaning_rules(self) -> list[tuple[str, str]]:
+ return resolve_cleaning_rules(self.query.pathsV2Filter, self.team)
+
+ @property
+ def max_steps(self) -> int:
+ if self.paths_v2_filter.maxSteps is not None:
+ return self.paths_v2_filter.maxSteps
+ return DEFAULT_MAX_STEPS
+
+ @property
+ def max_rows_per_step(self) -> int:
+ if self.paths_v2_filter.maxRowsPerStep is not None:
+ return self.paths_v2_filter.maxRowsPerStep
+ return DEFAULT_MAX_ROWS_PER_STEP
+
+ @property
+ def gap_interval(self) -> int:
+ if self.paths_v2_filter.gapInterval is not None:
+ return self.paths_v2_filter.gapInterval
+ return DEFAULT_GAP_INTERVAL
+
+ @property
+ def gap_interval_unit(self) -> FunnelConversionWindowTimeUnit:
+ if self.paths_v2_filter.gapIntervalUnit is not None:
+ return self.paths_v2_filter.gapIntervalUnit
+ return DEFAULT_GAP_INTERVAL_UNIT
+
+ @property
+ def collapse_repeats(self) -> bool:
+ if self.paths_v2_filter.collapseRepeats is not None:
+ return self.paths_v2_filter.collapseRepeats
+ return DEFAULT_COLLAPSE_REPEATS
+
+ @property
+ def anchor(self) -> PathsV2Anchor | None:
+ return self.paths_v2_filter.anchor
+
+ @property
+ def is_anchored(self) -> bool:
+ """Anchored mode when an anchor is set: one sequence per actor within window W, every segment a
+ plain funnel. Otherwise open mode: gap-split journeys."""
+ return self.anchor is not None
+
+ @property
+ def window_interval(self) -> int:
+ if self.paths_v2_filter.conversionWindowInterval is not None:
+ return self.paths_v2_filter.conversionWindowInterval
+ return DEFAULT_CONVERSION_WINDOW_INTERVAL
+
+ @property
+ def window_interval_unit(self) -> FunnelConversionWindowTimeUnit:
+ if self.paths_v2_filter.conversionWindowIntervalUnit is not None:
+ return self.paths_v2_filter.conversionWindowIntervalUnit
+ return DEFAULT_CONVERSION_WINDOW_INTERVAL_UNIT
+
+ @cached_property
+ def query_date_range(self) -> QueryDateRange:
+ return QueryDateRange(date_range=self.query.dateRange, team=self.team, interval=None, now=datetime.now())
+
+ @property
+ def result_row_limit(self) -> int:
+ """Exact upper bound of result rows for the configured grid, so the generic default
+ LIMIT 100 can never silently truncate results: per step one row per top item plus the
+ other row and a drop-off row, and per adjacent step pair one edge row per (source, target)
+ combination of top items and the other bucket."""
+ rows_per_step = self.max_rows_per_step + 1
+ node_rows = self.max_steps * rows_per_step
+ drop_off_rows = self.max_steps
+ edge_rows = (self.max_steps - 1) * rows_per_step * rows_per_step
+ return node_rows + drop_off_rows + edge_rows
+
+ def _gap_expr(self) -> ast.Expr:
+ # Fixed seconds via the funnels realization (month means 31 days), never calendar INTERVAL
+ # arithmetic, so a journey's gap G always equals the emitted funnel's conversion window.
+ return parse_expr(
+ "toIntervalSecond({seconds})",
+ placeholders={
+ "seconds": ast.Constant(value=conversion_window_to_seconds(self.gap_interval, self.gap_interval_unit))
+ },
+ )
+
+ def _window_interval_expr(self) -> ast.Expr:
+ # Window W realized the same fixed-seconds way as the gap, so it always equals the emitted
+ # funnel's conversion window.
+ return parse_expr(
+ "toIntervalSecond({seconds})",
+ placeholders={
+ "seconds": ast.Constant(
+ value=conversion_window_to_seconds(self.window_interval, self.window_interval_unit)
+ )
+ },
+ )
+
+ def _split_interval_expr(self) -> ast.Expr:
+ """The interval that splits an actor's events into journeys. Open mode splits on gap G. Anchored
+ mode splits on window W: the anchor prefilter already bounds every kept event to within W of the
+ anchor, so no adjacent pair can exceed W and the actor's events stay a single sequence."""
+ if self.is_anchored:
+ return self._window_interval_expr()
+ return self._gap_expr()
+
+ def _sorted_events_expr(self) -> ast.Expr:
+ """The per-actor event tuples in the order the grid reads them. Ascending time everywhere except
+ an end anchor, which sorts descending so the anchor (each actor's latest anchor event) lands at
+ step 0 and the grid reads backward in time toward it."""
+ events = parse_expr("groupArray(tuple(timestamp, path_item))")
+ if self.is_anchored and self.anchor is not None and self.anchor.type == PathsV2AnchorType.END:
+ # arrayReverse(arraySort(...)), not arrayReverseSort: HogQL aliases arrayReverseSort to the
+ # ascending arraySort, which would silently keep forward order.
+ return parse_expr("arrayReverse(arraySort(x -> x.1, {events}))", placeholders={"events": events})
+ return parse_expr("arraySort(x -> x.1, {events})", placeholders={"events": events})
+
+ def _event_base_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
+ """One row per in-range event matching a step source and no excluded item:
+ (timestamp, actor_id, path_item)."""
+ event_filters: list[ast.Expr] = [
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.GtEq,
+ left=ast.Field(chain=["timestamp"]),
+ right=self.query_date_range.date_from_to_start_of_interval_hogql(),
+ ),
+ ast.CompareOperation(
+ op=ast.CompareOperationOp.LtEq,
+ left=ast.Field(chain=["timestamp"]),
+ right=self.query_date_range.date_to_as_hogql(),
+ ),
+ item_universe_filter_expr(self.step_sources, self.query.pathsV2Filter, ast.Field(chain=["path_item"])),
+ ]
+
+ if self.query.properties is not None and self.query.properties != []:
+ event_filters.append(property_to_expr(self.query.properties, self.team))
+
+ if (
+ self.query.filterTestAccounts
+ and isinstance(self.team.test_account_filters, list)
+ and len(self.team.test_account_filters) > 0
+ ):
+ for prop in self.team.test_account_filters:
+ event_filters.append(property_to_expr(prop, self.team))
+
+ return parse_select(
+ """
+ SELECT
+ timestamp,
+ person_id AS actor_id,
+ {path_item} AS path_item
+ FROM events
+ WHERE {filters}
+ """,
+ placeholders={
+ "path_item": path_item_expr(self.step_sources, self.cleaning_rules),
+ "filters": ast.And(exprs=event_filters),
+ },
+ )
+
+ def _anchor_source(self) -> PathsV2StepSource:
+ assert self.anchor is not None
+ return step_source_for_event(self.step_sources, self.anchor.item.event)
+
+ def _anchor_item_expr(self) -> ast.Expr:
+ assert self.anchor is not None
+ return item_tuple_expr(self.anchor.item, self._anchor_source())
+
+ def _anchored_event_base_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
+ """Anchored mode's prefilter (a performance guardrail, not an optimization): resolve the anchor
+ actors and each actor's anchor timestamp first, then keep only those actors' events within
+ window W of their anchor. A start anchor takes the actor's first anchor-item occurrence and the
+ events from it forward; an end anchor takes the last occurrence and the events up to it. Either
+ way each kept actor contributes exactly the events of their single anchored sequence."""
+ assert self.anchor is not None
+ if self.anchor.type == PathsV2AnchorType.END:
+ anchor_ts_expr = parse_expr("max(timestamp)")
+ window_bounds = parse_expr(
+ "base.timestamp <= anchor.anchor_ts AND base.timestamp >= anchor.anchor_ts - {window}",
+ {"window": self._window_interval_expr()},
+ )
+ else:
+ anchor_ts_expr = parse_expr("min(timestamp)")
+ window_bounds = parse_expr(
+ "base.timestamp >= anchor.anchor_ts AND base.timestamp <= anchor.anchor_ts + {window}",
+ {"window": self._window_interval_expr()},
+ )
+ return parse_select(
+ """
+ WITH ranged_events AS ({event_base_query})
+ SELECT base.timestamp AS timestamp, base.actor_id AS actor_id, base.path_item AS path_item
+ FROM ranged_events AS base
+ INNER JOIN (
+ SELECT actor_id, {anchor_ts} AS anchor_ts
+ FROM ranged_events
+ WHERE path_item = {anchor_item}
+ GROUP BY actor_id
+ ) AS anchor ON base.actor_id = anchor.actor_id
+ WHERE {window_bounds}
+ """,
+ placeholders={
+ "event_base_query": self._event_base_query(),
+ "anchor_ts": anchor_ts_expr,
+ "anchor_item": self._anchor_item_expr(),
+ "window_bounds": window_bounds,
+ },
+ )
+
+ def _events_for_journeys_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
+ """The event rows the journey builder groups: prefiltered to the anchored window in anchored
+ mode, the full in-range set in open mode."""
+ if self.is_anchored:
+ return self._anchored_event_base_query()
+ return self._event_base_query()
+
+ def _elements_per_actor_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
+ """Per actor: build journeys, then flatten them into the elements the actor touches.
+
+ - Events sort by time and split into journeys wherever the gap exceeds the split interval
+ (a gap of exactly the interval keeps the journey together, matching the funnel conversion
+ window's inclusive comparison). Open mode splits on gap G; anchored mode splits on window W
+ over events the prefilter already bounded to within W of the anchor, so the actor keeps a
+ single sequence.
+ - Immediate repeats of the same path item collapse when collapseRepeats is on.
+ - Journeys keep only their first maxSteps items.
+ - Elements are tuples of (kind, step index, item, target item):
+ a node per journey position, an edge per adjacent position pair, and a drop-off at the
+ journey's final length when the journey ends within the grid.
+ """
+ if self.collapse_repeats:
+ collapsed_journeys_expr = parse_expr(
+ "arrayMap(journey -> arrayFilter((item, i) -> i = 1 OR item != journey[i - 1], journey, arrayEnumerate(journey)), journey_items)"
+ )
+ else:
+ collapsed_journeys_expr = ast.Field(chain=["journey_items"])
+
+ return parse_select(
+ """
+ SELECT
+ actor_id,
+ {sorted_events} AS event_tuples,
+ arrayPopBack(arrayPushFront(arrayMap(x -> x.1, event_tuples), NULL)) AS previous_timestamps,
+ arraySplit((x, previous_timestamp) -> ifNull(x.1 > previous_timestamp + {gap}, 1), event_tuples, previous_timestamps) AS journeys,
+ arrayMap(journey -> arrayMap(event_tuple -> event_tuple.2, journey), journeys) AS journey_items,
+ {collapsed_journeys} AS collapsed_journeys,
+ arrayMap(journey -> arraySlice(journey, 1, {max_steps}), collapsed_journeys) AS trimmed_journeys,
+ arrayFlatten(arrayMap(journey -> arrayMap((item, i) -> tuple({node_kind}, i, item, {no_item}), journey, arrayEnumerate(journey)), trimmed_journeys)) AS node_elements,
+ arrayFlatten(arrayMap(journey -> arrayMap((pair, i) -> tuple({edge_kind}, i, pair.1, pair.2), arrayZip(arrayPopBack(journey), arrayPopFront(journey)), arrayEnumerate(arrayZip(arrayPopBack(journey), arrayPopFront(journey)))), trimmed_journeys)) AS edge_elements,
+ arrayMap(journey_length -> tuple({drop_off_kind}, journey_length, {no_item}, {no_item}), arrayFilter(journey_length -> journey_length <= {max_steps}, arrayMap(journey -> length(journey), collapsed_journeys))) AS drop_off_elements,
+ arrayConcat(node_elements, edge_elements, drop_off_elements) AS elements
+ FROM {event_base_query}
+ GROUP BY actor_id
+ """,
+ placeholders={
+ "event_base_query": self._events_for_journeys_query(),
+ "sorted_events": self._sorted_events_expr(),
+ "gap": self._split_interval_expr(),
+ "collapsed_journeys": collapsed_journeys_expr,
+ "max_steps": ast.Constant(value=self.max_steps),
+ "node_kind": ast.Constant(value=ELEMENT_KIND_NODE),
+ "edge_kind": ast.Constant(value=ELEMENT_KIND_EDGE),
+ "drop_off_kind": ast.Constant(value=ELEMENT_KIND_DROP_OFF),
+ "no_item": parse_expr("tuple('', '')"),
+ },
+ )
+
+ def _element_counts_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
+ """Unique actors per element. The state is kept alongside the finalized count so the
+ top-N bucketing stage can merge non-top items into the other bucket without double
+ counting actors that touch several of them."""
+ return parse_select(
+ """
+ SELECT
+ element.1 AS kind,
+ element.2 AS step_index,
+ element.3 AS item,
+ element.4 AS target_item,
+ uniqExact(actor_id) AS actor_count,
+ uniqExactState(actor_id) AS actor_state
+ FROM {elements_per_actor_query}
+ ARRAY JOIN elements AS element
+ GROUP BY kind, step_index, item, target_item
+ """,
+ placeholders={"elements_per_actor_query": self._elements_per_actor_query()},
+ )
+
+ def _ranked_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
+ """Rank node rows per step by unique-actor count; the top maxRowsPerStep stay named."""
+ return parse_select(
+ """
+ SELECT
+ kind,
+ step_index,
+ item,
+ target_item,
+ actor_count,
+ actor_state,
+ row_number() OVER (PARTITION BY kind, step_index ORDER BY actor_count DESC, item.1 ASC, item.2 ASC) AS row_rank
+ FROM {element_counts_query}
+ """,
+ placeholders={"element_counts_query": self._element_counts_query()},
+ )
+
+ def _bucketed_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
+ """Attach each element's endpoint top-ness. Edges look their source up among the nodes of
+ their own step and their target among the nodes of the following step, since node ranks
+ exist only on node rows."""
+ return parse_select(
+ """
+ SELECT
+ kind,
+ step_index,
+ item,
+ target_item,
+ actor_state,
+ max(if(kind = {node_kind} AND row_rank <= {max_rows_per_step}, 1, 0)) OVER (PARTITION BY step_index, item) AS source_is_top,
+ max(if(kind = {node_kind} AND row_rank <= {max_rows_per_step}, 1, 0)) OVER (PARTITION BY if(kind = {edge_kind}, step_index + 1, step_index), if(kind = {edge_kind}, target_item, item)) AS target_is_top
+ FROM {ranked_query}
+ """,
+ placeholders={
+ "ranked_query": self._ranked_query(),
+ "max_rows_per_step": ast.Constant(value=self.max_rows_per_step),
+ "node_kind": ast.Constant(value=ELEMENT_KIND_NODE),
+ "edge_kind": ast.Constant(value=ELEMENT_KIND_EDGE),
+ },
+ )
+
+ def to_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
+ """Final per-element unique-actor counts, with non-top items merged into the other bucket.
+
+ Merging happens on the aggregate states, so an actor that touches several bucketed items
+ still counts once. Drop-off rows keep their placeholder item, since they are per step."""
+ query = parse_select(
+ """
+ SELECT
+ kind,
+ step_index,
+ multiIf(kind = {drop_off_kind}, item, source_is_top = 1, item, {other_item}) AS source_item,
+ multiIf(kind != {edge_kind}, target_item, target_is_top = 1, target_item, {other_item}) AS grouped_target_item,
+ uniqExactMerge(actor_state) AS actor_count
+ FROM {bucketed_query}
+ GROUP BY kind, step_index, source_item, grouped_target_item
+ ORDER BY kind ASC, step_index ASC, actor_count DESC, source_item ASC, grouped_target_item ASC
+ """,
+ placeholders={
+ "bucketed_query": self._bucketed_query(),
+ "drop_off_kind": ast.Constant(value=ELEMENT_KIND_DROP_OFF),
+ "edge_kind": ast.Constant(value=ELEMENT_KIND_EDGE),
+ "other_item": parse_expr("tuple({other}, '')", {"other": ast.Constant(value=PATHS_V2_OTHER)}),
+ },
+ )
+ assert isinstance(query, ast.SelectQuery)
+ query.limit = ast.Constant(value=self.result_row_limit)
+ return query
+
+ def _anchored_prefix_counts_query(self) -> ast.SelectQuery | ast.SelectSetQuery:
+ """Per-chain prefix counts for the hover funnel preview (anchored mode only). Each actor has
+ one sequence, so its prefixes nest into the chain tree the hover walks; a prefix's count is the
+ unique actors whose sequence begins with exactly that chain. Ordered by descending count and
+ capped at MAX_PREFIX_ROWS, so the visible top-item chains are always carried. Chains through
+ items the grid buckets into the other row still occupy rows here; _displayed_prefixes drops
+ them before the response ships."""
+ return parse_select(
+ """
+ WITH sequences AS (
+ SELECT actor_id, arrayElement(trimmed_journeys, 1) AS sequence
+ FROM {elements_per_actor_query}
+ )
+ SELECT arraySlice(sequence, 1, prefix_length) AS prefix, uniqExact(actor_id) AS actor_count
+ FROM sequences
+ ARRAY JOIN arrayEnumerate(sequence) AS prefix_length
+ GROUP BY prefix
+ ORDER BY actor_count DESC, length(prefix) ASC, prefix ASC
+ LIMIT {max_prefix_rows}
+ """,
+ placeholders={
+ "elements_per_actor_query": self._elements_per_actor_query(),
+ "max_prefix_rows": ast.Constant(value=MAX_PREFIX_ROWS),
+ },
+ )
+
+ def _item_expr(self, item: PathsV2Item) -> ast.Expr:
+ return item_tuple_expr(item, step_source_for_event(self.step_sources, item.event))
+
+ def _top_node_items_at_step_query(self, internal_step_index: int) -> ast.SelectQuery | ast.SelectSetQuery:
+ """The items of a step's named node rows: exactly the items `to_query` keeps out of the
+ other bucket, so an other-row actor set is their complement by construction."""
+ return parse_select(
+ """
+ SELECT item
+ FROM {ranked_query}
+ WHERE kind = {node_kind} AND row_rank <= {max_rows_per_step} AND step_index = {step_index}
+ """,
+ placeholders={
+ "ranked_query": self._ranked_query(),
+ "node_kind": ast.Constant(value=ELEMENT_KIND_NODE),
+ "max_rows_per_step": ast.Constant(value=self.max_rows_per_step),
+ "step_index": ast.Constant(value=internal_step_index),
+ },
+ )
+
+ def _element_actors_query(self, condition: ast.Expr) -> ast.SelectQuery | ast.SelectSetQuery:
+ return parse_select(
+ """
+ SELECT actor_id
+ FROM {elements_per_actor_query}
+ ARRAY JOIN elements AS element
+ WHERE {condition}
+ GROUP BY actor_id
+ """,
+ placeholders={
+ "elements_per_actor_query": self._elements_per_actor_query(),
+ "condition": condition,
+ },
+ )
+
+ def _element_condition(self, kind: str, internal_step_index: int) -> list[ast.Expr]:
+ return [
+ parse_expr("element.1 = {kind}", {"kind": ast.Constant(value=kind)}),
+ parse_expr("element.2 = {step_index}", {"step_index": ast.Constant(value=internal_step_index)}),
+ ]
+
+ def _required_step_index(self, element: PathsV2ElementSelector) -> int:
+ """The selector's stepIndex mapped to the runner's 1-based journey position."""
+ if element.stepIndex is None:
+ raise ValidationError(
+ f"A {element.elementType.value} element needs a stepIndex.", code="paths_v2_element_invalid"
+ )
+ return int(element.stepIndex) + 1
+
+ def _node_actors_query(self, element: PathsV2ElementSelector) -> ast.SelectQuery | ast.SelectSetQuery:
+ if element.item is None:
+ raise ValidationError("A node element needs an item.", code="paths_v2_element_invalid")
+ conditions = self._element_condition(ELEMENT_KIND_NODE, self._required_step_index(element))
+ conditions.append(parse_expr("element.3 = {item}", {"item": self._item_expr(element.item)}))
+ return self._element_actors_query(ast.And(exprs=conditions))
+
+ def _other_actors_query(self, element: PathsV2ElementSelector) -> ast.SelectQuery | ast.SelectSetQuery:
+ internal_step_index = self._required_step_index(element)
+ conditions = self._element_condition(ELEMENT_KIND_NODE, internal_step_index)
+ conditions.append(
+ parse_expr(
+ "element.3 NOT IN {top_items}", {"top_items": self._top_node_items_at_step_query(internal_step_index)}
+ )
+ )
+ return self._element_actors_query(ast.And(exprs=conditions))
+
+ def _drop_off_actors_query(self, element: PathsV2ElementSelector) -> ast.SelectQuery | ast.SelectSetQuery:
+ conditions = self._element_condition(ELEMENT_KIND_DROP_OFF, self._required_step_index(element))
+ return self._element_actors_query(ast.And(exprs=conditions))
+
+ def _edge_actors_query(self, element: PathsV2ElementSelector) -> ast.SelectQuery | ast.SelectSetQuery:
+ """The positional edge set: actors transitioning source → target at exactly this step pair,
+ matching the displayed ribbon count. A missing endpoint means that column's other row, i.e.
+ any item outside the column's named node rows."""
+ internal_step_index = self._required_step_index(element)
+ conditions = self._element_condition(ELEMENT_KIND_EDGE, internal_step_index)
+ if element.source is not None:
+ conditions.append(parse_expr("element.3 = {item}", {"item": self._item_expr(element.source)}))
+ else:
+ conditions.append(
+ parse_expr(
+ "element.3 NOT IN {top_items}",
+ {"top_items": self._top_node_items_at_step_query(internal_step_index)},
+ )
+ )
+ if element.target is not None:
+ conditions.append(parse_expr("element.4 = {item}", {"item": self._item_expr(element.target)}))
+ else:
+ conditions.append(
+ parse_expr(
+ "element.4 NOT IN {top_items}",
+ {"top_items": self._top_node_items_at_step_query(internal_step_index + 1)},
+ )
+ )
+ return self._element_actors_query(ast.And(exprs=conditions))
+
+ def _any_step_edge_actors_query(self, element: PathsV2ElementSelector) -> ast.SelectQuery | ast.SelectSetQuery:
+ """The position-free edge set: actors with a source → target transition anywhere in any of
+ their whole journeys. Whole journeys, not the trimmed ones, since this set must equal the
+ converted two-step funnel's, and the funnel has no notion of the display trim."""
+ if element.source is None or element.target is None:
+ raise ValidationError(
+ "An any-step edge element needs a named source and target item.", code="paths_v2_element_invalid"
+ )
+ if element.stepIndex is not None:
+ raise ValidationError(
+ "An any-step edge element cannot also pin a stepIndex.", code="paths_v2_element_invalid"
+ )
+ if self.is_anchored:
+ raise ValidationError(
+ "Any-step edge elements only exist in open mode; anchored segments convert as chains.",
+ code="paths_v2_element_invalid",
+ )
+ return parse_select(
+ """
+ SELECT actor_id
+ FROM {elements_per_actor_query}
+ WHERE arrayExists(
+ journey -> arrayExists(
+ (source_item, target_item) -> source_item = {source} AND target_item = {target},
+ arrayPopBack(journey),
+ arrayPopFront(journey)
+ ),
+ collapsed_journeys
+ )
+ GROUP BY actor_id
+ """,
+ placeholders={
+ "elements_per_actor_query": self._elements_per_actor_query(),
+ "source": self._item_expr(element.source),
+ "target": self._item_expr(element.target),
+ },
+ )
+
+ def _chain_actors_query(self, element: PathsV2ElementSelector) -> ast.SelectQuery | ast.SelectSetQuery:
+ """The chain set: actors whose anchored sequence begins with exactly the chain's items, the
+ same grouping `_anchored_prefix_counts_query` counts, so a chain modal equals its hover
+ preview count by construction."""
+ if not self.is_anchored:
+ raise ValidationError("Chain elements only exist in anchored mode.", code="paths_v2_element_invalid")
+ if not element.chain:
+ raise ValidationError("A chain element needs at least one path item.", code="paths_v2_element_invalid")
+ return parse_select(
+ """
+ SELECT actor_id
+ FROM {elements_per_actor_query}
+ WHERE arraySlice(arrayElement(trimmed_journeys, 1), 1, {chain_length}) = {chain_items}
+ GROUP BY actor_id
+ """,
+ placeholders={
+ "elements_per_actor_query": self._elements_per_actor_query(),
+ "chain_length": ast.Constant(value=len(element.chain)),
+ "chain_items": ast.Array(exprs=[self._item_expr(item) for item in element.chain]),
+ },
+ )
+
+ def to_actors_query(self, element: PathsV2ElementSelector) -> ast.SelectQuery | ast.SelectSetQuery:
+ """One actor query for every journey grid element. It rebuilds the same per-actor journeys
+ the grid was aggregated from and returns the unique actors behind the selected element, so
+ each persons modal equals its displayed number by construction."""
+ if element.elementType == PathsV2ElementType.NODE:
+ return self._node_actors_query(element)
+ if element.elementType == PathsV2ElementType.OTHER:
+ return self._other_actors_query(element)
+ if element.elementType == PathsV2ElementType.DROP_OFF:
+ return self._drop_off_actors_query(element)
+ if element.elementType == PathsV2ElementType.EDGE:
+ if element.anyStep:
+ return self._any_step_edge_actors_query(element)
+ return self._edge_actors_query(element)
+ if element.elementType == PathsV2ElementType.CHAIN:
+ return self._chain_actors_query(element)
+ raise ValidationError( # pragma: no cover - the schema enum is exhaustive
+ f"Unknown element type {element.elementType!r}.", code="paths_v2_element_invalid"
+ )
+
+ def _any_step_edge_counts_query(
+ self, pairs: list[tuple[PathsV2Item, PathsV2Item]]
+ ) -> ast.SelectQuery | ast.SelectSetQuery:
+ """Position-free unique-actor counts for the displayed named edges, over whole journeys:
+ the modal's "went source → target at any step" number, which the edge contract promises
+ equals the converted two-step funnel's count."""
+ pair_exprs: list[ast.Expr] = [
+ ast.Tuple(exprs=[self._item_expr(source), self._item_expr(target)]) for source, target in pairs
+ ]
+ query = parse_select(
+ """
+ SELECT pair.1 AS source_item, pair.2 AS target_item, uniqExact(actor_id) AS actor_count
+ FROM {elements_per_actor_query}
+ ARRAY JOIN arrayFilter(
+ pair -> pair IN {pairs},
+ arrayDistinct(arrayFlatten(arrayMap(
+ journey -> arrayZip(arrayPopBack(journey), arrayPopFront(journey)),
+ collapsed_journeys
+ )))
+ ) AS pair
+ GROUP BY pair
+ """,
+ placeholders={
+ "elements_per_actor_query": self._elements_per_actor_query(),
+ "pairs": ast.Tuple(exprs=pair_exprs),
+ },
+ )
+ assert isinstance(query, ast.SelectQuery)
+ # One row per requested pair, so the generic default LIMIT 100 can never silently drop the
+ # count for some of the displayed edges (a big grid asks for more than 100 pairs).
+ query.limit = ast.Constant(value=len(pairs))
+ return query
+
+ @staticmethod
+ def _pair_key(source: PathsV2Item, target: PathsV2Item) -> tuple[tuple[str, str | None], tuple[str, str | None]]:
+ return ((source.event, source.label), (target.event, target.label))
+
+ def _attach_any_step_counts(self, results: PathsV2Results) -> None:
+ """Open-mode edges between two named items carry the position-free count shown next to the
+ edge modal's positional set. One follow-up aggregation over the same journeys, restricted
+ to the pairs actually displayed."""
+ unique_pairs: list[tuple[PathsV2Item, PathsV2Item]] = []
+ seen: set[tuple[tuple[str, str | None], tuple[str, str | None]]] = set()
+ for edge in results.edges:
+ if edge.source is None or edge.target is None:
+ continue
+ key = self._pair_key(edge.source, edge.target)
+ if key not in seen:
+ seen.add(key)
+ unique_pairs.append((edge.source, edge.target))
+ if not unique_pairs:
+ return
+
+ count_response = self._execute(self._any_step_edge_counts_query(unique_pairs))
+ assert count_response.results is not None
+ counts: dict[tuple[tuple[str, str | None], tuple[str, str | None]], float] = {}
+ for source_tuple, target_tuple, actor_count in count_response.results:
+ source_item = self._to_path_item(source_tuple)
+ target_item = self._to_path_item(target_tuple)
+ # Displayed pairs always name real path items, never the other bucket.
+ assert source_item is not None and target_item is not None
+ counts[self._pair_key(source_item, target_item)] = actor_count
+
+ for edge in results.edges:
+ if edge.source is not None and edge.target is not None:
+ edge.anyStepCount = counts.get(self._pair_key(edge.source, edge.target))
+
+ def _to_path_item(self, item: tuple[str, str]) -> PathsV2Item | None:
+ event, label = item
+ if event == PATHS_V2_OTHER:
+ return None
+ for source in self.step_sources:
+ if source.event == event:
+ return PathsV2Item(event=event, label=label if source.namingProperty is not None else None)
+ return PathsV2Item(event=event, label=label)
+
+ def _to_prefixes(self, rows: list[tuple[Any, ...]]) -> list[PathsV2Prefix]:
+ prefixes: list[PathsV2Prefix] = []
+ for prefix_items, actor_count in rows:
+ items: list[PathsV2Item] = []
+ for raw_item in prefix_items:
+ item = self._to_path_item(raw_item)
+ # Raw sequence items always name a real path item, never the other bucket.
+ assert item is not None
+ items.append(item)
+ prefixes.append(PathsV2Prefix(items=items, count=actor_count))
+ return prefixes
+
+ @staticmethod
+ def _displayed_prefixes(steps: dict[int, PathsV2Step], prefixes: list[PathsV2Prefix]) -> list[PathsV2Prefix]:
+ """Only chains whose every item is a named row the grid renders at that position. Chains through
+ the other bucket never render (the hover preview skips them), and the serialized response must
+ not carry the bucketed labels: a shared insight hands raw results to viewers who cannot run
+ queries of their own, so labels the chart hides behind "Other" would leak there."""
+ displayed_items = {
+ (step_index, row.item.event, row.item.label) for step_index, step in steps.items() for row in step.rows
+ }
+ return [
+ prefix
+ for prefix in prefixes
+ if all((position, item.event, item.label) in displayed_items for position, item in enumerate(prefix.items))
+ ]
+
+ def _to_results(self, rows: list[tuple[Any, ...]], prefixes: list[PathsV2Prefix]) -> PathsV2Results:
+ steps: dict[int, PathsV2Step] = {}
+ edges: list[PathsV2Edge] = []
+
+ def step_for(one_based_index: int) -> PathsV2Step:
+ step_index = one_based_index - 1
+ if step_index not in steps:
+ steps[step_index] = PathsV2Step(stepIndex=step_index, rows=[], otherCount=0, dropOffCount=0)
+ return steps[step_index]
+
+ for kind, step_index, source_item, target_item, actor_count in rows:
+ if kind == ELEMENT_KIND_DROP_OFF:
+ step_for(step_index).dropOffCount = actor_count
+ elif kind == ELEMENT_KIND_NODE:
+ item = self._to_path_item(source_item)
+ if item is None:
+ step_for(step_index).otherCount = actor_count
+ else:
+ step_for(step_index).rows.append(PathsV2Row(item=item, count=actor_count))
+ elif kind == ELEMENT_KIND_EDGE:
+ edges.append(
+ PathsV2Edge(
+ stepIndex=step_index - 1,
+ source=self._to_path_item(source_item),
+ target=self._to_path_item(target_item),
+ count=actor_count,
+ )
+ )
+
+ def item_sort_key(item: PathsV2Item | None) -> tuple[bool, str, str]:
+ # The other bucket (None) sorts after named items.
+ if item is None:
+ return (True, "", "")
+ return (False, item.event, item.label or "")
+
+ for step in steps.values():
+ step.rows.sort(key=lambda row: (-row.count, row.item.event, row.item.label or ""))
+ edges.sort(
+ key=lambda edge: (edge.stepIndex, -edge.count, item_sort_key(edge.source), item_sort_key(edge.target))
+ )
+
+ return PathsV2Results(
+ steps=[steps[index] for index in sorted(steps)],
+ edges=edges,
+ prefixes=self._displayed_prefixes(steps, prefixes),
+ )
+
+ def _execute(self, query: ast.SelectQuery | ast.SelectSetQuery) -> Any:
+ return execute_hogql_query(
+ query_type="PathsV2Query",
+ query=query,
+ team=self.team,
+ user=self.user,
+ timings=self.timings,
+ modifiers=self.modifiers,
+ limit_context=self.limit_context,
+ settings=HogQLGlobalSettings(
+ # Same spill-to-disk guard funnels use, since per-actor event arrays are unbounded
+ max_bytes_before_external_group_by=MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY
+ ),
+ )
+
+ def _calculate(self) -> PathsV2QueryResponse:
+ query = self.to_query()
+ # Display-only response HogQL (never executed); bypass warehouse ACL so printing doesn't fail closed userless.
+ hogql = to_printed_hogql(query, self.team, bypass_warehouse_access_control=True)
+
+ response = self._execute(query)
+ assert response.results is not None
+
+ prefixes: list[PathsV2Prefix] = []
+ if self.is_anchored:
+ # A second aggregation over the same anchored sequences: the grid carries positional
+ # counts, this carries the per-chain counts the hover preview reads.
+ prefix_response = self._execute(self._anchored_prefix_counts_query())
+ assert prefix_response.results is not None
+ prefixes = self._to_prefixes(prefix_response.results)
+
+ results = self._to_results(response.results, prefixes)
+ if not self.is_anchored:
+ self._attach_any_step_counts(results)
+
+ return PathsV2QueryResponse(
+ results=results,
+ timings=response.timings,
+ hogql=hogql,
+ modifiers=self.modifiers,
+ resolved_date_range=ResolvedDateRangeResponse(
+ date_from=self.query_date_range.date_from(),
+ date_to=self.query_date_range.date_to(),
+ ),
+ )
diff --git a/products/product_analytics/backend/hogql_queries/paths_v2/test/__init__.py b/products/product_analytics/backend/hogql_queries/paths_v2/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/product_analytics/backend/hogql_queries/paths_v2/test/__snapshots__/test_paths_v2_query_runner.ambr b/products/product_analytics/backend/hogql_queries/paths_v2/test/__snapshots__/test_paths_v2_query_runner.ambr
new file mode 100644
index 000000000000..68c567873914
--- /dev/null
+++ b/products/product_analytics/backend/hogql_queries/paths_v2/test/__snapshots__/test_paths_v2_query_runner.ambr
@@ -0,0 +1,135 @@
+# serializer version: 1
+# name: TestPathsV2QueryRunner.test_default_pageview_preset_snapshot
+ '''
+ SELECT kind AS kind,
+ step_index AS step_index,
+ multiIf(ifNull(equals(kind, 'dropoff'), 0), item, equals(source_is_top, 1), item, tuple('$$__posthog_other__$$', '')) AS source_item,
+ multiIf(ifNull(notEquals(kind, 'edge'), 1), target_item, equals(target_is_top, 1), target_item, tuple('$$__posthog_other__$$', '')) AS grouped_target_item,
+ uniqExactMerge(actor_state) AS actor_count
+ FROM
+ (SELECT kind AS kind,
+ step_index AS step_index,
+ item AS item,
+ target_item AS target_item,
+ actor_state AS actor_state,
+ max(if(and(ifNull(equals(kind, 'node'), 0), lessOrEquals(row_rank, 3)), 1, 0)) OVER (PARTITION BY step_index, item) AS source_is_top,
+ max(if(and(ifNull(equals(kind, 'node'), 0), lessOrEquals(row_rank, 3)), 1, 0)) OVER (PARTITION BY if(ifNull(equals(kind, 'edge'), 0), plus(step_index, 1), step_index), if(ifNull(equals(kind, 'edge'), 0), target_item, item)) AS target_is_top
+ FROM
+ (SELECT kind AS kind,
+ step_index AS step_index,
+ item AS item,
+ target_item AS target_item,
+ actor_count AS actor_count,
+ actor_state AS actor_state,
+ row_number() OVER (PARTITION BY kind, step_index
+ ORDER BY actor_count DESC, (item).1 ASC, (item).2 ASC) AS row_rank
+ FROM
+ (SELECT element.1 AS kind,
+ element.2 AS step_index,
+ element.3 AS item,
+ element.4 AS target_item,
+ uniqExact(actor_id) AS actor_count,
+ uniqExactState(actor_id) AS actor_state
+ FROM
+ (SELECT actor_id AS actor_id,
+ arraySort(x -> x.1, groupArray(tuple(timestamp, path_item))) AS event_tuples,
+ arrayPopBack(arrayPushFront(arrayMap(x -> x.1, event_tuples), NULL)) AS previous_timestamps,
+ arraySplit((x, previous_timestamp) -> ifNull(ifNull(greater(x.1, plus(previous_timestamp, toIntervalSecond(1800))), 0), 1), event_tuples, previous_timestamps) AS journeys,
+ arrayMap(journey -> arrayMap(event_tuple -> event_tuple.2, journey), journeys) AS journey_items,
+ arrayMap(journey -> arrayFilter((item, i) -> or(ifNull(equals(i, 1), 0), ifNull(notEquals(item, journey[minus(i, 1)]), isNotNull(item)
+ or isNotNull(journey[minus(i, 1)]))), journey, arrayEnumerate(journey)), journey_items) AS collapsed_journeys,
+ arrayMap(journey -> arraySlice(journey, 1, 5), collapsed_journeys) AS trimmed_journeys,
+ arrayFlatten(arrayMap(journey -> arrayMap((item, i) -> tuple('node', i, item, tuple('', '')), journey, arrayEnumerate(journey)), trimmed_journeys)) AS node_elements,
+ arrayFlatten(arrayMap(journey -> arrayMap((pair, i) -> tuple('edge', i, pair.1, pair.2), arrayZip(arrayPopBack(journey), arrayPopFront(journey)), arrayEnumerate(arrayZip(arrayPopBack(journey), arrayPopFront(journey)))), trimmed_journeys)) AS edge_elements,
+ arrayMap(journey_length -> tuple('dropoff', journey_length, tuple('', ''), tuple('', '')), arrayFilter(journey_length -> ifNull(lessOrEquals(journey_length, 5), 0), arrayMap(journey -> length(journey), collapsed_journeys))) AS drop_off_elements,
+ arrayConcat(node_elements, edge_elements, drop_off_elements) AS elements
+ FROM
+ (SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS actor_id,
+ tuple(events.event, ifNull(multiIf(equals(events.event, '$pageview'), toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$pathname'), ''), 'null'), '^"|"$', '')), NULL), '')) AS path_item
+ FROM events
+ 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 events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2023-03-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2023-03-31 23:59:59', 'UTC'))), in(events.event, ['$pageview'])))
+ GROUP BY actor_id) ARRAY
+ JOIN elements AS element
+ GROUP BY kind,
+ step_index,
+ item,
+ target_item)))
+ GROUP BY kind,
+ step_index,
+ source_item,
+ grouped_target_item
+ ORDER BY kind ASC,
+ step_index ASC,
+ actor_count DESC,
+ source_item ASC,
+ grouped_target_item ASC
+ LIMIT 89 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=23622320128,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestPathsV2QueryRunner.test_default_pageview_preset_snapshot.1
+ '''
+ SELECT pair.1 AS source_item,
+ pair.2 AS target_item,
+ uniqExact(actor_id) AS actor_count
+ FROM
+ (SELECT actor_id AS actor_id,
+ arraySort(x -> x.1, groupArray(tuple(timestamp, path_item))) AS event_tuples,
+ arrayPopBack(arrayPushFront(arrayMap(x -> x.1, event_tuples), NULL)) AS previous_timestamps,
+ arraySplit((x, previous_timestamp) -> ifNull(ifNull(greater(x.1, plus(previous_timestamp, toIntervalSecond(1800))), 0), 1), event_tuples, previous_timestamps) AS journeys,
+ arrayMap(journey -> arrayMap(event_tuple -> event_tuple.2, journey), journeys) AS journey_items,
+ arrayMap(journey -> arrayFilter((item, i) -> or(ifNull(equals(i, 1), 0), ifNull(notEquals(item, journey[minus(i, 1)]), isNotNull(item)
+ or isNotNull(journey[minus(i, 1)]))), journey, arrayEnumerate(journey)), journey_items) AS collapsed_journeys,
+ arrayMap(journey -> arraySlice(journey, 1, 5), collapsed_journeys) AS trimmed_journeys,
+ arrayFlatten(arrayMap(journey -> arrayMap((item, i) -> tuple('node', i, item, tuple('', '')), journey, arrayEnumerate(journey)), trimmed_journeys)) AS node_elements,
+ arrayFlatten(arrayMap(journey -> arrayMap((pair, i) -> tuple('edge', i, pair.1, pair.2), arrayZip(arrayPopBack(journey), arrayPopFront(journey)), arrayEnumerate(arrayZip(arrayPopBack(journey), arrayPopFront(journey)))), trimmed_journeys)) AS edge_elements,
+ arrayMap(journey_length -> tuple('dropoff', journey_length, tuple('', ''), tuple('', '')), arrayFilter(journey_length -> ifNull(lessOrEquals(journey_length, 5), 0), arrayMap(journey -> length(journey), collapsed_journeys))) AS drop_off_elements,
+ arrayConcat(node_elements, edge_elements, drop_off_elements) AS elements
+ FROM
+ (SELECT toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS actor_id,
+ tuple(events.event, ifNull(multiIf(equals(events.event, '$pageview'), toString(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$pathname'), ''), 'null'), '^"|"$', '')), NULL), '')) AS path_item
+ FROM events
+ 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 events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 99999), greaterOrEquals(events.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2023-03-01 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2023-03-31 23:59:59', 'UTC'))), in(events.event, ['$pageview'])))
+ GROUP BY actor_id) ARRAY
+ JOIN arrayFilter(pair -> in(pair, tuple(tuple(tuple('$pageview', '/'), tuple('$pageview', '/pricing')))), arrayDistinct(arrayFlatten(arrayMap(journey -> arrayZip(arrayPopBack(journey), arrayPopFront(journey)), collapsed_journeys)))) AS pair
+ GROUP BY pair
+ LIMIT 1 SETTINGS readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=23622320128,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
diff --git a/products/product_analytics/backend/hogql_queries/paths_v2/test/test_funnel_converter.py b/products/product_analytics/backend/hogql_queries/paths_v2/test/test_funnel_converter.py
new file mode 100644
index 000000000000..08bf39c16b57
--- /dev/null
+++ b/products/product_analytics/backend/hogql_queries/paths_v2/test/test_funnel_converter.py
@@ -0,0 +1,568 @@
+from datetime import datetime, timedelta
+from typing import Any
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+from parameterized import parameterized
+from rest_framework.exceptions import ValidationError
+
+from posthog.schema import (
+ DateRange,
+ EventPropertyFilter,
+ EventsNode,
+ FunnelConversionWindowTimeUnit,
+ FunnelExclusionEventsNode,
+ HogQLPropertyFilter,
+ PathCleaningFilter,
+ PathsV2Anchor,
+ PathsV2AnchorType,
+ PathsV2Filter,
+ PathsV2Item,
+ PathsV2Query,
+ PathsV2StepSource,
+ PropertyOperator,
+ StepOrderValue,
+)
+
+from posthog.hogql_queries.insights.funnels.funnels_query_runner import FunnelsQueryRunner
+from posthog.test.test_journeys import journeys_for
+
+from products.product_analytics.backend.hogql_queries.paths_v2.funnel_converter import (
+ anchored_segment_to_funnels_query,
+ edge_to_funnels_query,
+ segment_to_funnels_query,
+)
+from products.product_analytics.backend.hogql_queries.paths_v2.paths_v2_query_runner import PathsV2QueryRunner
+
+DATE_RANGE = DateRange(date_from="2023-03-01", date_to="2023-03-31")
+
+
+def _sources(*events: str) -> list[PathsV2StepSource]:
+ return [PathsV2StepSource(event=event) for event in events]
+
+
+def _timeline(*events: str, start: str = "2023-03-10 10:00:00", step_minutes: int = 5) -> list[dict[str, Any]]:
+ start_dt = datetime.fromisoformat(start)
+ return [
+ {
+ "event": event,
+ "timestamp": (start_dt + timedelta(minutes=i * step_minutes)).strftime("%Y-%m-%d %H:%M:%S"),
+ }
+ for i, event in enumerate(events)
+ ]
+
+
+def _item(event: str, label: str | None = None) -> PathsV2Item:
+ return PathsV2Item(event=event, label=label)
+
+
+SIMPLE_SOURCES = _sources("a", "b", "c")
+
+# Each case pins the edge contract for one journey shape via two assertions on shared fixtures:
+# - the converted funnel reproduces the hand-derived POSITION-FREE count: unique actors with any
+# untrimmed journey where the target is the next included path item after the source;
+# - the runner's displayed edges stay POSITIONAL: one (stepIndex, count) row per step at which
+# the pair occurs.
+# Where the pair occurs at exactly one step the two numbers coincide; multi_step_pair and
+# trim_skew are the cases where they deliberately differ.
+# Tuple shape: (name, events_by_person, filter_overrides, source, target,
+# expected position-free funnel count, expected positional edge rows).
+EDGE_CONTRACT_CASES: list[
+ tuple[str, dict[str, Any], dict[str, Any], PathsV2Item, PathsV2Item, int, list[tuple[int, int]]]
+] = [
+ (
+ "simple_edge",
+ # p1 and p2 each have b as the next item after a; p3 goes to c instead.
+ {"p1": _timeline("a", "b"), "p2": _timeline("a", "b"), "p3": _timeline("a", "c")},
+ {},
+ _item("a"),
+ _item("b"),
+ 2,
+ [(0, 2)],
+ ),
+ (
+ "loop_revisit",
+ # b is followed by a once, at the journey's second position only.
+ {"p1": _timeline("a", "b", "a", "b")},
+ {},
+ _item("b"),
+ _item("a"),
+ 1,
+ [(1, 1)],
+ ),
+ (
+ "collapse_on_repeated_source",
+ # The repeated a re-anchors the funnel exactly like collapse merges the repeat.
+ {"p1": _timeline("a", "a", "b")},
+ {},
+ _item("a"),
+ _item("b"),
+ 1,
+ [(0, 1)],
+ ),
+ (
+ "collapse_off_self_edge",
+ # p2's intervening c breaks the self-edge on both sides.
+ {"p1": _timeline("a", "a", "b"), "p2": _timeline("a", "c", "a")},
+ {"collapseRepeats": False},
+ _item("a"),
+ _item("a"),
+ 1,
+ [(0, 1)],
+ ),
+ (
+ "gap_boundary",
+ # p1 sits exactly on the gap G, p2 one second beyond it; both engines must draw the same line.
+ {
+ "p1": [
+ {"event": "a", "timestamp": "2023-03-10 10:00:00"},
+ {"event": "b", "timestamp": "2023-03-10 10:30:00"},
+ ],
+ "p2": [
+ {"event": "a", "timestamp": "2023-03-11 10:00:00"},
+ {"event": "b", "timestamp": "2023-03-11 10:30:01"},
+ ],
+ },
+ {},
+ _item("a"),
+ _item("b"),
+ 1,
+ [(0, 1)],
+ ),
+ (
+ "intervening_included_item",
+ # p2's c is an included path item between a and b, so the edge and the funnel's
+ # item-strict exclusion must both drop p2.
+ {"p1": _timeline("a", "b"), "p2": _timeline("a", "c", "b")},
+ {},
+ _item("a"),
+ _item("b"),
+ 1,
+ [(0, 1)],
+ ),
+ (
+ "exclusion_reanchors",
+ # After the intervening c, the second a re-anchors: the edge exists (at the third
+ # position) and the funnel must count the actor rather than dropping them for the
+ # earlier exclusion.
+ {"p1": _timeline("a", "c", "a", "b")},
+ {},
+ _item("a"),
+ _item("b"),
+ 1,
+ [(2, 1)],
+ ),
+ (
+ "multiple_journeys_same_edge",
+ {
+ "p1": [
+ *_timeline("a", "b"),
+ *_timeline("a", "b", start="2023-03-10 14:00:00"),
+ ]
+ },
+ {},
+ _item("a"),
+ _item("b"),
+ 1,
+ [(0, 1)],
+ ),
+ (
+ "date_range_clipped_journey",
+ {
+ "p1": [
+ {"event": "a", "timestamp": "2023-02-28 23:50:00"},
+ {"event": "b", "timestamp": "2023-03-01 00:05:00"},
+ {"event": "c", "timestamp": "2023-03-01 00:10:00"},
+ ]
+ },
+ {},
+ _item("b"),
+ _item("c"),
+ 1,
+ [(0, 1)],
+ ),
+ (
+ "multi_step_pair",
+ # a is followed by b at step 0 for p1 and at step 1 for p2: the displayed grid keeps one
+ # positional row per step (1 actor each), while the position-free funnel counts the
+ # union of both actor sets.
+ {"p1": _timeline("a", "b"), "p2": _timeline("c", "a", "b")},
+ {},
+ _item("a"),
+ _item("b"),
+ 2,
+ [(0, 1), (1, 1)],
+ ),
+ (
+ "trim_skew",
+ # p1's only a-to-b adjacency sits beyond the maxSteps trim, so no a-to-b edge is
+ # displayed at all; the funnel still counts the actor because the contract is over
+ # untrimmed journeys and the trim is display-only.
+ {"p1": _timeline("x", "y", "a", "b")},
+ {"maxSteps": 2, "stepSources": _sources("x", "y", "a", "b")},
+ _item("a"),
+ _item("b"),
+ 1,
+ [],
+ ),
+]
+
+
+class TestPathsV2EdgeContract(ClickhouseTestMixin, APIBaseTest):
+ maxDiff = None
+
+ def _edge_rows(self, query: PathsV2Query, source: PathsV2Item, target: PathsV2Item) -> list[tuple[int, float]]:
+ results = PathsV2QueryRunner(query=query, team=self.team).calculate().results
+ return [
+ (edge.stepIndex, edge.count) for edge in results.edges if edge.source == source and edge.target == target
+ ]
+
+ def _funnel_count(self, query: PathsV2Query, source: PathsV2Item, target: PathsV2Item) -> float:
+ funnels_query = edge_to_funnels_query(query, self.team, source, target)
+ results = FunnelsQueryRunner(query=funnels_query, team=self.team).calculate().results
+ return results[1]["count"]
+
+ @parameterized.expand(EDGE_CONTRACT_CASES)
+ def test_funnel_counts_position_free_pairs(
+ self,
+ _name: str,
+ events_by_person: dict[str, list[dict[str, Any]]],
+ filter_overrides: dict[str, Any],
+ source: PathsV2Item,
+ target: PathsV2Item,
+ expected_funnel_count: int,
+ expected_edge_rows: list[tuple[int, int]],
+ ):
+ journeys_for(team=self.team, events_by_person=events_by_person)
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(**{"stepSources": SIMPLE_SOURCES, **filter_overrides}),
+ )
+
+ self.assertEqual(self._funnel_count(query, source, target), expected_funnel_count)
+ self.assertEqual(self._edge_rows(query, source, target), expected_edge_rows)
+
+ def test_naming_property_edge_matches_funnel(self):
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ "p1": [
+ {"event": "signup", "timestamp": "2023-03-10 10:00:00"},
+ {"event": "stage changed", "timestamp": "2023-03-10 10:05:00", "properties": {"stage": "lead"}},
+ ],
+ "p2": [
+ {"event": "signup", "timestamp": "2023-03-10 10:00:00"},
+ {"event": "stage changed", "timestamp": "2023-03-10 10:05:00", "properties": {"stage": "won"}},
+ ],
+ "p3": [
+ {"event": "signup", "timestamp": "2023-03-10 10:00:00"},
+ {"event": "stage changed", "timestamp": "2023-03-10 10:05:00", "properties": {"stage": "won"}},
+ {"event": "stage changed", "timestamp": "2023-03-10 10:10:00", "properties": {"stage": "lead"}},
+ ],
+ },
+ )
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(
+ stepSources=[
+ PathsV2StepSource(event="signup"),
+ PathsV2StepSource(event="stage changed", namingProperty="stage"),
+ ]
+ ),
+ )
+ source, target = _item("signup"), _item("stage changed", label="lead")
+
+ # Only p1 moves from signup straight to the lead stage; p3's won stage is an included item
+ # in between, which the funnel must exclude via the label-derived item.
+ self.assertEqual(self._funnel_count(query, source, target), 1)
+ self.assertEqual(self._edge_rows(query, source, target), [(0, 1)])
+
+ def test_path_cleaning_edge_matches_funnel(self):
+ self.team.path_cleaning_filters = [{"alias": "/item/<id>", "regex": r"/item/\d+"}]
+ self.team.save()
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ "p1": [
+ {"event": "$pageview", "timestamp": "2023-03-10 10:00:00", "properties": {"$pathname": "/item/1"}},
+ {"event": "$pageview", "timestamp": "2023-03-10 10:05:00", "properties": {"$pathname": "/about"}},
+ ],
+ "p2": [
+ {"event": "$pageview", "timestamp": "2023-03-10 10:00:00", "properties": {"$pathname": "/item/2"}},
+ {"event": "$pageview", "timestamp": "2023-03-10 10:05:00", "properties": {"$pathname": "/about"}},
+ ],
+ },
+ )
+ query = PathsV2Query(dateRange=DATE_RANGE)
+ source, target = _item("$pageview", label="/item/<id>"), _item("$pageview", label="/about")
+
+ # Both raw URLs clean into the same item, so the funnel's label filter must apply the
+ # same cleaning to match either of them.
+ self.assertEqual(self._funnel_count(query, source, target), 2)
+ self.assertEqual(self._edge_rows(query, source, target), [(0, 2)])
+
+ def test_excluded_items_edge_matches_funnel(self) -> None:
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ "p1": _timeline("a", "x", "b"),
+ "p2": _timeline("a", "b"),
+ "p3": _timeline("a", "c"),
+ },
+ )
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(stepSources=_sources("a", "b", "c", "x"), excludedItems=[_item("x")]),
+ )
+ source, target = _item("a"), _item("b")
+
+ # With x excluded, p1's intervening x is invisible on both sides: the paths runner bridges
+ # a -> b and the funnel's item-strict universe must not count x as a breaking event.
+ self.assertEqual(self._funnel_count(query, source, target), 2)
+ self.assertEqual(self._edge_rows(query, source, target), [(0, 2)])
+
+ def test_local_cleaning_edge_matches_funnel(self) -> None:
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ "p1": [
+ {"event": "$pageview", "timestamp": "2023-03-10 10:00:00", "properties": {"$pathname": "/item/1"}},
+ {"event": "$pageview", "timestamp": "2023-03-10 10:05:00", "properties": {"$pathname": "/about"}},
+ ],
+ "p2": [
+ {"event": "$pageview", "timestamp": "2023-03-10 10:00:00", "properties": {"$pathname": "/item/2"}},
+ {"event": "$pageview", "timestamp": "2023-03-10 10:05:00", "properties": {"$pathname": "/about"}},
+ ],
+ },
+ )
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(
+ localPathCleaningFilters=[PathCleaningFilter(alias="/item/<id>", regex=r"/item/\d+")]
+ ),
+ )
+ source, target = _item("$pageview", label="/item/<id>"), _item("$pageview", label="/about")
+
+ # Insight-local rules, with no team rules at all: the funnel's label filter must clean with
+ # the query's own rules, not just the team's.
+ self.assertEqual(self._funnel_count(query, source, target), 2)
+ self.assertEqual(self._edge_rows(query, source, target), [(0, 2)])
+
+ def test_property_filters_apply_to_both_sides(self):
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ "p1": [
+ {"event": "a", "timestamp": "2023-03-10 10:00:00", "properties": {"plan": "paid"}},
+ {"event": "b", "timestamp": "2023-03-10 10:05:00", "properties": {"plan": "paid"}},
+ ],
+ "p2": [
+ {"event": "a", "timestamp": "2023-03-10 10:00:00", "properties": {"plan": "free"}},
+ {"event": "b", "timestamp": "2023-03-10 10:05:00", "properties": {"plan": "free"}},
+ ],
+ },
+ )
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ properties=[EventPropertyFilter(key="plan", value="paid", operator=PropertyOperator.EXACT)],
+ pathsV2Filter=PathsV2Filter(stepSources=SIMPLE_SOURCES),
+ )
+ source, target = _item("a"), _item("b")
+
+ self.assertEqual(self._funnel_count(query, source, target), 1)
+ self.assertEqual(self._edge_rows(query, source, target), [(0, 1)])
+
+ def test_month_gap_uses_fixed_31_days_in_both_engines(self):
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ # 30-day gap: within the fixed 31-day month but beyond the calendar month
+ # (Feb 1 plus one month is Mar 1), so calendar INTERVAL arithmetic on either
+ # side would split the journey or fail the conversion.
+ "p1": [
+ {"event": "a", "timestamp": "2025-02-01 10:00:00"},
+ {"event": "b", "timestamp": "2025-03-03 10:00:00"},
+ ],
+ # 32-day gap: beyond the fixed 31 days, so both engines must drop it.
+ "p2": [
+ {"event": "a", "timestamp": "2025-02-01 10:00:00"},
+ {"event": "b", "timestamp": "2025-03-05 10:00:00"},
+ ],
+ },
+ )
+ query = PathsV2Query(
+ dateRange=DateRange(date_from="2025-02-01", date_to="2025-03-31"),
+ pathsV2Filter=PathsV2Filter(
+ stepSources=SIMPLE_SOURCES,
+ gapInterval=1,
+ gapIntervalUnit=FunnelConversionWindowTimeUnit.MONTH,
+ ),
+ )
+ source, target = _item("a"), _item("b")
+
+ # Both engines realize a one-month gap as DATERANGE_MAP's fixed 31 days
+ # (conversion_window_to_seconds), never as calendar months.
+ self.assertEqual(self._funnel_count(query, source, target), 1)
+ self.assertEqual(self._edge_rows(query, source, target), [(0, 1)])
+
+
+class TestEdgeToFunnelsQuery(APIBaseTest):
+ def test_converted_funnel_shape(self):
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ filterTestAccounts=True,
+ properties=[EventPropertyFilter(key="plan", value="paid", operator=PropertyOperator.EXACT)],
+ pathsV2Filter=PathsV2Filter(
+ stepSources=[
+ PathsV2StepSource(event="signup"),
+ PathsV2StepSource(event="stage changed", namingProperty="stage"),
+ ],
+ gapInterval=2,
+ gapIntervalUnit=FunnelConversionWindowTimeUnit.HOUR,
+ ),
+ )
+
+ funnels_query = edge_to_funnels_query(query, self.team, _item("signup"), _item("stage changed", label="lead"))
+
+ assert isinstance(funnels_query.series[0], EventsNode)
+ assert isinstance(funnels_query.series[1], EventsNode)
+ self.assertEqual(funnels_query.series[0].event, "signup")
+ self.assertIsNone(funnels_query.series[0].properties)
+ self.assertEqual(funnels_query.series[1].event, "stage changed")
+ assert funnels_query.series[1].properties is not None
+ label_filter = funnels_query.series[1].properties[0]
+ assert isinstance(label_filter, HogQLPropertyFilter)
+ self.assertEqual(label_filter.key, "equals(ifNull(toString(properties.stage), ''), 'lead')")
+
+ assert funnels_query.funnelsFilter is not None
+ self.assertEqual(funnels_query.funnelsFilter.funnelWindowInterval, 2)
+ self.assertEqual(funnels_query.funnelsFilter.funnelWindowIntervalUnit, FunnelConversionWindowTimeUnit.HOUR)
+ self.assertEqual(funnels_query.funnelsFilter.funnelOrderType, StepOrderValue.ORDERED)
+
+ assert funnels_query.funnelsFilter.exclusions is not None
+ exclusion = funnels_query.funnelsFilter.exclusions[0]
+ assert isinstance(exclusion, FunnelExclusionEventsNode)
+ self.assertIsNone(exclusion.event)
+ self.assertEqual(exclusion.funnelFromStep, 0)
+ self.assertEqual(exclusion.funnelToStep, 1)
+ assert exclusion.properties is not None
+ universe_filter = exclusion.properties[0]
+ assert isinstance(universe_filter, HogQLPropertyFilter)
+ self.assertIn("in(event, ['signup', 'stage changed'])", universe_filter.key)
+ self.assertIn("tuple('signup', '')", universe_filter.key)
+ self.assertIn("tuple('stage changed', 'lead')", universe_filter.key)
+ self.assertIn("toString(properties.stage)", universe_filter.key)
+
+ self.assertEqual(funnels_query.dateRange, query.dateRange)
+ self.assertEqual(funnels_query.properties, query.properties)
+ self.assertEqual(funnels_query.filterTestAccounts, True)
+
+ def test_rejects_item_without_step_source(self):
+ query = PathsV2Query(pathsV2Filter=PathsV2Filter(stepSources=_sources("a")))
+ with self.assertRaises(ValidationError):
+ edge_to_funnels_query(query, self.team, _item("a"), _item("unknown"))
+
+ def test_segment_funnel_shape(self):
+ query = PathsV2Query(dateRange=DATE_RANGE, pathsV2Filter=PathsV2Filter(stepSources=SIMPLE_SOURCES))
+
+ funnels_query = segment_to_funnels_query(
+ query,
+ self.team,
+ [_item("a"), _item("b"), _item("c")],
+ 15,
+ FunnelConversionWindowTimeUnit.MINUTE,
+ )
+
+ events = []
+ for step in funnels_query.series:
+ assert isinstance(step, EventsNode)
+ events.append(step.event)
+ self.assertEqual(events, ["a", "b", "c"])
+ assert funnels_query.funnelsFilter is not None
+ self.assertEqual(funnels_query.funnelsFilter.funnelWindowInterval, 15)
+ self.assertEqual(funnels_query.funnelsFilter.funnelOrderType, StepOrderValue.ORDERED)
+
+ assert funnels_query.funnelsFilter.exclusions is not None
+ exclusion = funnels_query.funnelsFilter.exclusions[0]
+ assert isinstance(exclusion, FunnelExclusionEventsNode)
+ # The exclusion spans every step, so an intervening included item anywhere in the chain drops it.
+ self.assertEqual(exclusion.funnelFromStep, 0)
+ self.assertEqual(exclusion.funnelToStep, 2)
+ assert exclusion.properties is not None
+ universe_filter = exclusion.properties[0]
+ assert isinstance(universe_filter, HogQLPropertyFilter)
+ self.assertIn("tuple('a', '')", universe_filter.key)
+ self.assertIn("tuple('b', '')", universe_filter.key)
+ self.assertIn("tuple('c', '')", universe_filter.key)
+
+ def test_anchored_segment_reads_window_from_query(self):
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(
+ stepSources=SIMPLE_SOURCES,
+ conversionWindowInterval=2,
+ conversionWindowIntervalUnit=FunnelConversionWindowTimeUnit.HOUR,
+ ),
+ )
+
+ funnels_query = anchored_segment_to_funnels_query(query, self.team, [_item("a"), _item("b")])
+
+ assert funnels_query.funnelsFilter is not None
+ self.assertEqual(funnels_query.funnelsFilter.funnelWindowInterval, 2)
+ self.assertEqual(funnels_query.funnelsFilter.funnelWindowIntervalUnit, FunnelConversionWindowTimeUnit.HOUR)
+
+ def test_segment_requires_two_items(self):
+ query = PathsV2Query(pathsV2Filter=PathsV2Filter(stepSources=SIMPLE_SOURCES))
+ with self.assertRaises(ValueError):
+ segment_to_funnels_query(query, self.team, [_item("a")], 30, FunnelConversionWindowTimeUnit.MINUTE)
+
+
+ANCHORED_SEGMENT_CASES: list[tuple[str, list[PathsV2Item], int]] = [
+ # Segment items in funnel (forward-time) order; expected count is both the displayed chain's prefix
+ # count and the plain funnel's count — the anchored contract holds when the two agree.
+ ("edge", [_item("a"), _item("b")], 4),
+ ("three_step", [_item("a"), _item("b"), _item("c")], 2),
+ ("revisit", [_item("a"), _item("b"), _item("a")], 1),
+]
+
+
+class TestPathsV2AnchoredSegmentContract(ClickhouseTestMixin, APIBaseTest):
+ maxDiff = None
+
+ def _query(self) -> PathsV2Query:
+ return PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(
+ stepSources=SIMPLE_SOURCES, anchor=PathsV2Anchor(type=PathsV2AnchorType.START, item=_item("a"))
+ ),
+ )
+
+ def _prefix_count(self, query: PathsV2Query, chain: list[PathsV2Item]) -> float:
+ results = PathsV2QueryRunner(query=query, team=self.team).calculate().results
+ wanted = [(item.event, item.label) for item in chain]
+ for prefix in results.prefixes:
+ if [(item.event, item.label) for item in prefix.items] == wanted:
+ return prefix.count
+ return 0
+
+ def _funnel_count(self, query: PathsV2Query, chain: list[PathsV2Item]) -> float:
+ funnels_query = anchored_segment_to_funnels_query(query, self.team, list(chain))
+ results = FunnelsQueryRunner(query=funnels_query, team=self.team).calculate().results
+ return results[len(chain) - 1]["count"]
+
+ @parameterized.expand(ANCHORED_SEGMENT_CASES)
+ def test_anchored_segment_equals_plain_funnel(self, _name: str, chain: list[PathsV2Item], expected: int):
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ "p1": _timeline("a", "b", "c"),
+ "p2": _timeline("a", "b"),
+ "p3": _timeline("a", "b", "c"),
+ "p4": _timeline("a", "b", "a"),
+ },
+ )
+ query = self._query()
+
+ # The displayed anchored chain and the plain funnel with window W count the same actors.
+ self.assertEqual(self._prefix_count(query, chain), expected)
+ self.assertEqual(self._funnel_count(query, chain), expected)
diff --git a/products/product_analytics/backend/hogql_queries/paths_v2/test/test_paths_v2_actors.py b/products/product_analytics/backend/hogql_queries/paths_v2/test/test_paths_v2_actors.py
new file mode 100644
index 000000000000..7569109c67a5
--- /dev/null
+++ b/products/product_analytics/backend/hogql_queries/paths_v2/test/test_paths_v2_actors.py
@@ -0,0 +1,475 @@
+from datetime import datetime, timedelta
+from typing import Any
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin
+
+from parameterized import parameterized
+from rest_framework.exceptions import ValidationError
+
+from posthog.schema import (
+ ActorsQuery,
+ DateRange,
+ FunnelsActorsQuery,
+ FunnelsQuery,
+ PathsV2ActorsQuery,
+ PathsV2Anchor,
+ PathsV2AnchorType,
+ PathsV2ElementSelector,
+ PathsV2ElementType,
+ PathsV2Filter,
+ PathsV2Item,
+ PathsV2Query,
+ PathsV2StepSource,
+)
+
+from posthog.hogql_queries.actors_query_runner import ActorsQueryRunner
+from posthog.hogql_queries.insights.insight_actors_query_runner import InsightActorsQueryRunner
+from posthog.models.person import Person
+from posthog.test.test_journeys import journeys_for
+
+from products.product_analytics.backend.hogql_queries.paths_v2.funnel_converter import (
+ anchored_segment_to_funnels_query,
+ edge_to_funnels_query,
+)
+from products.product_analytics.backend.hogql_queries.paths_v2.paths_v2_query_runner import PathsV2QueryRunner
+
+DATE_RANGE = DateRange(date_from="2023-03-01", date_to="2023-03-31")
+
+
+def _sources(*events: str) -> list[PathsV2StepSource]:
+ return [PathsV2StepSource(event=event) for event in events]
+
+
+def _timeline(
+ distinct_id: str, *events: str, start: str = "2023-03-10 10:00:00", step_minutes: int = 5
+) -> dict[str, list[dict[str, Any]]]:
+ start_dt = datetime.fromisoformat(start)
+ return {
+ distinct_id: [
+ {
+ "event": event,
+ "timestamp": (start_dt + timedelta(minutes=i * step_minutes)).strftime("%Y-%m-%d %H:%M:%S"),
+ }
+ for i, event in enumerate(events)
+ ]
+ }
+
+
+def _item(event: str, label: str | None = None) -> PathsV2Item:
+ return PathsV2Item(event=event, label=label)
+
+
+def _node(step_index: int, item: PathsV2Item) -> PathsV2ElementSelector:
+ return PathsV2ElementSelector(elementType=PathsV2ElementType.NODE, stepIndex=step_index, item=item)
+
+
+def _other(step_index: int) -> PathsV2ElementSelector:
+ return PathsV2ElementSelector(elementType=PathsV2ElementType.OTHER, stepIndex=step_index)
+
+
+def _drop_off(step_index: int) -> PathsV2ElementSelector:
+ return PathsV2ElementSelector(elementType=PathsV2ElementType.DROP_OFF, stepIndex=step_index)
+
+
+def _edge(step_index: int, source: PathsV2Item | None, target: PathsV2Item | None) -> PathsV2ElementSelector:
+ return PathsV2ElementSelector(
+ elementType=PathsV2ElementType.EDGE, stepIndex=step_index, source=source, target=target
+ )
+
+
+def _any_step_edge(source: PathsV2Item, target: PathsV2Item) -> PathsV2ElementSelector:
+ return PathsV2ElementSelector(elementType=PathsV2ElementType.EDGE, anyStep=True, source=source, target=target)
+
+
+def _chain(items: list[PathsV2Item]) -> PathsV2ElementSelector:
+ return PathsV2ElementSelector(elementType=PathsV2ElementType.CHAIN, chain=items)
+
+
+class PathsV2ActorsTestBase(ClickhouseTestMixin, APIBaseTest):
+ persons: dict[str, Person] = {}
+
+ def _names_for(self, query: PathsV2Query, element: PathsV2ElementSelector) -> set[str]:
+ response = InsightActorsQueryRunner(
+ query=PathsV2ActorsQuery(source=query, element=element), team=self.team
+ ).calculate()
+ assert response.results is not None
+ names_by_uuid = {person.uuid: name for name, person in self.persons.items()}
+ return {names_by_uuid[row[0]] for row in response.results}
+
+ def _funnel_actor_names(self, funnels_query: FunnelsQuery, funnel_step: int) -> set[str]:
+ actors_query = ActorsQuery(
+ source=FunnelsActorsQuery(source=funnels_query, funnelStep=funnel_step), select=["id"]
+ )
+ response = ActorsQueryRunner(query=actors_query, team=self.team).calculate()
+ names_by_uuid = {person.uuid: name for name, person in self.persons.items()}
+ return {names_by_uuid[row[0]] for row in response.results}
+
+ def _displayed_elements(self, query: PathsV2Query) -> tuple[dict[Any, float], dict[Any, set[str]]]:
+ """Every element the grid displays, keyed the same way twice: the count shown on it, and the
+ actor set its modal returns. Comparing the two dicts is the by-construction contract, with no
+ expected numbers written down — it holds for any fixture, in either chart mode."""
+ results = PathsV2QueryRunner(query=query, team=self.team).calculate().results
+ displayed_counts: dict[Any, float] = {}
+ actor_sets: dict[Any, set[str]] = {}
+ key: tuple[Any, ...]
+ for step in results.steps:
+ for row in step.rows:
+ key = ("node", step.stepIndex, row.item.event)
+ displayed_counts[key] = row.count
+ actor_sets[key] = self._names_for(query, _node(step.stepIndex, row.item))
+ if step.otherCount:
+ key = ("other", step.stepIndex)
+ displayed_counts[key] = step.otherCount
+ actor_sets[key] = self._names_for(query, _other(step.stepIndex))
+ if step.dropOffCount:
+ key = ("dropOff", step.stepIndex)
+ displayed_counts[key] = step.dropOffCount
+ actor_sets[key] = self._names_for(query, _drop_off(step.stepIndex))
+ for edge in results.edges:
+ key = ("edge", edge.stepIndex, edge.source and edge.source.event, edge.target and edge.target.event)
+ displayed_counts[key] = edge.count
+ actor_sets[key] = self._names_for(query, _edge(edge.stepIndex, edge.source, edge.target))
+ return displayed_counts, actor_sets
+
+
+class TestPathsV2ActorsElements(PathsV2ActorsTestBase):
+ maxDiff = None
+
+ def test_open_mode_every_displayed_element_equals_its_actor_set(self):
+ # A grid with named rows, a bucketed other row (e ties with d at step 2; d wins the
+ # name-ascending tie-break), drop-offs at every column, edges into and out of the other
+ # row, and one actor (p5) with two journeys to exercise per-element dedup.
+ self.persons = journeys_for(
+ team=self.team,
+ events_by_person={
+ **_timeline("p1", "a", "b", "c"),
+ **_timeline("p2", "a", "b", "d"),
+ **_timeline("p3", "a", "d", "c"),
+ **_timeline("p4", "d"),
+ "p5": [
+ *_timeline("p5", "a", "b")["p5"],
+ *_timeline("p5", "a", "e", "c", start="2023-03-10 14:00:00")["p5"],
+ ],
+ },
+ )
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(stepSources=_sources("a", "b", "c", "d", "e"), maxSteps=3, maxRowsPerStep=2),
+ )
+ displayed_counts, actor_sets = self._displayed_elements(query)
+
+ self.assertEqual(
+ actor_sets,
+ {
+ ("node", 0, "a"): {"p1", "p2", "p3", "p5"},
+ ("node", 0, "d"): {"p4"},
+ ("node", 1, "b"): {"p1", "p2", "p5"},
+ ("node", 1, "d"): {"p3"},
+ ("other", 1): {"p5"},
+ ("node", 2, "c"): {"p1", "p3", "p5"},
+ ("node", 2, "d"): {"p2"},
+ ("dropOff", 0): {"p4"},
+ ("dropOff", 1): {"p5"},
+ ("dropOff", 2): {"p1", "p2", "p3", "p5"},
+ ("edge", 0, "a", "b"): {"p1", "p2", "p5"},
+ ("edge", 0, "a", "d"): {"p3"},
+ ("edge", 0, "a", None): {"p5"},
+ ("edge", 1, "b", "c"): {"p1"},
+ ("edge", 1, "b", "d"): {"p2"},
+ ("edge", 1, "d", "c"): {"p3"},
+ ("edge", 1, None, "c"): {"p5"},
+ },
+ )
+ # Every modal equals the number on its element, for every element the grid displays.
+ self.assertEqual(displayed_counts, {key: len(names) for key, names in actor_sets.items()})
+
+ def test_edges_between_two_other_rows_equal_their_actor_sets(self):
+ # With one named row per step, p3's journey runs other → other: the only positional-edge
+ # shape where neither endpoint names a path item.
+ self.persons = journeys_for(
+ team=self.team,
+ events_by_person={
+ **_timeline("p1", "a", "b"),
+ **_timeline("p2", "a", "b"),
+ **_timeline("p3", "c", "d"),
+ },
+ )
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(stepSources=_sources("a", "b", "c", "d"), maxRowsPerStep=1),
+ )
+
+ displayed_counts, actor_sets = self._displayed_elements(query)
+
+ self.assertEqual(actor_sets[("edge", 0, None, None)], {"p3"})
+ self.assertEqual(displayed_counts, {key: len(names) for key, names in actor_sets.items()})
+
+ def test_collapse_off_every_displayed_element_equals_its_actor_set(self):
+ # Collapse off swaps the collapsed journeys for the raw ones in every aggregation stage, so
+ # immediate repeats become their own steps. Count and actor set must move together.
+ self.persons = journeys_for(
+ team=self.team,
+ events_by_person={
+ **_timeline("p1", "a", "a", "b"),
+ **_timeline("p2", "a", "b", "b"),
+ },
+ )
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(stepSources=_sources("a", "b"), collapseRepeats=False),
+ )
+
+ displayed_counts, actor_sets = self._displayed_elements(query)
+
+ self.assertGreater(len(displayed_counts), 4)
+ self.assertEqual(displayed_counts, {key: len(names) for key, names in actor_sets.items()})
+
+ def test_any_step_count_is_set_exactly_on_open_mode_named_edges(self):
+ self.persons = journeys_for(
+ team=self.team,
+ events_by_person={**_timeline("p1", "a", "b"), **_timeline("p5", "a", "e", "c")},
+ )
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(stepSources=_sources("a", "b", "c", "e"), maxRowsPerStep=1),
+ )
+ results = PathsV2QueryRunner(query=query, team=self.team).calculate().results
+
+ by_key = {
+ (edge.stepIndex, edge.source and edge.source.event, edge.target and edge.target.event): edge
+ for edge in results.edges
+ }
+ # a is the only named row at step 1; b and e tie at step 2 where b wins, bucketing e.
+ self.assertEqual(by_key[(0, "a", "b")].anyStepCount, 1)
+ self.assertIsNone(by_key[(0, "a", None)].anyStepCount)
+
+
+class TestPathsV2EdgeContractActorSets(PathsV2ActorsTestBase):
+ maxDiff = None
+
+ def test_any_step_edge_set_equals_funnel_actor_set(self):
+ # q3's a → b pair sits beyond the three-step display trim, so it is invisible to every
+ # positional edge but must count for the any-step set: the converted funnel knows no trim.
+ self.persons = journeys_for(
+ team=self.team,
+ events_by_person={
+ **_timeline("q1", "x", "a", "b"),
+ **_timeline("q2", "a", "b"),
+ **_timeline("q3", "w", "x", "a", "b"),
+ },
+ )
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(stepSources=_sources("w", "x", "a", "b"), maxSteps=3),
+ )
+ source, target = _item("a"), _item("b")
+
+ any_step_names = self._names_for(query, _any_step_edge(source, target))
+ funnel_names = self._funnel_actor_names(edge_to_funnels_query(query, self.team, source, target), funnel_step=2)
+ self.assertEqual(any_step_names, {"q1", "q2", "q3"})
+ self.assertEqual(any_step_names, funnel_names)
+
+ results = PathsV2QueryRunner(query=query, team=self.team).calculate().results
+ positional = {
+ (edge.stepIndex,): self._names_for(query, _edge(edge.stepIndex, edge.source, edge.target))
+ for edge in results.edges
+ if edge.source == source and edge.target == target
+ }
+ self.assertEqual(positional, {(0,): {"q2"}, (1,): {"q1"}})
+ for edge in results.edges:
+ if edge.source == source and edge.target == target:
+ self.assertEqual(edge.anyStepCount, 3)
+
+
+class TestPathsV2AnchoredChainActorSets(PathsV2ActorsTestBase):
+ maxDiff = None
+
+ def _query(self) -> PathsV2Query:
+ return PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(
+ stepSources=_sources("home", "cart", "checkout", "browse"),
+ anchor=PathsV2Anchor(type=PathsV2AnchorType.START, item=_item("home")),
+ ),
+ )
+
+ def _seed(self) -> None:
+ self.persons = journeys_for(
+ team=self.team,
+ events_by_person={
+ **_timeline("r1", "home", "cart", "checkout"),
+ **_timeline("r2", "home", "cart"),
+ **_timeline("r3", "home", "browse", "checkout"),
+ **_timeline("r4", "browse", "checkout"),
+ },
+ )
+
+ @parameterized.expand(
+ [
+ ("two_step_chain", ["home", "cart"], {"r1", "r2"}),
+ ("three_step_chain", ["home", "cart", "checkout"], {"r1"}),
+ ]
+ )
+ def test_chain_set_equals_prefix_count_and_funnel_actor_set(
+ self, _name: str, chain_events: list[str], expected_names: set[str]
+ ):
+ self._seed()
+ query = self._query()
+ chain = [_item(event) for event in chain_events]
+
+ chain_names = self._names_for(query, _chain(chain))
+ self.assertEqual(chain_names, expected_names)
+
+ results = PathsV2QueryRunner(query=query, team=self.team).calculate().results
+ prefix_counts = {tuple(item.event for item in prefix.items): prefix.count for prefix in results.prefixes}
+ self.assertEqual(prefix_counts[tuple(chain_events)], len(chain_names))
+
+ funnel_names = self._funnel_actor_names(
+ anchored_segment_to_funnels_query(query, self.team, list(chain)), funnel_step=len(chain)
+ )
+ self.assertEqual(chain_names, funnel_names)
+
+ def test_default_node_set_is_the_union_across_chains(self):
+ # The default card shows the merged union count; the hovered chain narrows it. Both
+ # states must resolve to their own displayed number's set.
+ self._seed()
+ query = self._query()
+
+ union_names = self._names_for(query, _node(2, _item("checkout")))
+ self.assertEqual(union_names, {"r1", "r3"})
+ chain_names = self._names_for(query, _chain([_item("home"), _item("cart"), _item("checkout")]))
+ self.assertEqual(chain_names, {"r1"})
+
+ def test_anchored_edges_carry_no_any_step_count(self):
+ self._seed()
+ results = PathsV2QueryRunner(query=self._query(), team=self.team).calculate().results
+ self.assertTrue(len(results.edges) > 0)
+ self.assertEqual({edge.anyStepCount for edge in results.edges}, {None})
+
+ @parameterized.expand(
+ [("start_anchor", PathsV2AnchorType.START, "home"), ("end_anchor", PathsV2AnchorType.END, "checkout")]
+ )
+ def test_every_displayed_element_equals_its_actor_set(
+ self, _name: str, anchor_type: PathsV2AnchorType, anchor_event: str
+ ) -> None:
+ # The open-mode contract, repeated for both anchor directions. An end anchor reverses each
+ # actor's sequence, so step 0 is the anchor and the grid reads backward in time; the
+ # modal-equals-count promise has to survive that reversal too.
+ self._seed()
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(
+ stepSources=_sources("home", "cart", "checkout", "browse"),
+ anchor=PathsV2Anchor(type=anchor_type, item=_item(anchor_event)),
+ ),
+ )
+
+ displayed_counts, actor_sets = self._displayed_elements(query)
+
+ # Guards the equality below against silently passing on an empty grid
+ self.assertGreater(len(displayed_counts), 4)
+ self.assertEqual(displayed_counts, {key: len(names) for key, names in actor_sets.items()})
+
+ def test_every_carried_prefix_equals_its_chain_actor_set(self):
+ # Every carried prefix is a hover preview the user can land on, so each re-labelled card's
+ # number must equal the set its click opens.
+ self._seed()
+ query = self._query()
+ results = PathsV2QueryRunner(query=query, team=self.team).calculate().results
+
+ self.assertGreater(len(results.prefixes), 0)
+ self.assertEqual(
+ {tuple(item.event for item in prefix.items): prefix.count for prefix in results.prefixes},
+ {
+ tuple(item.event for item in prefix.items): len(self._names_for(query, _chain(list(prefix.items))))
+ for prefix in results.prefixes
+ },
+ )
+
+
+class TestPathsV2ActorsValidation(APIBaseTest):
+ def _runner(self, anchored: bool = False) -> PathsV2QueryRunner:
+ paths_filter = PathsV2Filter(stepSources=_sources("a", "b"))
+ if anchored:
+ paths_filter.anchor = PathsV2Anchor(type=PathsV2AnchorType.START, item=_item("a"))
+ return PathsV2QueryRunner(query=PathsV2Query(dateRange=DATE_RANGE, pathsV2Filter=paths_filter), team=self.team)
+
+ @parameterized.expand(
+ [
+ ("node_without_item", False, PathsV2ElementSelector(elementType=PathsV2ElementType.NODE, stepIndex=0)),
+ (
+ "node_without_step_index",
+ False,
+ PathsV2ElementSelector(elementType=PathsV2ElementType.NODE, item=_item("a")),
+ ),
+ ("other_without_step_index", False, PathsV2ElementSelector(elementType=PathsV2ElementType.OTHER)),
+ ("drop_off_without_step_index", False, PathsV2ElementSelector(elementType=PathsV2ElementType.DROP_OFF)),
+ (
+ "positional_edge_without_step_index",
+ False,
+ PathsV2ElementSelector(elementType=PathsV2ElementType.EDGE, source=_item("a"), target=_item("b")),
+ ),
+ (
+ "any_step_edge_without_named_target",
+ False,
+ PathsV2ElementSelector(elementType=PathsV2ElementType.EDGE, anyStep=True, source=_item("a")),
+ ),
+ (
+ "any_step_edge_with_pinned_step",
+ False,
+ PathsV2ElementSelector(
+ elementType=PathsV2ElementType.EDGE,
+ anyStep=True,
+ stepIndex=0,
+ source=_item("a"),
+ target=_item("b"),
+ ),
+ ),
+ (
+ "any_step_edge_in_anchored_mode",
+ True,
+ PathsV2ElementSelector(
+ elementType=PathsV2ElementType.EDGE, anyStep=True, source=_item("a"), target=_item("b")
+ ),
+ ),
+ (
+ "chain_in_open_mode",
+ False,
+ PathsV2ElementSelector(elementType=PathsV2ElementType.CHAIN, chain=[_item("a")]),
+ ),
+ ("empty_chain", True, PathsV2ElementSelector(elementType=PathsV2ElementType.CHAIN, chain=[])),
+ ]
+ )
+ def test_invalid_element_selectors_reject(
+ self, _name: str, anchored: bool, element: PathsV2ElementSelector
+ ) -> None:
+ with self.assertRaises(ValidationError):
+ self._runner(anchored=anchored).to_actors_query(element)
+
+
+class TestPathsV2ActorsQueryAPI(ClickhouseTestMixin, APIBaseTest):
+ def test_modal_actors_query_round_trips_through_the_query_api(self):
+ persons = journeys_for(team=self.team, events_by_person=_timeline("p1", "a", "b"))
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/query/",
+ {
+ "query": {
+ "kind": "ActorsQuery",
+ "select": ["id"],
+ "source": {
+ "kind": "PathsV2ActorsQuery",
+ "source": {
+ "kind": "PathsV2Query",
+ "dateRange": {"date_from": "2023-03-01", "date_to": "2023-03-31"},
+ "pathsV2Filter": {"stepSources": [{"event": "a"}, {"event": "b"}]},
+ },
+ "element": {"elementType": "node", "stepIndex": 0, "item": {"event": "a"}},
+ },
+ }
+ },
+ )
+
+ self.assertEqual(response.status_code, 200, response.json())
+ results = response.json()["results"]
+ self.assertEqual([row[0] for row in results], [str(persons["p1"].uuid)])
diff --git a/products/product_analytics/backend/hogql_queries/paths_v2/test/test_paths_v2_query_runner.py b/products/product_analytics/backend/hogql_queries/paths_v2/test/test_paths_v2_query_runner.py
new file mode 100644
index 000000000000..e9ac3ac65b97
--- /dev/null
+++ b/products/product_analytics/backend/hogql_queries/paths_v2/test/test_paths_v2_query_runner.py
@@ -0,0 +1,966 @@
+from datetime import datetime, timedelta
+from typing import Any
+
+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, snapshot_clickhouse_queries
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from pydantic import ValidationError as PydanticValidationError
+from rest_framework.exceptions import ValidationError
+
+from posthog.schema import (
+ DateRange,
+ FunnelConversionWindowTimeUnit,
+ PathCleaningFilter,
+ PathsV2Anchor,
+ PathsV2AnchorType,
+ PathsV2Filter,
+ PathsV2Item,
+ PathsV2Query,
+ PathsV2Row,
+ PathsV2StepSource,
+)
+
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.test.test_journeys import journeys_for
+
+from products.product_analytics.backend.hogql_queries.paths_v2.path_item import resolve_step_sources
+from products.product_analytics.backend.hogql_queries.paths_v2.paths_v2_query_runner import PathsV2QueryRunner
+
+DATE_RANGE = DateRange(date_from="2023-03-01", date_to="2023-03-31")
+
+
+def _sources(*events: str) -> list[PathsV2StepSource]:
+ return [PathsV2StepSource(event=event) for event in events]
+
+
+def _timeline(
+ distinct_id: str, *events: str, start: str = "2023-03-10 10:00:00", step_minutes: int = 5
+) -> dict[str, list[dict[str, Any]]]:
+ start_dt = datetime.fromisoformat(start)
+ return {
+ distinct_id: [
+ {
+ "event": event,
+ "timestamp": (start_dt + timedelta(minutes=i * step_minutes)).strftime("%Y-%m-%d %H:%M:%S"),
+ }
+ for i, event in enumerate(events)
+ ]
+ }
+
+
+def _item(event: str, label: str | None = None) -> PathsV2Item:
+ return PathsV2Item(event=event, label=label)
+
+
+def _row(event: str, count: float, label: str | None = None) -> PathsV2Row:
+ return PathsV2Row(item=_item(event, label), count=count)
+
+
+def _edge(
+ step_index: int, source: PathsV2Item | None, target: PathsV2Item | None, count: float
+) -> tuple[int, PathsV2Item | None, PathsV2Item | None, float]:
+ return (step_index, source, target, count)
+
+
+class TestPathsV2FilterConstraints(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("max_steps_below_min", {"maxSteps": 1}),
+ ("max_steps_above_max", {"maxSteps": 21}),
+ ("max_rows_below_min", {"maxRowsPerStep": 0}),
+ ("max_rows_above_max", {"maxRowsPerStep": 11}),
+ ("step_sources_empty", {"stepSources": []}),
+ ("step_sources_above_max", {"stepSources": [PathsV2StepSource(event=f"e{i}") for i in range(21)]}),
+ ("excluded_items_above_max", {"excludedItems": [PathsV2Item(event=f"e{i}") for i in range(101)]}),
+ ]
+ )
+ def test_out_of_bounds_config_rejects(self, _name: str, kwargs: dict[str, Any]) -> None:
+ with self.assertRaises(PydanticValidationError):
+ PathsV2Filter(**kwargs)
+
+ def test_defaults(self) -> None:
+ paths_filter = PathsV2Filter()
+ self.assertEqual(paths_filter.maxSteps, 5)
+ self.assertEqual(paths_filter.maxRowsPerStep, 3)
+ self.assertEqual(paths_filter.gapInterval, 30)
+ self.assertEqual(paths_filter.gapIntervalUnit, FunnelConversionWindowTimeUnit.MINUTE)
+ self.assertEqual(paths_filter.collapseRepeats, True)
+ self.assertEqual(paths_filter.conversionWindowInterval, 30)
+ self.assertEqual(paths_filter.conversionWindowIntervalUnit, FunnelConversionWindowTimeUnit.MINUTE)
+ self.assertEqual(paths_filter.applyTeamPathCleaning, True)
+ self.assertIsNone(paths_filter.stepSources)
+ self.assertIsNone(paths_filter.anchor)
+ self.assertIsNone(paths_filter.excludedItems)
+ self.assertIsNone(paths_filter.localPathCleaningFilters)
+
+ def test_absent_step_sources_resolve_to_pageviews_preset(self) -> None:
+ # Saved queries may omit stepSources; the frontend preset picker mirrors this default,
+ # so a backend change here would silently relabel them.
+ self.assertEqual(
+ resolve_step_sources(PathsV2Query()),
+ [PathsV2StepSource(event="$pageview", namingProperty="$pathname")],
+ )
+
+
+class TestPathsV2Validation(ClickhouseTestMixin, APIBaseTest):
+ def _runner(self, paths_filter: PathsV2Filter) -> PathsV2QueryRunner:
+ return PathsV2QueryRunner(query=PathsV2Query(pathsV2Filter=paths_filter), team=self.team)
+
+ @parameterized.expand(
+ [
+ ("second_above_max", 3601, FunnelConversionWindowTimeUnit.SECOND),
+ ("minute_above_max", 1441, FunnelConversionWindowTimeUnit.MINUTE),
+ ("hour_above_max", 25, FunnelConversionWindowTimeUnit.HOUR),
+ ("day_above_max", 366, FunnelConversionWindowTimeUnit.DAY),
+ ("week_above_max", 54, FunnelConversionWindowTimeUnit.WEEK),
+ ("month_above_max", 13, FunnelConversionWindowTimeUnit.MONTH),
+ ("minute_below_min", 0, FunnelConversionWindowTimeUnit.MINUTE),
+ ]
+ )
+ def test_out_of_bounds_gap_rejects(self, _name: str, interval: int, unit: FunnelConversionWindowTimeUnit) -> None:
+ runner = self._runner(PathsV2Filter(gapInterval=interval, gapIntervalUnit=unit))
+ with self.assertRaisesMessage(ValidationError, "gapInterval"):
+ runner.validate()
+
+ @parameterized.expand(
+ [
+ ("second_max", 3600, FunnelConversionWindowTimeUnit.SECOND),
+ ("minute_max", 1440, FunnelConversionWindowTimeUnit.MINUTE),
+ ("day_min", 1, FunnelConversionWindowTimeUnit.DAY),
+ ]
+ )
+ def test_gap_bounds_are_inclusive(self, _name: str, interval: int, unit: FunnelConversionWindowTimeUnit) -> None:
+ self._runner(PathsV2Filter(gapInterval=interval, gapIntervalUnit=unit)).validate()
+
+ @parameterized.expand(
+ [
+ ("duplicate_events", _sources("a", "a")),
+ ("empty_event", _sources("")),
+ ]
+ )
+ def test_invalid_step_sources_reject(self, _name: str, sources: list[PathsV2StepSource]) -> None:
+ runner = self._runner(PathsV2Filter(stepSources=sources))
+ with self.assertRaisesMessage(ValidationError, "stepSources"):
+ runner.validate()
+
+ @parameterized.expand(
+ [
+ ("second_above_max", 3601, FunnelConversionWindowTimeUnit.SECOND),
+ ("minute_above_max", 1441, FunnelConversionWindowTimeUnit.MINUTE),
+ ("day_above_max", 366, FunnelConversionWindowTimeUnit.DAY),
+ ("minute_below_min", 0, FunnelConversionWindowTimeUnit.MINUTE),
+ ]
+ )
+ def test_out_of_bounds_window_rejects(
+ self, _name: str, interval: int, unit: FunnelConversionWindowTimeUnit
+ ) -> None:
+ runner = self._runner(PathsV2Filter(conversionWindowInterval=interval, conversionWindowIntervalUnit=unit))
+ with self.assertRaisesMessage(ValidationError, "conversionWindowInterval"):
+ runner.validate()
+
+ def test_window_bounds_are_inclusive(self) -> None:
+ self._runner(
+ PathsV2Filter(
+ conversionWindowInterval=1440, conversionWindowIntervalUnit=FunnelConversionWindowTimeUnit.MINUTE
+ )
+ ).validate()
+
+ def test_anchor_event_must_be_a_step_source(self) -> None:
+ runner = self._runner(
+ PathsV2Filter(
+ stepSources=_sources("a", "b"),
+ anchor=PathsV2Anchor(type=PathsV2AnchorType.START, item=PathsV2Item(event="missing")),
+ )
+ )
+ with self.assertRaisesMessage(ValidationError, "must be one of the step sources"):
+ runner.validate()
+
+ @parameterized.expand(
+ [
+ ("event_only", PathsV2Item(event="a")),
+ # A spurious label on a source without a naming property must not hide that the query
+ # anchors on (event, ''), which is the excluded item.
+ ("spurious_anchor_label", PathsV2Item(event="a", label="x")),
+ ]
+ )
+ def test_excluding_the_anchor_rejects(self, _name: str, anchor_item: PathsV2Item) -> None:
+ runner = self._runner(
+ PathsV2Filter(
+ stepSources=_sources("a", "b"),
+ anchor=PathsV2Anchor(type=PathsV2AnchorType.START, item=anchor_item),
+ excludedItems=[PathsV2Item(event="a")],
+ )
+ )
+ with self.assertRaisesMessage(ValidationError, "anchor"):
+ runner.validate()
+
+ @parameterized.expand(
+ [
+ # Editing step sources must not invalidate a saved exclude list; this exclusion is inert.
+ ("non_source_event", _sources("a"), [PathsV2Item(event="gone")]),
+ # A label-less exclusion of a naming-property source pins the item whose property is missing.
+ (
+ "label_less_on_naming_source",
+ [PathsV2StepSource(event="$pageview", namingProperty="$pathname")],
+ [PathsV2Item(event="$pageview")],
+ ),
+ ]
+ )
+ def test_permissive_exclusions_are_allowed(
+ self, _name: str, sources: list[PathsV2StepSource], excluded: list[PathsV2Item]
+ ) -> None:
+ self._runner(PathsV2Filter(stepSources=sources, excludedItems=excluded)).validate()
+
+ def test_anchor_on_naming_property_source_needs_a_label(self) -> None:
+ runner = self._runner(
+ PathsV2Filter(
+ stepSources=[PathsV2StepSource(event="$pageview", namingProperty="$pathname")],
+ anchor=PathsV2Anchor(type=PathsV2AnchorType.START, item=PathsV2Item(event="$pageview")),
+ )
+ )
+ with self.assertRaisesMessage(ValidationError, "needs a label"):
+ runner.validate()
+
+
+class TestPathsV2QueryRunner(ClickhouseTestMixin, APIBaseTest):
+ maxDiff = None
+
+ def _run(self, query: PathsV2Query) -> Any:
+ return PathsV2QueryRunner(query=query, team=self.team).calculate().results
+
+ def _steps(self, results: Any) -> list[tuple[int, list[PathsV2Row], float, float]]:
+ return [(step.stepIndex, step.rows, step.otherCount, step.dropOffCount) for step in results.steps]
+
+ def _edges(self, results: Any) -> list[tuple[int, PathsV2Item | None, PathsV2Item | None, float]]:
+ return [(edge.stepIndex, edge.source, edge.target, edge.count) for edge in results.edges]
+
+ def test_open_mode_journey_grid(self):
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ **_timeline("p1", "a", "b", "c", "d", "e"),
+ **_timeline("p2", "a", "s", "b", "c", "d", "e"),
+ **_timeline("p3", "a", "b", "c"),
+ **_timeline("p4", "a"),
+ },
+ )
+
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(stepSources=_sources("a", "b", "c", "d", "e", "s"), maxRowsPerStep=10),
+ )
+ results = self._run(query)
+
+ self.assertEqual(
+ self._steps(results),
+ [
+ (0, [_row("a", 4)], 0, 1),
+ (1, [_row("b", 2), _row("s", 1)], 0, 0),
+ (2, [_row("c", 2), _row("b", 1)], 0, 1),
+ (3, [_row("c", 1), _row("d", 1)], 0, 0),
+ (4, [_row("d", 1), _row("e", 1)], 0, 1),
+ ],
+ )
+ self.assertEqual(
+ self._edges(results),
+ [
+ _edge(0, _item("a"), _item("b"), 2),
+ _edge(0, _item("a"), _item("s"), 1),
+ _edge(1, _item("b"), _item("c"), 2),
+ _edge(1, _item("s"), _item("b"), 1),
+ _edge(2, _item("b"), _item("c"), 1),
+ _edge(2, _item("c"), _item("d"), 1),
+ _edge(3, _item("c"), _item("d"), 1),
+ _edge(3, _item("d"), _item("e"), 1),
+ ],
+ )
+
+ @parameterized.expand(
+ [
+ ("gap_of_exactly_g_stays_together", "2023-03-10 10:30:00", True),
+ ("gap_above_g_splits", "2023-03-10 10:30:01", False),
+ ]
+ )
+ def test_gap_boundary(self, _name: str, second_timestamp: str, same_journey: bool):
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ "p1": [
+ {"event": "a", "timestamp": "2023-03-10 10:00:00"},
+ {"event": "b", "timestamp": second_timestamp},
+ ]
+ },
+ )
+
+ query = PathsV2Query(dateRange=DATE_RANGE, pathsV2Filter=PathsV2Filter(stepSources=_sources("a", "b")))
+ results = self._run(query)
+
+ if same_journey:
+ self.assertEqual(
+ self._steps(results),
+ [(0, [_row("a", 1)], 0, 0), (1, [_row("b", 1)], 0, 1)],
+ )
+ self.assertEqual(self._edges(results), [_edge(0, _item("a"), _item("b"), 1)])
+ else:
+ # Two one-item journeys of the same actor: both start at the first step and both end
+ # there, so the actor still counts once per element.
+ self.assertEqual(
+ self._steps(results),
+ [(0, [_row("a", 1), _row("b", 1)], 0, 1)],
+ )
+ self.assertEqual(self._edges(results), [])
+
+ @parameterized.expand(
+ [
+ ("collapse_on", True),
+ ("collapse_off", False),
+ ]
+ )
+ def test_collapse_repeats(self, _name: str, collapse: bool):
+ journeys_for(team=self.team, events_by_person=_timeline("p1", "a", "a", "b"))
+
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(stepSources=_sources("a", "b"), collapseRepeats=collapse),
+ )
+ results = self._run(query)
+
+ if collapse:
+ self.assertEqual(
+ self._steps(results),
+ [(0, [_row("a", 1)], 0, 0), (1, [_row("b", 1)], 0, 1)],
+ )
+ self.assertEqual(self._edges(results), [_edge(0, _item("a"), _item("b"), 1)])
+ else:
+ self.assertEqual(
+ self._steps(results),
+ [(0, [_row("a", 1)], 0, 0), (1, [_row("a", 1)], 0, 0), (2, [_row("b", 1)], 0, 1)],
+ )
+ self.assertEqual(
+ self._edges(results),
+ [_edge(0, _item("a"), _item("a"), 1), _edge(1, _item("a"), _item("b"), 1)],
+ )
+
+ def test_unique_actor_dedup_across_journeys(self):
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ "p1": [
+ *_timeline("p1", "a", "b")["p1"],
+ *_timeline("p1", "a", "c", start="2023-03-10 14:00:00")["p1"],
+ ],
+ **_timeline("p2", "a", "b"),
+ },
+ )
+
+ query = PathsV2Query(dateRange=DATE_RANGE, pathsV2Filter=PathsV2Filter(stepSources=_sources("a", "b", "c")))
+ results = self._run(query)
+
+ # p1 touches (step 0, a) with both journeys but counts once; the edge a -> b counts p1 once
+ # alongside p2. Both of p1's journeys end at the second step, deduped into one drop-off.
+ self.assertEqual(
+ self._steps(results),
+ [
+ (0, [_row("a", 2)], 0, 0),
+ (1, [_row("b", 2), _row("c", 1)], 0, 2),
+ ],
+ )
+ self.assertEqual(
+ self._edges(results),
+ [_edge(0, _item("a"), _item("b"), 2), _edge(0, _item("a"), _item("c"), 1)],
+ )
+
+ def test_other_bucketing_dedups_actors(self):
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ **_timeline("p1", "x", "m1"),
+ "p2": [
+ *_timeline("p2", "x", "m2")["p2"],
+ *_timeline("p2", "x", "m3", start="2023-03-10 14:00:00")["p2"],
+ ],
+ **_timeline("p3", "x", "m1"),
+ },
+ )
+
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(stepSources=_sources("x", "m1", "m2", "m3"), maxRowsPerStep=1),
+ )
+ results = self._run(query)
+
+ # m2 and m3 fall beyond the top row at the second step. p2 touches both, so the other row
+ # counts p2 once, and so does the edge from x into the other bucket.
+ self.assertEqual(
+ self._steps(results),
+ [
+ (0, [_row("x", 3)], 0, 0),
+ (1, [_row("m1", 2)], 1, 3),
+ ],
+ )
+ self.assertEqual(
+ self._edges(results),
+ [
+ _edge(0, _item("x"), _item("m1"), 2),
+ _edge(0, _item("x"), None, 1),
+ ],
+ )
+
+ def test_date_range_clips_journeys(self):
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ "p1": [
+ {"event": "a", "timestamp": "2023-02-28 23:50:00"},
+ {"event": "b", "timestamp": "2023-03-01 00:05:00"},
+ {"event": "c", "timestamp": "2023-03-01 00:10:00"},
+ ]
+ },
+ )
+
+ query = PathsV2Query(dateRange=DATE_RANGE, pathsV2Filter=PathsV2Filter(stepSources=_sources("a", "b", "c")))
+ results = self._run(query)
+
+ # The pre-range event is invisible, so the journey starts at its first in-range item.
+ self.assertEqual(
+ self._steps(results),
+ [(0, [_row("b", 1)], 0, 0), (1, [_row("c", 1)], 0, 1)],
+ )
+ self.assertEqual(self._edges(results), [_edge(0, _item("b"), _item("c"), 1)])
+
+ def test_naming_property_sources(self):
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ "p1": [
+ {"event": "signup", "timestamp": "2023-03-10 10:00:00"},
+ {"event": "stage changed", "timestamp": "2023-03-10 10:05:00", "properties": {"stage": "lead"}},
+ {"event": "stage changed", "timestamp": "2023-03-10 10:10:00", "properties": {"stage": "won"}},
+ ],
+ "p2": [
+ {"event": "signup", "timestamp": "2023-03-10 10:00:00"},
+ {"event": "stage changed", "timestamp": "2023-03-10 10:05:00"},
+ ],
+ },
+ )
+
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(
+ stepSources=[
+ PathsV2StepSource(event="signup"),
+ PathsV2StepSource(event="stage changed", namingProperty="stage"),
+ ]
+ ),
+ )
+ results = self._run(query)
+
+ # Consecutive events of the same source with different labels are distinct items; a missing
+ # naming property labels the item with an empty string; sources without a naming property
+ # have no label at all.
+ self.assertEqual(
+ self._steps(results),
+ [
+ (0, [_row("signup", 2)], 0, 0),
+ (1, [_row("stage changed", 1, label=""), _row("stage changed", 1, label="lead")], 0, 1),
+ (2, [_row("stage changed", 1, label="won")], 0, 1),
+ ],
+ )
+ self.assertEqual(
+ self._edges(results),
+ [
+ _edge(0, _item("signup"), _item("stage changed", label=""), 1),
+ _edge(0, _item("signup"), _item("stage changed", label="lead"), 1),
+ _edge(1, _item("stage changed", label="lead"), _item("stage changed", label="won"), 1),
+ ],
+ )
+
+ def test_path_cleaning_merges_items(self):
+ self.team.path_cleaning_filters = [{"alias": "/item/<id>", "regex": r"/item/\d+"}]
+ self.team.save()
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ "p1": [
+ {"event": "$pageview", "timestamp": "2023-03-10 10:00:00", "properties": {"$pathname": "/item/1"}},
+ {"event": "$pageview", "timestamp": "2023-03-10 10:05:00", "properties": {"$pathname": "/item/2"}},
+ {"event": "$pageview", "timestamp": "2023-03-10 10:10:00", "properties": {"$pathname": "/about"}},
+ ]
+ },
+ )
+
+ query = PathsV2Query(dateRange=DATE_RANGE)
+ results = self._run(query)
+
+ # Cleaning applies before collapse, so the two /item/<id> pageviews merge into one item.
+ self.assertEqual(
+ self._steps(results),
+ [
+ (0, [_row("$pageview", 1, label="/item/<id>")], 0, 0),
+ (1, [_row("$pageview", 1, label="/about")], 0, 1),
+ ],
+ )
+ self.assertEqual(
+ self._edges(results),
+ [_edge(0, _item("$pageview", label="/item/<id>"), _item("$pageview", label="/about"), 1)],
+ )
+
+ def test_excluded_items_drop_from_universe(self) -> None:
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ **_timeline("p1", "a", "x", "b"),
+ **_timeline("p2", "x"),
+ },
+ )
+
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(stepSources=_sources("a", "b", "x"), excludedItems=[_item("x")]),
+ )
+ results = self._run(query)
+
+ # Excluded events vanish from the universe before journeys are built: p1's journey bridges
+ # a -> b instead of splitting around x, and p2 has no journey at all. A display-level filter
+ # would drop the a -> x and x -> b edges without producing the bridged a -> b edge.
+ self.assertEqual(
+ self._steps(results),
+ [(0, [_row("a", 1)], 0, 0), (1, [_row("b", 1)], 0, 1)],
+ )
+ self.assertEqual(self._edges(results), [_edge(0, _item("a"), _item("b"), 1)])
+
+ def test_excluded_item_matches_the_label_not_the_event(self) -> None:
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ "p1": [
+ {"event": "$pageview", "timestamp": "2023-03-10 10:00:00", "properties": {"$pathname": "/home"}},
+ {"event": "$pageview", "timestamp": "2023-03-10 10:05:00", "properties": {"$pathname": "/login"}},
+ {"event": "$pageview", "timestamp": "2023-03-10 10:10:00", "properties": {"$pathname": "/app"}},
+ ]
+ },
+ )
+
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(excludedItems=[_item("$pageview", label="/login")]),
+ )
+ results = self._run(query)
+
+ # Only the (event, label) item is excluded; the source's other items stay.
+ self.assertEqual(
+ self._steps(results),
+ [
+ (0, [_row("$pageview", 1, label="/home")], 0, 0),
+ (1, [_row("$pageview", 1, label="/app")], 0, 1),
+ ],
+ )
+ self.assertEqual(
+ self._edges(results),
+ [_edge(0, _item("$pageview", label="/home"), _item("$pageview", label="/app"), 1)],
+ )
+
+ def test_local_path_cleaning_applies_after_team_rules(self) -> None:
+ self.team.path_cleaning_filters = [{"alias": "/item/:id", "regex": r"/item/\d+"}]
+ self.team.save()
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ "p1": [
+ {"event": "$pageview", "timestamp": "2023-03-10 10:00:00", "properties": {"$pathname": "/item/1"}},
+ {"event": "$pageview", "timestamp": "2023-03-10 10:05:00", "properties": {"$pathname": "/about"}},
+ ]
+ },
+ )
+
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(localPathCleaningFilters=[PathCleaningFilter(alias="<id>", regex=":id")]),
+ )
+ results = self._run(query)
+
+ # The local rule's regex only matches the team rule's output, so this label proves both that
+ # local rules apply and that they run after the team's.
+ self.assertEqual(
+ self._steps(results),
+ [
+ (0, [_row("$pageview", 1, label="/item/<id>")], 0, 0),
+ (1, [_row("$pageview", 1, label="/about")], 0, 1),
+ ],
+ )
+
+ def test_team_path_cleaning_can_be_disabled(self) -> None:
+ self.team.path_cleaning_filters = [{"alias": "/item/<id>", "regex": r"/item/\d+"}]
+ self.team.save()
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ "p1": [
+ {"event": "$pageview", "timestamp": "2023-03-10 10:00:00", "properties": {"$pathname": "/item/1"}},
+ {"event": "$pageview", "timestamp": "2023-03-10 10:05:00", "properties": {"$pathname": "/item/2"}},
+ ]
+ },
+ )
+
+ query = PathsV2Query(dateRange=DATE_RANGE, pathsV2Filter=PathsV2Filter(applyTeamPathCleaning=False))
+ results = self._run(query)
+
+ # With the team's rules off, the raw URLs stay distinct items instead of merging.
+ self.assertEqual(
+ self._steps(results),
+ [
+ (0, [_row("$pageview", 1, label="/item/1")], 0, 0),
+ (1, [_row("$pageview", 1, label="/item/2")], 0, 1),
+ ],
+ )
+
+ def test_null_team_path_cleaning_filters(self) -> None:
+ # The nullable JSONField's None must behave like "no rules", not crash rule resolution.
+ self.team.path_cleaning_filters = None
+ self.team.save()
+ journeys_for(team=self.team, events_by_person=_timeline("p1", "a"))
+
+ query = PathsV2Query(dateRange=DATE_RANGE, pathsV2Filter=PathsV2Filter(stepSources=_sources("a")))
+
+ self.assertEqual(self._steps(self._run(query)), [(0, [_row("a", 1)], 0, 1)])
+
+ def test_max_steps_trims_journeys(self):
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ **_timeline("p1", "a", "b", "c", "d", "e"),
+ **_timeline("p2", "a", "b", "c"),
+ },
+ )
+
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(stepSources=_sources("a", "b", "c", "d", "e"), maxSteps=3),
+ )
+ results = self._run(query)
+
+ # p1's journey continues beyond the grid: its items past the third step are invisible and
+ # it never counts as a drop-off. p2's journey genuinely ends at the third step.
+ self.assertEqual(
+ self._steps(results),
+ [
+ (0, [_row("a", 2)], 0, 0),
+ (1, [_row("b", 2)], 0, 0),
+ (2, [_row("c", 2)], 0, 1),
+ ],
+ )
+ self.assertEqual(
+ self._edges(results),
+ [_edge(0, _item("a"), _item("b"), 2), _edge(1, _item("b"), _item("c"), 2)],
+ )
+
+ @snapshot_clickhouse_queries
+ def test_default_pageview_preset_snapshot(self):
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ "p1": [
+ {"event": "$pageview", "timestamp": "2023-03-10 10:00:00", "properties": {"$pathname": "/"}},
+ {"event": "$pageview", "timestamp": "2023-03-10 10:05:00", "properties": {"$pathname": "/pricing"}},
+ {"event": "other event", "timestamp": "2023-03-10 10:07:00"},
+ ]
+ },
+ )
+
+ results = self._run(PathsV2Query(dateRange=DATE_RANGE))
+
+ # Events outside the step sources are invisible and do not break adjacency.
+ self.assertEqual(
+ self._steps(results),
+ [
+ (0, [_row("$pageview", 1, label="/")], 0, 0),
+ (1, [_row("$pageview", 1, label="/pricing")], 0, 1),
+ ],
+ )
+ self.assertEqual(
+ self._edges(results),
+ [_edge(0, _item("$pageview", label="/"), _item("$pageview", label="/pricing"), 1)],
+ )
+
+ def test_executable_via_query_api(self):
+ journeys_for(team=self.team, events_by_person=_timeline("p1", "a", "b"))
+
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/query/",
+ {
+ "query": {
+ "kind": "PathsV2Query",
+ "dateRange": {"date_from": "2023-03-01", "date_to": "2023-03-31"},
+ "pathsV2Filter": {"stepSources": [{"event": "a"}, {"event": "b"}]},
+ }
+ },
+ )
+
+ self.assertEqual(response.status_code, 200, response.json())
+ results = response.json()["results"]
+ self.assertEqual(len(results["steps"]), 2)
+ self.assertEqual(len(results["edges"]), 1)
+
+ def test_query_api_rejects_out_of_bounds_config(self):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/query/",
+ {"query": {"kind": "PathsV2Query", "pathsV2Filter": {"maxSteps": 21}}},
+ )
+
+ self.assertEqual(response.status_code, 400)
+ self.assertIn("maxSteps", str(response.json()))
+
+ def test_elements_per_actor_stage(self):
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ "p1": [
+ *_timeline("p1", "a", "a", "b")["p1"],
+ *_timeline("p1", "c", start="2023-03-10 14:00:00")["p1"],
+ ]
+ },
+ )
+
+ runner = PathsV2QueryRunner(
+ query=PathsV2Query(dateRange=DATE_RANGE, pathsV2Filter=PathsV2Filter(stepSources=_sources("a", "b", "c"))),
+ team=self.team,
+ )
+ response = execute_hogql_query(
+ query=runner._elements_per_actor_query(),
+ team=self.team,
+ )
+
+ self.assertEqual(len(response.results), 1)
+ assert response.columns is not None
+ elements = response.results[0][response.columns.index("elements")]
+ self.assertCountEqual(
+ elements,
+ [
+ # first journey, collapsed to [a, b]
+ ("node", 1, ("a", ""), ("", "")),
+ ("node", 2, ("b", ""), ("", "")),
+ ("edge", 1, ("a", ""), ("b", "")),
+ ("dropoff", 2, ("", ""), ("", "")),
+ # second journey, split off by the four-hour gap
+ ("node", 1, ("c", ""), ("", "")),
+ ("dropoff", 1, ("", ""), ("", "")),
+ ],
+ )
+
+
+def _anchor(event: str, anchor_type: PathsV2AnchorType = PathsV2AnchorType.START) -> PathsV2Anchor:
+ return PathsV2Anchor(type=anchor_type, item=PathsV2Item(event=event))
+
+
+def _prefix(items: list[tuple[str, str | None]], count: float) -> tuple[tuple[tuple[str, str | None], ...], float]:
+ return (tuple(items), count)
+
+
+class TestPathsV2AnchoredMode(ClickhouseTestMixin, APIBaseTest):
+ maxDiff = None
+
+ def _run(self, query: PathsV2Query) -> Any:
+ return PathsV2QueryRunner(query=query, team=self.team).calculate().results
+
+ def _steps(self, results: Any) -> list[tuple[int, list[PathsV2Row], float, float]]:
+ return [(step.stepIndex, step.rows, step.otherCount, step.dropOffCount) for step in results.steps]
+
+ def _edges(self, results: Any) -> list[tuple[int, PathsV2Item | None, PathsV2Item | None, float]]:
+ return [(edge.stepIndex, edge.source, edge.target, edge.count) for edge in results.edges]
+
+ def _prefixes(self, results: Any) -> set[tuple[tuple[tuple[str, str | None], ...], float]]:
+ return {(tuple((item.event, item.label) for item in prefix.items), prefix.count) for prefix in results.prefixes}
+
+ def test_anchored_start_journey_grid(self):
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ **_timeline("p1", "a", "b", "c"),
+ **_timeline("p2", "a", "b", "d"),
+ **_timeline("p3", "a", "x"),
+ # z precedes the anchor, so the prefilter drops it and the sequence starts at a.
+ **_timeline("p4", "z", "a", "b"),
+ },
+ )
+
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(
+ stepSources=_sources("a", "b", "c", "d", "x", "z"), anchor=_anchor("a"), maxRowsPerStep=10
+ ),
+ )
+ results = self._run(query)
+
+ # One sequence per actor from the anchor: p1 [a,b,c], p2 [a,b,d], p3 [a,x], p4 [a,b]. The anchor
+ # is the single 100% node; drop-offs count actors whose sequence ends at that step.
+ self.assertEqual(
+ self._steps(results),
+ [
+ (0, [_row("a", 4)], 0, 0),
+ (1, [_row("b", 3), _row("x", 1)], 0, 2),
+ (2, [_row("c", 1), _row("d", 1)], 0, 2),
+ ],
+ )
+ self.assertEqual(
+ self._edges(results),
+ [
+ _edge(0, _item("a"), _item("b"), 3),
+ _edge(0, _item("a"), _item("x"), 1),
+ _edge(1, _item("b"), _item("c"), 1),
+ _edge(1, _item("b"), _item("d"), 1),
+ ],
+ )
+ # Prefix counts nest into the chain tree the hover preview walks.
+ self.assertEqual(
+ self._prefixes(results),
+ {
+ _prefix([("a", None)], 4),
+ _prefix([("a", None), ("b", None)], 3),
+ _prefix([("a", None), ("x", None)], 1),
+ _prefix([("a", None), ("b", None), ("c", None)], 1),
+ _prefix([("a", None), ("b", None), ("d", None)], 1),
+ },
+ )
+
+ def test_prefixes_carry_only_displayed_chains(self):
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ **_timeline("p1", "a", "b"),
+ **_timeline("p2", "a", "b"),
+ **_timeline("p3", "a", "b"),
+ **_timeline("p4", "a", "x"),
+ },
+ )
+
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(stepSources=_sources("a", "b", "x"), anchor=_anchor("a"), maxRowsPerStep=1),
+ )
+ results = self._run(query)
+
+ # x lands in step 1's other row, so its label must not ship in the prefixes either: a shared
+ # insight exposes the raw response, and the hover preview skips other-bucket chains anyway.
+ self.assertEqual(
+ self._steps(results),
+ [(0, [_row("a", 4)], 0, 0), (1, [_row("b", 3)], 1, 4)],
+ )
+ self.assertEqual(
+ self._prefixes(results),
+ {_prefix([("a", None)], 4), _prefix([("a", None), ("b", None)], 3)},
+ )
+
+ def test_anchored_prefilter_bounds_actors_to_the_window(self):
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ # b sits 40 min past the anchor, beyond the 30 min window, so it never joins the sequence.
+ "p1": [
+ {"event": "a", "timestamp": "2023-03-10 10:00:00"},
+ {"event": "b", "timestamp": "2023-03-10 10:40:00"},
+ ],
+ # No anchor event at all, so this actor is excluded entirely.
+ **_timeline("p2", "b", "c"),
+ # Anchor plus an in-window step.
+ "p3": [
+ {"event": "a", "timestamp": "2023-03-10 10:00:00"},
+ {"event": "b", "timestamp": "2023-03-10 10:20:00"},
+ ],
+ },
+ )
+
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(stepSources=_sources("a", "b", "c"), anchor=_anchor("a"), maxRowsPerStep=10),
+ )
+ results = self._run(query)
+
+ self.assertEqual(
+ self._steps(results),
+ [(0, [_row("a", 2)], 0, 1), (1, [_row("b", 1)], 0, 1)],
+ )
+ self.assertEqual(self._edges(results), [_edge(0, _item("a"), _item("b"), 1)])
+ self.assertEqual(
+ self._prefixes(results),
+ {_prefix([("a", None)], 2), _prefix([("a", None), ("b", None)], 1)},
+ )
+
+ def test_anchored_keeps_single_sequence_across_a_gap(self):
+ # A 45 min gap would split into two journeys in open mode (gap G defaults to 30 min); anchored
+ # mode never splits, so with a 60 min window the two events stay one sequence and the edge exists.
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ "p1": [
+ {"event": "a", "timestamp": "2023-03-10 10:00:00"},
+ {"event": "b", "timestamp": "2023-03-10 10:45:00"},
+ ]
+ },
+ )
+
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(
+ stepSources=_sources("a", "b"),
+ anchor=_anchor("a"),
+ conversionWindowInterval=60,
+ conversionWindowIntervalUnit=FunnelConversionWindowTimeUnit.MINUTE,
+ ),
+ )
+ results = self._run(query)
+
+ self.assertEqual(
+ self._steps(results),
+ [(0, [_row("a", 1)], 0, 0), (1, [_row("b", 1)], 0, 1)],
+ )
+ self.assertEqual(self._edges(results), [_edge(0, _item("a"), _item("b"), 1)])
+
+ def test_anchored_end_anchor_reads_backward(self):
+ journeys_for(
+ team=self.team,
+ events_by_person={
+ **_timeline("p1", "a", "b", "x"),
+ **_timeline("p2", "c", "b", "x"),
+ },
+ )
+
+ query = PathsV2Query(
+ dateRange=DATE_RANGE,
+ pathsV2Filter=PathsV2Filter(
+ stepSources=_sources("a", "b", "c", "x"),
+ anchor=_anchor("x", PathsV2AnchorType.END),
+ maxRowsPerStep=10,
+ ),
+ )
+ results = self._run(query)
+
+ # End anchor: x is the single 100% node at step 0 and the grid reads backward in time toward it,
+ # so p1 becomes [x, b, a] and p2 becomes [x, b, c].
+ self.assertEqual(
+ self._steps(results),
+ [
+ (0, [_row("x", 2)], 0, 0),
+ (1, [_row("b", 2)], 0, 0),
+ (2, [_row("a", 1), _row("c", 1)], 0, 2),
+ ],
+ )
+ self.assertEqual(
+ self._edges(results),
+ [
+ _edge(0, _item("x"), _item("b"), 2),
+ _edge(1, _item("b"), _item("a"), 1),
+ _edge(1, _item("b"), _item("c"), 1),
+ ],
+ )
+ self.assertEqual(
+ self._prefixes(results),
+ {
+ _prefix([("x", None)], 2),
+ _prefix([("x", None), ("b", None)], 2),
+ _prefix([("x", None), ("b", None), ("a", None)], 1),
+ _prefix([("x", None), ("b", None), ("c", None)], 1),
+ },
+ )
diff --git a/products/product_analytics/backend/models/insight.py b/products/product_analytics/backend/models/insight.py
index 26f5d38ef54a..108a5cc29f22 100644
--- a/products/product_analytics/backend/models/insight.py
+++ b/products/product_analytics/backend/models/insight.py
@@ -29,6 +29,7 @@ _ANALYTICS_INSIGHT_QUERY_KINDS = frozenset(
"FunnelsQuery",
"RetentionQuery",
"PathsQuery",
+ "PathsV2Query",
"StickinessQuery",
"LifecycleQuery",
"CalendarHeatmapQuery",
diff --git a/products/product_analytics/backend/routes.py b/products/product_analytics/backend/routes.py
index 1baf92984bfa..b36bcbd026c0 100644
--- a/products/product_analytics/backend/routes.py
+++ b/products/product_analytics/backend/routes.py
@@ -5,6 +5,7 @@ from posthog.settings import EE_AVAILABLE
import products.alerts.backend.api.alert as alert
from products.product_analytics.backend.api.insight import InsightViewSet
from products.product_analytics.backend.api.insight_variable import InsightVariableViewSet
+from products.product_analytics.backend.api.paths_v2 import PathsV2ViewSet
def register_routes(routers: RouterRegistry) -> None:
@@ -44,3 +45,10 @@ def register_routes(routers: RouterRegistry) -> None:
"project_insight_variables",
["team_id"],
)
+
+ routers.projects.register(
+ r"paths_v2",
+ PathsV2ViewSet,
+ "project_paths_v2",
+ ["team_id"],
+ )
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 97f2f87ef989..cde54d9f2530 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -2676,6 +2676,173 @@ export interface PathsQueryApi {
version?: number | null
}
+export interface PathsV2ItemApi {
+ /** Event of the step source this item belongs to. */
+ event: string
+ /** Label value from the source's naming property, after path cleaning. An empty string when the property is missing on the event. Null for sources without a naming property. */
+ label?: string | null
+}
+
+export type PathsV2AnchorTypeApi = (typeof PathsV2AnchorTypeApi)[keyof typeof PathsV2AnchorTypeApi]
+
+export const PathsV2AnchorTypeApi = {
+ Start: 'start',
+ End: 'end',
+} as const
+
+export interface PathsV2AnchorApi {
+ /** The path item the chart anchors on. Its event must be one of the step sources. */
+ item: PathsV2ItemApi
+ /** `start` runs each actor's single sequence forward from the anchor item; `end` runs it up to the anchor item. Either way the anchor is the grid's single 100% node. */
+ type: PathsV2AnchorTypeApi
+}
+
+export interface PathsV2StepSourceApi {
+ /** Name of the event this source matches. */
+ event: string
+ /** Event property whose value labels the path item, e.g. `$pathname` for pageviews. Team path cleaning rules are applied to the value. Without a naming property, the event itself is the path item. */
+ namingProperty?: string | null
+}
+
+export interface PathsV2FilterApi {
+ /** Anchor selecting anchored mode. When set, each actor contributes exactly one sequence bounded by the conversion window, so every displayed segment equals a plain funnel. Absent selects open mode, which splits an actor's events into journeys on the inactivity gap instead. */
+ anchor?: PathsV2AnchorApi | null
+ /** Apply the team's path cleaning rules to naming property values before they become path items. */
+ applyTeamPathCleaning?: boolean | null
+ /** Merge immediate repeats of the same path item within a journey. */
+ collapseRepeats?: boolean | null
+ /** Anchored mode's single conversion window W, anchored at the anchor and reused verbatim as the emitted funnel's window. Bounds per unit are validated server-side against CONVERSION_WINDOW_INTERVAL_BOUNDS, the same funnel conversion window bounds as the gap. */
+ conversionWindowInterval?: number | null
+ conversionWindowIntervalUnit?: FunnelConversionWindowTimeUnitApi | null
+ /** Path items dropped from the item universe: events deriving to one of these items are ignored as if their event were not a step source, on both the paths side and the "view as funnel" side. */
+ excludedItems?: PathsV2ItemApi[] | null
+ /** Inactivity gap that splits an actor's events into journeys. Bounds per unit are validated server-side against CONVERSION_WINDOW_INTERVAL_BOUNDS, the funnel conversion window bounds. */
+ gapInterval?: number | null
+ gapIntervalUnit?: FunnelConversionWindowTimeUnitApi | null
+ /** Path cleaning rules for this insight only, applied after the team's rules. */
+ localPathCleaningFilters?: PathCleaningFilterApi[] | null
+ /** Number of path item rows per step; items beyond this go into the "other" row. */
+ maxRowsPerStep?: number | null
+ /** Number of journey steps (columns) shown. */
+ maxSteps?: number | null
+ /** Step sources defining which events can become path items. Defaults to the pageviews preset: `$pageview` named by `$pathname`. */
+ stepSources?: PathsV2StepSourceApi[] | null
+}
+
+export interface PathsV2EdgeApi {
+ /** Unique actors who transition from source to target at any step of any of their whole journeys, the position-free count behind "went source → target at any step". Equals the two-step item-strict funnel's converted count. Only set in open mode on edges between two named items. */
+ anyStepCount?: number | null
+ /** Unique actors with a journey that transitions from source to target between these steps. */
+ count: number
+ /** Source path item, or null for the source column's "other" row. */
+ source: PathsV2ItemApi | null
+ /** 0-based step index of the source column; the target sits at `stepIndex + 1`. */
+ stepIndex: number
+ /** Target path item, or null for the target column's "other" row. */
+ target: PathsV2ItemApi | null
+}
+
+export interface PathsV2PrefixApi {
+ /** Unique actors whose anchored sequence begins with exactly these items. */
+ count: number
+ /** The chain's path items in order, starting at the anchor. */
+ items: PathsV2ItemApi[]
+}
+
+export interface PathsV2RowApi {
+ /** Unique actors with a journey whose item at this step is this path item. */
+ count: number
+ item: PathsV2ItemApi
+}
+
+export interface PathsV2StepApi {
+ /** Unique actors whose journey ends at this step. */
+ dropOffCount: number
+ /** Unique actors at this step whose path item is beyond the top rows. */
+ otherCount: number
+ /** Top path items at this step, ordered by unique-actor count descending. */
+ rows: PathsV2RowApi[]
+ /** 0-based step index (column) in the journey grid. */
+ stepIndex: number
+}
+
+export interface PathsV2ResultsApi {
+ edges: PathsV2EdgeApi[]
+ /** Concrete anchored chains with per-chain unique-actor counts, ordered by descending count. Empty in open mode; in anchored mode it carries the counts the hover funnel preview reads per chain. Only chains the grid displays in full are carried: chains through the other bucket are omitted, so the response never exposes labels the chart hides. */
+ prefixes: PathsV2PrefixApi[]
+ steps: PathsV2StepApi[]
+}
+
+export interface PathsV2QueryResponseApi {
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null
+ /** Generated HogQL query. */
+ hogql?: string | null
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiersApi | null
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatusApi | null
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponseApi | null
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponseApi | null
+ results: PathsV2ResultsApi
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTimingApi[] | null
+ /** Connector-synced data warehouse sources referenced by this query, if any. */
+ used_data_warehouse_sources?: DataWarehouseSourceUsageApi[] | null
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
+ warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null
+}
+
+export interface PathsV2QueryApi {
+ /** Colors used in the insight's visualization */
+ dataColorTheme?: number | null
+ /** Date range for the query */
+ dateRange?: DateRangeApi | null
+ /** Exclude internal and test users by applying the respective filters */
+ filterTestAccounts?: boolean | null
+ kind?: 'PathsV2Query'
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiersApi | null
+ /** Properties specific to the paths v2 insight */
+ pathsV2Filter?: PathsV2FilterApi | null
+ /** Property filters for all series */
+ properties?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ )[]
+ | PropertyGroupFilterApi
+ | null
+ response?: PathsV2QueryResponseApi | null
+ /** Tags that will be added to the Query log comment */
+ tags?: QueryLogTagsApi | null
+ /** version of the node, used for schema migrations */
+ version?: number | null
+}
+
export type StickinessQueryResponseApiResultsItem = { [key: string]: unknown }
export interface StickinessQueryResponseApi {
@@ -3270,6 +3437,7 @@ export interface InsightVizNodeApi {
| FunnelsQueryApi
| RetentionQueryApi
| PathsQueryApi
+ | PathsV2QueryApi
| StickinessQueryApi
| LifecycleQueryApi
| WebStatsTableQueryApi
@@ -4415,6 +4583,7 @@ export interface InsightActorsQueryApi {
| FunnelsQueryApi
| RetentionQueryApi
| PathsQueryApi
+ | PathsV2QueryApi
| StickinessQueryApi
| LifecycleQueryApi
| WebStatsTableQueryApi
@@ -5160,6 +5329,45 @@ export interface StickinessActorsQueryApi {
version?: number | null
}
+export type PathsV2ElementTypeApi = (typeof PathsV2ElementTypeApi)[keyof typeof PathsV2ElementTypeApi]
+
+export const PathsV2ElementTypeApi = {
+ Node: 'node',
+ Edge: 'edge',
+ DropOff: 'dropOff',
+ Other: 'other',
+ Chain: 'chain',
+} as const
+
+export interface PathsV2ElementSelectorApi {
+ /** Match the source → target transition at any step of any whole journey instead of at one step pair: the position-free set behind an edge's anyStepCount. Requires a named source and target and open mode. Edge elements only. */
+ anyStep?: boolean | null
+ /** The chain's path items in order from the anchor. Returns the actors whose anchored sequence begins with exactly these items, the set behind a hover preview's per-chain counts. Chain elements only, anchored mode only. Bounded by the step maximum: a longer chain can never match a displayed card. */
+ chain?: PathsV2ItemApi[] | null
+ elementType: PathsV2ElementTypeApi
+ /** The node card's path item. Node elements only. */
+ item?: PathsV2ItemApi | null
+ /** The edge's source path item; omit for the source column's "other" row. Edge elements only. */
+ source?: PathsV2ItemApi | null
+ /** 0-based step index (column) of the element; for an edge, its source column. Required for node, other, dropOff, and positional edge elements. */
+ stepIndex?: number | null
+ /** The edge's target path item; omit for the target column's "other" row. Edge elements only. */
+ target?: PathsV2ItemApi | null
+}
+
+export interface PathsV2ActorsQueryApi {
+ element: PathsV2ElementSelectorApi
+ includeRecordings?: boolean | null
+ kind?: 'PathsV2ActorsQuery'
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiersApi | null
+ response?: ActorsQueryResponseApi | null
+ source: PathsV2QueryApi
+ tags?: QueryLogTagsApi | null
+ /** version of the node, used for schema migrations */
+ version?: number | null
+}
+
export interface HogQLFiltersApi {
dateRange?: DateRangeApi | null
filterTestAccounts?: boolean | null
@@ -5308,6 +5516,7 @@ export interface ActorsQueryApi {
| FunnelCorrelationActorsQueryApi
| ExperimentActorsQueryApi
| StickinessActorsQueryApi
+ | PathsV2ActorsQueryApi
| HogQLQueryApi
| null
tags?: QueryLogTagsApi | null
@@ -5589,6 +5798,7 @@ export interface WebVitalsQueryApi {
| FunnelsQueryApi
| RetentionQueryApi
| PathsQueryApi
+ | PathsV2QueryApi
| StickinessQueryApi
| LifecycleQueryApi
| WebStatsTableQueryApi
@@ -7946,6 +8156,28 @@ export interface InsightViewedRequestApi {
insight_ids: number[]
}
+export interface PathsV2SegmentItemApi {
+ /** Event of the step source this path item belongs to. */
+ event: string
+ /**
+ * Label value from the source's naming property, after path cleaning. Null or omitted for sources without a naming property; an empty string means the property was missing on the event.
+ * @nullable
+ */
+ label?: string | null
+}
+
+export interface PathsV2SegmentToFunnelRequestApi {
+ /** The PathsV2Query the segment is displayed under (JSON object with kind `PathsV2Query`). Step sources, path cleaning, excluded items, date range, and the gap or conversion window are read from it, so the emitted funnel counts exactly what the chart shows. */
+ query: unknown
+ /** The segment's path items in displayed order. In open mode exactly two items - a single edge, source then target. In anchored mode the concrete chain as shown, starting at the anchor. */
+ items: PathsV2SegmentItemApi[]
+}
+
+export interface PathsV2SegmentToFunnelResponseApi {
+ /** The FunnelsQuery (JSON object with kind `FunnelsQuery`) that reproduces the segment's displayed unique-actor count exactly. Wrap it in an InsightVizNode to open it as a funnel insight. */
+ funnels_query: unknown
+}
+
export type ColumnConfigurationsListParams = {
/**
* Number of results to return per page.
@@ -8118,6 +8350,7 @@ export type InsightsListInsight = (typeof InsightsListInsight)[keyof typeof Insi
export const InsightsListInsight = {
Funnels: 'FUNNELS',
+ Journeys: 'JOURNEYS',
Json: 'JSON',
Lifecycle: 'LIFECYCLE',
Paths: 'PATHS',
diff --git a/products/product_analytics/frontend/generated/api.ts b/products/product_analytics/frontend/generated/api.ts
index d77e1569e481..55ea28796d74 100644
--- a/products/product_analytics/frontend/generated/api.ts
+++ b/products/product_analytics/frontend/generated/api.ts
@@ -51,6 +51,8 @@ import type {
PatchedColumnConfigurationApi,
PatchedElementApi,
PatchedInsightApi,
+ PathsV2SegmentToFunnelRequestApi,
+ PathsV2SegmentToFunnelResponseApi,
} from './api.schemas'
// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
@@ -1032,3 +1034,24 @@ export const insightsViewedCreate = async (
body: JSON.stringify(insightViewedRequestApi),
})
}
+
+export const getPathsV2SegmentToFunnelCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/paths_v2/segment_to_funnel/`
+}
+
+/**
+ * Converts a displayed journeys segment into the funnel query that reproduces its unique-actor count exactly. In open mode only a single edge converts (a two-step funnel with the inactivity gap as conversion window); in anchored mode any anchor-rooted chain converts (window W). The funnel is returned as JSON and is not executed or persisted here.
+ * @summary Convert a journey segment to a funnel
+ */
+export const pathsV2SegmentToFunnelCreate = async (
+ projectId: string,
+ pathsV2SegmentToFunnelRequestApi: PathsV2SegmentToFunnelRequestApi,
+ options?: RequestInit
+): Promise<PathsV2SegmentToFunnelResponseApi> => {
+ return apiMutator<PathsV2SegmentToFunnelResponseApi>(getPathsV2SegmentToFunnelCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(pathsV2SegmentToFunnelRequestApi),
+ })
+}
diff --git a/products/product_analytics/frontend/generated/api.zod.ts b/products/product_analytics/frontend/generated/api.zod.ts
index f62e0b1d0b7c..0b15893e2020 100644
--- a/products/product_analytics/frontend/generated/api.zod.ts
+++ b/products/product_analytics/frontend/generated/api.zod.ts
@@ -334,3 +334,30 @@ export const InsightsViewedCreateBody = /* @__PURE__ */ zod.object({
.max(insightsViewedCreateBodyInsightIdsMax)
.describe('Insight IDs that were just viewed by the current user. At most 2500 ids per request.'),
})
+
+/**
+ * Converts a displayed journeys segment into the funnel query that reproduces its unique-actor count exactly. In open mode only a single edge converts (a two-step funnel with the inactivity gap as conversion window); in anchored mode any anchor-rooted chain converts (window W). The funnel is returned as JSON and is not executed or persisted here.
+ * @summary Convert a journey segment to a funnel
+ */
+export const PathsV2SegmentToFunnelCreateBody = /* @__PURE__ */ zod.object({
+ query: zod
+ .unknown()
+ .describe(
+ 'The PathsV2Query the segment is displayed under (JSON object with kind `PathsV2Query`). Step sources, path cleaning, excluded items, date range, and the gap or conversion window are read from it, so the emitted funnel counts exactly what the chart shows.'
+ ),
+ items: zod
+ .array(
+ zod.object({
+ event: zod.string().describe('Event of the step source this path item belongs to.'),
+ label: zod
+ .string()
+ .nullish()
+ .describe(
+ "Label value from the source's naming property, after path cleaning. Null or omitted for sources without a naming property; an empty string means the property was missing on the event."
+ ),
+ })
+ )
+ .describe(
+ "The segment's path items in displayed order. In open mode exactly two items - a single edge, source then target. In anchored mode the concrete chain as shown, starting at the anchor."
+ ),
+})
diff --git a/products/product_analytics/frontend/insights/journeys/JourneyGrid.tsx b/products/product_analytics/frontend/insights/journeys/JourneyGrid.tsx
new file mode 100644
index 000000000000..14843b13fbfd
--- /dev/null
+++ b/products/product_analytics/frontend/insights/journeys/JourneyGrid.tsx
@@ -0,0 +1,343 @@
+import { useMemo } from 'react'
+
+import { Tooltip } from '@posthog/lemon-ui'
+
+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+import { percentage } from 'lib/utils/numbers'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { midEllipsis, pluralize } from 'lib/utils/strings'
+
+import {
+ JourneyChainHighlight,
+ JourneyGridModel,
+ JourneyGridRibbon,
+ JourneyGridRow,
+ JourneyGridRowKind,
+ ribbonPath,
+} from './journeyGridModel'
+
+const CARD_WIDTH = 224
+const COLUMN_GAP = 104
+const CARD_HEIGHT = 66
+const ROW_GAP = 14
+const HEADER_HEIGHT = 28
+const PORT_TOP_OFFSET = 6
+const PORT_GAP = 2
+const MAX_RIBBON_THICKNESS = 36
+const MIN_RIBBON_THICKNESS = 2
+const MAX_LABEL_CHARS = 30
+const RIBBON_OPACITY = 0.15
+const RIBBON_OPACITY_ON_CHAIN = 0.4
+const RIBBON_OPACITY_DIMMED = 0.06
+
+interface CardGeometry {
+ row: JourneyGridRow
+ stepIndex: number
+ x: number
+ y: number
+}
+
+interface RibbonGeometry {
+ ribbon: JourneyGridRibbon
+ thickness: number
+ fromX: number
+ fromY: number
+ toX: number
+ toY: number
+}
+
+function cardKey(stepIndex: number, rowKey: string): string {
+ return `${stepIndex}:${rowKey}`
+}
+
+export function JourneyGrid({
+ model,
+ isAnchored,
+ nodeColor,
+ chainHighlight,
+ onCardClick,
+ onCardHover,
+ onRibbonClick,
+ onRibbonHover,
+ onGridLeave,
+}: {
+ model: JourneyGridModel
+ isAnchored: boolean
+ nodeColor: string
+ chainHighlight?: JourneyChainHighlight | null
+ onCardClick?: (stepIndex: number, row: JourneyGridRow) => void
+ onCardHover?: (stepIndex: number, row: JourneyGridRow) => void
+ onRibbonClick?: (ribbon: JourneyGridRibbon) => void
+ onRibbonHover?: (ribbon: JourneyGridRibbon) => void
+ onGridLeave?: () => void
+}): JSX.Element {
+ const { cards, ribbons, chartWidth, chartHeight } = useMemo(() => {
+ const cardByKey = new Map<string, CardGeometry>()
+ const cards: CardGeometry[] = []
+ let maxCardBottom = 0
+ model.columns.forEach((column, columnIndex) => {
+ let y = HEADER_HEIGHT
+ for (const row of column.rows) {
+ const card = { row, stepIndex: column.stepIndex, x: columnIndex * (CARD_WIDTH + COLUMN_GAP), y }
+ cardByKey.set(cardKey(column.stepIndex, row.key), card)
+ cards.push(card)
+ y += CARD_HEIGHT + ROW_GAP
+ }
+ maxCardBottom = Math.max(maxCardBottom, y - ROW_GAP)
+ })
+
+ const thicknessFor = (count: number): number =>
+ Math.max(MIN_RIBBON_THICKNESS, (count / Math.max(model.maxRibbonCount, 1)) * MAX_RIBBON_THICKNESS)
+
+ // Resolve each ribbon's cards once, then stack the ports on each card side in the vertical
+ // order of the connected cards, so ribbons out of one card never cross at the card edge.
+ const resolvedRibbons = model.ribbons.flatMap((ribbon) => {
+ const sourceCardKey = cardKey(ribbon.sourceStep, ribbon.sourceKey)
+ const targetCardKey = cardKey(ribbon.sourceStep + 1, ribbon.targetKey)
+ const source = cardByKey.get(sourceCardKey)
+ const target = cardByKey.get(targetCardKey)
+ return source && target ? [{ ribbon, source, target, sourceCardKey, targetCardKey }] : []
+ })
+ resolvedRibbons.sort((a, b) => a.source.y - b.source.y || a.target.y - b.target.y)
+
+ const outCursor = new Map<string, number>()
+ const inCursor = new Map<string, number>()
+ const ribbons: RibbonGeometry[] = resolvedRibbons.map(
+ ({ ribbon, source, target, sourceCardKey, targetCardKey }) => {
+ const thickness = thicknessFor(ribbon.count)
+ const fromY = source.y + PORT_TOP_OFFSET + (outCursor.get(sourceCardKey) ?? 0)
+ const toY = target.y + PORT_TOP_OFFSET + (inCursor.get(targetCardKey) ?? 0)
+ outCursor.set(sourceCardKey, (outCursor.get(sourceCardKey) ?? 0) + thickness + PORT_GAP)
+ inCursor.set(targetCardKey, (inCursor.get(targetCardKey) ?? 0) + thickness + PORT_GAP)
+ return {
+ ribbon,
+ thickness,
+ fromX: source.x + CARD_WIDTH,
+ fromY,
+ toX: target.x,
+ toY,
+ }
+ }
+ )
+
+ const chartWidth = model.columns.length * (CARD_WIDTH + COLUMN_GAP) - COLUMN_GAP
+ const chartHeight = maxCardBottom + 16
+ return { cards, ribbons, chartWidth, chartHeight }
+ }, [model])
+
+ const ribbonOpacity = (ribbon: JourneyGridRibbon): number => {
+ if (!chainHighlight) {
+ return RIBBON_OPACITY
+ }
+ return chainHighlight.ribbonKeys.has(ribbon.key) ? RIBBON_OPACITY_ON_CHAIN : RIBBON_OPACITY_DIMMED
+ }
+
+ return (
+ <div className="overflow-auto p-4" data-attr="journey-grid" onMouseLeave={onGridLeave}>
+ {/* eslint-disable-next-line react/forbid-dom-props */}
+ <div className="relative" style={{ width: chartWidth, height: chartHeight }}>
+ <svg width={chartWidth} height={chartHeight} className="absolute inset-0 pointer-events-none">
+ {ribbons.map(({ ribbon, thickness, fromX, fromY, toX, toY }) => (
+ <Tooltip
+ key={ribbon.key}
+ title={
+ <div className="flex flex-col gap-0.5">
+ <span className="font-semibold">
+ {ribbon.sourceLabel} → {ribbon.targetLabel}
+ </span>
+ <span>
+ {pluralize(ribbon.count, 'person', 'people')} (
+ {percentage(ribbon.fractionOfSource, 1)} of {ribbon.sourceLabel})
+ </span>
+ </div>
+ }
+ >
+ <path
+ d={ribbonPath(fromX, fromY, thickness, toX, toY, thickness)}
+ fill={nodeColor}
+ opacity={ribbonOpacity(ribbon)}
+ // The transparent stroke widens the hover target without changing the
+ // drawn shape, so hair-thin ribbons can still be hovered for a tooltip.
+ stroke="transparent"
+ strokeWidth={8}
+ className={`pointer-events-auto hover:opacity-40 transition-opacity ${
+ onRibbonClick ? 'cursor-pointer' : ''
+ }`}
+ data-attr="journey-grid-ribbon"
+ role={onRibbonClick ? 'button' : undefined}
+ tabIndex={onRibbonClick ? 0 : undefined}
+ aria-label={
+ onRibbonClick
+ ? `${ribbon.sourceLabel} → ${ribbon.targetLabel}, ${pluralize(
+ ribbon.count,
+ 'person',
+ 'people'
+ )}`
+ : undefined
+ }
+ onClick={onRibbonClick ? () => onRibbonClick(ribbon) : undefined}
+ onMouseEnter={() => onRibbonHover?.(ribbon)}
+ onFocus={() => onRibbonHover?.(ribbon)}
+ onKeyDown={
+ onRibbonClick
+ ? (event) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault()
+ onRibbonClick(ribbon)
+ }
+ }
+ : undefined
+ }
+ />
+ </Tooltip>
+ ))}
+ </svg>
+
+ {model.columns.map((column, columnIndex) => (
+ <div
+ key={`header-${column.stepIndex}`}
+ className="absolute text-xs font-semibold text-secondary"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ left: columnIndex * (CARD_WIDTH + COLUMN_GAP), top: 0, width: CARD_WIDTH }}
+ >
+ Step {column.stepIndex + 1}
+ </div>
+ ))}
+
+ {cards.map(({ row, stepIndex, x, y }) => (
+ <JourneyCard
+ key={cardKey(stepIndex, row.key)}
+ row={row}
+ x={x}
+ y={y}
+ isAnchored={isAnchored}
+ nodeColor={nodeColor}
+ chainCount={
+ chainHighlight ? chainHighlight.countByCardKey[cardKey(stepIndex, row.key)] : undefined
+ }
+ chainFraction={
+ chainHighlight ? chainHighlight.fractionByCardKey[cardKey(stepIndex, row.key)] : undefined
+ }
+ dimmed={
+ !!chainHighlight && chainHighlight.countByCardKey[cardKey(stepIndex, row.key)] === undefined
+ }
+ onClick={onCardClick ? () => onCardClick(stepIndex, row) : undefined}
+ onMouseEnter={onCardHover ? () => onCardHover(stepIndex, row) : undefined}
+ />
+ ))}
+ </div>
+ </div>
+ )
+}
+
+const CARD_STYLES: Record<JourneyGridRowKind, { container: string; text: string; dataAttr: string }> = {
+ item: { container: 'border bg-surface-primary', text: '', dataAttr: 'journey-grid-node' },
+ other: { container: 'border border-dashed bg-surface-primary', text: '', dataAttr: 'journey-grid-other-row' },
+ dropOff: { container: 'border border-transparent', text: 'text-secondary', dataAttr: 'journey-grid-drop-off-row' },
+}
+
+function dropOffTooltip(isAnchored: boolean): string {
+ if (isAnchored) {
+ return 'People whose journey ends at this step.'
+ }
+ return (
+ 'People whose journey ends at this step. ' +
+ 'Every number counts unique people, and one person can appear in several rows of a column, ' +
+ 'so the percentages in a column can add up to more than 100%.'
+ )
+}
+
+function JourneyCard({
+ row,
+ x,
+ y,
+ isAnchored,
+ nodeColor,
+ chainCount,
+ chainFraction,
+ dimmed,
+ onClick,
+ onMouseEnter,
+}: {
+ row: JourneyGridRow
+ x: number
+ y: number
+ isAnchored: boolean
+ nodeColor: string
+ /** The active chain's count for this card; set only while the card is on the hovered chain. */
+ chainCount?: number
+ /** The chain count's share of the column total, so the bar describes the number shown above it. */
+ chainFraction?: number
+ dimmed?: boolean
+ onClick?: () => void
+ onMouseEnter?: () => void
+}): JSX.Element {
+ const styles = CARD_STYLES[row.kind]
+ const onChain = chainCount !== undefined
+ const tooltip =
+ row.kind === 'dropOff' ? (
+ dropOffTooltip(isAnchored)
+ ) : row.kind === 'other' ? (
+ 'Less common steps at this position, grouped together.'
+ ) : (
+ <>
+ {row.label}
+ {row.item?.label != null && <span className="text-muted"> ({row.item.event})</span>}
+ </>
+ )
+
+ return (
+ // The whole card is the tooltip trigger — a label-only trigger makes the tooltip vanish
+ // as soon as the pointer moves onto the count or progress bar within the card.
+ <Tooltip title={tooltip}>
+ <div
+ className={`absolute rounded px-2 py-1.5 transition-opacity ${styles.container} ${
+ onClick ? 'cursor-pointer' : ''
+ } ${dimmed ? 'opacity-40' : ''}`}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ left: x,
+ top: y,
+ width: CARD_WIDTH,
+ height: CARD_HEIGHT,
+ ...(onChain ? { boxShadow: `0 0 0 2px ${nodeColor}` } : {}),
+ }}
+ data-attr={styles.dataAttr}
+ role={onClick ? 'button' : undefined}
+ tabIndex={onClick ? 0 : undefined}
+ onClick={onClick}
+ onMouseEnter={onMouseEnter}
+ onKeyDown={
+ onClick
+ ? (event) => {
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault()
+ onClick()
+ }
+ }
+ : undefined
+ }
+ >
+ <div className={`text-xs font-semibold truncate ${styles.text}`}>
+ {midEllipsis(row.label, MAX_LABEL_CHARS)}
+ </div>
+ <div className="flex items-baseline gap-1.5 mt-0.5">
+ <span className={`text-sm font-semibold ${styles.text}`}>
+ {humanFriendlyNumber(onChain ? chainCount : row.count)}
+ </span>
+ {!onChain && <span className="text-xs text-secondary">{percentage(row.fraction, 1)}</span>}
+ {onChain && <span className="text-xs text-secondary">on this path</span>}
+ </div>
+ {row.kind !== 'dropOff' && (
+ <LemonProgress
+ percent={Math.max(2, (onChain ? (chainFraction ?? 0) : row.fraction) * 100)}
+ strokeColor={row.kind === 'other' ? 'var(--color-gray-400)' : nodeColor}
+ bgColor="var(--color-fill-secondary)"
+ smoothing={false}
+ className="mt-1"
+ />
+ )}
+ </div>
+ </Tooltip>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/journeys/Journeys.tsx b/products/product_analytics/frontend/insights/journeys/Journeys.tsx
new file mode 100644
index 000000000000..8f3a248b4385
--- /dev/null
+++ b/products/product_analytics/frontend/insights/journeys/Journeys.tsx
@@ -0,0 +1,35 @@
+import { useActions, useValues } from 'kea'
+
+import { InsightEmptyState } from 'scenes/insights/EmptyStates'
+import { insightLogic } from 'scenes/insights/insightLogic'
+
+import { JourneyGrid } from './JourneyGrid'
+import { journeysDataLogic } from './journeysDataLogic'
+
+export function Journeys({ showPersonsModal = true }: { showPersonsModal?: boolean }): JSX.Element {
+ const { insightProps } = useValues(insightLogic)
+ const { gridModel, isAnchored, theme, activeChainHighlight } = useValues(journeysDataLogic(insightProps))
+ const { cardClicked, cardHovered, ribbonClicked, ribbonHovered, gridLeft } = useActions(
+ journeysDataLogic(insightProps)
+ )
+
+ if (gridModel.columns.length === 0) {
+ return <InsightEmptyState />
+ }
+
+ return (
+ <JourneyGrid
+ model={gridModel}
+ isAnchored={isAnchored}
+ nodeColor={theme?.['preset-1'] ?? '#000000'}
+ chainHighlight={activeChainHighlight}
+ // Shared and embedded views cannot open a persons modal, so the elements must not look
+ // clickable or take focus as buttons there.
+ onCardClick={showPersonsModal ? cardClicked : undefined}
+ onCardHover={cardHovered}
+ onRibbonClick={showPersonsModal ? ribbonClicked : undefined}
+ onRibbonHover={ribbonHovered}
+ onGridLeave={gridLeft}
+ />
+ )
+}
diff --git a/products/product_analytics/frontend/insights/journeys/JourneysExclusions.tsx b/products/product_analytics/frontend/insights/journeys/JourneysExclusions.tsx
new file mode 100644
index 000000000000..2606ecb12656
--- /dev/null
+++ b/products/product_analytics/frontend/insights/journeys/JourneysExclusions.tsx
@@ -0,0 +1,94 @@
+import { useActions, useValues } from 'kea'
+
+import { PropertyValue } from 'lib/components/PropertyFilters/components/PropertyValue'
+import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { LemonSnack } from 'lib/lemon-ui/LemonSnack'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { PathsV2Item, PathsV2StepSource } from '~/queries/schema/schema-general'
+import { EditorFilterProps, PropertyFilterType, PropertyOperator } from '~/types'
+
+import { excludedItemChips, excludedLabelsForSource } from './exclusionUtils'
+import { journeysDataLogic } from './journeysDataLogic'
+
+function activeChipExplanation(item: PathsV2Item, source: PathsV2StepSource): string {
+ if (source.namingProperty) {
+ return `Excludes ${item.event} events with no value for ${source.namingProperty}.`
+ }
+ return `Excludes all ${item.event} events.`
+}
+
+export function JourneysExclusions({ insightProps }: EditorFilterProps): JSX.Element {
+ const { pathsV2Filter, stepSources, excludedItems } = useValues(journeysDataLogic(insightProps))
+ const { setExcludedLabels, removeExcludedItem } = useActions(journeysDataLogic(insightProps))
+ const { currentTeam } = useValues(teamLogic)
+
+ const namingSources = stepSources.filter((source) => source.namingProperty)
+ const chips = excludedItemChips(excludedItems, stepSources)
+ const hasCleaningRules =
+ ((pathsV2Filter?.applyTeamPathCleaning ?? true) && (currentTeam?.path_cleaning_filters || []).length > 0) ||
+ (pathsV2Filter?.localPathCleaningFilters ?? []).length > 0
+
+ return (
+ <div className="flex flex-col gap-2">
+ {namingSources.length === 0 && (
+ <div className="text-secondary">
+ Exclusions apply to step sources with a naming property. To exclude a whole event, remove its step
+ source instead.
+ </div>
+ )}
+ {namingSources.map((source) => (
+ <div key={source.event} className="flex flex-col gap-1">
+ {namingSources.length > 1 && (
+ <PropertyKeyInfo value={source.event} type={TaxonomicFilterGroupType.Events} disablePopover />
+ )}
+ <PropertyValue
+ propertyKey={source.namingProperty as string}
+ type={PropertyFilterType.Event}
+ operator={PropertyOperator.Exact}
+ eventNames={[source.event]}
+ value={excludedLabelsForSource(excludedItems, source)}
+ onSet={(labels: string[]) => setExcludedLabels(source, labels ?? [])}
+ placeholder="Values to exclude"
+ />
+ </div>
+ ))}
+ {namingSources.length > 0 && hasCleaningRules && (
+ <div className="text-secondary text-xs">
+ Path cleaning applies before matching. Exclude the cleaned value shown on the chart.
+ </div>
+ )}
+ {chips.active.length > 0 && (
+ <div className="flex flex-col gap-1">
+ <div className="text-secondary">Also excluded:</div>
+ <div className="flex flex-wrap gap-1">
+ {chips.active.map((item, index) => {
+ const source = stepSources.find(({ event }) => event === item.event) as PathsV2StepSource
+ return (
+ <Tooltip key={index} title={activeChipExplanation(item, source)}>
+ <LemonSnack onClose={() => removeExcludedItem(item)}>
+ {source.namingProperty ? `${item.event} with no value` : item.event}
+ </LemonSnack>
+ </Tooltip>
+ )
+ })}
+ </div>
+ </div>
+ )}
+ {chips.inert.length > 0 && (
+ <div className="flex flex-col gap-1">
+ <div className="text-secondary">Not applied. No step source produces these items:</div>
+ <div className="flex flex-wrap gap-1">
+ {chips.inert.map((item, index) => (
+ <LemonSnack key={index} onClose={() => removeExcludedItem(item)}>
+ {item.label || item.event}
+ </LemonSnack>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/journeys/JourneysSettings.tsx b/products/product_analytics/frontend/insights/journeys/JourneysSettings.tsx
new file mode 100644
index 000000000000..ae1447d22d46
--- /dev/null
+++ b/products/product_analytics/frontend/insights/journeys/JourneysSettings.tsx
@@ -0,0 +1,81 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonInput, LemonSwitch } from '@posthog/lemon-ui'
+
+import { PathCleaningControls } from 'lib/components/PathCleanFilters/PathCleaningControls'
+import { LemonLabel } from 'lib/lemon-ui/LemonLabel/LemonLabel'
+
+import { EditorFilterProps } from '~/types'
+
+import { MAX_ROWS_PER_STEP_BOUNDS, MAX_STEPS_BOUNDS } from './editorBounds'
+import { journeysDataLogic } from './journeysDataLogic'
+
+export function JourneysSettings({ insightProps }: EditorFilterProps): JSX.Element {
+ const { pathsV2Filter, draftMaxSteps, draftMaxRowsPerStep } = useValues(journeysDataLogic(insightProps))
+ const { updateInsightFilter, setDraftMaxSteps, setDraftMaxRowsPerStep, commitGridSize } = useActions(
+ journeysDataLogic(insightProps)
+ )
+
+ return (
+ <div className="flex flex-col gap-4 mt-2">
+ <div className="flex gap-4">
+ <div className="flex flex-col gap-1">
+ <LemonLabel info="How many steps of each journey are shown, as columns of the grid.">
+ Maximum steps
+ </LemonLabel>
+ <LemonInput
+ type="number"
+ min={MAX_STEPS_BOUNDS.min}
+ max={MAX_STEPS_BOUNDS.max}
+ value={draftMaxSteps ?? pathsV2Filter?.maxSteps ?? undefined}
+ placeholder="5"
+ onChange={(value) => setDraftMaxSteps(value ?? null)}
+ onBlur={commitGridSize}
+ onPressEnter={commitGridSize}
+ data-attr="journeys-max-steps"
+ />
+ </div>
+ <div className="flex flex-col gap-1">
+ <LemonLabel info='How many path items are shown per step. Items beyond this are grouped into the "Other" row.'>
+ Rows per step
+ </LemonLabel>
+ <LemonInput
+ type="number"
+ min={MAX_ROWS_PER_STEP_BOUNDS.min}
+ max={MAX_ROWS_PER_STEP_BOUNDS.max}
+ value={draftMaxRowsPerStep ?? pathsV2Filter?.maxRowsPerStep ?? undefined}
+ placeholder="3"
+ onChange={(value) => setDraftMaxRowsPerStep(value ?? null)}
+ onBlur={commitGridSize}
+ onPressEnter={commitGridSize}
+ data-attr="journeys-max-rows-per-step"
+ />
+ </div>
+ </div>
+ <LemonSwitch
+ checked={pathsV2Filter?.collapseRepeats ?? true}
+ onChange={(collapseRepeats) => updateInsightFilter({ collapseRepeats })}
+ label="Collapse repeated steps"
+ tooltip="Merge immediate repeats of the same path item within a journey. For example, A → A → B becomes A → B."
+ bordered
+ fullWidth
+ data-attr="journeys-collapse-repeats"
+ />
+ <div>
+ <LemonLabel
+ className="mb-2"
+ info="Rules that rewrite path item names with regex, mostly to normalize URLs. Rules added here apply only to this insight; rules from the project settings apply to all insights."
+ >
+ Path cleaning rules
+ </LemonLabel>
+ <PathCleaningControls
+ localFilters={pathsV2Filter?.localPathCleaningFilters ?? []}
+ setLocalFilters={(localPathCleaningFilters) => updateInsightFilter({ localPathCleaningFilters })}
+ applyGlobal={pathsV2Filter?.applyTeamPathCleaning ?? true}
+ setApplyGlobal={(applyTeamPathCleaning) => updateInsightFilter({ applyTeamPathCleaning })}
+ data-attr="journeys-apply-team-path-cleaning"
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/journeys/JourneysStepSourcePicker.tsx b/products/product_analytics/frontend/insights/journeys/JourneysStepSourcePicker.tsx
new file mode 100644
index 000000000000..42711cbd7113
--- /dev/null
+++ b/products/product_analytics/frontend/insights/journeys/JourneysStepSourcePicker.tsx
@@ -0,0 +1,136 @@
+import { useActions, useValues } from 'kea'
+import { useState } from 'react'
+
+import { IconPlusSmall, IconTrash } from '@posthog/icons'
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { TaxonomicStringPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'
+import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+
+import { EditorFilterProps } from '~/types'
+
+import { EventName } from 'products/actions/frontend/components/EventName'
+
+import { MAX_STEP_SOURCES } from './editorBounds'
+import { journeysDataLogic } from './journeysDataLogic'
+import { STEP_SOURCE_PRESETS, StepSourcePreset, presetForStepSources } from './stepSourcePresets'
+
+const PRESET_OPTIONS = Object.values(STEP_SOURCE_PRESETS).map(({ key, label }) => ({
+ value: key,
+ label,
+ 'data-attr': `journeys-step-source-${key}`,
+}))
+
+export function JourneysStepSourcePicker({ insightProps }: EditorFilterProps): JSX.Element {
+ const { pathsV2Filter, stepSources, anchor } = useValues(journeysDataLogic(insightProps))
+ const { setStepSources, setStepSourceEvent, setStepSourceNamingProperty, addStepSource, removeStepSource } =
+ useActions(journeysDataLogic(insightProps))
+
+ // A new source only enters the query once its event is picked, as a source without an event is
+ // not a valid query. Until then it exists as this pending row.
+ const [showPendingSource, setShowPendingSource] = useState(false)
+
+ const preset = presetForStepSources(pathsV2Filter?.stepSources ?? undefined)
+
+ return (
+ <div className="flex flex-col gap-2">
+ <LemonSegmentedButton
+ size="small"
+ value={preset?.key}
+ onChange={(key: StepSourcePreset['key']) => {
+ setStepSources(STEP_SOURCE_PRESETS[key].stepSources)
+ setShowPendingSource(false)
+ }}
+ options={PRESET_OPTIONS}
+ />
+ {stepSources.map((source, index) => {
+ const isAnchorSource = anchor?.item.event === source.event
+ return (
+ <div key={index} className="flex items-center gap-2">
+ <Tooltip title={isAnchorSource ? "This source is the journey's anchor" : undefined}>
+ <span className="inline-flex">
+ <EventName
+ value={source.event}
+ onChange={(event) => setStepSourceEvent(index, event)}
+ disabled={isAnchorSource}
+ />
+ </span>
+ </Tooltip>
+ <span className="text-secondary shrink-0">named by</span>
+ <TaxonomicStringPopover
+ groupType={TaxonomicFilterGroupType.EventProperties}
+ value={source.namingProperty ?? undefined}
+ onChange={(namingProperty) => setStepSourceNamingProperty(index, namingProperty)}
+ renderValue={(namingProperty) => (
+ <PropertyKeyInfo
+ value={namingProperty}
+ type={TaxonomicFilterGroupType.EventProperties}
+ disablePopover
+ />
+ )}
+ eventNames={[source.event]}
+ placeholder="Event name only"
+ allowClear
+ size="small"
+ type="secondary"
+ data-attr={`journeys-step-source-naming-property-${index}`}
+ />
+ <LemonButton
+ icon={<IconTrash />}
+ size="small"
+ onClick={() => removeStepSource(index)}
+ disabledReason={
+ stepSources.length === 1
+ ? 'At least one step source is required'
+ : isAnchorSource
+ ? "This source is the journey's anchor"
+ : undefined
+ }
+ tooltip="Remove step source"
+ data-attr={`journeys-step-source-remove-${index}`}
+ />
+ </div>
+ )
+ })}
+ {showPendingSource ? (
+ <div className="flex items-center gap-2">
+ <EventName
+ value=""
+ onChange={(event) => {
+ addStepSource(event)
+ setShowPendingSource(false)
+ }}
+ placeholder="Select event"
+ />
+ <LemonButton
+ icon={<IconTrash />}
+ size="small"
+ onClick={() => setShowPendingSource(false)}
+ tooltip="Remove step source"
+ data-attr="journeys-step-source-remove-new"
+ />
+ </div>
+ ) : (
+ <div>
+ <LemonButton
+ icon={<IconPlusSmall />}
+ size="small"
+ type="secondary"
+ onClick={() => setShowPendingSource(true)}
+ disabledReason={
+ stepSources.length >= MAX_STEP_SOURCES
+ ? `A journey supports up to ${MAX_STEP_SOURCES} step sources`
+ : undefined
+ }
+ data-attr="journeys-step-source-add"
+ >
+ Add step source
+ </LemonButton>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/journeys/JourneysViewAsFunnelButton.tsx b/products/product_analytics/frontend/insights/journeys/JourneysViewAsFunnelButton.tsx
new file mode 100644
index 000000000000..f92a7fbfefa6
--- /dev/null
+++ b/products/product_analytics/frontend/insights/journeys/JourneysViewAsFunnelButton.tsx
@@ -0,0 +1,39 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton } from '@posthog/lemon-ui'
+
+import { IconOpenInNew } from 'lib/lemon-ui/icons'
+
+import { PathsV2Item } from '~/queries/schema/schema-general'
+import { InsightLogicProps } from '~/types'
+
+import { journeysDataLogic } from './journeysDataLogic'
+
+export function JourneysViewAsFunnelButton({
+ logicProps,
+ items,
+ tooltip,
+}: {
+ logicProps: InsightLogicProps
+ /** The segment's path items in displayed order; the logic sends them to the converter endpoint. */
+ items: PathsV2Item[]
+ tooltip: string
+}): JSX.Element {
+ const logic = journeysDataLogic(logicProps)
+ const { segmentFunnelLoading } = useValues(logic)
+ const { viewSegmentAsFunnel } = useActions(logic)
+
+ return (
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ icon={<IconOpenInNew />}
+ loading={segmentFunnelLoading}
+ tooltip={tooltip}
+ onClick={() => viewSegmentAsFunnel(items)}
+ data-attr="journeys-view-as-funnel"
+ >
+ View as funnel
+ </LemonButton>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/journeys/editorBounds.test.ts b/products/product_analytics/frontend/insights/journeys/editorBounds.test.ts
new file mode 100644
index 000000000000..2e6e608883fe
--- /dev/null
+++ b/products/product_analytics/frontend/insights/journeys/editorBounds.test.ts
@@ -0,0 +1,17 @@
+import schema from '~/queries/schema.json'
+
+import { MAX_ROWS_PER_STEP_BOUNDS, MAX_STEP_SOURCES, MAX_STEPS_BOUNDS } from './editorBounds'
+
+describe('journeys editor bounds', () => {
+ // The server rejects out-of-bounds values instead of clamping, so drifted editor bounds either
+ // block values the server accepts or let through values the server rejects.
+ it('match the PathsV2Filter schema bounds', () => {
+ const properties = (schema as any).definitions.PathsV2Filter.properties
+ expect(MAX_STEPS_BOUNDS).toEqual({ min: properties.maxSteps.minimum, max: properties.maxSteps.maximum })
+ expect(MAX_ROWS_PER_STEP_BOUNDS).toEqual({
+ min: properties.maxRowsPerStep.minimum,
+ max: properties.maxRowsPerStep.maximum,
+ })
+ expect(MAX_STEP_SOURCES).toBe(properties.stepSources.maxItems)
+ })
+})
diff --git a/products/product_analytics/frontend/insights/journeys/editorBounds.ts b/products/product_analytics/frontend/insights/journeys/editorBounds.ts
new file mode 100644
index 000000000000..783d74e9decf
--- /dev/null
+++ b/products/product_analytics/frontend/insights/journeys/editorBounds.ts
@@ -0,0 +1,6 @@
+// Mirrors of PathsV2Filter's schema bounds, which the server enforces without clamping.
+// editorBounds.test.ts pins each constant to the generated schema.json.
+
+export const MAX_STEPS_BOUNDS = { min: 2, max: 20 }
+export const MAX_ROWS_PER_STEP_BOUNDS = { min: 1, max: 10 }
+export const MAX_STEP_SOURCES = 20
diff --git a/products/product_analytics/frontend/insights/journeys/exclusionUtils.test.ts b/products/product_analytics/frontend/insights/journeys/exclusionUtils.test.ts
new file mode 100644
index 000000000000..b7dca31e44ac
--- /dev/null
+++ b/products/product_analytics/frontend/insights/journeys/exclusionUtils.test.ts
@@ -0,0 +1,45 @@
+import { PathsV2Item, PathsV2StepSource } from '~/queries/schema/schema-general'
+
+import { excludedItemChips, excludedLabelsForSource, withExcludedLabels } from './exclusionUtils'
+
+const pageviews: PathsV2StepSource = { event: '$pageview', namingProperty: '$pathname' }
+const screens: PathsV2StepSource = { event: '$screen', namingProperty: '$screen_name' }
+const signup: PathsV2StepSource = { event: 'signup' }
+
+describe('journeys exclusion utils', () => {
+ const excluded: PathsV2Item[] = [
+ { event: '$pageview', label: '/login' },
+ { event: '$screen', label: 'Login' },
+ { event: '$pageview' },
+ { event: 'signup' },
+ { event: 'signup', label: 'x' },
+ { event: 'gone', label: '/x' },
+ ]
+
+ it('lists only the labels editable through the given source', () => {
+ expect(excludedLabelsForSource(excluded, pageviews)).toEqual(['/login'])
+ })
+
+ it("replaces one source's labels without touching other exclusions", () => {
+ expect(withExcludedLabels(excluded, pageviews, ['/logout'])).toEqual([
+ { event: '$screen', label: 'Login' },
+ { event: '$pageview' },
+ { event: 'signup' },
+ { event: 'signup', label: 'x' },
+ { event: 'gone', label: '/x' },
+ { event: '$pageview', label: '/logout' },
+ ])
+ })
+
+ it('splits chip exclusions into applied and inert exactly as the backend matches them', () => {
+ expect(excludedItemChips(excluded, [pageviews, screens, signup])).toEqual({
+ // (event, '') items: the whole signup event, and pageviews with no pathname.
+ active: [{ event: '$pageview' }, { event: 'signup' }],
+ // No derivable item can equal these: a labeled item of a label-less source, an unknown event.
+ inert: [
+ { event: 'signup', label: 'x' },
+ { event: 'gone', label: '/x' },
+ ],
+ })
+ })
+})
diff --git a/products/product_analytics/frontend/insights/journeys/exclusionUtils.ts b/products/product_analytics/frontend/insights/journeys/exclusionUtils.ts
new file mode 100644
index 000000000000..442b4a62b6a1
--- /dev/null
+++ b/products/product_analytics/frontend/insights/journeys/exclusionUtils.ts
@@ -0,0 +1,53 @@
+import { PathsV2Item, PathsV2StepSource } from '~/queries/schema/schema-general'
+
+/** Whether an excluded item is editable through a source's exclusion row: it targets a current
+ * naming-property source with a non-empty label. Empty and missing labels mean the same excluded
+ * item, (event, ''), which the chip groups cover instead. */
+function isEditableThrough(item: PathsV2Item, source: PathsV2StepSource): boolean {
+ return !!source.namingProperty && source.event === item.event && !!item.label
+}
+
+/** The excluded labels of one naming-property source, in exclude-list order. */
+export function excludedLabelsForSource(excludedItems: PathsV2Item[], source: PathsV2StepSource): string[] {
+ return excludedItems.filter((item) => isEditableThrough(item, source)).map((item) => item.label as string)
+}
+
+/** Replace one source's excluded labels, leaving every other exclusion untouched. */
+export function withExcludedLabels(
+ excludedItems: PathsV2Item[],
+ source: PathsV2StepSource,
+ labels: string[]
+): PathsV2Item[] {
+ return [
+ ...excludedItems.filter((item) => !isEditableThrough(item, source)),
+ ...labels.map((label) => ({ event: source.event, label })),
+ ]
+}
+
+export interface ExcludedItemChips {
+ /** Exclusions the backend applies but no exclusion row can edit: the (event, '') items, which
+ * for a source without a naming property mean the whole event and for one with a naming
+ * property mean the item whose property value is missing. */
+ active: PathsV2Item[]
+ /** Exclusions no derivable item can equal, which the backend keeps inert: their event is not a
+ * step source, or they name a label on a source without a naming property. */
+ inert: PathsV2Item[]
+}
+
+/** Split the exclusions no row edits into chips, mirroring the backend's (event, label or '')
+ * matching so the editor never claims an applied exclusion is inert or the other way around. */
+export function excludedItemChips(excludedItems: PathsV2Item[], stepSources: PathsV2StepSource[]): ExcludedItemChips {
+ const chips: ExcludedItemChips = { active: [], inert: [] }
+ for (const item of excludedItems) {
+ const source = stepSources.find(({ event }) => event === item.event)
+ if (!source) {
+ chips.inert.push(item)
+ } else if (!item.label) {
+ chips.active.push(item)
+ } else if (!source.namingProperty) {
+ chips.inert.push(item)
+ }
+ // Otherwise the item is editable through its source's exclusion row.
+ }
+ return chips
+}
diff --git a/products/product_analytics/frontend/insights/journeys/journeyGridModel.test.ts b/products/product_analytics/frontend/insights/journeys/journeyGridModel.test.ts
new file mode 100644
index 000000000000..3a92c686d959
--- /dev/null
+++ b/products/product_analytics/frontend/insights/journeys/journeyGridModel.test.ts
@@ -0,0 +1,240 @@
+import { PathsV2Results } from '~/queries/schema/schema-general'
+
+import {
+ OTHER_ROW_KEY,
+ buildJourneyGridModel,
+ chainCardKey,
+ dominantDisplayedChain,
+ isChainDisplayed,
+ journeyItemKey,
+ journeyItemLabel,
+} from './journeyGridModel'
+
+const item = (event: string, label?: string | null): { event: string; label?: string | null } => ({ event, label })
+
+describe('journeyGridModel', () => {
+ describe('buildJourneyGridModel', () => {
+ it('returns an empty model for null or empty results', () => {
+ expect(buildJourneyGridModel(null)).toEqual({
+ columns: [],
+ ribbons: [],
+ maxRibbonCount: 0,
+ displayedItemKeys: new Set(),
+ })
+ expect(buildJourneyGridModel({ steps: [], edges: [], prefixes: [] })).toEqual({
+ columns: [],
+ ribbons: [],
+ maxRibbonCount: 0,
+ displayedItemKeys: new Set(),
+ })
+ })
+
+ it('orders each column as named rows, then other, then drop-off, with per-step totals', () => {
+ const results: PathsV2Results = {
+ steps: [
+ {
+ stepIndex: 0,
+ rows: [
+ { item: item('$pageview', '/home'), count: 60 },
+ { item: item('$pageview', '/pricing'), count: 30 },
+ ],
+ otherCount: 10,
+ dropOffCount: 25,
+ },
+ ],
+ edges: [],
+ prefixes: [],
+ }
+
+ const model = buildJourneyGridModel(results)
+
+ expect(model.columns).toHaveLength(1)
+ const column = model.columns[0]
+ // The displayed total is named rows plus the other row; drop-off actors are already in those rows
+ expect(column.total).toEqual(100)
+ expect(column.rows.map((row) => [row.kind, row.label, row.count, row.fraction])).toEqual([
+ ['item', '/home', 60, 0.6],
+ ['item', '/pricing', 30, 0.3],
+ ['other', 'Other', 10, 0.1],
+ ['dropOff', 'Ends here', 25, 0.25],
+ ])
+ })
+
+ it('omits zero-count other and drop-off rows and survives an all-zero column', () => {
+ const model = buildJourneyGridModel({
+ steps: [{ stepIndex: 0, rows: [], otherCount: 0, dropOffCount: 0 }],
+ edges: [],
+ prefixes: [],
+ })
+ expect(model.columns[0].rows).toEqual([])
+ expect(model.columns[0].total).toEqual(0)
+ })
+
+ it('sorts columns by step index', () => {
+ const model = buildJourneyGridModel({
+ steps: [
+ { stepIndex: 1, rows: [{ item: item('a', null), count: 1 }], otherCount: 0, dropOffCount: 0 },
+ { stepIndex: 0, rows: [{ item: item('b', null), count: 2 }], otherCount: 0, dropOffCount: 0 },
+ ],
+ edges: [],
+ prefixes: [],
+ })
+ expect(model.columns.map((column) => column.stepIndex)).toEqual([0, 1])
+ })
+
+ it('resolves ribbons to rows, mapping null endpoints to the other row', () => {
+ const results: PathsV2Results = {
+ steps: [
+ {
+ stepIndex: 0,
+ rows: [{ item: item('$pageview', '/home'), count: 50 }],
+ otherCount: 5,
+ dropOffCount: 0,
+ },
+ {
+ stepIndex: 1,
+ rows: [{ item: item('$pageview', '/pricing'), count: 20 }],
+ otherCount: 8,
+ dropOffCount: 0,
+ },
+ ],
+ edges: [
+ {
+ stepIndex: 0,
+ source: item('$pageview', '/home'),
+ target: item('$pageview', '/pricing'),
+ count: 20,
+ },
+ { stepIndex: 0, source: item('$pageview', '/home'), target: null, count: 5 },
+ { stepIndex: 0, source: null, target: item('$pageview', '/pricing'), count: 3 },
+ ],
+ prefixes: [],
+ }
+
+ const model = buildJourneyGridModel(results)
+
+ expect(model.ribbons.map((ribbon) => [ribbon.sourceKey, ribbon.targetKey, ribbon.count])).toEqual([
+ [journeyItemKey(item('$pageview', '/home')), journeyItemKey(item('$pageview', '/pricing')), 20],
+ [journeyItemKey(item('$pageview', '/home')), OTHER_ROW_KEY, 5],
+ [OTHER_ROW_KEY, journeyItemKey(item('$pageview', '/pricing')), 3],
+ ])
+ // Edge share is relative to the source row's count (positional: ribbons subset their cards)
+ expect(model.ribbons[0].fractionOfSource).toEqual(0.4)
+ expect(model.ribbons[2].fractionOfSource).toEqual(0.6)
+ expect(model.maxRibbonCount).toEqual(20)
+ })
+
+ it('skips zero-count edges and edges whose endpoints are not in the grid', () => {
+ const model = buildJourneyGridModel({
+ steps: [
+ {
+ stepIndex: 0,
+ rows: [{ item: item('$pageview', '/home'), count: 10 }],
+ otherCount: 0,
+ dropOffCount: 0,
+ },
+ {
+ stepIndex: 1,
+ rows: [{ item: item('$pageview', '/pricing'), count: 10 }],
+ otherCount: 0,
+ dropOffCount: 0,
+ },
+ ],
+ edges: [
+ { stepIndex: 0, source: item('$pageview', '/home'), target: item('$pageview', '/gone'), count: 4 },
+ { stepIndex: 0, source: null, target: item('$pageview', '/pricing'), count: 2 },
+ {
+ stepIndex: 0,
+ source: item('$pageview', '/home'),
+ target: item('$pageview', '/pricing'),
+ count: 0,
+ },
+ ],
+ prefixes: [],
+ })
+ expect(model.ribbons).toEqual([])
+ })
+
+ it('lists only the named rows it renders as displayed item keys', () => {
+ const model = buildJourneyGridModel({
+ steps: [
+ {
+ stepIndex: 0,
+ rows: [{ item: item('$pageview', '/home'), count: 10 }],
+ otherCount: 3,
+ dropOffCount: 2,
+ },
+ ],
+ edges: [],
+ prefixes: [],
+ })
+ expect(model.displayedItemKeys).toEqual(new Set([chainCardKey(0, item('$pageview', '/home'))]))
+ })
+ })
+
+ describe('hover chain selection', () => {
+ const home = item('$pageview', '/home')
+ const cart = item('$pageview', '/cart')
+ const hidden = item('$pageview', '/hidden')
+ const checkout = item('$pageview', '/checkout')
+ const displayed = new Set([chainCardKey(0, home), chainCardKey(1, cart), chainCardKey(2, checkout)])
+
+ it('picks the dominant chain ending at the card, prefixes arriving count-descending', () => {
+ const prefixes = [
+ { items: [home, cart, checkout], count: 30 },
+ { items: [home, cart], count: 40 },
+ { items: [home], count: 100 },
+ ]
+ expect(dominantDisplayedChain(prefixes, 2, journeyItemKey(checkout), displayed)).toEqual([
+ home,
+ cart,
+ checkout,
+ ])
+ })
+
+ it('skips chains running through an item the grid bucketed into the other row', () => {
+ // The dominant chain reaches /checkout via /hidden, which has no card, so previewing it
+ // would break the highlight and name an item the chart never showed.
+ const prefixes = [
+ { items: [home, hidden, checkout], count: 90 },
+ { items: [home, cart, checkout], count: 10 },
+ ]
+ expect(dominantDisplayedChain(prefixes, 2, journeyItemKey(checkout), displayed)).toEqual([
+ home,
+ cart,
+ checkout,
+ ])
+ })
+
+ it('returns null when no chain of the right length and ending is displayable', () => {
+ const prefixes = [{ items: [home, hidden, checkout], count: 90 }]
+ expect(dominantDisplayedChain(prefixes, 2, journeyItemKey(checkout), displayed)).toBeNull()
+ // A chain of the wrong length never matches a card at that column
+ expect(
+ dominantDisplayedChain([{ items: [home, cart], count: 5 }], 2, journeyItemKey(cart), displayed)
+ ).toBeNull()
+ })
+
+ it('treats a chain as displayed only when every position has a card', () => {
+ expect(isChainDisplayed([home, cart], displayed)).toBe(true)
+ expect(isChainDisplayed([home, hidden], displayed)).toBe(false)
+ // Right items, wrong positions
+ expect(isChainDisplayed([cart, home], displayed)).toBe(false)
+ })
+ })
+
+ describe('item identity and labels', () => {
+ it('keeps a null label (no naming property) distinct from an empty label', () => {
+ expect(journeyItemKey(item('$pageview', null))).not.toEqual(journeyItemKey(item('$pageview', '')))
+ })
+
+ test.each([
+ ['a null label falls back to the event name', item('custom_event', null), 'custom_event'],
+ ['an undefined label falls back to the event name', item('custom_event'), 'custom_event'],
+ ['an empty label reads as empty', item('$pageview', ''), '(empty)'],
+ ['a set label is used as is', item('$pageview', '/home'), '/home'],
+ ])('%s', (_name, input, expected) => {
+ expect(journeyItemLabel(input)).toEqual(expected)
+ })
+ })
+})
diff --git a/products/product_analytics/frontend/insights/journeys/journeyGridModel.ts b/products/product_analytics/frontend/insights/journeys/journeyGridModel.ts
new file mode 100644
index 000000000000..6b6dd16bff73
--- /dev/null
+++ b/products/product_analytics/frontend/insights/journeys/journeyGridModel.ts
@@ -0,0 +1,216 @@
+import { PathsV2Item, PathsV2Prefix, PathsV2Results } from '~/queries/schema/schema-general'
+
+export const OTHER_ROW_KEY = 'other'
+const DROP_OFF_ROW_KEY = 'dropOff'
+
+export type JourneyGridRowKind = 'item' | 'other' | 'dropOff'
+
+export interface JourneyGridRow {
+ /** Unique within the column; ribbons reference rows by (stepIndex, key). */
+ key: string
+ kind: JourneyGridRowKind
+ item: PathsV2Item | null
+ label: string
+ count: number
+ /** Share of the column's displayed total; 0 when the total is 0. */
+ fraction: number
+}
+
+export interface JourneyGridColumn {
+ stepIndex: number
+ /** Named item rows by count descending, then the other row, then the drop-off row. */
+ rows: JourneyGridRow[]
+ /** The column's displayed unique-actor total: named rows plus the other row. */
+ total: number
+}
+
+export interface JourneyGridRibbon {
+ key: string
+ /** Column index of the source row; the target row sits at sourceStep + 1. */
+ sourceStep: number
+ sourceKey: string
+ targetKey: string
+ count: number
+ /** Share of the source row's count, shown in the ribbon tooltip. */
+ fractionOfSource: number
+ sourceLabel: string
+ targetLabel: string
+ /** The endpoints' path items; null for an endpoint on the column's other row. */
+ sourceItem: PathsV2Item | null
+ targetItem: PathsV2Item | null
+ /** Position-free count of the transition at any step; only on open-mode named-named edges. */
+ anyStepCount: number | null
+}
+
+export interface JourneyGridModel {
+ columns: JourneyGridColumn[]
+ ribbons: JourneyGridRibbon[]
+ maxRibbonCount: number
+ /** Card keys of the named rows the grid actually renders, so a hover chain can be restricted to
+ * items the user can see. Items beyond the top rows per step live in the other row instead. */
+ displayedItemKeys: Set<string>
+}
+
+/** The active hover-preview chain resolved against the grid: per-card chain counts plus the
+ * ribbons connecting them. Card keys are `${stepIndex}:${rowKey}`, ribbon keys match ribbon.key. */
+export interface JourneyChainHighlight {
+ chain: PathsV2Item[]
+ countByCardKey: Record<string, number>
+ /** The chain count as a share of the card's column total, so a re-labelled card's bar keeps
+ * describing the number printed on it rather than the merged union's. */
+ fractionByCardKey: Record<string, number>
+ ribbonKeys: Set<string>
+}
+
+export function chainCardKey(stepIndex: number, item: PathsV2Item): string {
+ return `${stepIndex}:${journeyItemKey(item)}`
+}
+
+export function journeyRibbonKey(sourceStep: number, sourceKey: string, targetKey: string): string {
+ return `${sourceStep}:${sourceKey}→${targetKey}`
+}
+
+/** Whether every item of a chain is a named card the grid renders at that item's position. */
+export function isChainDisplayed(items: PathsV2Item[], displayedItemKeys: Set<string>): boolean {
+ return items.every((item, position) => displayedItemKeys.has(chainCardKey(position, item)))
+}
+
+/**
+ * The most common chain of `stepIndex + 1` items ending at `itemKey`, or null if none is previewable.
+ *
+ * Prefixes arrive count-descending, so the first match is the dominant chain. Chains running through
+ * items the grid bucketed into the other row are skipped: their cards do not exist, so the highlight
+ * would show disconnected islands and the modal title would name an item the chart never displayed.
+ */
+export function dominantDisplayedChain(
+ prefixes: PathsV2Prefix[],
+ stepIndex: number,
+ itemKey: string,
+ displayedItemKeys: Set<string>
+): PathsV2Item[] | null {
+ const match = prefixes.find(
+ (prefix) =>
+ prefix.items.length === stepIndex + 1 &&
+ journeyItemKey(prefix.items[stepIndex]) === itemKey &&
+ isChainDisplayed(prefix.items, displayedItemKeys)
+ )
+ return match?.items ?? null
+}
+
+export function isCardOnChain(chain: PathsV2Item[] | null, stepIndex: number, rowKey: string): boolean {
+ return (
+ chain !== null &&
+ stepIndex < chain.length &&
+ journeyItemKey(chain[stepIndex]) === rowKey &&
+ rowKey !== OTHER_ROW_KEY
+ )
+}
+
+export function journeyItemKey(item: PathsV2Item): string {
+ // The label distinguishes null (source without a naming property) from '' (missing property value)
+ return `item:${JSON.stringify([item.event, item.label ?? null])}`
+}
+
+export function journeyItemLabel(item: PathsV2Item): string {
+ if (item.label == null) {
+ return item.event
+ }
+ return item.label === '' ? '(empty)' : item.label
+}
+
+export function buildJourneyGridModel(results: PathsV2Results | null): JourneyGridModel {
+ if (!results || results.steps.length === 0) {
+ return { columns: [], ribbons: [], maxRibbonCount: 0, displayedItemKeys: new Set() }
+ }
+
+ const steps = [...results.steps].sort((a, b) => a.stepIndex - b.stepIndex)
+
+ const columns: JourneyGridColumn[] = steps.map((step) => {
+ const total = step.rows.reduce((sum, row) => sum + row.count, 0) + step.otherCount
+ const rows: JourneyGridRow[] = step.rows.map((row) => ({
+ key: journeyItemKey(row.item),
+ kind: 'item' as const,
+ item: row.item,
+ label: journeyItemLabel(row.item),
+ count: row.count,
+ fraction: total > 0 ? row.count / total : 0,
+ }))
+ if (step.otherCount > 0) {
+ rows.push({
+ key: OTHER_ROW_KEY,
+ kind: 'other',
+ item: null,
+ label: 'Other',
+ count: step.otherCount,
+ fraction: total > 0 ? step.otherCount / total : 0,
+ })
+ }
+ if (step.dropOffCount > 0) {
+ rows.push({
+ key: DROP_OFF_ROW_KEY,
+ kind: 'dropOff',
+ item: null,
+ label: 'Ends here',
+ count: step.dropOffCount,
+ fraction: total > 0 ? step.dropOffCount / total : 0,
+ })
+ }
+ return { stepIndex: step.stepIndex, rows, total }
+ })
+
+ const rowByStepAndKey = new Map<string, JourneyGridRow>()
+ const displayedItemKeys = new Set<string>()
+ for (const column of columns) {
+ for (const row of column.rows) {
+ rowByStepAndKey.set(`${column.stepIndex}:${row.key}`, row)
+ if (row.kind === 'item') {
+ displayedItemKeys.add(`${column.stepIndex}:${row.key}`)
+ }
+ }
+ }
+
+ const ribbons: JourneyGridRibbon[] = []
+ for (const edge of results.edges) {
+ if (edge.count <= 0) {
+ continue
+ }
+ const sourceKey = edge.source ? journeyItemKey(edge.source) : OTHER_ROW_KEY
+ const targetKey = edge.target ? journeyItemKey(edge.target) : OTHER_ROW_KEY
+ const sourceRow = rowByStepAndKey.get(`${edge.stepIndex}:${sourceKey}`)
+ const targetRow = rowByStepAndKey.get(`${edge.stepIndex + 1}:${targetKey}`)
+ // The runner buckets edge endpoints the same way as node rows, so both should resolve;
+ // skip defensively rather than render a dangling ribbon.
+ if (!sourceRow || !targetRow) {
+ continue
+ }
+ ribbons.push({
+ key: journeyRibbonKey(edge.stepIndex, sourceKey, targetKey),
+ sourceStep: edge.stepIndex,
+ sourceKey,
+ targetKey,
+ count: edge.count,
+ fractionOfSource: sourceRow.count > 0 ? edge.count / sourceRow.count : 0,
+ sourceLabel: sourceRow.label,
+ targetLabel: targetRow.label,
+ sourceItem: edge.source ?? null,
+ targetItem: edge.target ?? null,
+ anyStepCount: edge.anyStepCount ?? null,
+ })
+ }
+
+ const maxRibbonCount = ribbons.reduce((max, ribbon) => Math.max(max, ribbon.count), 0)
+
+ return { columns, ribbons, maxRibbonCount, displayedItemKeys }
+}
+
+/** A closed band from the source card's right edge to the target card's left edge. */
+export function ribbonPath(x0: number, y0: number, t0: number, x1: number, y1: number, t1: number): string {
+ const xm = (x0 + x1) / 2
+ return [
+ `M ${x0},${y0}`,
+ `C ${xm},${y0} ${xm},${y1} ${x1},${y1}`,
+ `L ${x1},${y1 + t1}`,
+ `C ${xm},${y1 + t1} ${xm},${y0 + t0} ${x0},${y0 + t0}`,
+ 'Z',
+ ].join(' ')
+}
diff --git a/products/product_analytics/frontend/insights/journeys/journeysDataLogic.ts b/products/product_analytics/frontend/insights/journeys/journeysDataLogic.ts
new file mode 100644
index 000000000000..d251f9a1fbbc
--- /dev/null
+++ b/products/product_analytics/frontend/insights/journeys/journeysDataLogic.ts
@@ -0,0 +1,532 @@
+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import type { ReactNode } from 'react'
+
+import { ApiConfig } from 'lib/api'
+import type { DataColorTheme } from 'lib/colors'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { newInternalTab } from 'lib/utils/newInternalTab'
+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
+import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'
+import { openPersonsModal } from 'scenes/trends/persons-modal/PersonsModal'
+import { urls } from 'scenes/urls'
+
+import {
+ InsightFilter,
+ InsightVizNode,
+ NodeKind,
+ PathsV2Anchor,
+ PathsV2ElementSelector,
+ PathsV2ElementType,
+ PathsV2Filter,
+ PathsV2Item,
+ PathsV2Prefix,
+ PathsV2Query,
+ PathsV2Results,
+ PathsV2StepSource,
+} from '~/queries/schema/schema-general'
+import type {
+ FunnelsQuery,
+ LifecycleQuery,
+ PathsQuery,
+ RetentionQuery,
+ StickinessQuery,
+ TrendsQuery,
+ WebOverviewQuery,
+ WebStatsTableQuery,
+} from '~/queries/schema/schema-general'
+import { InsightLogicProps } from '~/types'
+
+import { pathsV2SegmentToFunnelCreate } from '../../generated/api'
+import { MAX_ROWS_PER_STEP_BOUNDS, MAX_STEPS_BOUNDS } from './editorBounds'
+import { withExcludedLabels } from './exclusionUtils'
+import {
+ JourneyChainHighlight,
+ JourneyGridModel,
+ JourneyGridRibbon,
+ JourneyGridRow,
+ buildJourneyGridModel,
+ chainCardKey,
+ dominantDisplayedChain,
+ isCardOnChain,
+ isChainDisplayed,
+ journeyItemKey,
+ journeyRibbonKey,
+} from './journeyGridModel'
+import {
+ journeysChainModalTitle,
+ journeysDropOffModalTitle,
+ journeysEdgeModalTitle,
+ journeysNodeModalTitle,
+ journeysOtherModalTitle,
+} from './journeysModalTitles'
+import { DEFAULT_STEP_SOURCES } from './stepSourcePresets'
+
+const DEFAULT_JOURNEYS_LOGIC_KEY = 'default_journeys_key'
+
+function chainKey(items: PathsV2Item[]): string {
+ return JSON.stringify(items.map(journeyItemKey))
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface journeysDataLogicValues {
+ insightData: Record<string, any> // insightVizDataLogic
+ pathsV2Filter: PathsV2Filter | null | undefined // insightVizDataLogic
+ theme: DataColorTheme | null // insightVizDataLogic
+ vizQuerySource:
+ | FunnelsQuery
+ | LifecycleQuery
+ | PathsQuery
+ | PathsV2Query
+ | RetentionQuery
+ | StickinessQuery
+ | TrendsQuery
+ | WebOverviewQuery
+ | WebStatsTableQuery
+ | null // insightVizDataLogic
+ activeChain: PathsV2Item[] | null
+ activeChainHighlight: JourneyChainHighlight | null
+ anchor: PathsV2Anchor | null
+ draftMaxRowsPerStep: number | null
+ draftMaxSteps: number | null
+ excludedItems: PathsV2Item[]
+ gridModel: JourneyGridModel
+ isAnchored: boolean
+ prefixCounts: Map<string, number>
+ prefixes: PathsV2Prefix[]
+ results: PathsV2Results | null
+ segmentFunnelLoading: boolean
+ stepSources: PathsV2StepSource[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface journeysDataLogicActions {
+ updateInsightFilter: (insightFilter: InsightFilter) => {
+ insightFilter: InsightFilter
+ } // insightVizDataLogic
+ addStepSource: (event: string) => {
+ event: string
+ }
+ cardClicked: (
+ stepIndex: number,
+ row: JourneyGridRow
+ ) => {
+ row: JourneyGridRow
+ stepIndex: number
+ }
+ cardHovered: (
+ stepIndex: number,
+ row: JourneyGridRow
+ ) => {
+ row: JourneyGridRow
+ stepIndex: number
+ }
+ commitGridSize: () => {
+ value: true
+ }
+ gridLeft: () => {
+ value: true
+ }
+ removeExcludedItem: (item: PathsV2Item) => {
+ item: PathsV2Item
+ }
+ removeStepSource: (index: number) => {
+ index: number
+ }
+ ribbonClicked: (ribbon: JourneyGridRibbon) => {
+ ribbon: JourneyGridRibbon
+ }
+ ribbonHovered: (ribbon: JourneyGridRibbon) => {
+ ribbon: JourneyGridRibbon
+ }
+ setActiveChain: (chain: PathsV2Item[] | null) => {
+ chain: PathsV2Item[] | null
+ }
+ setDraftMaxRowsPerStep: (maxRowsPerStep: number | null) => {
+ maxRowsPerStep: number | null
+ }
+ setDraftMaxSteps: (maxSteps: number | null) => {
+ maxSteps: number | null
+ }
+ setExcludedLabels: (
+ source: PathsV2StepSource,
+ labels: string[]
+ ) => {
+ labels: string[]
+ source: PathsV2StepSource
+ }
+ setStepSourceEvent: (
+ index: number,
+ event: string
+ ) => {
+ event: string
+ index: number
+ }
+ setStepSourceNamingProperty: (
+ index: number,
+ namingProperty: string
+ ) => {
+ index: number
+ namingProperty: string
+ }
+ setStepSources: (stepSources: PathsV2StepSource[]) => {
+ stepSources: PathsV2StepSource[]
+ }
+ viewSegmentAsFunnel: (items: PathsV2Item[]) => {
+ items: PathsV2Item[]
+ }
+ viewSegmentAsFunnelFinished: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface journeysDataLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ results: (insightData: Record<string, any>) => PathsV2Results | null
+ isAnchored: (pathsV2Filter: PathsV2Filter | null | undefined) => boolean
+ gridModel: (results: PathsV2Results | null) => JourneyGridModel
+ stepSources: (pathsV2Filter: PathsV2Filter | null | undefined) => PathsV2StepSource[]
+ anchor: (pathsV2Filter: PathsV2Filter | null | undefined) => PathsV2Anchor | null
+ excludedItems: (pathsV2Filter: PathsV2Filter | null | undefined) => PathsV2Item[]
+ prefixes: (results: PathsV2Results | null) => PathsV2Prefix[]
+ prefixCounts: (prefixes: PathsV2Prefix[]) => Map<string, number>
+ activeChainHighlight: (
+ activeChain: PathsV2Item[] | null,
+ prefixCounts: Map<string, number>,
+ gridModel: JourneyGridModel
+ ) => JourneyChainHighlight | null
+ }
+}
+
+export type journeysDataLogicType = MakeLogicType<
+ journeysDataLogicValues,
+ journeysDataLogicActions,
+ InsightLogicProps,
+ journeysDataLogicMeta
+>
+
+const clamp = (value: number, bounds: { min: number; max: number }): number =>
+ Math.min(Math.max(value, bounds.min), bounds.max)
+
+export const journeysDataLogic = kea<journeysDataLogicType>([
+ props({} as InsightLogicProps),
+ key(keyForInsightLogicProps(DEFAULT_JOURNEYS_LOGIC_KEY)),
+ path((key) => ['products', 'product_analytics', 'insights', 'journeys', 'journeysDataLogic', key]),
+ connect((props: InsightLogicProps) => ({
+ values: [
+ insightVizDataLogic(props),
+ ['insightData', 'pathsV2Filter', 'theme', 'querySource as vizQuerySource'],
+ ],
+ actions: [insightVizDataLogic(props), ['updateInsightFilter']],
+ })),
+ actions({
+ setStepSources: (stepSources: PathsV2StepSource[]) => ({ stepSources }),
+ setStepSourceEvent: (index: number, event: string) => ({ index, event }),
+ setStepSourceNamingProperty: (index: number, namingProperty: string) => ({ index, namingProperty }),
+ addStepSource: (event: string) => ({ event }),
+ removeStepSource: (index: number) => ({ index }),
+ setExcludedLabels: (source: PathsV2StepSource, labels: string[]) => ({ source, labels }),
+ removeExcludedItem: (item: PathsV2Item) => ({ item }),
+ setDraftMaxSteps: (maxSteps: number | null) => ({ maxSteps }),
+ setDraftMaxRowsPerStep: (maxRowsPerStep: number | null) => ({ maxRowsPerStep }),
+ commitGridSize: true,
+ cardClicked: (stepIndex: number, row: JourneyGridRow) => ({ stepIndex, row }),
+ ribbonClicked: (ribbon: JourneyGridRibbon) => ({ ribbon }),
+ cardHovered: (stepIndex: number, row: JourneyGridRow) => ({ stepIndex, row }),
+ ribbonHovered: (ribbon: JourneyGridRibbon) => ({ ribbon }),
+ gridLeft: true,
+ setActiveChain: (chain: PathsV2Item[] | null) => ({ chain }),
+ viewSegmentAsFunnel: (items: PathsV2Item[]) => ({ items }),
+ viewSegmentAsFunnelFinished: true,
+ }),
+ reducers({
+ // Grid-size inputs commit on blur/enter rather than per keystroke; null means untouched,
+ // so external filter changes keep showing through until the user edits.
+ draftMaxSteps: [
+ null as number | null,
+ {
+ setDraftMaxSteps: (_, { maxSteps }) => maxSteps,
+ },
+ ],
+ draftMaxRowsPerStep: [
+ null as number | null,
+ {
+ setDraftMaxRowsPerStep: (_, { maxRowsPerStep }) => maxRowsPerStep,
+ },
+ ],
+ // The hover-preview chain (anchored mode). Hovering a card or a ribbon activates the dominant
+ // chain reaching it; hovering a card already on the chain keeps the chain, so the pointer can
+ // travel from a ribbon onto a chain card and the card's click opens the chain's persons
+ // rather than the union's. Leaving the grid clears it.
+ activeChain: [
+ null as PathsV2Item[] | null,
+ {
+ setActiveChain: (_, { chain }) => chain,
+ updateInsightFilter: () => null,
+ },
+ ],
+ // Guards the "view as funnel" buttons against double-submission while the converter
+ // endpoint round-trip is in flight.
+ segmentFunnelLoading: [
+ false,
+ {
+ viewSegmentAsFunnel: () => true,
+ viewSegmentAsFunnelFinished: () => false,
+ },
+ ],
+ }),
+ selectors({
+ results: [
+ (s) => [s.insightData],
+ (insightData: Record<string, any> | null): PathsV2Results | null => {
+ const results = insightData?.result ?? insightData?.results
+ return results && Array.isArray(results.steps) ? (results as PathsV2Results) : null
+ },
+ ],
+ isAnchored: [
+ (s) => [s.pathsV2Filter],
+ (pathsV2Filter: PathsV2Filter | null): boolean => !!pathsV2Filter?.anchor,
+ ],
+ gridModel: [
+ (s) => [s.results],
+ (results: PathsV2Results | null): JourneyGridModel => buildJourneyGridModel(results),
+ ],
+ stepSources: [
+ (s) => [s.pathsV2Filter],
+ (pathsV2Filter: PathsV2Filter | null): PathsV2StepSource[] =>
+ pathsV2Filter?.stepSources ?? DEFAULT_STEP_SOURCES,
+ ],
+ anchor: [
+ (s) => [s.pathsV2Filter],
+ (pathsV2Filter: PathsV2Filter | null): PathsV2Anchor | null => pathsV2Filter?.anchor ?? null,
+ ],
+ excludedItems: [
+ (s) => [s.pathsV2Filter],
+ (pathsV2Filter: PathsV2Filter | null): PathsV2Item[] => pathsV2Filter?.excludedItems ?? [],
+ ],
+ prefixes: [(s) => [s.results], (results: PathsV2Results | null): PathsV2Prefix[] => results?.prefixes ?? []],
+ prefixCounts: [
+ (s) => [s.prefixes],
+ (prefixes: PathsV2Prefix[]): Map<string, number> =>
+ new Map(prefixes.map((prefix) => [chainKey(prefix.items), prefix.count])),
+ ],
+ activeChainHighlight: [
+ (s) => [s.activeChain, s.prefixCounts, s.gridModel],
+ (
+ activeChain: PathsV2Item[] | null,
+ prefixCounts: Map<string, number>,
+ gridModel: JourneyGridModel
+ ): JourneyChainHighlight | null => {
+ if (!activeChain || activeChain.length === 0) {
+ return null
+ }
+ const totalByStep = new Map(gridModel.columns.map((column) => [column.stepIndex, column.total]))
+ const countByCardKey: Record<string, number> = {}
+ const fractionByCardKey: Record<string, number> = {}
+ const ribbonKeys = new Set<string>()
+ for (let position = 0; position < activeChain.length; position++) {
+ const count = prefixCounts.get(chainKey(activeChain.slice(0, position + 1)))
+ if (count === undefined) {
+ // A sub-chain fell beyond the carried prefix rows: no honest preview exists.
+ return null
+ }
+ const cardKey = chainCardKey(position, activeChain[position])
+ countByCardKey[cardKey] = count
+ const total = totalByStep.get(position) ?? 0
+ fractionByCardKey[cardKey] = total > 0 ? count / total : 0
+ if (position > 0) {
+ ribbonKeys.add(
+ journeyRibbonKey(
+ position - 1,
+ journeyItemKey(activeChain[position - 1]),
+ journeyItemKey(activeChain[position])
+ )
+ )
+ }
+ }
+ return { chain: activeChain, countByCardKey, fractionByCardKey, ribbonKeys }
+ },
+ ],
+ }),
+ listeners(({ actions, values, props }) => ({
+ setStepSources: ({ stepSources }) => {
+ actions.updateInsightFilter({ stepSources })
+ },
+ setStepSourceEvent: ({ index, event }) => {
+ if (values.stepSources.some((source, i) => i !== index && source.event === event)) {
+ lemonToast.info(`${event} is already a step source`)
+ return
+ }
+ // The naming property does not carry over: it usually does not exist on the new event,
+ // and a stale one would silently merge all its items under an empty label.
+ actions.setStepSources(values.stepSources.map((source, i) => (i === index ? { event } : source)))
+ },
+ setStepSourceNamingProperty: ({ index, namingProperty }) => {
+ actions.setStepSources(
+ values.stepSources.map((source, i) =>
+ i === index ? { event: source.event, ...(namingProperty ? { namingProperty } : {}) } : source
+ )
+ )
+ },
+ addStepSource: ({ event }) => {
+ if (values.stepSources.some((source) => source.event === event)) {
+ lemonToast.info(`${event} is already a step source`)
+ return
+ }
+ actions.setStepSources([...values.stepSources, { event }])
+ },
+ removeStepSource: ({ index }) => {
+ actions.setStepSources(values.stepSources.filter((_, i) => i !== index))
+ },
+ setExcludedLabels: ({ source, labels }) => {
+ actions.updateInsightFilter({ excludedItems: withExcludedLabels(values.excludedItems, source, labels) })
+ },
+ removeExcludedItem: ({ item }) => {
+ actions.updateInsightFilter({ excludedItems: values.excludedItems.filter((existing) => existing !== item) })
+ },
+ commitGridSize: () => {
+ const update: Partial<PathsV2Filter> = {}
+ if (values.draftMaxSteps !== null) {
+ const maxSteps = clamp(values.draftMaxSteps, MAX_STEPS_BOUNDS)
+ if (maxSteps !== values.draftMaxSteps) {
+ actions.setDraftMaxSteps(maxSteps)
+ }
+ if (maxSteps !== (values.pathsV2Filter?.maxSteps ?? undefined)) {
+ update.maxSteps = maxSteps
+ }
+ }
+ if (values.draftMaxRowsPerStep !== null) {
+ const maxRowsPerStep = clamp(values.draftMaxRowsPerStep, MAX_ROWS_PER_STEP_BOUNDS)
+ if (maxRowsPerStep !== values.draftMaxRowsPerStep) {
+ actions.setDraftMaxRowsPerStep(maxRowsPerStep)
+ }
+ if (maxRowsPerStep !== (values.pathsV2Filter?.maxRowsPerStep ?? undefined)) {
+ update.maxRowsPerStep = maxRowsPerStep
+ }
+ }
+ if (Object.keys(update).length > 0) {
+ actions.updateInsightFilter(update)
+ }
+ },
+ cardClicked: ({ stepIndex, row }) => {
+ const openModalFor = (element: PathsV2ElementSelector, title: ReactNode): void => {
+ const source = values.vizQuerySource
+ if (source?.kind !== NodeKind.PathsV2Query) {
+ return
+ }
+ openPersonsModal({
+ title,
+ query: { kind: NodeKind.PathsV2ActorsQuery, source: source as PathsV2Query, element },
+ })
+ }
+ if (values.activeChain && isCardOnChain(values.activeChain, stepIndex, row.key)) {
+ // The card currently shows this chain's count, so its modal is the chain's people.
+ const chain = values.activeChain.slice(0, stepIndex + 1)
+ openModalFor({ elementType: PathsV2ElementType.Chain, chain }, journeysChainModalTitle(chain, props))
+ return
+ }
+ if (row.kind === 'item' && row.item) {
+ openModalFor(
+ { elementType: PathsV2ElementType.Node, stepIndex, item: row.item },
+ journeysNodeModalTitle(stepIndex, row.item)
+ )
+ } else if (row.kind === 'other') {
+ openModalFor({ elementType: PathsV2ElementType.Other, stepIndex }, journeysOtherModalTitle(stepIndex))
+ } else if (row.kind === 'dropOff') {
+ openModalFor(
+ { elementType: PathsV2ElementType.DropOff, stepIndex },
+ journeysDropOffModalTitle(stepIndex)
+ )
+ }
+ },
+ ribbonClicked: ({ ribbon }) => {
+ const source = values.vizQuerySource
+ if (source?.kind !== NodeKind.PathsV2Query) {
+ return
+ }
+ openPersonsModal({
+ title: journeysEdgeModalTitle(
+ ribbon.sourceStep,
+ ribbon.sourceItem,
+ ribbon.targetItem,
+ ribbon.anyStepCount,
+ props
+ ),
+ query: {
+ kind: NodeKind.PathsV2ActorsQuery,
+ source: source as PathsV2Query,
+ element: {
+ elementType: PathsV2ElementType.Edge,
+ stepIndex: ribbon.sourceStep,
+ source: ribbon.sourceItem ?? undefined,
+ target: ribbon.targetItem ?? undefined,
+ },
+ },
+ })
+ },
+ ribbonHovered: ({ ribbon }) => {
+ if (!values.isAnchored || !ribbon.sourceItem || !ribbon.targetItem) {
+ if (values.activeChain) {
+ actions.setActiveChain(null)
+ }
+ return
+ }
+ // Prefixes come count-descending, so the first chain through this ribbon is the most
+ // common one: the ribbon pins the chain's last hop, the dominant prefix fills the rest.
+ const chain = values.prefixes.find(
+ (prefix) =>
+ prefix.items.length === ribbon.sourceStep + 2 &&
+ journeyItemKey(prefix.items[ribbon.sourceStep]) === ribbon.sourceKey &&
+ journeyItemKey(prefix.items[ribbon.sourceStep + 1]) === ribbon.targetKey &&
+ isChainDisplayed(prefix.items, values.gridModel.displayedItemKeys)
+ )
+ actions.setActiveChain(chain?.items ?? null)
+ },
+ cardHovered: ({ stepIndex, row }) => {
+ // A card already on the active chain keeps it, so the pointer can travel from a ribbon
+ // onto the chain's cards and the card's click still opens the chain's people.
+ if (values.activeChain && isCardOnChain(values.activeChain, stepIndex, row.key)) {
+ return
+ }
+ // Only a named card past the anchor column previews a chain: the anchor column is the
+ // whole population, and the other and drop-off rows are union-only elements.
+ const chain =
+ values.isAnchored && stepIndex > 0 && row.kind === 'item'
+ ? dominantDisplayedChain(values.prefixes, stepIndex, row.key, values.gridModel.displayedItemKeys)
+ : null
+ if (chain !== null || values.activeChain) {
+ actions.setActiveChain(chain)
+ }
+ },
+ gridLeft: () => {
+ if (values.activeChain) {
+ actions.setActiveChain(null)
+ }
+ },
+ viewSegmentAsFunnel: async ({ items }) => {
+ const source = values.vizQuerySource
+ if (source?.kind !== NodeKind.PathsV2Query) {
+ actions.viewSegmentAsFunnelFinished()
+ return
+ }
+ try {
+ // The converter has exactly one implementation, server-side; the frontend only
+ // relays the displayed segment and opens whatever funnel comes back.
+ const response = await pathsV2SegmentToFunnelCreate(String(ApiConfig.getCurrentTeamId()), {
+ query: source,
+ items,
+ })
+ const query: InsightVizNode = {
+ kind: NodeKind.InsightVizNode,
+ source: response.funnels_query as FunnelsQuery,
+ }
+ newInternalTab(urls.insightNew({ query }))
+ } catch {
+ lemonToast.error("Couldn't open this as a funnel. Please try again.")
+ } finally {
+ actions.viewSegmentAsFunnelFinished()
+ }
+ },
+ })),
+])
diff --git a/products/product_analytics/frontend/insights/journeys/journeysModalTitles.tsx b/products/product_analytics/frontend/insights/journeys/journeysModalTitles.tsx
new file mode 100644
index 000000000000..2ccec42fba3f
--- /dev/null
+++ b/products/product_analytics/frontend/insights/journeys/journeysModalTitles.tsx
@@ -0,0 +1,73 @@
+import { pluralize } from 'lib/utils/strings'
+
+import { PathsV2Item } from '~/queries/schema/schema-general'
+import { InsightLogicProps } from '~/types'
+
+import { journeyItemLabel } from './journeyGridModel'
+import { JourneysViewAsFunnelButton } from './JourneysViewAsFunnelButton'
+
+const OTHER_LABEL = 'less common items'
+
+function stepNumber(stepIndex: number): number {
+ return stepIndex + 1
+}
+
+export function journeysNodeModalTitle(stepIndex: number, item: PathsV2Item): string {
+ return `People at ${journeyItemLabel(item)} (step ${stepNumber(stepIndex)})`
+}
+
+export function journeysOtherModalTitle(stepIndex: number): string {
+ return `People at ${OTHER_LABEL} (step ${stepNumber(stepIndex)})`
+}
+
+export function journeysDropOffModalTitle(stepIndex: number): string {
+ return `People whose journey ends at step ${stepNumber(stepIndex)}`
+}
+
+export function journeysChainModalTitle(chain: PathsV2Item[], logicProps?: InsightLogicProps): JSX.Element {
+ return (
+ <div className="flex items-center gap-2">
+ <span>People who went {chain.map(journeyItemLabel).join(' → ')}</span>
+ {logicProps && chain.length >= 2 && (
+ <JourneysViewAsFunnelButton
+ logicProps={logicProps}
+ items={chain}
+ tooltip="Opens this path as a new funnel insight. Its step counts match the highlighted path."
+ />
+ )}
+ </div>
+ )
+}
+
+export function journeysEdgeModalTitle(
+ stepIndex: number,
+ sourceItem: PathsV2Item | null,
+ targetItem: PathsV2Item | null,
+ anyStepCount: number | null,
+ logicProps?: InsightLogicProps
+): JSX.Element {
+ const sourceLabel = sourceItem ? journeyItemLabel(sourceItem) : OTHER_LABEL
+ const targetLabel = targetItem ? journeyItemLabel(targetItem) : OTHER_LABEL
+ return (
+ <>
+ <div>
+ People who went {sourceLabel} → {targetLabel} (step {stepNumber(stepIndex)} →{' '}
+ {stepNumber(stepIndex + 1)})
+ </div>
+ {anyStepCount !== null && sourceItem && targetItem && (
+ <div className="flex items-center gap-2 text-sm font-normal text-secondary">
+ <span>
+ {pluralize(anyStepCount, 'person', 'people')} went {sourceLabel} → {targetLabel} at any step
+ </span>
+ {logicProps && (
+ <JourneysViewAsFunnelButton
+ logicProps={logicProps}
+ items={[sourceItem, targetItem]}
+ tooltip="Opens a new funnel insight counting this transition at any step. Its count matches the number shown here."
+ />
+ )}
+ </div>
+ )}
+ </>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/journeys/journeysSummary.ts b/products/product_analytics/frontend/insights/journeys/journeysSummary.ts
new file mode 100644
index 000000000000..0e138ab316d4
--- /dev/null
+++ b/products/product_analytics/frontend/insights/journeys/journeysSummary.ts
@@ -0,0 +1,42 @@
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+
+import { PathsV2AnchorType, PathsV2Filter } from '~/queries/schema/schema-general'
+import { getCoreFilterDefinition } from '~/taxonomy/helpers'
+
+import { journeyItemLabel } from './journeyGridModel'
+import { presetForStepSources } from './stepSourcePresets'
+
+function eventLabel(event: string): string {
+ return getCoreFilterDefinition(event, TaxonomicFilterGroupType.Events)?.label ?? event
+}
+
+export function journeysSummaryParts(filter: PathsV2Filter | null | undefined): {
+ /** Step sources as a phrase: the preset label ("page views"), or the picked events' labels. */
+ sources: string
+ /** Anchored-mode phrase pieces; null in open mode. */
+ anchor: { verb: 'starting' | 'ending'; label: string } | null
+} {
+ // An empty source list is rejected server-side; treating it like the absent default keeps the
+ // pageviews fallback encoded in one place (presetForStepSources).
+ const stepSources = filter?.stepSources?.length ? filter.stepSources : undefined
+ const preset = presetForStepSources(stepSources)
+ const sources = preset
+ ? preset.label.toLowerCase()
+ : (stepSources ?? []).map((source) => eventLabel(source.event)).join(' and ')
+ const anchor = filter?.anchor
+ return {
+ sources,
+ anchor: anchor
+ ? {
+ verb: anchor.type === PathsV2AnchorType.End ? 'ending' : 'starting',
+ label: journeyItemLabel(anchor.item),
+ }
+ : null,
+ }
+}
+
+/** One-line journeys summary; doubles as the auto-generated insight name. Sync format with PathsV2Summary in InsightDetails. */
+export function summarizeJourneys(filter: PathsV2Filter | null | undefined): string {
+ const { sources, anchor } = journeysSummaryParts(filter)
+ return `Journeys based on ${sources}${anchor ? ` ${anchor.verb} at ${anchor.label}` : ''}`
+}
diff --git a/products/product_analytics/frontend/insights/journeys/stepSourcePresets.ts b/products/product_analytics/frontend/insights/journeys/stepSourcePresets.ts
new file mode 100644
index 000000000000..0ae162fd6e9b
--- /dev/null
+++ b/products/product_analytics/frontend/insights/journeys/stepSourcePresets.ts
@@ -0,0 +1,45 @@
+import { PathsV2StepSource } from '~/queries/schema/schema-general'
+
+export interface StepSourcePreset {
+ key: 'pageViews' | 'screenViews'
+ label: string
+ stepSources: PathsV2StepSource[]
+}
+
+/** One-click step source configurations, replacing v1's checkbox event-type buckets. */
+export const STEP_SOURCE_PRESETS: Record<StepSourcePreset['key'], StepSourcePreset> = {
+ pageViews: {
+ key: 'pageViews',
+ label: 'Page views',
+ stepSources: [{ event: '$pageview', namingProperty: '$pathname' }],
+ },
+ screenViews: {
+ key: 'screenViews',
+ label: 'Screen views',
+ stepSources: [{ event: '$screen', namingProperty: '$screen_name' }],
+ },
+}
+
+/** What the runner defaults absent step sources to: the page views preset. */
+export const DEFAULT_STEP_SOURCES = STEP_SOURCE_PRESETS.pageViews.stepSources
+
+/** The preset matching the given step sources, or null when they were customized. */
+export function presetForStepSources(stepSources: PathsV2StepSource[] | undefined): StepSourcePreset | null {
+ if (!stepSources) {
+ // The runner defaults absent step sources to the page views preset.
+ return STEP_SOURCE_PRESETS.pageViews
+ }
+ for (const preset of Object.values(STEP_SOURCE_PRESETS)) {
+ if (
+ stepSources.length === preset.stepSources.length &&
+ preset.stepSources.every(
+ (source, index) =>
+ stepSources[index].event === source.event &&
+ (stepSources[index].namingProperty ?? null) === (source.namingProperty ?? null)
+ )
+ ) {
+ return preset
+ }
+ }
+ return null
+}
diff --git a/products/product_analytics/manifest.tsx b/products/product_analytics/manifest.tsx
index b951c2e49826..efc94d9bda03 100644
--- a/products/product_analytics/manifest.tsx
+++ b/products/product_analytics/manifest.tsx
@@ -138,6 +138,15 @@ export const manifest: ProductManifest = {
visualOrder: INSIGHT_VISUAL_ORDER.paths,
sceneKeys: ['Insight'],
},
+ {
+ path: `Insight/Journeys`,
+ type: 'insight',
+ href: urls.insightNew({ type: InsightType.JOURNEYS }),
+ flag: FEATURE_FLAGS.PRODUCT_ANALYTICS_PATHS_V2,
+ iconType: 'insight/paths',
+ visualOrder: INSIGHT_VISUAL_ORDER.journeys,
+ sceneKeys: ['Insight'],
+ },
{
path: `Insight/Stickiness`,
type: 'insight',
diff --git a/products/product_analytics/mcp/tools.yaml b/products/product_analytics/mcp/tools.yaml
index e1cc9302bda2..4bda8efc8909 100644
--- a/products/product_analytics/mcp/tools.yaml
+++ b/products/product_analytics/mcp/tools.yaml
@@ -373,3 +373,6 @@ tools:
insights-viewed-create:
operation: insights_viewed_create
enabled: false
+ paths-v2-segment-to-funnel-create:
+ operation: paths_v2_segment_to_funnel_create
+ enabled: false
diff --git a/products/slack_app/backend/slack_link_unfurl.py b/products/slack_app/backend/slack_link_unfurl.py
index 362ab3b39324..fa48db6b85dc 100644
--- a/products/slack_app/backend/slack_link_unfurl.py
+++ b/products/slack_app/backend/slack_link_unfurl.py
@@ -32,6 +32,7 @@ _QUERY_KIND_TO_SHORT_NAME: dict[str, str] = {
"FunnelCorrelationQuery": "Funnel correlation",
"RetentionQuery": "Retention",
"PathsQuery": "Paths",
+ "PathsV2Query": "Journeys",
"StickinessQuery": "Stickiness",
"LifecycleQuery": "Lifecycle",
"WebStatsTableQuery": "Web analytics",
diff --git a/products/slack_app/backend/tests/test_link_unfurl.py b/products/slack_app/backend/tests/test_link_unfurl.py
index 32aa02bf087e..8a7137bcffd8 100644
--- a/products/slack_app/backend/tests/test_link_unfurl.py
+++ b/products/slack_app/backend/tests/test_link_unfurl.py
@@ -74,6 +74,14 @@ class TestInsightResourceLabel:
)
assert _insight_resource_label(insight) == "Trends insight"
+ def test_insight_viz_journeys(self) -> None:
+ # Guards the user-facing name: without the map entry this would leak "PathsV2 insight".
+ insight = Insight(
+ team_id=1,
+ query={"kind": "InsightVizNode", "source": {"kind": "PathsV2Query"}},
+ )
+ assert _insight_resource_label(insight) == "Journeys insight"
+
def test_data_viz_sql(self):
insight = Insight(
team_id=1,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 40ba64904fc5..f787690b99bb 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -3540,6 +3540,147 @@ export namespace Schemas {
version?: number | null;
}
+ export interface PathsV2Item {
+ /** Event of the step source this item belongs to. */
+ event: string;
+ /** Label value from the source's naming property, after path cleaning. An empty string when the property is missing on the event. Null for sources without a naming property. */
+ label?: string | null;
+ }
+
+ export type PathsV2AnchorType = typeof PathsV2AnchorType[keyof typeof PathsV2AnchorType];
+
+
+ export const PathsV2AnchorType = {
+ Start: 'start',
+ End: 'end',
+ } as const;
+
+ export interface PathsV2Anchor {
+ /** The path item the chart anchors on. Its event must be one of the step sources. */
+ item: PathsV2Item;
+ /** `start` runs each actor's single sequence forward from the anchor item; `end` runs it up to the anchor item. Either way the anchor is the grid's single 100% node. */
+ type: PathsV2AnchorType;
+ }
+
+ export interface PathsV2StepSource {
+ /** Name of the event this source matches. */
+ event: string;
+ /** Event property whose value labels the path item, e.g. `$pathname` for pageviews. Team path cleaning rules are applied to the value. Without a naming property, the event itself is the path item. */
+ namingProperty?: string | null;
+ }
+
+ export interface PathsV2Filter {
+ /** Anchor selecting anchored mode. When set, each actor contributes exactly one sequence bounded by the conversion window, so every displayed segment equals a plain funnel. Absent selects open mode, which splits an actor's events into journeys on the inactivity gap instead. */
+ anchor?: PathsV2Anchor | null;
+ /** Apply the team's path cleaning rules to naming property values before they become path items. */
+ applyTeamPathCleaning?: boolean | null;
+ /** Merge immediate repeats of the same path item within a journey. */
+ collapseRepeats?: boolean | null;
+ /** Anchored mode's single conversion window W, anchored at the anchor and reused verbatim as the emitted funnel's window. Bounds per unit are validated server-side against CONVERSION_WINDOW_INTERVAL_BOUNDS, the same funnel conversion window bounds as the gap. */
+ conversionWindowInterval?: number | null;
+ conversionWindowIntervalUnit?: FunnelConversionWindowTimeUnit | null;
+ /** Path items dropped from the item universe: events deriving to one of these items are ignored as if their event were not a step source, on both the paths side and the "view as funnel" side. */
+ excludedItems?: PathsV2Item[] | null;
+ /** Inactivity gap that splits an actor's events into journeys. Bounds per unit are validated server-side against CONVERSION_WINDOW_INTERVAL_BOUNDS, the funnel conversion window bounds. */
+ gapInterval?: number | null;
+ gapIntervalUnit?: FunnelConversionWindowTimeUnit | null;
+ /** Path cleaning rules for this insight only, applied after the team's rules. */
+ localPathCleaningFilters?: PathCleaningFilter[] | null;
+ /** Number of path item rows per step; items beyond this go into the "other" row. */
+ maxRowsPerStep?: number | null;
+ /** Number of journey steps (columns) shown. */
+ maxSteps?: number | null;
+ /** Step sources defining which events can become path items. Defaults to the pageviews preset: `$pageview` named by `$pathname`. */
+ stepSources?: PathsV2StepSource[] | null;
+ }
+
+ export interface PathsV2Edge {
+ /** Unique actors who transition from source to target at any step of any of their whole journeys, the position-free count behind "went source → target at any step". Equals the two-step item-strict funnel's converted count. Only set in open mode on edges between two named items. */
+ anyStepCount?: number | null;
+ /** Unique actors with a journey that transitions from source to target between these steps. */
+ count: number;
+ /** Source path item, or null for the source column's "other" row. */
+ source: PathsV2Item | null;
+ /** 0-based step index of the source column; the target sits at `stepIndex + 1`. */
+ stepIndex: number;
+ /** Target path item, or null for the target column's "other" row. */
+ target: PathsV2Item | null;
+ }
+
+ export interface PathsV2Prefix {
+ /** Unique actors whose anchored sequence begins with exactly these items. */
+ count: number;
+ /** The chain's path items in order, starting at the anchor. */
+ items: PathsV2Item[];
+ }
+
+ export interface PathsV2Row {
+ /** Unique actors with a journey whose item at this step is this path item. */
+ count: number;
+ item: PathsV2Item;
+ }
+
+ export interface PathsV2Step {
+ /** Unique actors whose journey ends at this step. */
+ dropOffCount: number;
+ /** Unique actors at this step whose path item is beyond the top rows. */
+ otherCount: number;
+ /** Top path items at this step, ordered by unique-actor count descending. */
+ rows: PathsV2Row[];
+ /** 0-based step index (column) in the journey grid. */
+ stepIndex: number;
+ }
+
+ export interface PathsV2Results {
+ edges: PathsV2Edge[];
+ /** Concrete anchored chains with per-chain unique-actor counts, ordered by descending count. Empty in open mode; in anchored mode it carries the counts the hover funnel preview reads per chain. Only chains the grid displays in full are carried: chains through the other bucket are omitted, so the response never exposes labels the chart hides. */
+ prefixes: PathsV2Prefix[];
+ steps: PathsV2Step[];
+ }
+
+ export interface PathsV2QueryResponse {
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null;
+ /** Generated HogQL query. */
+ hogql?: string | null;
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatus | null;
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponse | null;
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponse | null;
+ results: PathsV2Results;
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ /** Connector-synced data warehouse sources referenced by this query, if any. */
+ used_data_warehouse_sources?: DataWarehouseSourceUsage[] | null;
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
+ warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
+ }
+
+ export interface PathsV2Query {
+ /** Colors used in the insight's visualization */
+ dataColorTheme?: number | null;
+ /** Date range for the query */
+ dateRange?: DateRange | null;
+ /** Exclude internal and test users by applying the respective filters */
+ filterTestAccounts?: boolean | null;
+ kind?: 'PathsV2Query';
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ /** Properties specific to the paths v2 insight */
+ pathsV2Filter?: PathsV2Filter | null;
+ /** Property filters for all series */
+ properties?: (EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | MetricPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | AccountCustomPropertyFilter | WorkflowVariablePropertyFilter)[] | PropertyGroupFilter | null;
+ response?: PathsV2QueryResponse | null;
+ /** Tags that will be added to the Query log comment */
+ tags?: QueryLogTags | null;
+ /** version of the node, used for schema migrations */
+ version?: number | null;
+ }
+
export type StickinessQueryResponseResultsItem = { [key: string]: unknown };
export interface StickinessQueryResponse {
@@ -3986,7 +4127,7 @@ export namespace Schemas {
modifiers?: HogQLQueryModifiers | null;
response?: ActorsQueryResponse | null;
series?: number | null;
- source: TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery | WebStatsTableQuery | WebOverviewQuery;
+ source: TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | WebStatsTableQuery | WebOverviewQuery;
status?: string | null;
tags?: QueryLogTags | null;
/** version of the node, used for schema migrations */
@@ -4468,6 +4609,46 @@ export namespace Schemas {
version?: number | null;
}
+ export type PathsV2ElementType = typeof PathsV2ElementType[keyof typeof PathsV2ElementType];
+
+
+ export const PathsV2ElementType = {
+ Node: 'node',
+ Edge: 'edge',
+ DropOff: 'dropOff',
+ Other: 'other',
+ Chain: 'chain',
+ } as const;
+
+ export interface PathsV2ElementSelector {
+ /** Match the source → target transition at any step of any whole journey instead of at one step pair: the position-free set behind an edge's anyStepCount. Requires a named source and target and open mode. Edge elements only. */
+ anyStep?: boolean | null;
+ /** The chain's path items in order from the anchor. Returns the actors whose anchored sequence begins with exactly these items, the set behind a hover preview's per-chain counts. Chain elements only, anchored mode only. Bounded by the step maximum: a longer chain can never match a displayed card. */
+ chain?: PathsV2Item[] | null;
+ elementType: PathsV2ElementType;
+ /** The node card's path item. Node elements only. */
+ item?: PathsV2Item | null;
+ /** The edge's source path item; omit for the source column's "other" row. Edge elements only. */
+ source?: PathsV2Item | null;
+ /** 0-based step index (column) of the element; for an edge, its source column. Required for node, other, dropOff, and positional edge elements. */
+ stepIndex?: number | null;
+ /** The edge's target path item; omit for the target column's "other" row. Edge elements only. */
+ target?: PathsV2Item | null;
+ }
+
+ export interface PathsV2ActorsQuery {
+ element: PathsV2ElementSelector;
+ includeRecordings?: boolean | null;
+ kind?: 'PathsV2ActorsQuery';
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ response?: ActorsQueryResponse | null;
+ source: PathsV2Query;
+ tags?: QueryLogTags | null;
+ /** version of the node, used for schema migrations */
+ version?: number | null;
+ }
+
export interface HogQLFilters {
dateRange?: DateRange | null;
filterTestAccounts?: boolean | null;
@@ -4595,7 +4776,7 @@ export namespace Schemas {
response?: ActorsQueryResponse | null;
search?: string | null;
select?: string[] | null;
- source?: InsightActorsQuery | FunnelsActorsQuery | FunnelCorrelationActorsQuery | ExperimentActorsQuery | StickinessActorsQuery | HogQLQuery | null;
+ source?: InsightActorsQuery | FunnelsActorsQuery | FunnelCorrelationActorsQuery | ExperimentActorsQuery | StickinessActorsQuery | PathsV2ActorsQuery | HogQLQuery | null;
tags?: QueryLogTags | null;
/** version of the node, used for schema migrations */
version?: number | null;
@@ -5068,7 +5249,7 @@ export namespace Schemas {
showLastComputationRefresh?: boolean | null;
showResults?: boolean | null;
showTable?: boolean | null;
- source: TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery | WebStatsTableQuery | WebOverviewQuery;
+ source: TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | WebStatsTableQuery | WebOverviewQuery;
suppressSessionAnalysisWarning?: boolean | null;
/** version of the node, used for schema migrations */
version?: number | null;
@@ -6384,7 +6565,7 @@ export namespace Schemas {
sampling?: WebAnalyticsSampling | null;
/** Sampling rate */
samplingFactor?: number | null;
- source: TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery | WebStatsTableQuery | WebOverviewQuery;
+ source: TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | WebStatsTableQuery | WebOverviewQuery;
tags?: QueryLogTags | null;
useSessionsTable?: boolean | null;
/** version of the node, used for schema migrations */
@@ -36583,7 +36764,7 @@ export namespace Schemas {
export interface InsightActorsQueryOptions {
kind?: 'InsightActorsQueryOptions';
response?: InsightActorsQueryOptionsResponse | null;
- source: InsightActorsQuery | FunnelsActorsQuery | FunnelCorrelationActorsQuery | StickinessActorsQuery | ExperimentActorsQuery;
+ source: InsightActorsQuery | FunnelsActorsQuery | FunnelCorrelationActorsQuery | StickinessActorsQuery | ExperimentActorsQuery | PathsV2ActorsQuery;
/** version of the node, used for schema migrations */
version?: number | null;
}
@@ -58788,6 +58969,28 @@ export namespace Schemas {
views: number;
}
+ export interface PathsV2SegmentItem {
+ /** Event of the step source this path item belongs to. */
+ event: string;
+ /**
+ * Label value from the source's naming property, after path cleaning. Null or omitted for sources without a naming property; an empty string means the property was missing on the event.
+ * @nullable
+ */
+ label?: string | null;
+ }
+
+ export interface PathsV2SegmentToFunnelRequest {
+ /** The PathsV2Query the segment is displayed under (JSON object with kind `PathsV2Query`). Step sources, path cleaning, excluded items, date range, and the gap or conversion window are read from it, so the emitted funnel counts exactly what the chart shows. */
+ query: unknown;
+ /** The segment's path items in displayed order. In open mode exactly two items - a single edge, source then target. In anchored mode the concrete chain as shown, starting at the anchor. */
+ items: PathsV2SegmentItem[];
+ }
+
+ export interface PathsV2SegmentToFunnelResponse {
+ /** The FunnelsQuery (JSON object with kind `FunnelsQuery`) that reproduces the segment's displayed unique-actor count exactly. Wrap it in an InsightVizNode to open it as a funnel insight. */
+ funnels_query: unknown;
+ }
+
export interface PauseResponse {
/** Always 'paused'. */
status: string;
@@ -61690,7 +61893,7 @@ export namespace Schemas {
* ```
*
* For more details on HogQL queries, see the [PostHog HogQL documentation](/docs/hogql#api-access). */
- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
/** Whether results should be calculated sync or async, and how much to rely on the cache:
* - `'blocking'` - calculate synchronously (returning only when the query is done), UNLESS there are very fresh results in the cache
* - `'async'` - kick off background calculation (returning immediately with a query status), UNLESS there are very fresh results in the cache
@@ -63198,8 +63401,6 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative62ResultsItem = { [key: string]: unknown };
-
export interface QueryResponseAlternative62 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -63213,7 +63414,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative62ResultsItem[];
+ results: PathsV2Results;
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -63222,7 +63423,31 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative64 {
+ export type QueryResponseAlternative63ResultsItem = { [key: string]: unknown };
+
+ export interface QueryResponseAlternative63 {
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null;
+ /** Generated HogQL query. */
+ hogql?: string | null;
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatus | null;
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponse | null;
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponse | null;
+ results: QueryResponseAlternative63ResultsItem[];
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ /** Connector-synced data warehouse sources referenced by this query, if any. */
+ used_data_warehouse_sources?: DataWarehouseSourceUsage[] | null;
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
+ warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
+ }
+
+ export interface QueryResponseAlternative65 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -63249,14 +63474,14 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative65Tables = {[key: string]: DatabaseSchemaPostHogTable | DatabaseSchemaSystemTable | DatabaseSchemaDataWarehouseTable | DatabaseSchemaViewTable | DatabaseSchemaManagedViewTable | DatabaseSchemaBatchExportTable | DatabaseSchemaMaterializedViewTable | DatabaseSchemaEndpointTable};
+ export type QueryResponseAlternative66Tables = {[key: string]: DatabaseSchemaPostHogTable | DatabaseSchemaSystemTable | DatabaseSchemaDataWarehouseTable | DatabaseSchemaViewTable | DatabaseSchemaManagedViewTable | DatabaseSchemaBatchExportTable | DatabaseSchemaMaterializedViewTable | DatabaseSchemaEndpointTable};
- export interface QueryResponseAlternative65 {
+ export interface QueryResponseAlternative66 {
joins: DataWarehouseViewLink[];
- tables: QueryResponseAlternative65Tables;
+ tables: QueryResponseAlternative66Tables;
}
- export interface QueryResponseAlternative66 {
+ export interface QueryResponseAlternative67 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
has_next: boolean;
@@ -63281,7 +63506,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative67 {
+ export interface QueryResponseAlternative68 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -63309,7 +63534,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative68 {
+ export interface QueryResponseAlternative69 {
count: number;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -63332,7 +63557,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative69 {
+ export interface QueryResponseAlternative70 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63354,7 +63579,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative70 {
+ export interface QueryResponseAlternative71 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63376,7 +63601,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative71 {
+ export interface QueryResponseAlternative72 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore?: boolean | null;
@@ -63403,7 +63628,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative72 {
+ export interface QueryResponseAlternative73 {
/** Result rows for the comparison period when `compareFilter.compare` is true. */
compare?: AggregatedSpanRow[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -63427,7 +63652,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative73 {
+ export interface QueryResponseAlternative74 {
/** Result rows for the comparison period when `compareFilter.compare` is true. */
compare?: SpanTreeNode[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -63451,7 +63676,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative74 {
+ export interface QueryResponseAlternative75 {
/** Result rows for the comparison period when `compareFilter.compare` is true. */
compare?: AttributeBreakdownRow[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
@@ -63475,13 +63700,13 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative75 {
+ export interface QueryResponseAlternative76 {
questions: string[];
/** Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics. */
warnings?: DataWarehouseSyncWarning[] | null;
}
- export interface QueryResponseAlternative76 {
+ export interface QueryResponseAlternative77 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore?: boolean | null;
@@ -63506,7 +63731,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative77 {
+ export interface QueryResponseAlternative78 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
hasMore?: boolean | null;
@@ -63531,7 +63756,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative78 {
+ export interface QueryResponseAlternative79 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63553,7 +63778,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative79 {
+ export interface QueryResponseAlternative80 {
columns?: string[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -63579,7 +63804,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative82 {
+ export interface QueryResponseAlternative83 {
/** Timestamp of the newer trace */
newerTimestamp?: string | null;
/** ID of the newer trace (chronologically after current) */
@@ -63594,7 +63819,7 @@ export namespace Schemas {
warnings?: DataWarehouseSyncWarning[] | null;
}
- export interface QueryResponseAlternative83 {
+ export interface QueryResponseAlternative84 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63616,7 +63841,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative84 {
+ export interface QueryResponseAlternative85 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63638,7 +63863,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative85 {
+ export interface QueryResponseAlternative86 {
columns: unknown[];
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -63668,7 +63893,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative86 {
+ export interface QueryResponseAlternative87 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63690,7 +63915,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative87 {
+ export interface QueryResponseAlternative88 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -63717,9 +63942,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative88ResultsItem = { [key: string]: unknown };
+ export type QueryResponseAlternative89ResultsItem = { [key: string]: unknown };
- export interface QueryResponseAlternative88 {
+ export interface QueryResponseAlternative89 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63732,7 +63957,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative88ResultsItem[];
+ results: QueryResponseAlternative89ResultsItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -63741,7 +63966,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative89 {
+ export interface QueryResponseAlternative90 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63763,7 +63988,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative90 {
+ export interface QueryResponseAlternative91 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63785,7 +64010,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative91 {
+ export interface QueryResponseAlternative92 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63807,7 +64032,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative92 {
+ export interface QueryResponseAlternative93 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63829,7 +64054,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative93 {
+ export interface QueryResponseAlternative94 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63851,7 +64076,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative94 {
+ export interface QueryResponseAlternative95 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63873,7 +64098,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative95 {
+ export interface QueryResponseAlternative96 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63896,7 +64121,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative96 {
+ export interface QueryResponseAlternative97 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63918,7 +64143,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative97 {
+ export interface QueryResponseAlternative98 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63940,7 +64165,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative98 {
+ export interface QueryResponseAlternative99 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63962,7 +64187,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative99 {
+ export interface QueryResponseAlternative100 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -63984,7 +64209,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative100 {
+ export interface QueryResponseAlternative101 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -64006,7 +64231,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative101 {
+ export interface QueryResponseAlternative102 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -64028,7 +64253,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative102 {
+ export interface QueryResponseAlternative103 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -64050,7 +64275,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative103 {
+ export interface QueryResponseAlternative104 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -64072,7 +64297,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative104 {
+ export interface QueryResponseAlternative105 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -64094,18 +64319,18 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative12 | QueryResponseAlternative13 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative26 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | unknown | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative56 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative62 | QueryResponseAlternative64 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative82 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative85 | QueryResponseAlternative86 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104;
+ export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative12 | QueryResponseAlternative13 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative26 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | unknown | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative56 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative85 | QueryResponseAlternative86 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104 | QueryResponseAlternative105;
export interface QueryStatusResponse {
query_status: QueryStatus;
}
export interface QueryUpgradeRequest {
- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
}
export interface QueryUpgradeResponse {
- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
}
export interface QuotaResourceLimit {
@@ -83050,6 +83275,7 @@ export namespace Schemas {
export const InsightsListInsight = {
Funnels: 'FUNNELS',
+ Journeys: 'JOURNEYS',
Json: 'JSON',
Lifecycle: 'LIFECYCLE',
Paths: 'PATHS',
diff --git a/services/mcp/src/generated/product_analytics/api.ts b/services/mcp/src/generated/product_analytics/api.ts
index fe921371969b..2b2e1f630027 100644
--- a/services/mcp/src/generated/product_analytics/api.ts
+++ b/services/mcp/src/generated/product_analytics/api.ts
@@ -116,7 +116,7 @@ export const InsightsListQueryParams = /* @__PURE__ */ zod.object({
'Opt in to receiving the deprecated `dashboards` field in insight payloads. Once opt-in enforcement is enabled, API-token callers stop receiving it by default; use `dashboard_tiles` instead.'
),
insight: zod
- .enum(['FUNNELS', 'JSON', 'LIFECYCLE', 'PATHS', 'RETENTION', 'SQL', 'STICKINESS', 'TRENDS'])
+ .enum(['FUNNELS', 'JOURNEYS', 'JSON', 'LIFECYCLE', 'PATHS', 'RETENTION', 'SQL', 'STICKINESS', 'TRENDS'])
.optional()
.describe(
'Restrict to a single insight type. `JSON` matches non-wrapper query insights; `SQL` matches HogQL queries.'
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json
index 7992d5d10f3a..bc920940fbaa 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/insights-list.json
@@ -35,7 +35,7 @@
},
"insight": {
"description": "Restrict to a single insight type. `JSON` matches non-wrapper query insights; `SQL` matches HogQL queries.",
- "enum": ["FUNNELS", "JSON", "LIFECYCLE", "PATHS", "RETENTION", "SQL", "STICKINESS", "TRENDS"],
+ "enum": ["FUNNELS", "JOURNEYS", "JSON", "LIFECYCLE", "PATHS", "RETENTION", "SQL", "STICKINESS", "TRENDS"],
"type": "string"
},
"last_viewed_date_from": {