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(experiments): fix actors query for drop off on the first step of the funnel. (#62295)

Rodrigo Iloro21502a0edb72
diff --git a/frontend/src/scenes/experiments/charts/funnel/StepBar.tsx b/frontend/src/scenes/experiments/charts/funnel/StepBar.tsx
index e14edb259db1..183172f1bbad 100644
--- a/frontend/src/scenes/experiments/charts/funnel/StepBar.tsx
+++ b/frontend/src/scenes/experiments/charts/funnel/StepBar.tsx
@@ -77,16 +77,9 @@ function openExperimentPersonsModalForSeries({
return
}
- // Skip drop-off queries for the first metric step (stepIndex 1)
- // Drop-offs at step 1 would mean "exposed but never entered the funnel",
- // which can't be queried via the actors funnel (it starts at the first metric event)
- if (!converted && backendStepNo === 1) {
- return
- }
-
- // For drop-offs, the mapping is straightforward
- // Frontend step 2 drop-off = "completed step 1 ($pageview) but not step 2 (click)" = backend -2 = -stepIndex
- // Frontend step 3 drop-off = "completed step 2 (click) but not step 3 (next event)" = backend -3 = -stepIndex
+ // For drop-offs, the mapping is straightforward (funnelStep = -stepIndex):
+ // Step 1 drop-off = "exposed but did not reach the first metric event" = backend -1
+ // Step 2 drop-off = "completed step 1 but not step 2 (click)" = backend -2
const funnelStep = converted ? backendStepNo : -backendStepNo
// Create ExperimentActorsQuery with exposure configuration
@@ -183,7 +176,7 @@ export function StepBar({ step, stepIndex }: StepBarProps): JSX.Element | null {
className="StepBar__backdrop"
onClick={handleDropoffClick}
style={{
- cursor: stepIndex > 1 ? 'pointer' : 'default',
+ cursor: stepIndex > 0 ? 'pointer' : 'default',
}}
/>
<div
diff --git a/products/experiments/backend/hogql_queries/experiment_query_runner.py b/products/experiments/backend/hogql_queries/experiment_query_runner.py
index 4c12f0cf306a..c0d8159e0acf 100644
--- a/products/experiments/backend/hogql_queries/experiment_query_runner.py
+++ b/products/experiments/backend/hogql_queries/experiment_query_runner.py
@@ -861,46 +861,21 @@ class ExperimentQueryRunner(QueryRunner):
num_metric_steps = len(self.metric.series)
- # Validate step range (same validation as before)
- if funnel_step == -1:
- # -1 would mean "dropped before first metric step" which is invalid
- # because we only query exposed users who are already past the exposure checkpoint
- # Build event names string (handle EventsNode, ActionsNode, and ExperimentDataWarehouseNode)
- from posthog.schema import ActionsNode, EventsNode
-
- event_names: list[str] = []
- for step in self.metric.series[:2]:
- if isinstance(step, EventsNode):
- event_names.append(step.event or "All events")
- elif isinstance(step, ActionsNode):
- event_names.append(f"Action {step.id}")
- else: # ExperimentDataWarehouseNode
- event_names.append(f"DW table {step.table_name}")
-
- metric_events_str = " → ".join(event_names)
- if len(self.metric.series) > 2:
- metric_events_str += " → ..."
-
- raise ValidationError(
- f"Cannot query drop-offs before the first metric step in experiment funnels. "
- f"Experiment funnel structure: [Exposure → {metric_events_str}]. "
- f"Drop-offs at funnelStep=-1 would mean 'exposed but never entered the funnel', "
- f"which cannot be queried through the actors API. "
- f"Valid drop-off steps: -2 (dropped after first metric step) to -{num_metric_steps + 1}."
- )
-
- if funnel_step < -1:
+ # funnelStep=-1 is a valid drop-off: "exposed but never reached the first metric step".
+ # step_reached is 0-indexed with exposure as step 0, so the WHERE clause resolves it to
+ # step_reached == 0 — the exposed users who did not validly enter the funnel.
+ if funnel_step < 0:
max_drop_off = -(num_metric_steps + 1)
if funnel_step < max_drop_off:
raise ValidationError(
f"Invalid drop-off step {funnel_step} for experiment with {num_metric_steps} metric steps. "
- f"Valid drop-off steps: -2 (dropped after first metric step) to {max_drop_off}."
+ f"Valid drop-off steps: -1 (exposed, did not reach first metric step) to {max_drop_off}."
)
if funnel_step > num_metric_steps:
raise ValidationError(
f"Invalid conversion step {funnel_step} for experiment with {num_metric_steps} metric steps. "
- f"Valid conversion steps: 1 (first metric step) to {num_metric_steps}."
+ f"Valid conversion steps: 0 (exposure step) to {num_metric_steps}."
)
# Extract exposure configuration from actors query
diff --git a/products/experiments/backend/hogql_queries/test/__snapshots__/test_experiment_actors_query.ambr b/products/experiments/backend/hogql_queries/test/__snapshots__/test_experiment_actors_query.ambr
index 35440be9046b..79b9c98f0122 100644
--- a/products/experiments/backend/hogql_queries/test/__snapshots__/test_experiment_actors_query.ambr
+++ b/products/experiments/backend/hogql_queries/test/__snapshots__/test_experiment_actors_query.ambr
@@ -304,7 +304,79 @@
use_hive_partitioning=0
'''
# ---
-# name: TestExperimentActorsQuery.test_experiment_funnel_actors_4_dropoffs_control
+# name: TestExperimentActorsQuery.test_experiment_funnel_actors_4_dropoffs_step1_control
+ '''
+ SELECT source.id,
+ source.id AS id
+ FROM
+ (WITH exposures AS
+ (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
+ if(greater(uniqExact(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', '')), 1), '$multiple', any(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', ''))) AS variant,
+ min(toTimeZone(events.timestamp, 'UTC')) AS first_exposure_time,
+ max(toTimeZone(events.timestamp, 'UTC')) AS last_exposure_time,
+ argMin(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS exposure_event_uuid,
+ argMin(events.`$session_id`, toTimeZone(events.timestamp, 'UTC')) AS exposure_session_id
+ 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, assumeNotNull(toDateTime('2020-01-01 12:00:00', 'UTC'))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC'))), and(equals(events.event, '$feature_flag_called'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag'), ''), 'null'), '^"|"$', ''), 'test-experiment'), 0)), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', ''), ['control', 'test']))
+ GROUP BY entity_id),
+ metric_events AS
+ (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
+ toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ events.uuid AS uuid,
+ nullIf(nullIf(events.`$session_id`, ''), 'null') AS session_id,
+ multiply(1, and(equals(events.event, '$feature_flag_called'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag'), ''), 'null'), '^"|"$', ''), 'test-experiment'), 0))) AS step_0,
+ if(equals(events.event, 'signup'), 1, 0) AS step_1,
+ if(equals(events.event, 'purchase'), 1, 0) AS step_2
+ 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, assumeNotNull(toDateTime('2020-01-01 12:00:00', 'UTC'))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC'))), or(and(equals(events.event, '$feature_flag_called'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag'), ''), 'null'), '^"|"$', ''), 'test-experiment'), 0)), or(equals(events.event, 'signup'), equals(events.event, 'purchase'))))),
+ entity_metrics AS
+ (SELECT exposures.entity_id AS entity_id,
+ exposures.variant AS variant,
+ exposures.exposure_event_uuid AS exposure_event_uuid,
+ (arraySort(x -> minus(0, x.1), arrayMap(result -> tuple(result.1, if(and(ifNull(greaterOrEquals(result.1, 0), 0), ifNull(greater(length(result.4), result.1), 0)), if(ifNull(greater(length(arrayElement(result.4, plus(result.1, 1))), 0), 0), toString(arrayElement(result.4, plus(result.1, 1))[1]), ''), '')), aggregate_funnel_array(3, 94608000, 'first_touch', 'ordered', array(array('')), [], arraySort(t -> t.1, arrayFilter(t -> and(isNotNull(t.1), isNotNull(t.2)), groupArray(tuple(accurateCastOrNull(toTimeZone(metric_events.timestamp, 'UTC'), 'Float64'), metric_events.uuid, array(''), arrayFilter(x -> ifNull(greater(x, 0), 0), [multiply(1, metric_events.step_0), multiply(2, metric_events.step_1), multiply(3, metric_events.step_2)]))))))))[1]).1 AS step_reached
+ FROM exposures
+ LEFT JOIN metric_events ON equals(exposures.entity_id, metric_events.entity_id)
+ GROUP BY exposures.entity_id,
+ exposures.variant,
+ exposures.exposure_event_uuid) SELECT entity_metrics.entity_id AS actor_id,
+ entity_metrics.variant AS variant,
+ actor_id AS id
+ FROM entity_metrics
+ WHERE and(ifNull(greaterOrEquals(entity_metrics.step_reached, 0), 0), ifNull(less(entity_metrics.step_reached, 1), 0), ifNull(equals(variant, 'control'), 0))
+ ORDER BY entity_metrics.entity_id ASC) AS source
+ ORDER BY source.id ASC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ 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=0,
+ 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: TestExperimentActorsQuery.test_experiment_funnel_actors_5_dropoffs_control
'''
SELECT source.id,
source.id AS id
@@ -376,7 +448,7 @@
use_hive_partitioning=0
'''
# ---
-# name: TestExperimentActorsQuery.test_experiment_funnel_actors_5_conversions_step1_test
+# name: TestExperimentActorsQuery.test_experiment_funnel_actors_6_conversions_step1_test
'''
SELECT source.id,
source.id AS id
@@ -448,7 +520,7 @@
use_hive_partitioning=0
'''
# ---
-# name: TestExperimentActorsQuery.test_experiment_funnel_actors_6_conversions_step2_test
+# name: TestExperimentActorsQuery.test_experiment_funnel_actors_7_conversions_step2_test
'''
SELECT source.id,
source.id AS id
@@ -520,7 +592,79 @@
use_hive_partitioning=0
'''
# ---
-# name: TestExperimentActorsQuery.test_experiment_funnel_actors_7_dropoffs_test
+# name: TestExperimentActorsQuery.test_experiment_funnel_actors_8_dropoffs_step1_test
+ '''
+ SELECT source.id,
+ source.id AS id
+ FROM
+ (WITH exposures AS
+ (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
+ if(greater(uniqExact(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', '')), 1), '$multiple', any(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', ''))) AS variant,
+ min(toTimeZone(events.timestamp, 'UTC')) AS first_exposure_time,
+ max(toTimeZone(events.timestamp, 'UTC')) AS last_exposure_time,
+ argMin(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS exposure_event_uuid,
+ argMin(events.`$session_id`, toTimeZone(events.timestamp, 'UTC')) AS exposure_session_id
+ 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, assumeNotNull(toDateTime('2020-01-01 12:00:00', 'UTC'))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC'))), and(equals(events.event, '$feature_flag_called'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag'), ''), 'null'), '^"|"$', ''), 'test-experiment'), 0)), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', ''), ['control', 'test']))
+ GROUP BY entity_id),
+ metric_events AS
+ (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
+ toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ events.uuid AS uuid,
+ nullIf(nullIf(events.`$session_id`, ''), 'null') AS session_id,
+ multiply(1, and(equals(events.event, '$feature_flag_called'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag'), ''), 'null'), '^"|"$', ''), 'test-experiment'), 0))) AS step_0,
+ if(equals(events.event, 'signup'), 1, 0) AS step_1,
+ if(equals(events.event, 'purchase'), 1, 0) AS step_2
+ 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, assumeNotNull(toDateTime('2020-01-01 12:00:00', 'UTC'))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC'))), or(and(equals(events.event, '$feature_flag_called'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag'), ''), 'null'), '^"|"$', ''), 'test-experiment'), 0)), or(equals(events.event, 'signup'), equals(events.event, 'purchase'))))),
+ entity_metrics AS
+ (SELECT exposures.entity_id AS entity_id,
+ exposures.variant AS variant,
+ exposures.exposure_event_uuid AS exposure_event_uuid,
+ (arraySort(x -> minus(0, x.1), arrayMap(result -> tuple(result.1, if(and(ifNull(greaterOrEquals(result.1, 0), 0), ifNull(greater(length(result.4), result.1), 0)), if(ifNull(greater(length(arrayElement(result.4, plus(result.1, 1))), 0), 0), toString(arrayElement(result.4, plus(result.1, 1))[1]), ''), '')), aggregate_funnel_array(3, 94608000, 'first_touch', 'ordered', array(array('')), [], arraySort(t -> t.1, arrayFilter(t -> and(isNotNull(t.1), isNotNull(t.2)), groupArray(tuple(accurateCastOrNull(toTimeZone(metric_events.timestamp, 'UTC'), 'Float64'), metric_events.uuid, array(''), arrayFilter(x -> ifNull(greater(x, 0), 0), [multiply(1, metric_events.step_0), multiply(2, metric_events.step_1), multiply(3, metric_events.step_2)]))))))))[1]).1 AS step_reached
+ FROM exposures
+ LEFT JOIN metric_events ON equals(exposures.entity_id, metric_events.entity_id)
+ GROUP BY exposures.entity_id,
+ exposures.variant,
+ exposures.exposure_event_uuid) SELECT entity_metrics.entity_id AS actor_id,
+ entity_metrics.variant AS variant,
+ actor_id AS id
+ FROM entity_metrics
+ WHERE and(ifNull(greaterOrEquals(entity_metrics.step_reached, 0), 0), ifNull(less(entity_metrics.step_reached, 1), 0), ifNull(equals(variant, 'test'), 0))
+ ORDER BY entity_metrics.entity_id ASC) AS source
+ ORDER BY source.id ASC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ 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=0,
+ 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: TestExperimentActorsQuery.test_experiment_funnel_actors_9_dropoffs_test
'''
SELECT source.id,
source.id AS id
@@ -664,6 +808,78 @@
use_hive_partitioning=0
'''
# ---
+# name: TestExperimentActorsQuery.test_experiment_funnel_actors_step1_dropoff_counts_pre_exposure_signup
+ '''
+ SELECT source.id,
+ source.id AS id
+ FROM
+ (WITH exposures AS
+ (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
+ if(greater(uniqExact(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', '')), 1), '$multiple', any(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', ''))) AS variant,
+ min(toTimeZone(events.timestamp, 'UTC')) AS first_exposure_time,
+ max(toTimeZone(events.timestamp, 'UTC')) AS last_exposure_time,
+ argMin(events.uuid, toTimeZone(events.timestamp, 'UTC')) AS exposure_event_uuid,
+ argMin(events.`$session_id`, toTimeZone(events.timestamp, 'UTC')) AS exposure_session_id
+ 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, assumeNotNull(toDateTime('2020-01-01 12:00:00', 'UTC'))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC'))), and(equals(events.event, '$feature_flag_called'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag'), ''), 'null'), '^"|"$', ''), 'test-experiment'), 0)), in(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag_response'), ''), 'null'), '^"|"$', ''), ['control', 'test']))
+ GROUP BY entity_id),
+ metric_events AS
+ (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS entity_id,
+ toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ events.uuid AS uuid,
+ nullIf(nullIf(events.`$session_id`, ''), 'null') AS session_id,
+ multiply(1, and(equals(events.event, '$feature_flag_called'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag'), ''), 'null'), '^"|"$', ''), 'test-experiment'), 0))) AS step_0,
+ if(equals(events.event, 'signup'), 1, 0) AS step_1,
+ if(equals(events.event, 'purchase'), 1, 0) AS step_2
+ 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, assumeNotNull(toDateTime('2020-01-01 12:00:00', 'UTC'))), lessOrEquals(events.timestamp, assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC'))), or(and(equals(events.event, '$feature_flag_called'), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, '$feature_flag'), ''), 'null'), '^"|"$', ''), 'test-experiment'), 0)), or(equals(events.event, 'signup'), equals(events.event, 'purchase'))))),
+ entity_metrics AS
+ (SELECT exposures.entity_id AS entity_id,
+ exposures.variant AS variant,
+ exposures.exposure_event_uuid AS exposure_event_uuid,
+ (arraySort(x -> minus(0, x.1), arrayMap(result -> tuple(result.1, if(and(ifNull(greaterOrEquals(result.1, 0), 0), ifNull(greater(length(result.4), result.1), 0)), if(ifNull(greater(length(arrayElement(result.4, plus(result.1, 1))), 0), 0), toString(arrayElement(result.4, plus(result.1, 1))[1]), ''), '')), aggregate_funnel_array(3, 94608000, 'first_touch', 'ordered', array(array('')), [], arraySort(t -> t.1, arrayFilter(t -> and(isNotNull(t.1), isNotNull(t.2)), groupArray(tuple(accurateCastOrNull(toTimeZone(metric_events.timestamp, 'UTC'), 'Float64'), metric_events.uuid, array(''), arrayFilter(x -> ifNull(greater(x, 0), 0), [multiply(1, metric_events.step_0), multiply(2, metric_events.step_1), multiply(3, metric_events.step_2)]))))))))[1]).1 AS step_reached
+ FROM exposures
+ LEFT JOIN metric_events ON equals(exposures.entity_id, metric_events.entity_id)
+ GROUP BY exposures.entity_id,
+ exposures.variant,
+ exposures.exposure_event_uuid) SELECT entity_metrics.entity_id AS actor_id,
+ entity_metrics.variant AS variant,
+ actor_id AS id
+ FROM entity_metrics
+ WHERE and(ifNull(greaterOrEquals(entity_metrics.step_reached, 0), 0), ifNull(less(entity_metrics.step_reached, 1), 0), ifNull(equals(variant, 'control'), 0))
+ ORDER BY entity_metrics.entity_id ASC) AS source
+ ORDER BY source.id ASC
+ LIMIT 101
+ OFFSET 0 SETTINGS optimize_aggregation_in_order=1,
+ join_algorithm='auto',
+ 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=0,
+ 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: TestExperimentActorsQuery.test_experiment_funnel_actors_with_recordings
'''
SELECT source.id,
diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_actors_query.py b/products/experiments/backend/hogql_queries/test/test_experiment_actors_query.py
index 82a5d1bec5a2..c6aee5a62fcb 100644
--- a/products/experiments/backend/hogql_queries/test/test_experiment_actors_query.py
+++ b/products/experiments/backend/hogql_queries/test/test_experiment_actors_query.py
@@ -151,9 +151,11 @@ class TestExperimentActorsQuery(ExperimentQueryRunnerBaseTest, ClickhouseTestMix
("exposure_test", 0, "test", 10), # Step 0 = all exposed actors (test)
("conversions_step1_control", 1, "control", 6), # Step 1 conversions (signup)
("conversions_step2_control", 2, "control", 4), # Step 2 conversions (purchase)
+ ("dropoffs_step1_control", -1, "control", 4), # Step 1 drop-offs (exposed, no signup)
("dropoffs_control", -2, "control", 2), # Step 2 drop-offs (signup but no purchase)
("conversions_step1_test", 1, "test", 8), # Step 1 conversions (signup) - test variant
("conversions_step2_test", 2, "test", 6), # Step 2 conversions (purchase) - test variant
+ ("dropoffs_step1_test", -1, "test", 2), # Step 1 drop-offs (exposed, no signup) - test variant
("dropoffs_test", -2, "test", 2), # Step 2 drop-offs - test variant
]
)
@@ -362,39 +364,11 @@ class TestExperimentActorsQuery(ExperimentQueryRunnerBaseTest, ClickhouseTestMix
Experiment funnels have unique constraints:
- Exposure is step 0 in main query and queryable via the actors query (returns all exposed actors)
- - funnelStep=-1 is invalid (would mean "exposed but never entered funnel")
+ - funnelStep=-1 is valid (exposed, did not reach the first metric step)
- Out-of-range steps should be rejected
"""
feature_flag, experiment, experiment_query = self._create_experiment_with_funnel()
- # Test -1: Invalid drop-off (would mean "dropped before first metric step")
- # Error message should explain the experiment funnel structure and why this is invalid
- experiment_actors_query = ExperimentActorsQuery(
- kind="ExperimentActorsQuery",
- source=experiment_query,
- funnelStep=-1,
- funnelStepBreakdown="control",
- includeRecordings=False,
- )
-
- actors_query = ActorsQuery(
- source=experiment_actors_query,
- select=["id", "person"],
- )
-
- with self.assertRaises(Exception) as context:
- ActorsQueryRunner(query=actors_query, team=self.team).calculate()
-
- error_message = str(context.exception)
- # Verify error message contains all key information
- self.assertIn("Cannot query drop-offs before the first metric step", error_message)
- self.assertIn("experiment funnel", error_message.lower())
- self.assertIn("Exposure", error_message) # Shows funnel structure
- self.assertIn("signup", error_message) # Shows first metric event name
- self.assertIn("exposed but never entered the funnel", error_message) # Explains WHY invalid
- self.assertIn("Valid drop-off steps: -2", error_message) # Shows valid range
- self.assertIn("-3", error_message) # Shows upper bound of valid range
-
# Test out-of-range drop-off (2-step funnel, so -3 is last valid, -4 is invalid)
# Error message should show the invalid step, number of metric steps, and valid range
experiment_actors_query_out_of_range = ExperimentActorsQuery(
@@ -416,7 +390,7 @@ class TestExperimentActorsQuery(ExperimentQueryRunnerBaseTest, ClickhouseTestMix
error_message = str(context.exception)
self.assertIn("Invalid drop-off step -4", error_message) # Shows the invalid value
self.assertIn("2 metric steps", error_message) # Shows context
- self.assertIn("Valid drop-off steps: -2", error_message) # Shows valid range start
+ self.assertIn("Valid drop-off steps: -1", error_message) # Shows valid range start
self.assertIn("-3", error_message) # Shows valid range end
# Test out-of-range conversion (2-step funnel, so 3 is invalid)
@@ -440,8 +414,8 @@ class TestExperimentActorsQuery(ExperimentQueryRunnerBaseTest, ClickhouseTestMix
error_message = str(context.exception)
self.assertIn("Invalid conversion step 3", error_message) # Shows the invalid value
self.assertIn("2 metric steps", error_message) # Shows context
- self.assertIn("Valid conversion steps: 1", error_message) # Shows valid range start
- self.assertIn("(first metric step) to 2", error_message) # Shows valid range end with explanation
+ self.assertIn("Valid conversion steps: 0", error_message) # Shows valid range start
+ self.assertIn("(exposure step) to 2", error_message) # Shows valid range end with explanation
@freeze_time("2020-01-01T12:00:00Z")
@snapshot_clickhouse_queries
@@ -533,6 +507,70 @@ class TestExperimentActorsQuery(ExperimentQueryRunnerBaseTest, ClickhouseTestMix
assert len(response.results) == 1
assert response.results[0][1]["distinct_ids"][0] == "user_after_exposure"
+ @freeze_time("2020-01-01T12:00:00Z")
+ @snapshot_clickhouse_queries
+ def test_experiment_funnel_actors_step1_dropoff_counts_pre_exposure_signup(self):
+ """
+ Step-1 drop-offs (funnelStep=-1) are "exposed but did not reach the first metric step".
+
+ A signup that happened BEFORE exposure does not count toward the funnel, so that user
+ is exposed-only (step_reached=0) and should appear as a step-1 drop-off. A user who
+ signed up AFTER exposure reached the first metric step and must be excluded.
+ """
+ feature_flag, experiment, experiment_query = self._create_experiment_with_funnel()
+
+ # Signup before exposure -> does not enter the funnel -> step-1 drop-off
+ _create_person(distinct_ids=["user_before_exposure"], team_id=self.team.pk)
+ _create_event(
+ team=self.team,
+ event="signup",
+ distinct_id="user_before_exposure",
+ timestamp="2020-01-02T10:00:00Z",
+ )
+ _create_event(
+ team=self.team,
+ event="$feature_flag_called",
+ distinct_id="user_before_exposure",
+ timestamp="2020-01-02T12:00:00Z",
+ properties={"$feature_flag": feature_flag.key, "$feature_flag_response": "control"},
+ )
+
+ # Signup after exposure -> reaches first metric step -> NOT a step-1 drop-off
+ _create_person(distinct_ids=["user_after_exposure"], team_id=self.team.pk)
+ _create_event(
+ team=self.team,
+ event="$feature_flag_called",
+ distinct_id="user_after_exposure",
+ timestamp="2020-01-02T12:00:00Z",
+ properties={"$feature_flag": feature_flag.key, "$feature_flag_response": "control"},
+ )
+ _create_event(
+ team=self.team,
+ event="signup",
+ distinct_id="user_after_exposure",
+ timestamp="2020-01-02T13:00:00Z",
+ )
+
+ flush_persons_and_events()
+
+ experiment_actors_query = ExperimentActorsQuery(
+ kind="ExperimentActorsQuery",
+ source=experiment_query,
+ funnelStep=-1,
+ funnelStepBreakdown="control",
+ includeRecordings=False,
+ )
+
+ actors_query = ActorsQuery(
+ source=experiment_actors_query,
+ select=["id", "person"],
+ )
+
+ response = ActorsQueryRunner(query=actors_query, team=self.team).calculate()
+
+ assert len(response.results) == 1
+ assert response.results[0][1]["distinct_ids"][0] == "user_before_exposure"
+
@parameterized.expand(
[
(