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.

fix(experiments): treat exposure as funnel entry in replay drop-off (#77604)

Marcel Poelker1cf3ced8b76f
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
index 5ba3d67a67b6..9bc5ab5ccd20 100644
--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx
@@ -43,7 +43,7 @@ const MODE_SUMMARIES: Record<ExperimentReplayMetricFilterMode, string> = {
fired_all: 'fired events from every selected metric',
fired_any: 'fired events from at least one selected metric',
no_metric_activity: 'fired no events from the selected metrics',
- funnel_dropoff: "started the funnel but didn't finish it",
+ funnel_dropoff: "were exposed but didn't finish the funnel",
}
/**
@@ -86,7 +86,7 @@ function metricFilterTriggerLabel(
/** Why a picked mode isn't narrowing the list — it needs a selection it doesn't have yet. */
function unappliedModeReason(mode: ExperimentReplayMetricFilterMode): string {
return mode === 'funnel_dropoff'
- ? 'Pick a funnel metric with at least two steps that can be matched to recordings. Showing every exposed recording until then.'
+ ? 'Pick a funnel metric whose last step can be matched to recordings. Showing every exposed recording until then.'
: 'Pick at least one metric. Showing every exposed recording until then.'
}
@@ -154,7 +154,7 @@ const METRIC_FILTER_MODE_OPTIONS: { value: ExperimentReplayMetricFilterMode; lab
value: 'funnel_dropoff',
label: "Didn't finish funnel",
tooltip:
- "Sessions that reached a funnel metric's first step but not its last one during the recording. The same person may have finished it in a later session.",
+ "Sessions that saw the experiment but didn't fire a funnel metric's last step during the recording. The exposure counts as the funnel's first step. The same person may have finished it in a later session.",
},
]
@@ -276,7 +276,7 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):
<DropdownMenuGroup>
<DropdownMenuLabel inset className="flex items-center gap-1">
{reason === NOT_A_FUNNEL_REASON
- ? 'Needs two funnel steps'
+ ? 'Needs a funnel metric'
: "Can't match to recordings"}
<Tooltip title={reason}>
<IconInfo className="size-3 shrink-0" />
diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
index dd3a701a2b64..8588434bada5 100644
--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
@@ -21,8 +21,8 @@ import {
} from 'products/experiments/frontend/generated/api'
import {
- FUNNEL_DATA_WAREHOUSE_BOUNDARY_REASON,
- FUNNEL_SERVER_SIDE_BOUNDARY_REASON,
+ FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON,
+ FUNNEL_SERVER_SIDE_COMPLETION_REASON,
getViewRecordingFiltersForVariant,
} from '../utils'
import { RETENTION_UNLINKABLE_REASON } from '../viewRecordingsLinkabilityLogic'
@@ -594,7 +594,7 @@ describe('experimentReplayTabLogic', () => {
logic.actions.setMetricFilterMode('funnel_dropoff')
}).toFinishAllListeners()
- // A mean metric has no steps to drop off between, and only one funnel can be compared.
+ // A mean metric isn't a funnel, and drop-off takes exactly one funnel at a time.
expect(logic.values.effectiveMetricUuids).toEqual(['metric-funnel'])
expect(experimentsSessionBucketsCreate).toHaveBeenLastCalledWith(expect.any(String), 42, {
bucket: 'funnel_dropoff',
@@ -610,7 +610,7 @@ describe('experimentReplayTabLogic', () => {
{ kind: NodeKind.EventsNode, event: 'client_step' },
{ kind: NodeKind.EventsNode, event: 'server_side_step' },
],
- FUNNEL_SERVER_SIDE_BOUNDARY_REASON,
+ FUNNEL_SERVER_SIDE_COMPLETION_REASON,
],
[
'data warehouse',
@@ -619,7 +619,7 @@ describe('experimentReplayTabLogic', () => {
{ kind: NodeKind.EventsNode, event: 'purchase' },
{ kind: NodeKind.ExperimentDataWarehouseNode, table_name: 'stripe_charges' },
],
- FUNNEL_DATA_WAREHOUSE_BOUNDARY_REASON,
+ FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON,
],
])('refuses drop-off when the funnel finishes on a %s step', async (_name, series, expectedReason) => {
seenTogetherSpy.mockResolvedValue({ ...ALL_LINKABLE, server_side_step: false })
@@ -637,9 +637,9 @@ describe('experimentReplayTabLogic', () => {
unmatchableFinish.actions.setMetricFilterMode('funnel_dropoff')
}).toFinishAllListeners()
- // Both steps between the boundaries stay matchable, so the metric is selectable in every
- // other mode. Drop-off is the one that reads the last step, and a completion no recording
- // can show would return everyone who entered as not having finished.
+ // The other steps stay matchable, so the metric is selectable in every other mode.
+ // Drop-off is the one that reads the last step, and a completion no recording can show
+ // would return every exposed session as not having finished.
expect(unmatchableFinish.values.metricOptions.find((option) => option.uuid === 'metric-funnel')).toMatchObject({
unlinkable: false,
dropoffReason: expectedReason,
@@ -651,6 +651,36 @@ describe('experimentReplayTabLogic', () => {
unmatchableFinish.unmount()
})
+ it('asks the endpoint for drop-off on a single-step funnel', async () => {
+ const oneStepFunnel = experimentReplayTabLogic({
+ experiment: {
+ ...EXPERIMENT,
+ id: 51,
+ metrics_secondary: [
+ { ...FUNNEL_METRIC, series: [{ kind: NodeKind.EventsNode, event: 'client_step' }] },
+ ],
+ } as unknown as Experiment,
+ })
+ oneStepFunnel.mount()
+
+ await expectLogic(oneStepFunnel, () => {
+ oneStepFunnel.actions.setMetricSelected('metric-funnel', true)
+ oneStepFunnel.actions.setMetricFilterMode('funnel_dropoff')
+ }).toFinishAllListeners()
+
+ // The funnel's first step is the exposure, so one series step is a complete funnel. A
+ // single-event metric must not fall back to the client-side filter path other modes use.
+ expect(oneStepFunnel.values.metricOptions.find((option) => option.uuid === 'metric-funnel')).toMatchObject({
+ dropoffReason: null,
+ })
+ expect(experimentsSessionBucketsCreate).toHaveBeenLastCalledWith(expect.any(String), 51, {
+ bucket: 'funnel_dropoff',
+ metric_uuids: ['metric-funnel'],
+ variant: null,
+ })
+ oneStepFunnel.unmount()
+ })
+
it('keeps the list empty when the bucket fails, rather than widening it silently', async () => {
;(experimentsSessionBucketsCreate as jest.Mock).mockRejectedValue(new Error('boom'))
diff --git a/frontend/src/scenes/experiments/utils.test.ts b/frontend/src/scenes/experiments/utils.test.ts
index dcdbf7774b74..15802179038f 100644
--- a/frontend/src/scenes/experiments/utils.test.ts
+++ b/frontend/src/scenes/experiments/utils.test.ts
@@ -30,6 +30,9 @@ import {
import { filterToMetricConfig } from './metricQueryUtils'
import { getNiceTickValues } from './MetricsView/shared/utils'
import {
+ FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON,
+ FUNNEL_SERVER_SIDE_COMPLETION_REASON,
+ NOT_A_FUNNEL_REASON,
applySessionLinkability,
exposureConfigToFilter,
featureFlagEligibleForExperiment,
@@ -37,6 +40,7 @@ import {
getBaselineVariantKey,
getEventCountQuery,
getExposureFallbackFilter,
+ getFunnelDropoffReason,
getOrderedMetricsWithResults,
getSessionLinkabilityEventNames,
getViewRecordingFilters,
@@ -733,6 +737,57 @@ describe('applySessionLinkability', () => {
})
})
+describe('getFunnelDropoffReason', () => {
+ const unlinkable = new Set(['server_side_step'])
+ const clientStep = { kind: NodeKind.EventsNode, event: 'client_step' }
+ const serverSideStep = { kind: NodeKind.EventsNode, event: 'server_side_step' }
+ const warehouseStep = { kind: NodeKind.ExperimentDataWarehouseNode, table_name: 'stripe_charges' }
+ const funnelMetric = (series: unknown[]): ExperimentMetric =>
+ ({
+ kind: NodeKind.ExperimentMetric,
+ metric_type: ExperimentMetricType.FUNNEL,
+ series,
+ }) as unknown as ExperimentMetric
+
+ // The exposure event is an experiment funnel's implicit first step, so only the last series
+ // step has to be matchable to recordings.
+ it.each([
+ { case: 'allows a single-step funnel', metric: funnelMetric([clientStep]), expected: null },
+ {
+ case: 'allows a funnel whose first series step is server-side',
+ metric: funnelMetric([serverSideStep, clientStep]),
+ expected: null,
+ },
+ {
+ case: 'allows a funnel whose first series step is in the data warehouse',
+ metric: funnelMetric([warehouseStep, clientStep]),
+ expected: null,
+ },
+ {
+ case: 'refuses a single-step funnel whose only step is server-side',
+ metric: funnelMetric([serverSideStep]),
+ expected: FUNNEL_SERVER_SIDE_COMPLETION_REASON,
+ },
+ {
+ case: 'refuses a funnel whose last step is in the data warehouse',
+ metric: funnelMetric([clientStep, warehouseStep]),
+ expected: FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON,
+ },
+ { case: 'refuses a funnel with no steps', metric: funnelMetric([]), expected: NOT_A_FUNNEL_REASON },
+ {
+ case: 'refuses a non-funnel metric',
+ metric: {
+ kind: NodeKind.ExperimentMetric,
+ metric_type: ExperimentMetricType.MEAN,
+ source: clientStep,
+ } as unknown as ExperimentMetric,
+ expected: NOT_A_FUNNEL_REASON,
+ },
+ ])('$case', ({ metric, expected }) => {
+ expect(getFunnelDropoffReason(metric, unlinkable)).toBe(expected)
+ })
+})
+
describe('getViewRecordingFiltersLegacy', () => {
const featureFlagKey = 'jan-16-running'
diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.ts
index 710d6b1ac355..4d30cad19dc7 100644
--- a/frontend/src/scenes/experiments/utils.ts
+++ b/frontend/src/scenes/experiments/utils.ts
@@ -414,35 +414,32 @@ export function getMetricSessionFilters(metric: ExperimentMetric): UniversalFilt
}
export const NOT_A_FUNNEL_REASON =
- 'This filter compares a funnel’s first and last step, so it needs a funnel metric with at least two steps that can be matched to recordings.'
+ "This filter shows sessions that didn't finish a funnel, so it needs a funnel metric."
-export const FUNNEL_SERVER_SIDE_BOUNDARY_REASON =
- "This filter compares a funnel's first and last step. One of them is captured server-side without a session ID, so recordings can't be matched."
+export const FUNNEL_SERVER_SIDE_COMPLETION_REASON =
+ "This filter reads a funnel's last step. This one is captured server-side without a session ID, so recordings can't be matched."
-export const FUNNEL_DATA_WAREHOUSE_BOUNDARY_REASON =
- "This filter compares a funnel's first and last step. One of them is measured in the data warehouse, which has no session events to match recordings on."
+export const FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON =
+ "This filter reads a funnel's last step. This one is measured in the data warehouse, which has no session events to match recordings on."
/**
- * Why drop-off can't be asked of this metric, or null when it can. It compares the funnel's first
- * step against its last, so both of those have to be matchable — which the whole-metric
- * linkability check can't stand in for, since a funnel stays matchable on the steps between them.
- * Mirrors the `session_buckets` endpoint, which refuses the same shapes rather than counting a
- * completion no recording can show as zero in every session.
+ * Why drop-off can't be asked of this metric, or null when it can. An experiment funnel's first
+ * step is always the exposure event (the analysis prepends it), so drop-off reads only the
+ * funnel's last step, and that step alone has to be matchable. The whole-metric linkability
+ * check can't stand in for this, since a funnel stays matchable on its other steps. Mirrors the
+ * `session_buckets` endpoint, which refuses the same shapes rather than counting a completion no
+ * recording can show as zero in every session.
*/
export function getFunnelDropoffReason(metric: ExperimentMetric, unlinkableEventNames: Set<string>): string | null {
- if (!isExperimentFunnelMetric(metric) || getMetricSessionFilters(metric).length < 2) {
+ if (!isExperimentFunnelMetric(metric) || metric.series.length === 0) {
return NOT_A_FUNNEL_REASON
}
- const boundaries = [metric.series[0], metric.series[metric.series.length - 1]]
- if (boundaries.some((step) => step.kind === NodeKind.ExperimentDataWarehouseNode)) {
- return FUNNEL_DATA_WAREHOUSE_BOUNDARY_REASON
+ const completion = metric.series[metric.series.length - 1]
+ if (completion.kind === NodeKind.ExperimentDataWarehouseNode) {
+ return FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON
}
- if (
- boundaries.some(
- (step) => step.kind === NodeKind.EventsNode && step.event && unlinkableEventNames.has(step.event)
- )
- ) {
- return FUNNEL_SERVER_SIDE_BOUNDARY_REASON
+ if (completion.kind === NodeKind.EventsNode && completion.event && unlinkableEventNames.has(completion.event)) {
+ return FUNNEL_SERVER_SIDE_COMPLETION_REASON
}
return null
}
diff --git a/products/experiments/backend/presentation/serializers.py b/products/experiments/backend/presentation/serializers.py
index 6c343f336c84..b2a645046a5c 100644
--- a/products/experiments/backend/presentation/serializers.py
+++ b/products/experiments/backend/presentation/serializers.py
@@ -1745,9 +1745,10 @@ class ExperimentSessionBucketRequestSerializer(serializers.Serializer):
help_text=(
"Which question the returned session set answers. 'fired_any': the session fired at least one event "
"of any listed metric (an OR the recordings query itself can't express). 'no_metric_activity': the "
- "session fired none of them. 'funnel_dropoff': the session fired the funnel metric's first step and "
- "never reached its last one. All three are session-scoped and goal-free: they say what happened in "
- "the session, not whether it helped or hurt the metric."
+ "session fired none of them. 'funnel_dropoff': the session saw an exposure event but never fired the "
+ "funnel metric's last step; the exposure is the funnel's implicit first step, the same as in the "
+ "experiment analysis. All three are session-scoped and goal-free: they say what happened in the "
+ "session, not whether it helped or hurt the metric."
),
)
metric_uuids = serializers.ListField(
diff --git a/products/experiments/backend/presentation/views.py b/products/experiments/backend/presentation/views.py
index 060befd39260..b6f764e6704d 100644
--- a/products/experiments/backend/presentation/views.py
+++ b/products/experiments/backend/presentation/views.py
@@ -1445,7 +1445,7 @@ class EnterpriseExperimentsViewSet(
"""Session recordings of this experiment matching a bucket.
Answers the questions a recordings query can't express on its own — "fired any of these
- metrics", "fired none of them", "entered the funnel but never completed it in this
+ metrics", "fired none of them", "was exposed but never completed the funnel in this
session" — by returning a bounded, most-recent-first list of session IDs to pass back as
a recordings query's session_ids. POST because the metric list doesn't fit a query
string; the endpoint only reads.
diff --git a/products/experiments/backend/session_buckets.py b/products/experiments/backend/session_buckets.py
index 78b718cc78ff..834ee688fc11 100644
--- a/products/experiments/backend/session_buckets.py
+++ b/products/experiments/backend/session_buckets.py
@@ -2,9 +2,9 @@
A recordings query carries a single AND/OR operator across its whole filter tree, so the tab
can only ask "fired every one of these metrics". Three questions it cannot express client-side
-are answered here instead — "fired any of these", "fired none of them", and "entered the funnel
-but never completed it in this session" — by computing the matching session ids server-side and
-feeding them to the playlist as `RecordingsQuery.session_ids`.
+are answered here instead — "fired any of these", "fired none of them", and "was exposed but
+never completed the funnel in this session" — by computing the matching session ids server-side
+and feeding them to the playlist as `RecordingsQuery.session_ids`.
Buckets are goal-free: they say what happened in the session, never whether it helped or hurt a
metric. The analysis counts per person over the whole run window, while a recording is one
@@ -31,9 +31,10 @@ specific happened, which the stamped property doesn't imply, so a custom exposur
can't be matched is refused with a reason rather than answered over a wider population.
Metrics whose every source is such an event are excluded with a reason instead of silently
matching nothing, which for `no_metric_activity` would otherwise inflate the bucket to the whole
-exposed population. Drop-off narrows that rule to the two steps it reads: a funnel stays
-matchable overall while its first or last step can't be seen in a recording, and counting an
-unobservable completion as zero would return everyone who entered.
+exposed population. Drop-off narrows that rule to the one step it reads, the funnel's last: an
+experiment funnel's first step is the exposure event, which every bucket already requires
+in-session, so a funnel stays matchable overall while its completion can't be seen in a
+recording, and counting an unobservable completion as zero would return every exposed session.
"""
import json
@@ -125,14 +126,15 @@ CUSTOM_EXPOSURE_UNLINKABLE_REASON = (
"This experiment's exposure event has only ever been captured server-side, where there is no session to "
"record, so no session can match it."
)
-# Drop-off reads two of a funnel's steps, so its own boundary check is narrower than the
-# whole-metric one above: a funnel stays matchable on the steps between them.
-FUNNEL_SERVER_SIDE_BOUNDARY_REASON = (
- "Drop-off reads this funnel's first and last step. One of them has only ever been captured server-side, "
+# Drop-off reads only a funnel's last step, because an experiment funnel's first step is the
+# exposure event, which every bucket already requires in-session. Its check is therefore
+# narrower than the whole-metric one above: a funnel stays matchable on its other steps.
+FUNNEL_SERVER_SIDE_COMPLETION_REASON = (
+ "Drop-off reads this funnel's last step. It has only ever been captured server-side, "
"where there is no session to record, so it can never be matched to a recording."
)
-FUNNEL_DATA_WAREHOUSE_BOUNDARY_REASON = (
- "Drop-off reads this funnel's first and last step. One of them is measured in the data warehouse, "
+FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON = (
+ "Drop-off reads this funnel's last step. It is measured in the data warehouse, "
"which has no session events to match recordings on."
)
@@ -342,8 +344,9 @@ def _cache_key(
limit: int,
default_exposure_event: str,
) -> str:
- # The version segment must be bumped whenever SessionBucketScan changes shape: entries are
- # pickled, so a deploy would otherwise restore instances missing the new fields.
+ # The version segment must be bumped whenever SessionBucketScan changes shape (entries are
+ # pickled, so a deploy would otherwise restore instances missing the new fields) and whenever
+ # a bucket's semantics change, so a warm entry can't keep answering the old question.
spec = json.dumps(
[
bucket.value,
@@ -365,7 +368,7 @@ def _cache_key(
]
)
digest = hashlib.sha256(spec.encode()).hexdigest()[:16]
- return f"experiment_session_bucket_v3_{team.pk}_{user.pk}_{experiment.pk}_{digest}"
+ return f"experiment_session_bucket_v4_{team.pk}_{user.pk}_{experiment.pk}_{digest}"
def _resolve_requested_metrics(experiment: Experiment, metric_uuids: list[str]) -> list[MetricEventSource]:
@@ -419,11 +422,11 @@ def _partition_metrics(
if bucket == SessionBucket.FUNNEL_DROPOFF:
if len(considered) != 1:
raise SessionBucketUnavailable("The drop-off bucket takes exactly one funnel metric.")
- boundary_reason = _funnel_boundary_reason(considered[0], never_linked)
- if boundary_reason is not None:
+ completion_reason = _funnel_completion_reason(considered[0], never_linked)
+ if completion_reason is not None:
# Raised rather than excluded: drop-off takes one metric, so excluding it would leave
# the generic "none of these can be matched" message and lose the reason.
- raise SessionBucketUnavailable(boundary_reason)
+ raise SessionBucketUnavailable(completion_reason)
return considered, excluded
@@ -491,54 +494,48 @@ def _metric_condition(metric: MetricEventSource, team: Team) -> ast.Expr:
return ast.Or(exprs=conditions) if len(conditions) > 1 else conditions[0]
-def _funnel_boundary_steps(metric: MetricEventSource) -> tuple[MetricSource, MetricSource]:
- """The two steps drop-off is computed from: the funnel's entry and its completion."""
+def _funnel_completion_step(metric: MetricEventSource) -> MetricSource:
+ """The one step drop-off is computed from: the funnel's completion. The funnel's implicit
+ first step is the exposure event, which the bucket query already requires in-session."""
steps = [source for source in metric.sources if source.role == MetricSourceRole.STEP]
- if len(steps) < 2:
+ if not steps:
raise SessionBucketUnavailable(
- "Drop-off needs a funnel with at least two steps that can be matched to recordings."
+ "Drop-off needs a funnel metric with at least one step that can be matched to recordings."
)
- return steps[0], steps[-1]
+ return steps[-1]
-def _funnel_boundary_reason(metric: MetricEventSource, never_linked: set[str]) -> Optional[str]:
+def _funnel_completion_reason(metric: MetricEventSource, never_linked: set[str]) -> Optional[str]:
"""Why drop-off can't be asked of this funnel, or None when it can.
The whole-metric check in `_exclusion_reason` is too coarse here. It clears a funnel as long
- as one of its steps can be matched, while drop-off rests on two specific ones — so a funnel
- whose completion is a server-side charge passes there and then counts that completion as
- zero in every session, returning everyone who entered as not having finished.
+ as one of its steps can be matched, while drop-off rests on the last one specifically. A
+ funnel whose completion is a server-side charge passes there and would then count that
+ completion as zero in every session, returning every exposed session as not having finished.
"""
- entry, completion = _funnel_boundary_steps(metric)
+ completion = _funnel_completion_step(metric)
# Data-warehouse steps are dropped from `sources` while the survivors keep their real
- # position, so a gap at either end means the boundary read landed on an inner step.
- if entry.index != 0 or completion.index != completion.total - 1:
- return FUNNEL_DATA_WAREHOUSE_BOUNDARY_REASON
- boundary_events = {
- step.node.event for step in (entry, completion) if isinstance(step.node, EventsNode) and step.node.event
- }
- if boundary_events & never_linked:
- return FUNNEL_SERVER_SIDE_BOUNDARY_REASON
+ # position, so a gap at the end means the completion read landed on an inner step.
+ if completion.index != completion.total - 1:
+ return FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON
+ if isinstance(completion.node, EventsNode) and completion.node.event and completion.node.event in never_linked:
+ return FUNNEL_SERVER_SIDE_COMPLETION_REASON
return None
-def _funnel_step_conditions(metric: MetricEventSource, team: Team) -> tuple[ast.Expr, ast.Expr, int]:
- """The funnel's entry condition, its completion condition, and how many times the completion
- event must fire to count as completed.
+def _funnel_completion_condition(metric: MetricEventSource, team: Team) -> tuple[ast.Expr, int]:
+ """The funnel's completion condition, and how many times the completion event must fire to
+ count as completed.
- A funnel can list one event as several steps (the "N-th occurrence" shape), where entry and
- completion are the same condition and only the occurrence count tells them apart — the same
- positional reading the per-source hits use.
+ A funnel can list one event as several steps (the "N-th occurrence" shape), where completing
+ means firing that event as many times as it appears in the series, the same positional
+ reading the per-source hits use.
"""
steps = [source for source in metric.sources if source.role == MetricSourceRole.STEP]
- entry_step, completion_step = _funnel_boundary_steps(metric)
+ completion_step = _funnel_completion_step(metric)
completion_signature = node_signature(completion_step.node)
completion_occurrences = sum(1 for step in steps if node_signature(step.node) == completion_signature)
- return (
- build_source_condition(entry_step.node, team),
- build_source_condition(completion_step.node, team),
- completion_occurrences,
- )
+ return build_source_condition(completion_step.node, team), completion_occurrences
def _query_bucket_sessions(
@@ -607,17 +604,15 @@ def _query_bucket_sessions(
op=ast.CompareOperationOp.Eq, left=count_if(any_metric_condition()), right=ast.Constant(value=0)
)
else:
- entry, completion, completion_occurrences = _funnel_step_conditions(considered[0], team)
- # Count-based on purpose: the filter promises "fired the last step's event", not funnel ordering.
- bucket_predicate = ast.And(
- exprs=[
- ast.CompareOperation(op=ast.CompareOperationOp.Gt, left=count_if(entry), right=ast.Constant(value=0)),
- ast.CompareOperation(
- op=ast.CompareOperationOp.Lt,
- left=count_if(completion),
- right=ast.Constant(value=completion_occurrences),
- ),
- ]
+ completion, completion_occurrences = _funnel_completion_condition(considered[0], team)
+ # The funnel's implicit first step is the exposure event, and the HAVING below already
+ # requires an in-session exposure for every bucket, so drop-off needs only the completion
+ # side. Count-based on purpose: the filter promises "fired the last step's event", not
+ # funnel ordering.
+ bucket_predicate = ast.CompareOperation(
+ op=ast.CompareOperationOp.Lt,
+ left=count_if(completion),
+ right=ast.Constant(value=completion_occurrences),
)
# The WHERE keeps the OR of every condition the query can match on, so ClickHouse still prunes
diff --git a/products/experiments/backend/test/test_session_buckets_api.py b/products/experiments/backend/test/test_session_buckets_api.py
index e7559d98731a..9510abc598c4 100644
--- a/products/experiments/backend/test/test_session_buckets_api.py
+++ b/products/experiments/backend/test/test_session_buckets_api.py
@@ -63,6 +63,13 @@ REPEATED_STEP_FUNNEL_METRIC = {
"name": "Second upload",
"series": [{"kind": "EventsNode", "event": "uploaded file"}, {"kind": "EventsNode", "event": "uploaded file"}],
}
+SINGLE_STEP_FUNNEL_METRIC = {
+ "kind": "ExperimentMetric",
+ "metric_type": "funnel",
+ "uuid": "99999999-9999-9999-9999-999999999999",
+ "name": "Purchase funnel",
+ "series": [{"kind": "EventsNode", "event": "purchase"}],
+}
RETENTION_METRIC = {
"kind": "ExperimentMetric",
"metric_type": "retention",
@@ -274,57 +281,53 @@ class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):
@parameterized.expand(
[
- # Distinct entry and completion events: entering is one event, completing is the other.
- ("distinct_steps", CHECKOUT_FUNNEL_METRIC, "cart viewed", "purchase"),
- # One event repeated as two steps ("the second upload"): entry and completion match the
- # same event, so only the occurrence count tells them apart.
- ("repeated_step", REPEATED_STEP_FUNNEL_METRIC, "uploaded file", "uploaded file"),
+ # Firing an earlier series step still isn't completing.
+ ("distinct_steps", CHECKOUT_FUNNEL_METRIC, ["cart viewed"], ["cart viewed", "purchase"]),
+ # One event repeated as two steps ("the second upload"): completing means firing it as
+ # many times as it appears, so a single occurrence is still a drop-off.
+ ("repeated_step", REPEATED_STEP_FUNNEL_METRIC, ["uploaded file"], ["uploaded file", "uploaded file"]),
+ # A single-step funnel is exposure → event; an unrelated event isn't the completion.
+ ("single_step", SINGLE_STEP_FUNNEL_METRIC, ["cart viewed"], ["purchase"]),
]
)
- def test_funnel_dropoff_returns_entered_but_not_completed(
- self, _name: str, metric: dict[str, Any], entry_event: str, completion_event: str
+ def test_funnel_dropoff_returns_exposed_sessions_that_never_completed(
+ self, _name: str, metric: dict[str, Any], partial_events: list[str], completing_events: list[str]
) -> None:
experiment = self._create_experiment(metrics=[metric])
- dropped_off = self._session(events=[(entry_event, datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])
+ exposed_only = self._session()
+ partial = self._session(
+ events=[
+ (event, datetime(2026, 1, 9, 10, 5 + index, tzinfo=UTC)) for index, event in enumerate(partial_events)
+ ]
+ )
completed = self._session(
events=[
- (entry_event, datetime(2026, 1, 9, 10, 5, tzinfo=UTC)),
- (completion_event, datetime(2026, 1, 9, 10, 7, tzinfo=UTC)),
+ (event, datetime(2026, 1, 9, 10, 5 + index, tzinfo=UTC))
+ for index, event in enumerate(completing_events)
]
)
- never_entered = self._session()
flush_persons_and_events()
response = self._post_bucket(experiment, bucket="funnel_dropoff", metric_uuids=[metric["uuid"]])
+ # The exposure is the funnel's first step, the same as in the experiment analysis, so
+ # being exposed is entering the funnel; not completing is what puts a session here.
assert response.status_code == status.HTTP_200_OK, response.json()
session_ids = response.json()["session_ids"]
- assert session_ids == [dropped_off]
+ assert set(session_ids) == {exposed_only, partial}
assert completed not in session_ids
- assert never_entered not in session_ids
@parameterized.expand(
[
- # The completion side: without the check every session that entered comes back as
- # "didn't finish", including the ones whose purchase really did happen.
+ # Without the check every exposed session comes back as "didn't finish", including
+ # the ones whose purchase really did happen.
(
"server_side_completion",
_funnel("a1111111-1111-1111-1111-111111111111", "Checkout", [CART, SERVER_CHARGE]),
"captured server-side",
),
- # The entry side fails the other way, to a silently empty bucket.
- (
- "server_side_entry",
- _funnel("a2222222-2222-2222-2222-222222222222", "Charge then buy", [SERVER_CHARGE, PURCHASE]),
- "captured server-side",
- ),
- # A data-warehouse step is dropped from the metric's sources, so the positional read
- # would silently promote an inner step to the funnel's boundary.
- (
- "data_warehouse_entry",
- _funnel("a3333333-3333-3333-3333-333333333333", "Charge first", [DATA_WAREHOUSE_STEP, CART, PURCHASE]),
- "data warehouse",
- ),
+ # A data-warehouse completion is dropped from the metric's sources, so the positional
+ # read would silently promote an inner step to the funnel's completion.
(
"data_warehouse_completion",
_funnel("a4444444-4444-4444-4444-444444444444", "Charge last", [CART, PURCHASE, DATA_WAREHOUSE_STEP]),
@@ -332,7 +335,7 @@ class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):
),
]
)
- def test_funnel_dropoff_refuses_when_a_boundary_step_cannot_be_matched(
+ def test_funnel_dropoff_refuses_when_the_completion_step_cannot_be_matched(
self, _name: str, metric: dict[str, Any], expected_reason: str
) -> None:
experiment = self._create_experiment(metrics=[metric])
@@ -346,13 +349,13 @@ class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):
response = self._post_bucket(experiment, bucket="funnel_dropoff", metric_uuids=[metric["uuid"]])
- # Drop-off is the count of the funnel's first step against its last one. When either can't
- # appear in a recording the predicate answers a question nobody asked, and every exposed
- # session lands in (or out of) the bucket with nothing on screen saying why.
+ # Drop-off counts the funnel's last step. When that step can't appear in a recording the
+ # predicate answers a question nobody asked, and every exposed session lands in the
+ # bucket with nothing on screen saying why.
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
assert expected_reason in response.json()["detail"]
- def test_funnel_dropoff_boundary_check_survives_an_action_step(self) -> None:
+ def test_funnel_dropoff_completion_check_survives_an_action_step(self) -> None:
action = Action.objects.create(team=self.team, name="Viewed cart", steps_json=[{"event": "cart viewed"}])
metric = _funnel(
"a7777777-7777-7777-7777-777777777777",
@@ -366,19 +369,43 @@ class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):
response = self._post_bucket(experiment, bucket="funnel_dropoff", metric_uuids=[metric["uuid"]])
# An action among the steps makes the metric's event names unresolvable as a whole, but the
- # boundary steps are still concrete events. Looking names up per metric rather than per
- # source would leave the completion event out of the linkability read, and the boundary
+ # completion step is still a concrete event. Looking names up per metric rather than per
+ # source would leave the completion event out of the linkability read, and the completion
# check would pass on a name it never asked about.
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
assert "captured server-side" in response.json()["detail"]
- def test_funnel_dropoff_allows_an_unmatchable_step_between_the_boundaries(self) -> None:
- metric = _funnel("a5555555-5555-5555-5555-555555555555", "Checkout", [CART, SERVER_CHARGE, PURCHASE])
+ @parameterized.expand(
+ [
+ # The funnel's entry is the exposure, so a first series step no recording can show
+ # doesn't gate the question the way the completion does.
+ (
+ "server_side_first_step",
+ _funnel("a2222222-2222-2222-2222-222222222222", "Charge then buy", [SERVER_CHARGE, PURCHASE]),
+ [],
+ ),
+ (
+ "server_side_middle_step",
+ _funnel("a5555555-5555-5555-5555-555555555555", "Checkout", [CART, SERVER_CHARGE, PURCHASE]),
+ ["cart viewed"],
+ ),
+ (
+ "data_warehouse_first_step",
+ _funnel("a3333333-3333-3333-3333-333333333333", "Charge first", [DATA_WAREHOUSE_STEP, CART, PURCHASE]),
+ ["cart viewed"],
+ ),
+ ]
+ )
+ def test_funnel_dropoff_allows_unmatchable_steps_before_the_completion(
+ self, _name: str, metric: dict[str, Any], dropped_events: list[str]
+ ) -> None:
experiment = self._create_experiment(metrics=[metric])
- dropped_off = self._session(events=[("cart viewed", datetime(2026, 1, 9, 10, 5, tzinfo=UTC))])
+ dropped_off = self._session(
+ events=[(event, datetime(2026, 1, 9, 10, 5, tzinfo=UTC)) for event in dropped_events]
+ )
completed = self._session(
events=[
- ("cart viewed", datetime(2026, 1, 9, 10, 5, tzinfo=UTC)),
+ *[(event, datetime(2026, 1, 9, 10, 5, tzinfo=UTC)) for event in dropped_events],
("purchase", datetime(2026, 1, 9, 10, 7, tzinfo=UTC)),
]
)
@@ -386,8 +413,8 @@ class TestExperimentSessionBuckets(ClickhouseTestMixin, APILicensedTest):
response = self._post_bucket(experiment, bucket="funnel_dropoff", metric_uuids=[metric["uuid"]])
- # Only the two boundary steps are read, so a server-side step between them costs nothing.
- # Refusing here would take drop-off away from funnels it answers correctly.
+ # Only the completion step is read, so steps before it that no recording can show cost
+ # nothing. Refusing here would take drop-off away from funnels it answers correctly.
assert response.status_code == status.HTTP_200_OK, response.json()
assert response.json()["session_ids"] == [dropped_off]
assert completed not in response.json()["session_ids"]
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index 45e01c810ff3..152cb0784f70 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -2181,7 +2181,7 @@ export const ExperimentSessionBucketEnumApi = {
* Request body for the session-bucket endpoint.
*/
export interface ExperimentSessionBucketRequestApi {
- /** Which question the returned session set answers. 'fired_any': the session fired at least one event of any listed metric (an OR the recordings query itself can't express). 'no_metric_activity': the session fired none of them. 'funnel_dropoff': the session fired the funnel metric's first step and never reached its last one. All three are session-scoped and goal-free: they say what happened in the session, not whether it helped or hurt the metric.
+ /** Which question the returned session set answers. 'fired_any': the session fired at least one event of any listed metric (an OR the recordings query itself can't express). 'no_metric_activity': the session fired none of them. 'funnel_dropoff': the session saw an exposure event but never fired the funnel metric's last step; the exposure is the funnel's implicit first step, the same as in the experiment analysis. All three are session-scoped and goal-free: they say what happened in the session, not whether it helped or hurt the metric.
*
* * `fired_any` - fired_any
* * `no_metric_activity` - no_metric_activity
diff --git a/products/experiments/frontend/generated/api.ts b/products/experiments/frontend/generated/api.ts
index 1fa25d279b19..3fb711b22635 100644
--- a/products/experiments/frontend/generated/api.ts
+++ b/products/experiments/frontend/generated/api.ts
@@ -875,7 +875,7 @@ export const getExperimentsSessionBucketsCreateUrl = (projectId: string, id: num
* Session recordings of this experiment matching a bucket.
*
* Answers the questions a recordings query can't express on its own — "fired any of these
- * metrics", "fired none of them", "entered the funnel but never completed it in this
+ * metrics", "fired none of them", "was exposed but never completed the funnel in this
* session" — by returning a bounded, most-recent-first list of session IDs to pass back as
* a recordings query's session_ids. POST because the metric list doesn't fit a query
* string; the endpoint only reads.
diff --git a/products/experiments/frontend/generated/api.zod.ts b/products/experiments/frontend/generated/api.zod.ts
index 25250d66e710..bf5826055720 100644
--- a/products/experiments/frontend/generated/api.zod.ts
+++ b/products/experiments/frontend/generated/api.zod.ts
@@ -1059,7 +1059,7 @@ export const ExperimentsRecalculateTimeseriesCreateBody = /* @__PURE__ */ zod
* Session recordings of this experiment matching a bucket.
*
* Answers the questions a recordings query can't express on its own — "fired any of these
- * metrics", "fired none of them", "entered the funnel but never completed it in this
+ * metrics", "fired none of them", "was exposed but never completed the funnel in this
* session" — by returning a bounded, most-recent-first list of session IDs to pass back as
* a recordings query's session_ids. POST because the metric list doesn't fit a query
* string; the endpoint only reads.
@@ -1079,7 +1079,7 @@ export const ExperimentsSessionBucketsCreateBody = /* @__PURE__ */ zod
'\* `fired_any` - fired_any\n\* `no_metric_activity` - no_metric_activity\n\* `funnel_dropoff` - funnel_dropoff'
)
.describe(
- "Which question the returned session set answers. 'fired_any': the session fired at least one event of any listed metric (an OR the recordings query itself can't express). 'no_metric_activity': the session fired none of them. 'funnel_dropoff': the session fired the funnel metric's first step and never reached its last one. All three are session-scoped and goal-free: they say what happened in the session, not whether it helped or hurt the metric.\n\n\* `fired_any` - fired_any\n\* `no_metric_activity` - no_metric_activity\n\* `funnel_dropoff` - funnel_dropoff"
+ "Which question the returned session set answers. 'fired_any': the session fired at least one event of any listed metric (an OR the recordings query itself can't express). 'no_metric_activity': the session fired none of them. 'funnel_dropoff': the session saw an exposure event but never fired the funnel metric's last step; the exposure is the funnel's implicit first step, the same as in the experiment analysis. All three are session-scoped and goal-free: they say what happened in the session, not whether it helped or hurt the metric.\n\n\* `fired_any` - fired_any\n\* `no_metric_activity` - no_metric_activity\n\* `funnel_dropoff` - funnel_dropoff"
),
metric_uuids: zod
.array(zod.string().describe("UUID of one of the experiment's metrics."))
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 28e763b01149..8d001d76c5a6 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -29394,7 +29394,7 @@ export namespace Schemas {
* Request body for the session-bucket endpoint.
*/
export interface ExperimentSessionBucketRequest {
- /** Which question the returned session set answers. 'fired_any': the session fired at least one event of any listed metric (an OR the recordings query itself can't express). 'no_metric_activity': the session fired none of them. 'funnel_dropoff': the session fired the funnel metric's first step and never reached its last one. All three are session-scoped and goal-free: they say what happened in the session, not whether it helped or hurt the metric.
+ /** Which question the returned session set answers. 'fired_any': the session fired at least one event of any listed metric (an OR the recordings query itself can't express). 'no_metric_activity': the session fired none of them. 'funnel_dropoff': the session saw an exposure event but never fired the funnel metric's last step; the exposure is the funnel's implicit first step, the same as in the experiment analysis. All three are session-scoped and goal-free: they say what happened in the session, not whether it helped or hurt the metric.
*
* * `fired_any` - fired_any
* * `no_metric_activity` - no_metric_activity