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): Reject ignored settings on exposure-start retention metrics (#104413)

Juraj Majerik04b9e4f57552
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index b2505d5bb909..5d45f862bfdd 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -24724,7 +24724,7 @@
},
"start_event": {
"$ref": "#/definitions/ExperimentApiRetentionStart",
- "description": "For retention metrics: start event. Pass {\"kind\": \"ExperimentExposureNode\"} to start retention from the experiment's exposure event; start_handling and conversion window are ignored then."
+ "description": "For retention metrics: start event. Pass {\"kind\": \"ExperimentExposureNode\"} to start retention from the experiment's exposure event; a conversion window or 'last_seen' start_handling is rejected then, because the start is always the user's first exposure."
},
"start_handling": {
"enum": ["first_seen", "last_seen"],
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index cfceedf11605..6575c74fd3c2 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -5655,7 +5655,8 @@ export interface ExperimentApiMetric {
* binomial-style denominator, which is never clamped. */
denominator_outlier_handling?: ExperimentMetricOutlierHandling
/** For retention metrics: start event. Pass {"kind": "ExperimentExposureNode"} to start retention
- * from the experiment's exposure event; start_handling and conversion window are ignored then. */
+ * from the experiment's exposure event; a conversion window or 'last_seen' start_handling is
+ * rejected then, because the start is always the user's first exposure. */
start_event?: ExperimentApiRetentionStart
/** For retention metrics: completion event. */
completion_event?: ExperimentApiEventSource
@@ -5855,7 +5856,7 @@ export type ExperimentRetentionMetric = ExperimentMetricBaseProperties & {
retention_window_end: integer
retention_window_unit: FunnelConversionWindowTimeUnit
- // How to handle the start of the retention window. Ignored for an
+ // How to handle the start of the retention window. Must be 'first_seen' for an
// ExperimentExposureNode start, which always anchors on the first exposure.
start_handling: 'first_seen' | 'last_seen'
}
diff --git a/frontend/src/scenes/experiments/ExperimentMetricForm.test.tsx b/frontend/src/scenes/experiments/ExperimentMetricForm.test.tsx
index 5a1534933a1a..50849f728980 100644
--- a/frontend/src/scenes/experiments/ExperimentMetricForm.test.tsx
+++ b/frontend/src/scenes/experiments/ExperimentMetricForm.test.tsx
@@ -95,7 +95,9 @@ describe('ExperimentMetricForm', () => {
retention_window_start: 1,
retention_window_end: 7,
retention_window_unit: FunnelConversionWindowTimeUnit.Day,
- start_handling: 'first_seen',
+ start_handling: 'last_seen',
+ conversion_window: 14,
+ conversion_window_unit: FunnelConversionWindowTimeUnit.Day,
}
const handleSetMetric = jest.fn()
@@ -107,10 +109,14 @@ describe('ExperimentMetricForm', () => {
expect(form.getByText('When users have multiple start events')).toBeInTheDocument()
expect(form.getByText('Conversion window limit')).toBeInTheDocument()
+ // switching to exposure clears the settings the backend rejects for an exposure start
await userEvent.click(form.getByText('Experiment exposure'))
expect(handleSetMetric).toHaveBeenCalledWith({
...metric,
start_event: { kind: NodeKind.ExperimentExposureNode },
+ start_handling: 'first_seen',
+ conversion_window: undefined,
+ conversion_window_unit: undefined,
})
const exposureMetric = handleSetMetric.mock.calls[0][0]
@@ -125,10 +131,14 @@ describe('ExperimentMetricForm', () => {
expect(form.queryByText('When users have multiple start events')).not.toBeInTheDocument()
expect(form.queryByText('Conversion window limit')).not.toBeInTheDocument()
+ // switching back restores the custom start event and its cleared settings
await userEvent.click(form.getByText('Custom event'))
expect(handleSetMetric).toHaveBeenLastCalledWith({
...exposureMetric,
start_event: startEvent,
+ start_handling: 'last_seen',
+ conversion_window: 14,
+ conversion_window_unit: FunnelConversionWindowTimeUnit.Day,
})
})
})
diff --git a/frontend/src/scenes/experiments/ExperimentMetricForm.tsx b/frontend/src/scenes/experiments/ExperimentMetricForm.tsx
index 79d9ac1c5fca..54498b369ea5 100644
--- a/frontend/src/scenes/experiments/ExperimentMetricForm.tsx
+++ b/frontend/src/scenes/experiments/ExperimentMetricForm.tsx
@@ -148,8 +148,13 @@ export function ExperimentMetricForm({
const allowedMathTypes = getAllowedMathTypes(metric.metric_type)
const [eventCount, setEventCount] = useState<number | null>(null)
const [isLoading, setIsLoading] = useState(false)
- // holds the literal start event while the exposure sentinel is selected, so switching back restores it
- const previousStartEvent = useRef<ExperimentMetricSource | null>(null)
+ // holds the custom start configuration while the exposure sentinel is selected, so switching back restores it
+ const previousRetentionStart = useRef<{
+ start_event: ExperimentMetricSource
+ start_handling: 'first_seen' | 'last_seen'
+ conversion_window?: number
+ conversion_window_unit?: FunnelConversionWindowTimeUnit
+ } | null>(null)
const getEventTypeLabel = (): string => {
if (isExperimentMeanMetric(metric)) {
@@ -508,21 +513,34 @@ export function ExperimentMetricForm({
onChange={(value) => {
if (value === 'exposure') {
if (!isExperimentExposureNode(metric.start_event)) {
- previousStartEvent.current = metric.start_event
+ previousRetentionStart.current = {
+ start_event: metric.start_event,
+ start_handling: metric.start_handling,
+ conversion_window: metric.conversion_window,
+ conversion_window_unit: metric.conversion_window_unit,
+ }
}
+ // the backend rejects a conversion window or 'last_seen' start handling on an exposure start
handleSetMetric({
...metric,
start_event: { kind: NodeKind.ExperimentExposureNode },
+ start_handling: 'first_seen',
+ conversion_window: undefined,
+ conversion_window_unit: undefined,
})
} else {
+ const previous = previousRetentionStart.current
handleSetMetric({
...metric,
- start_event: previousStartEvent.current ?? {
+ start_event: previous?.start_event ?? {
kind: NodeKind.EventsNode,
event: '$pageview',
name: '$pageview',
math: ExperimentMetricMathType.TotalCount,
},
+ start_handling: previous?.start_handling ?? 'first_seen',
+ conversion_window: previous?.conversion_window,
+ conversion_window_unit: previous?.conversion_window_unit,
})
}
}}
diff --git a/posthog/schema.py b/posthog/schema.py
index a2a52e01afd5..173fe6ce614b 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -17772,7 +17772,8 @@ class ExperimentApiMetric(BaseModel):
description=(
'For retention metrics: start event. Pass {"kind":'
' "ExperimentExposureNode"} to start retention from the experiment\'s'
- " exposure event; start_handling and conversion window are ignored then."
+ " exposure event; a conversion window or 'last_seen' start_handling is"
+ " rejected then, because the start is always the user's first exposure."
),
)
start_handling: StartHandling | None = None
diff --git a/products/experiments/backend/experiment_saved_metric_service.py b/products/experiments/backend/experiment_saved_metric_service.py
index aef93df76c47..7b03bf6b1668 100644
--- a/products/experiments/backend/experiment_saved_metric_service.py
+++ b/products/experiments/backend/experiment_saved_metric_service.py
@@ -20,6 +20,7 @@ from posthog.schema import (
from posthog.models.team.team import Team
+from products.experiments.backend.hogql_queries.retention_validation import retention_metric_error
from products.experiments.backend.models.experiment import (
LEGACY_METRIC_KINDS,
ExperimentSavedMetric,
@@ -62,7 +63,10 @@ class ExperimentSavedMetricService:
elif query["metric_type"] == ExperimentMetricType.RATIO:
ExperimentRatioMetric(**query)
elif query["metric_type"] == ExperimentMetricType.RETENTION:
- ExperimentRetentionMetric(**query)
+ retention_metric = ExperimentRetentionMetric(**query)
+ retention_error = retention_metric_error(retention_metric)
+ if retention_error:
+ raise ValidationError(retention_error)
else:
raise ValidationError(
"ExperimentMetric metric_type must be 'mean', 'funnel', 'ratio', or 'retention'"
diff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.py
index 8957e18e5ca3..35f12c82271a 100644
--- a/products/experiments/backend/experiment_service.py
+++ b/products/experiments/backend/experiment_service.py
@@ -29,6 +29,7 @@ from posthog.schema import (
ExperimentFunnelMetric,
ExperimentMeanMetric,
ExperimentMetric,
+ ExperimentRetentionMetric,
)
from posthog.hogql import ast
@@ -70,6 +71,7 @@ from products.experiments.backend.hogql_queries.exposure_query_logic import (
resolve_default_exposure_event,
)
from products.experiments.backend.hogql_queries.funnel_validation import FunnelDWValidator
+from products.experiments.backend.hogql_queries.retention_validation import retention_metric_error
from products.experiments.backend.metric_utils import filter_metric_group_ids_by_event
from products.experiments.backend.models.experiment import (
EXPOSURE_FROZEN_COHORT_KEY,
@@ -860,6 +862,10 @@ class ExperimentService:
f"Invalid metric at index {i}: a threshold cannot be combined with "
"outlier handling (winsorization)."
)
+ elif isinstance(actual_metric, ExperimentRetentionMetric):
+ retention_error = retention_metric_error(actual_metric)
+ if retention_error:
+ raise ValidationError(f"Invalid metric at index {i}: {retention_error}")
except pydantic.ValidationError as e:
# Surface only the field locations and error types from pydantic — not the
diff --git a/products/experiments/backend/hogql_queries/retention_validation.py b/products/experiments/backend/hogql_queries/retention_validation.py
new file mode 100644
index 000000000000..31d9c79a4cc1
--- /dev/null
+++ b/products/experiments/backend/hogql_queries/retention_validation.py
@@ -0,0 +1,27 @@
+"""Validation for experiment retention metric configurations."""
+
+from posthog.schema import ExperimentExposureNode, ExperimentRetentionMetric, StartHandling
+
+
+def retention_metric_error(metric: ExperimentRetentionMetric) -> str | None:
+ """Returns an error message when the retention metric configuration is invalid, else None.
+
+ The query engine ignores the conversion window and start handling for an
+ exposure-anchored start, so accepting them would store settings that never apply.
+ """
+ if not isinstance(metric.start_event, ExperimentExposureNode):
+ return None
+
+ if metric.conversion_window is not None or metric.conversion_window_unit is not None:
+ return (
+ "a conversion window cannot be combined with an experiment exposure start. "
+ "Retention already anchors on each user's first exposure."
+ )
+
+ if metric.start_handling == StartHandling.LAST_SEEN:
+ return (
+ "start_handling 'last_seen' cannot be combined with an experiment exposure start. "
+ "Retention always anchors on each user's first exposure."
+ )
+
+ return None
diff --git a/products/experiments/backend/test/test_experiment_saved_metric_service.py b/products/experiments/backend/test/test_experiment_saved_metric_service.py
index 9cb2fd2ded03..b7de86c90195 100644
--- a/products/experiments/backend/test/test_experiment_saved_metric_service.py
+++ b/products/experiments/backend/test/test_experiment_saved_metric_service.py
@@ -59,6 +59,22 @@ class TestExperimentSavedMetricService(APIBaseTest):
},
"ExperimentMetric metric_type must be 'mean', 'funnel', 'ratio', or 'retention'",
),
+ (
+ "conversion_window_on_exposure_start_retention",
+ {
+ "kind": "ExperimentMetric",
+ "metric_type": "retention",
+ "start_event": {"kind": "ExperimentExposureNode"},
+ "completion_event": {"kind": "EventsNode", "event": "purchase"},
+ "retention_window_start": 0,
+ "retention_window_end": 7,
+ "retention_window_unit": "day",
+ "start_handling": "first_seen",
+ "conversion_window": 14,
+ "conversion_window_unit": "day",
+ },
+ "a conversion window cannot be combined with an experiment exposure start",
+ ),
]
)
def test_create_saved_metric_validates_query(
diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.py
index b68c601bdf3f..c18f00d26788 100644
--- a/products/experiments/backend/test/test_experiment_service.py
+++ b/products/experiments/backend/test/test_experiment_service.py
@@ -1054,6 +1054,19 @@ class TestExperimentService(APIBaseTest):
"start_handling": "first_seen",
},
),
+ (
+ "valid_retention_exposure_start",
+ {
+ "kind": "ExperimentMetric",
+ "metric_type": "retention",
+ "start_event": {"kind": "ExperimentExposureNode"},
+ "completion_event": {"kind": "EventsNode", "event": "purchase"},
+ "retention_window_start": 0,
+ "retention_window_end": 7,
+ "retention_window_unit": "day",
+ "start_handling": "first_seen",
+ },
+ ),
]
)
def test_validate_experiment_metrics_accepts_valid_payloads(self, _: str, metric: dict) -> None:
@@ -1186,6 +1199,56 @@ class TestExperimentService(APIBaseTest):
)
assert "threshold" in str(ctx.exception), f"Expected 'threshold' in error: {ctx.exception}"
+ # ------------------------------------------------------------------
+ # validate_experiment_metrics — retention with an exposure start
+ # ------------------------------------------------------------------
+
+ @staticmethod
+ def _retention_metric(**overrides) -> dict:
+ return {
+ "kind": "ExperimentMetric",
+ "metric_type": "retention",
+ "start_event": {"kind": "ExperimentExposureNode"},
+ "completion_event": {"kind": "EventsNode", "event": "purchase"},
+ "retention_window_start": 0,
+ "retention_window_end": 7,
+ "retention_window_unit": "day",
+ "start_handling": "first_seen",
+ **overrides,
+ }
+
+ def test_validate_experiment_metrics_accepts_conversion_window_on_custom_start_retention(self) -> None:
+ ExperimentService.validate_experiment_metrics(
+ [
+ self._retention_metric(
+ start_event={"kind": "EventsNode", "event": "$pageview"},
+ start_handling="last_seen",
+ conversion_window=14,
+ conversion_window_unit="day",
+ )
+ ]
+ )
+
+ @parameterized.expand(
+ [
+ (
+ "conversion_window",
+ {"conversion_window": 14, "conversion_window_unit": "day"},
+ "conversion window",
+ ),
+ ("conversion_window_unit_only", {"conversion_window_unit": "day"}, "conversion window"),
+ ("last_seen_start_handling", {"start_handling": "last_seen"}, "last_seen"),
+ ]
+ )
+ def test_validate_experiment_metrics_rejects_ignored_settings_on_exposure_start(
+ self, _: str, overrides: dict, expected_fragment: str
+ ) -> None:
+ with self.assertRaises(ValidationError) as ctx:
+ ExperimentService.validate_experiment_metrics([self._retention_metric(**overrides)])
+ assert expected_fragment in str(ctx.exception), (
+ f"Expected fragment {expected_fragment!r} in error: {ctx.exception}"
+ )
+
# ------------------------------------------------------------------
# validate_experiment_metrics — improved pydantic error messages
# ------------------------------------------------------------------
diff --git a/products/experiments/frontend/generated/api.schemas.ts b/products/experiments/frontend/generated/api.schemas.ts
index a310a2913493..74371b6d57fc 100644
--- a/products/experiments/frontend/generated/api.schemas.ts
+++ b/products/experiments/frontend/generated/api.schemas.ts
@@ -1488,7 +1488,7 @@ export interface ExperimentApiMetricApi {
series?: ExperimentApiEventSourceApi[] | null
/** For mean metrics: event source. */
source?: ExperimentApiEventSourceApi | null
- /** For retention metrics: start event. Pass {"kind": "ExperimentExposureNode"} to start retention from the experiment's exposure event; start_handling and conversion window are ignored then. */
+ /** For retention metrics: start event. Pass {"kind": "ExperimentExposureNode"} to start retention from the experiment's exposure event; a conversion window or 'last_seen' start_handling is rejected then, because the start is always the user's first exposure. */
start_event?: ExperimentApiRetentionStartApi | null
start_handling?: StartHandlingApi | null
/** For mean metrics: when set, reports the percentage of users whose per-user summed/counted value reaches or exceeds this threshold. Only meaningful for sum/count math types. */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index ba7a60d8763c..3d1ad8f9ea4a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -38950,7 +38950,7 @@ export namespace Schemas {
series?: ExperimentApiEventSource[] | null;
/** For mean metrics: event source. */
source?: ExperimentApiEventSource | null;
- /** For retention metrics: start event. Pass {"kind": "ExperimentExposureNode"} to start retention from the experiment's exposure event; start_handling and conversion window are ignored then. */
+ /** For retention metrics: start event. Pass {"kind": "ExperimentExposureNode"} to start retention from the experiment's exposure event; a conversion window or 'last_seen' start_handling is rejected then, because the start is always the user's first exposure. */
start_event?: ExperimentApiRetentionStart | null;
start_handling?: StartHandling | null;
/** For mean metrics: when set, reports the percentage of users whose per-user summed/counted value reaches or exceeds this threshold. Only meaningful for sum/count math types. */
diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.ts
index 1026f265d5b9..c546e090162a 100644
--- a/services/mcp/src/generated/experiments/api.ts
+++ b/services/mcp/src/generated/experiments/api.ts
@@ -5606,7 +5606,7 @@ export const ExperimentsCreateBody = () => zod
])
.optional()
.describe(
- 'For retention metrics: start event. Pass {\"kind\": \"ExperimentExposureNode\"} to start retention from the experiment\'s exposure event; start_handling and conversion window are ignored then.'
+ 'For retention metrics: start event. Pass {\"kind\": \"ExperimentExposureNode\"} to start retention from the experiment\'s exposure event; a conversion window or \'last_seen\' start_handling is rejected then, because the start is always the user\'s first exposure.'
),
start_handling: zod.union([zod.enum(['first_seen', 'last_seen']), zod.null()]).optional(),
threshold: zod
@@ -6648,7 +6648,7 @@ export const ExperimentsCreateBody = () => zod
])
.optional()
.describe(
- 'For retention metrics: start event. Pass {\"kind\": \"ExperimentExposureNode\"} to start retention from the experiment\'s exposure event; start_handling and conversion window are ignored then.'
+ 'For retention metrics: start event. Pass {\"kind\": \"ExperimentExposureNode\"} to start retention from the experiment\'s exposure event; a conversion window or \'last_seen\' start_handling is rejected then, because the start is always the user\'s first exposure.'
),
start_handling: zod.union([zod.enum(['first_seen', 'last_seen']), zod.null()]).optional(),
threshold: zod
@@ -11569,7 +11569,7 @@ export const ExperimentsPartialUpdateBody = () => zod
])
.optional()
.describe(
- 'For retention metrics: start event. Pass {\"kind\": \"ExperimentExposureNode\"} to start retention from the experiment\'s exposure event; start_handling and conversion window are ignored then.'
+ 'For retention metrics: start event. Pass {\"kind\": \"ExperimentExposureNode\"} to start retention from the experiment\'s exposure event; a conversion window or \'last_seen\' start_handling is rejected then, because the start is always the user\'s first exposure.'
),
start_handling: zod.union([zod.enum(['first_seen', 'last_seen']), zod.null()]).optional(),
threshold: zod
@@ -12615,7 +12615,7 @@ export const ExperimentsPartialUpdateBody = () => zod
])
.optional()
.describe(
- 'For retention metrics: start event. Pass {\"kind\": \"ExperimentExposureNode\"} to start retention from the experiment\'s exposure event; start_handling and conversion window are ignored then.'
+ 'For retention metrics: start event. Pass {\"kind\": \"ExperimentExposureNode\"} to start retention from the experiment\'s exposure event; a conversion window or \'last_seen\' start_handling is rejected then, because the start is always the user\'s first exposure.'
),
start_handling: zod.union([zod.enum(['first_seen', 'last_seen']), zod.null()]).optional(),
threshold: zod
@@ -17511,7 +17511,7 @@ export const ExperimentsDuplicateCreateBody = () => zod
])
.optional()
.describe(
- 'For retention metrics: start event. Pass {\"kind\": \"ExperimentExposureNode\"} to start retention from the experiment\'s exposure event; start_handling and conversion window are ignored then.'
+ 'For retention metrics: start event. Pass {\"kind\": \"ExperimentExposureNode\"} to start retention from the experiment\'s exposure event; a conversion window or \'last_seen\' start_handling is rejected then, because the start is always the user\'s first exposure.'
),
start_handling: zod.union([zod.enum(['first_seen', 'last_seen']), zod.null()]).optional(),
threshold: zod
@@ -18557,7 +18557,7 @@ export const ExperimentsDuplicateCreateBody = () => zod
])
.optional()
.describe(
- 'For retention metrics: start event. Pass {\"kind\": \"ExperimentExposureNode\"} to start retention from the experiment\'s exposure event; start_handling and conversion window are ignored then.'
+ 'For retention metrics: start event. Pass {\"kind\": \"ExperimentExposureNode\"} to start retention from the experiment\'s exposure event; a conversion window or \'last_seen\' start_handling is rejected then, because the start is always the user\'s first exposure.'
),
start_handling: zod.union([zod.enum(['first_seen', 'last_seen']), zod.null()]).optional(),
threshold: zod
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json
index 644f1fdf9544..201d88683607 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json
@@ -7516,7 +7516,7 @@
"type": "null"
}
],
- "description": "For retention metrics: start event. Pass {\"kind\": \"ExperimentExposureNode\"} to start retention from the experiment's exposure event; start_handling and conversion window are ignored then."
+ "description": "For retention metrics: start event. Pass {\"kind\": \"ExperimentExposureNode\"} to start retention from the experiment's exposure event; a conversion window or 'last_seen' start_handling is rejected then, because the start is always the user's first exposure."
},
"start_handling": {
"anyOf": [
@@ -9214,7 +9214,7 @@
"type": "null"
}
],
- "description": "For retention metrics: start event. Pass {\"kind\": \"ExperimentExposureNode\"} to start retention from the experiment's exposure event; start_handling and conversion window are ignored then."
+ "description": "For retention metrics: start event. Pass {\"kind\": \"ExperimentExposureNode\"} to start retention from the experiment's exposure event; a conversion window or 'last_seen' start_handling is rejected then, because the start is always the user's first exposure."
},
"start_handling": {
"anyOf": [