: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(experiments): adds threshold support on mean metrics. (#63872)
Rodrigo Iloroa23dd358afa2
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex bf239c9b9927..c5dbba60eca6 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -18820,6 +18820,10 @@"enum": ["first_seen", "last_seen"],"type": "string"},+ "threshold": {+ "description": "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.",+ "type": "number"+ },"upper_bound_percentile": {"description": "For mean metrics: winsorization upper percentile bound, as a fraction in [0, 1] (e.g. 0.99 for the 99th percentile). Per-user values above this percentile are clamped to it before aggregation.","maximum": 1,@@ -19505,6 +19509,10 @@"source": {"$ref": "#/definitions/ExperimentMetricSource"},+ "threshold": {+ "description": "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.",+ "type": "number"+ },"upper_bound_percentile": {"description": "Winsorization upper percentile bound, as a fraction in [0, 1] (e.g. 0.99 for the 99th percentile).","maximum": 1,@@ -19541,6 +19549,10 @@"source": {"$ref": "#/definitions/ExperimentMetricSource"},+ "threshold": {+ "description": "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.",+ "type": "number"+ },"upper_bound_percentile": {"description": "Winsorization upper percentile bound, as a fraction in [0, 1] (e.g. 0.99 for the 99th percentile).","maximum": 1,diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 096bda7eeae1..86190566be5d 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -3869,6 +3869,9 @@ export interface ExperimentApiMetric {upper_bound_percentile?: number/** For mean metrics: exclude zero values when computing the winsorization percentile thresholds. */ignore_zeros?: boolean+ /** 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. */+ threshold?: number/** For ratio metrics: winsorization applied to the numerator aggregate, independently of the* denominator and each with its own percentile thresholds. */numerator_outlier_handling?: ExperimentMetricOutlierHandling@@ -4013,6 +4016,9 @@ export type ExperimentMeanMetric = ExperimentMetricBaseProperties &ExperimentMetricOutlierHandling & {metric_type: ExperimentMetricType.MEANsource: ExperimentMetricSource+ /** 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. */+ threshold?: number}export const isExperimentMeanMetric = (metric: ExperimentMetric): metric is ExperimentMeanMetric =>diff --git a/frontend/src/queries/validators.js b/frontend/src/queries/validators.jsindex fc17030bdd75..898ada2007a6 100644--- a/frontend/src/queries/validators.js+++ b/frontend/src/queries/validators.js@@ -5914,6 +5914,11 @@ const schema63 = {response: { type: 'object' },sharedMetricId: { type: 'number' },source: { $ref: '#/definitions/ExperimentMetricSource' },+ threshold: {+ description:+ '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.',+ type: 'number',+ },upper_bound_percentile: {description:'Winsorization upper percentile bound, as a fraction in [0, 1] (e.g. 0.99 for the 99th percentile).',@@ -10140,43 +10145,49 @@ function validate79(data, { instancePath = '', parentData, parentDataProperty, rvar valid0 = true}if (valid0) {- if (- data.upper_bound_percentile !==- undefined- ) {- let data14 = data.upper_bound_percentile+ if (data.threshold !== undefined) {+ let data14 = data.thresholdconst _errs31 = errors- if (errors === _errs31) {- if (+ if (+ !(typeof data14 == 'number' &&isFinite(data14)- ) {+ )+ ) {+ validate79.errors = [+ {+ instancePath:+ instancePath ++ '/threshold',+ schemaPath:+ '#/properties/threshold/type',+ keyword: 'type',+ params: { type: 'number' },+ message: 'must be number',+ },+ ]+ return false+ }+ var valid0 = _errs31 === errors+ } else {+ var valid0 = true+ }+ if (valid0) {+ if (+ data.upper_bound_percentile !==+ undefined+ ) {+ let data15 =+ data.upper_bound_percentile+ const _errs33 = errors+ if (errors === _errs33) {if (- data14 > 1 ||- isNaN(data14)+ typeof data15 == 'number' &&+ isFinite(data15)) {- validate79.errors = [- {- instancePath:- instancePath +- '/upper_bound_percentile',- schemaPath:- '#/properties/upper_bound_percentile/maximum',- keyword: 'maximum',- params: {- comparison:- '<=',- limit: 1,- },- message:- 'must be <= 1',- },- ]- return false- } else {if (- data14 < 0 ||- isNaN(data14)+ data15 > 1 ||+ isNaN(data15)) {validate79.errors = [{@@ -10184,93 +10195,89 @@ function validate79(data, { instancePath = '', parentData, parentDataProperty, rinstancePath +'/upper_bound_percentile',schemaPath:- '#/properties/upper_bound_percentile/minimum',+ '#/properties/upper_bound_percentile/maximum',keyword:- 'minimum',+ 'maximum',params: {comparison:- '>=',- limit: 0,+ '<=',+ limit: 1,},message:- 'must be >= 0',+ 'must be <= 1',},]return false+ } else {+ if (+ data15 < 0 ||+ isNaN(data15)+ ) {+ validate79.errors =+ [+ {+ instancePath:+ instancePath ++ '/upper_bound_percentile',+ schemaPath:+ '#/properties/upper_bound_percentile/minimum',+ keyword:+ 'minimum',+ params: {+ comparison:+ '>=',+ limit: 0,+ },+ message:+ 'must be >= 0',+ },+ ]+ return false+ }}- }- } else {- validate79.errors = [- {- instancePath:- instancePath +- '/upper_bound_percentile',- schemaPath:- '#/properties/upper_bound_percentile/type',- keyword: 'type',- params: {- type: 'number',- },- message:- 'must be number',- },- ]- return false- }- }- var valid0 = _errs31 === errors- } else {- var valid0 = true- }- if (valid0) {- if (data.uuid !== undefined) {- const _errs33 = errors- if (typeof data.uuid !== 'string') {- validate79.errors = [- {- instancePath:- instancePath +- '/uuid',- schemaPath:- '#/properties/uuid/type',- keyword: 'type',- params: {- type: 'string',+ } else {+ validate79.errors = [+ {+ instancePath:+ instancePath ++ '/upper_bound_percentile',+ schemaPath:+ '#/properties/upper_bound_percentile/type',+ keyword: 'type',+ params: {+ type: 'number',+ },+ message:+ 'must be number',},- message:- 'must be string',- },- ]- return false+ ]+ return false+ }}var valid0 = _errs33 === errors} else {var valid0 = true}if (valid0) {- if (data.version !== undefined) {- let data16 = data.version+ if (data.uuid !== undefined) {const _errs35 = errorsif (- !(- typeof data16 ==- 'number' &&- isFinite(data16)- )+ typeof data.uuid !==+ 'string') {validate79.errors = [{instancePath:instancePath +- '/version',+ '/uuid',schemaPath:- '#/properties/version/type',+ '#/properties/uuid/type',keyword: 'type',params: {- type: 'number',+ type: 'string',},message:- 'must be number',+ 'must be string',},]return false@@ -10279,6 +10286,42 @@ function validate79(data, { instancePath = '', parentData, parentDataProperty, r} else {var valid0 = true}+ if (valid0) {+ if (+ data.version !== undefined+ ) {+ let data17 = data.version+ const _errs37 = errors+ if (+ !(+ typeof data17 ==+ 'number' &&+ isFinite(data17)+ )+ ) {+ validate79.errors = [+ {+ instancePath:+ instancePath ++ '/version',+ schemaPath:+ '#/properties/version/type',+ keyword: 'type',+ params: {+ type: 'number',+ },+ message:+ 'must be number',+ },+ ]+ return false+ }+ var valid0 =+ _errs37 === errors+ } else {+ var valid0 = true+ }+ }}}}diff --git a/frontend/src/scenes/experiments/ExperimentMetricForm.tsx b/frontend/src/scenes/experiments/ExperimentMetricForm.tsxindex be5729e8b795..fc7e8e2a21b9 100644--- a/frontend/src/scenes/experiments/ExperimentMetricForm.tsx+++ b/frontend/src/scenes/experiments/ExperimentMetricForm.tsx@@ -41,6 +41,7 @@ import {ExperimentMetricOutlierHandling,ExperimentRatioMetricOutlierHandling,} from './ExperimentMetricOutlierHandling'+import { ExperimentMetricThreshold, isThresholdAvailableForMath } from './ExperimentMetricThreshold'import { filterToMetricConfig, filterToMetricSource } from './metricQueryUtils'import { createFilterForSource, getFilter } from './metricQueryUtils'import { commonActionFilterProps } from './Metrics/Selectors'@@ -155,10 +156,16 @@ export function ExperimentMetricForm({const handleSetFilters = ({ actions, events, data_warehouse }: Partial<FilterType>): void => {const metricConfig = filterToMetricConfig(metric.metric_type, actions, events, data_warehouse)if (metricConfig) {- handleSetMetric({- ...metric,- ...metricConfig,- })+ const updatedMetric = { ...metric, ...metricConfig }+ /**+ * Switching to a math type that doesn't support thresholds must clear any stale+ * threshold, otherwise the disabled threshold input traps the value and outlier+ * handling stays disabled with no way to recover.+ */+ if (isExperimentMeanMetric(updatedMetric) && !isThresholdAvailableForMath(updatedMetric.source.math)) {+ updatedMetric.threshold = undefined+ }+ handleSetMetric(updatedMetric)}}@@ -366,6 +373,25 @@ export function ExperimentMetricForm({</Link></div>)}+ <ExperimentMetricThreshold+ math={metric.source.math}+ value={metric.threshold}+ onChange={(value) =>+ handleSetMetric({+ ...metric,+ threshold: value,+ /**+ * Setting a threshold disables outlier handling, so clear any stale+ * bounds to keep the metric consistent with the UI and pass validation.+ */+ ...(value !== undefined && {+ lower_bound_percentile: undefined,+ upper_bound_percentile: undefined,+ ignore_zeros: undefined,+ }),+ })+ }+ /></>)}diff --git a/frontend/src/scenes/experiments/ExperimentMetricOutlierHandling.tsx b/frontend/src/scenes/experiments/ExperimentMetricOutlierHandling.tsxindex 02a514122d90..15a4af181b39 100644--- a/frontend/src/scenes/experiments/ExperimentMetricOutlierHandling.tsx+++ b/frontend/src/scenes/experiments/ExperimentMetricOutlierHandling.tsx@@ -11,20 +11,25 @@ import {ExperimentRatioMetric,} from '~/queries/schema/schema-general'+import { isMetricThresholdSet } from './ExperimentMetricThreshold'+const DESCRIPTION = 'Set winsorization lower and upper bounds to cap metric values at the specified percentiles.'function OutlierHandlingControls({value,onChange,+ disabled = false,}: {value: ExperimentMetricOutlierHandlingConfigonChange: (next: ExperimentMetricOutlierHandlingConfig) => void+ disabled?: boolean}): JSX.Element {return (<div className="flex flex-col gap-2"><div className="flex items-center gap-2"><LemonCheckboxlabel="Lower bound percentile"+ disabled={disabled}checked={value.lower_bound_percentile !== undefined}onChange={(checked) => onChange({ ...value, lower_bound_percentile: checked ? 0.05 : undefined })}/>@@ -46,6 +51,7 @@ function OutlierHandlingControls({<div className="flex items-center gap-2"><LemonCheckboxlabel="Upper bound percentile"+ disabled={disabled}checked={value.upper_bound_percentile !== undefined}onChange={(checked) => onChange({ ...value, upper_bound_percentile: checked ? 0.95 : undefined })}/>@@ -75,6 +81,7 @@ function OutlierHandlingControls({<span><LemonCheckboxlabel="Ignore zeros when calculating upper bound"+ disabled={disabled}checked={value.ignore_zeros ?? false}onChange={(checked) => onChange({ ...value, ignore_zeros: checked })}/>@@ -93,20 +100,37 @@ export function ExperimentMetricOutlierHandling({metric: ExperimentMeanMetrichandleSetMetric: (newMetric: ExperimentMetric) => void}): JSX.Element {+ /**+ * Winsorization caps continuous outliers, which is meaningless once a threshold+ * collapses the metric into a binary outcome.+ */+ const disabledByThreshold = isMetricThresholdSet(metric)+return (<SceneSectiontitle="Outlier handling"titleHelper={<>Prevent outliers from skewing results by capping the lower and upper bounds of a metric.</>}- description={<p className="text-muted text-xs -mb-1">{DESCRIPTION}</p>}+ description={+ <p className="text-muted text-xs -mb-1">+ {disabledByThreshold ? 'Not available when a threshold is set.' : DESCRIPTION}+ </p>+ }>- <OutlierHandlingControls- value={{- lower_bound_percentile: metric.lower_bound_percentile,- upper_bound_percentile: metric.upper_bound_percentile,- ignore_zeros: metric.ignore_zeros,- }}- onChange={(next) => handleSetMetric({ ...metric, ...next })}- />+ <Tooltip+ title={disabledByThreshold ? 'Outlier handling is not available when a threshold is set.' : undefined}+ >+ <div>+ <OutlierHandlingControls+ disabled={disabledByThreshold}+ value={{+ lower_bound_percentile: metric.lower_bound_percentile,+ upper_bound_percentile: metric.upper_bound_percentile,+ ignore_zeros: metric.ignore_zeros,+ }}+ onChange={(next) => handleSetMetric({ ...metric, ...next })}+ />+ </div>+ </Tooltip></SceneSection>)}diff --git a/frontend/src/scenes/experiments/ExperimentMetricThreshold.tsx b/frontend/src/scenes/experiments/ExperimentMetricThreshold.tsxnew file mode 100644index 000000000000..6e67aa9aa51b--- /dev/null+++ b/frontend/src/scenes/experiments/ExperimentMetricThreshold.tsx@@ -0,0 +1,75 @@+import { LemonInput } from '@posthog/lemon-ui'++import { LemonLabel } from 'lib/lemon-ui/LemonLabel'+import { Tooltip } from 'lib/lemon-ui/Tooltip'++import {+ ExperimentMeanMetric,+ ExperimentMetric,+ MathType,+ isExperimentMeanMetric,+} from '~/queries/schema/schema-general'+import { ExperimentMetricMathType } from '~/types'++/**+ * Threshold turns a per-user accumulated value into a binary outcome ("did this user reach N"),+ * so it only makes sense for math types that sum/count per user.+ */+const THRESHOLD_ENABLED_MATH_TYPES = new Set<MathType>([+ ExperimentMetricMathType.Sum,+ ExperimentMetricMathType.TotalCount,+])++export function isThresholdAvailableForMath(math: MathType | undefined): boolean {+ return math !== undefined && THRESHOLD_ENABLED_MATH_TYPES.has(math)+}++/** Whether the metric has a valid threshold applied, so the header should show a cue.+ * A 0 threshold is treated as unset (an always-true proportion is meaningless). */+export const isMetricThresholdSet = (metric: ExperimentMetric): boolean =>+ isExperimentMeanMetric(metric) && !!metric.threshold++export const isMetricThresholdCueVisible = (metric: ExperimentMetric): metric is ExperimentMeanMetric =>+ isExperimentMeanMetric(metric) && !!metric.threshold && isThresholdAvailableForMath(metric.source.math)++export interface ExperimentMetricThresholdProps {+ math: MathType | undefined+ value: number | undefined+ onChange: (value: number | undefined) => void+}++export function ExperimentMetricThreshold({ math, value, onChange }: ExperimentMetricThresholdProps): JSX.Element {+ const enabled = isThresholdAvailableForMath(math)++ return (+ <div className="mt-4">+ <LemonLabel+ info="Reports the percentage of exposed users whose per-user value reaches or exceeds this threshold. Only available for summed or counted metrics."+ className="mb-1"+ >+ Threshold+ </LemonLabel>+ <Tooltip title={enabled ? undefined : 'Thresholds are only available for summed or counted metrics'}>+ <LemonInput+ type="number"+ className="max-w-32"+ fullWidth={false}+ min={0}+ step={1}+ placeholder="e.g. 100"+ value={value}+ /**+ * Treat empty / cleared (0) / NaN as "no threshold" so dependent fields re-enable.+ */+ onChange={(newValue) => onChange(newValue ? newValue : undefined)}+ disabled={!enabled}+ />+ </Tooltip>+ <div className="text-muted text-xs mt-1">+ {enabled+ ? 'For example, reports the percentage of users who reach 100 total words across the experiment.'+ : 'Thresholds are only available for summed or counted metrics.'}+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx b/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsxindex f1cb446b4ca2..c1de1b9b9cd7 100644--- a/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx+++ b/frontend/src/scenes/experiments/MetricsView/shared/MetricHeader.tsx@@ -1,11 +1,12 @@import { useActions } from 'kea'import { useState } from 'react'-import { IconCopy, IconEllipsis, IconPencil, IconStack, IconTrash } from '@posthog/icons'-import { LemonButton, LemonDialog, LemonDropdown, LemonMenu, LemonTag } from '@posthog/lemon-ui'+import { IconCopy, IconEllipsis, IconPencil, IconStack, IconTarget, IconTrash } from '@posthog/icons'+import { LemonButton, LemonDialog, LemonDropdown, LemonMenu, LemonTag, Tooltip } from '@posthog/lemon-ui'import { TaxonomicFilter } from 'lib/components/TaxonomicFilter/TaxonomicFilter'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { isMetricThresholdCueVisible } from 'scenes/experiments/ExperimentMetricThreshold'import { METRIC_CONTEXTS, experimentMetricModalLogic } from 'scenes/experiments/Metrics/experimentMetricModalLogic'import { sharedMetricDetailsModalLogic } from 'scenes/experiments/Metrics/sharedMetricDetailsModalLogic'import { modalsLogic } from 'scenes/experiments/modalsLogic'@@ -279,10 +280,19 @@ export const MetricHeader = ({</div>)}</div>- <div className="deprecated-space-x-1">+ <div className="flex flex-wrap items-center gap-1"><LemonTag type="muted" size="small">{getMetricTag(metric)}</LemonTag>+ {isMetricThresholdCueVisible(metric) && (+ <Tooltip+ title={`Reports the percentage of users whose value reaches or exceeds ${metric.threshold}.`}+ >+ <LemonTag type="muted" size="small" icon={<IconTarget />}>+ ≥ {metric.threshold}+ </LemonTag>+ </Tooltip>+ )}{experiment.parameters?.prompt_metadata && (<LemonTag type="completion" size="small">LLMdiff --git a/frontend/src/scenes/experiments/MetricsView/shared/utils.test.ts b/frontend/src/scenes/experiments/MetricsView/shared/utils.test.tsindex 4b1fa43edbaa..f85efd50b9f7 100644--- a/frontend/src/scenes/experiments/MetricsView/shared/utils.test.ts+++ b/frontend/src/scenes/experiments/MetricsView/shared/utils.test.ts@@ -1,16 +1,18 @@import type { ExperimentFunnelsQuery, ExperimentMetric, ExperimentTrendsQuery } from '~/queries/schema/schema-general'import { ExperimentMetricType, NodeKind } from '~/queries/schema/schema-general'-import { ExperimentMetricGoal, ExperimentMetricMathType } from '~/types'+import { ExperimentMetricGoal, ExperimentMetricMathType, FunnelConversionWindowTimeUnit } from '~/types'import {type ExperimentVariantResult,formatChanceToWinForGoal,+ formatMetricValue,formatPValue,formatTickValue,getChanceToWin,getDefaultMetricTitle,getMetricColors,getMetricTag,+ isProportionMetric,isWinning,} from './utils'@@ -282,3 +284,73 @@ describe('formatTickValue', () => {expect(formatTickValue(input)).toBe(expected)})})++const meanMetric = (threshold?: number): ExperimentMetric => ({+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.MEAN,+ source: { kind: NodeKind.EventsNode, event: 'purchase', math: ExperimentMetricMathType.Sum },+ ...(threshold != null ? { threshold } : {}),+})++const funnelMetric: ExperimentMetric = {+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.FUNNEL,+ series: [{ kind: NodeKind.EventsNode, event: 'signup' }],+}++const retentionMetric: ExperimentMetric = {+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.RETENTION,+ start_event: { kind: NodeKind.EventsNode, event: 'signup' },+ completion_event: { kind: NodeKind.EventsNode, event: 'return' },+ retention_window_start: 0,+ retention_window_end: 7,+ retention_window_unit: FunnelConversionWindowTimeUnit.Day,+ start_handling: 'first_seen',+}++const ratioMetric: ExperimentMetric = {+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.RATIO,+ numerator: { kind: NodeKind.EventsNode, event: 'revenue' },+ denominator: { kind: NodeKind.EventsNode, event: 'sessions' },+}++describe('isProportionMetric', () => {+ const cases: { label: string; metric: ExperimentMetric; expected: boolean }[] = [+ { label: 'threshold mean', metric: meanMetric(5), expected: true },+ { label: 'plain mean', metric: meanMetric(), expected: false },+ { label: 'funnel', metric: funnelMetric, expected: true },+ { label: 'retention', metric: retentionMetric, expected: true },+ { label: 'ratio', metric: ratioMetric, expected: false },+ ]+ it.each(cases)('classifies $label metric', ({ metric, expected }) => {+ expect(isProportionMetric(metric)).toBe(expected)+ })+})++describe('formatMetricValue', () => {+ it('formats a plain mean metric as a raw number', () => {+ expect(formatMetricValue({ sum: 4, number_of_samples: 100 }, meanMetric())).toBe('0.04')+ })++ it('formats a threshold mean metric as a percentage', () => {+ expect(formatMetricValue({ sum: 40, number_of_samples: 100 }, meanMetric(5))).toBe('40.00%')+ })++ it('formats a funnel metric as a percentage', () => {+ expect(formatMetricValue({ sum: 25, number_of_samples: 100 }, funnelMetric)).toBe('25.00%')+ })++ it('formats a retention metric as a percentage', () => {+ expect(formatMetricValue({ sum: 60, number_of_samples: 100 }, retentionMetric)).toBe('60.00%')+ })++ it('formats a ratio metric as a quotient', () => {+ expect(formatMetricValue({ sum: 50, denominator_sum: 200 }, ratioMetric)).toBe('0.25')+ })++ it('returns "—" when the value is not a number', () => {+ expect(formatMetricValue({ sum: 0, number_of_samples: 0 }, meanMetric())).toBe('—')+ })+})diff --git a/frontend/src/scenes/experiments/MetricsView/shared/utils.ts b/frontend/src/scenes/experiments/MetricsView/shared/utils.tsindex d098ec0d0f7f..e394acd7b422 100644--- a/frontend/src/scenes/experiments/MetricsView/shared/utils.ts+++ b/frontend/src/scenes/experiments/MetricsView/shared/utils.ts@@ -16,8 +16,10 @@ import {ExperimentMetricType,ExperimentStatsValidationFailure,NodeKind,+ isExperimentFunnelMetric,isExperimentMeanMetric,isExperimentRatioMetric,+ isExperimentRetentionMetric,} from '~/queries/schema/schema-general'import { ExperimentMetricGoal } from '~/types'@@ -259,6 +261,18 @@ export function formatDeltaPercent(result: ExperimentVariantResult, decimals: nureturn `${deltaPercent > 0 ? '+' : ''}${formatted}%`}+/**+ * A proportion metric's value is a fraction of users in [0, 1] (conversion rate, retention rate, or+ * the share crossing a mean metric's threshold), so it reads as a percentage. A plain mean metric is+ * a raw average and a ratio metric is its own quotient, so neither is a proportion.+ */+export function isProportionMetric(metric: ExperimentMetric): boolean {+ if (isExperimentMeanMetric(metric)) {+ return metric.threshold != null+ }+ return isExperimentFunnelMetric(metric) || isExperimentRetentionMetric(metric)+}+export function formatMetricValue(data: any, metric: ExperimentMetric): string {if (isExperimentRatioMetric(metric)) {// For ratio metrics, we need to calculate the ratio from sum and denominator_sum@@ -273,9 +287,7 @@ export function formatMetricValue(data: any, metric: ExperimentMetric): string {if (isNaN(primaryValue)) {return '—'}- return isExperimentMeanMetric(metric)- ? humanFriendlyLargeNumber(primaryValue)- : `${(primaryValue * 100).toFixed(2)}%`+ return isProportionMetric(metric) ? `${(primaryValue * 100).toFixed(2)}%` : humanFriendlyLargeNumber(primaryValue)}export function getMetricSubtitleValues(diff --git a/posthog/schema.py b/posthog/schema.pyindex 2878cb1907fb..b88788410f31 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -4884,6 +4884,14 @@ class ExperimentApiMetric(BaseModel):default=None, description="For retention metrics: start event.")start_handling: StartHandling | None = None+ threshold: float | None = Field(+ default=None,+ description=(+ "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."+ ),+ )upper_bound_percentile: confloat(ge=0.0, le=1.0) | None = Field(default=None,description=(@@ -23911,6 +23919,14 @@ class ExperimentMeanMetric(BaseModel):response: dict[str, Any] | None = NonesharedMetricId: float | None = Nonesource: EventsNode | ActionsNode | ExperimentDataWarehouseNode = Field(..., discriminator="kind")+ threshold: float | None = Field(+ default=None,+ description=(+ "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."+ ),+ )upper_bound_percentile: confloat(ge=0.0, le=1.0) | None = Field(default=None,description=(@@ -23934,6 +23950,14 @@ class ExperimentMeanMetricTypeProps(BaseModel):)metric_type: Literal["mean"] = "mean"source: EventsNode | ActionsNode | ExperimentDataWarehouseNode = Field(..., discriminator="kind")+ threshold: float | None = Field(+ default=None,+ description=(+ "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."+ ),+ )upper_bound_percentile: confloat(ge=0.0, le=1.0) | None = Field(default=None,description=(diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 0864852fe804..465f1e245415 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -5185,6 +5185,8 @@ export interface ExperimentMeanMetricApi {response?: ExperimentMeanMetricApiResponsesharedMetricId?: number | nullsource: EventsNodeApi | ActionsNodeApi | ExperimentDataWarehouseNodeApi+ /** 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. */+ threshold?: number | null/** Winsorization upper percentile bound, as a fraction in [0, 1] (e.g. 0.99 for the 99th percentile). */upper_bound_percentile?: number | nulluuid?: string | nulldiff --git a/products/experiments/backend/experiment_service.py b/products/experiments/backend/experiment_service.pyindex 180c67c559ed..aa87a521b9b8 100644--- a/products/experiments/backend/experiment_service.py+++ b/products/experiments/backend/experiment_service.py@@ -18,7 +18,13 @@ import pydanticimport structlogfrom rest_framework.exceptions import ValidationError-from posthog.schema import ActionsNode, ExperimentEventExposureConfig, ExperimentFunnelMetric, ExperimentMetric+from posthog.schema import (+ ActionsNode,+ ExperimentEventExposureConfig,+ ExperimentFunnelMetric,+ ExperimentMeanMetric,+ ExperimentMetric,+)from posthog.api.cohort import CohortSerializerfrom posthog.event_usage import EventSource, report_user_action@@ -30,6 +36,7 @@ from posthog.utils import str_to_boolfrom products.actions.backend.models.action import Actionfrom products.cohorts.backend.models.cohort import Cohort+from products.experiments.backend.hogql_queries.base_query_utils import is_threshold_supported_mathfrom products.experiments.backend.hogql_queries.experiment_metric_fingerprint import compute_metric_fingerprintfrom products.experiments.backend.hogql_queries.funnel_validation import FunnelDWValidatorfrom products.experiments.backend.metric_utils import collect_metric_events_and_action_ids, resolve_action_events@@ -414,6 +421,29 @@ class ExperimentService:)# Additional validation for funnel metrics with DW stepsFunnelDWValidator.validate_funnel_metric(actual_metric)+ elif isinstance(actual_metric, ExperimentMeanMetric) and actual_metric.threshold is not None:+ # A threshold turns the per-user value into a binary "did the user reach N"+ # outcome, which only makes sense for sum/count math types.+ source_math = getattr(actual_metric.source, "math", None)+ if not is_threshold_supported_math(source_math):+ raise ValidationError(+ f"Invalid metric at index {i}: a threshold is only supported for "+ "sum or count (total) math types."+ )+ # A non-positive threshold is satisfied by every user (missing users+ # accumulate to 0), producing a meaningless 100% proportion.+ if actual_metric.threshold <= 0:+ raise ValidationError(f"Invalid metric at index {i}: threshold must be a positive number.")+ # Winsorization caps continuous outliers, which is meaningless once the+ # value collapses to a binary threshold outcome.+ if (+ actual_metric.lower_bound_percentile is not None+ or actual_metric.upper_bound_percentile is not None+ ):+ raise ValidationError(+ f"Invalid metric at index {i}: a threshold cannot be combined with "+ "outlier handling (winsorization)."+ )except pydantic.ValidationError as e:# Surface only the field locations and error types from pydantic — not thediff --git a/products/experiments/backend/hogql_queries/base_query_utils.py b/products/experiments/backend/hogql_queries/base_query_utils.pyindex 01ec4bb53c6b..9998635ae890 100644--- a/products/experiments/backend/hogql_queries/base_query_utils.py+++ b/products/experiments/backend/hogql_queries/base_query_utils.py@@ -104,6 +104,15 @@ def is_continuous(return False+def is_threshold_supported_math(math_type: ExperimentMetricMathType | None) -> bool:+ """Whether a per-user value can be meaningfully compared to a threshold.++ Only sum/count produce a per-user accumulation where "did the user reach N"+ turns cleanly into a binary outcome.+ """+ return math_type in [ExperimentMetricMathType.SUM, ExperimentMetricMathType.TOTAL]++def get_source_value_expr(source: Union[EventsNode, ActionsNode, ExperimentDataWarehouseNode]) -> ast.Expr:"""Returns the expression for extracting values from a given source (EventsNode, ActionsNode, or DataWarehouseNode).diff --git a/products/experiments/backend/hogql_queries/cuped_config.py b/products/experiments/backend/hogql_queries/cuped_config.pyindex 8e1c7481727c..09e22dd5a6ce 100644--- a/products/experiments/backend/hogql_queries/cuped_config.py+++ b/products/experiments/backend/hogql_queries/cuped_config.py@@ -49,6 +49,10 @@ def _resolve_lookback_days(experiment_value: Any, team_default: Any) -> int:def _metric_supports_cuped(metric: object) -> bool:if isinstance(metric, ExperimentMeanMetric):+ # A thresholded mean is a binary "did the user reach N" outcome; CUPED's+ # continuous variance reduction does not apply to a proportion.+ if metric.threshold is not None:+ return False# Session property metrics use a separate session-deduplication CTE pipeline.# Keep CUPED disabled there until the same single-scan windowing is implemented.if isinstance(metric.source, (ActionsNode, EventsNode)) and is_session_property_metric(metric.source):diff --git a/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py b/products/experiments/backend/hogql_queries/experiment_mean_query_builder.pyindex 29c4e33beea3..ab858d337b85 100644--- a/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py+++ b/products/experiments/backend/hogql_queries/experiment_mean_query_builder.py@@ -269,6 +269,21 @@ class MeanQueryBuilder:else "")+ # When a threshold is set, each user's value collapses to a binary "reached the+ # threshold" outcome, turning the mean into a proportion. total_sum becomes the+ # count of users who crossed; sum_of_squares equals it since 1^2 = 1 and 0^2 = 0.+ if self._b.metric.threshold is not None:+ per_user_value = "if(entity_metrics.value >= {threshold}, 1, 0)"+ total_sum_expr = f"sum({per_user_value})"+ total_sum_squares_expr = total_sum_expr+ else:+ total_sum_expr = "sum(entity_metrics.value)"+ total_sum_squares_expr = "sum(power(entity_metrics.value, 2))"++ placeholders = self.get_mean_query_common_placeholders()+ if self._b.metric.threshold is not None:+ placeholders["threshold"] = ast.Constant(value=self._b.metric.threshold)+query = parse_select(f"""WITH {common_ctes}@@ -276,14 +291,14 @@ class MeanQueryBuilder:SELECTentity_metrics.variant AS variant,count(entity_metrics.entity_id) AS num_users,- sum(entity_metrics.value) AS total_sum,- sum(power(entity_metrics.value, 2)) AS total_sum_of_squares{cuped_selects}+ {total_sum_expr} AS total_sum,+ {total_sum_squares_expr} AS total_sum_of_squares{cuped_selects}-- breakdown columns added programmatically belowFROM entity_metricsGROUP BY entity_metrics.variant-- breakdown columns added programmatically below""",- placeholders=self.get_mean_query_common_placeholders(),+ placeholders=placeholders,)assert isinstance(query, ast.SelectQuery)diff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambrindex d8ae93e520ec..b45db2d263b7 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/__snapshots__/test_mean_metric.ambr@@ -1617,6 +1617,134 @@use_hive_partitioning=0'''# ---+# name: TestExperimentMeanMetric.test_threshold_sum_metric_counts_users_crossing_0_direct+ '''+ 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 tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)+ LEFT JOIN+ (SELECT person.id AS id,+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email+ FROM person+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),+ (SELECT person.id AS id, max(person.version) AS version+ FROM person+ WHERE equals(person.team_id, 99999)+ GROUP BY person.id+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS events__person ON equals(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id), events__person.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)), ifNull(notILike(toString(events__person.properties___email), '%@posthog.com%'), 1), 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,+ coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'amount'), ''), 'null'), '^"|"$', ''), 'Float64'), 0) AS value+ FROM events+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 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'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, 'purchase'))),+ entity_metrics AS+ (SELECT exposures.entity_id AS entity_id,+ exposures.variant AS variant,+ sum(coalesce(accurateCastOrNull(metric_events.value, 'Float64'), 0)) AS value+ FROM exposures+ LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')))+ GROUP BY exposures.entity_id,+ exposures.variant)+ SELECT entity_metrics.variant AS variant,+ count(entity_metrics.entity_id) AS num_users,+ sum(if(ifNull(greaterOrEquals(entity_metrics.value, 100.0), 0), 1, 0)) AS total_sum,+ sum(if(ifNull(greaterOrEquals(entity_metrics.value, 100.0), 0), 1, 0)) AS total_sum_of_squares+ FROM entity_metrics+ GROUP BY entity_metrics.variant+ LIMIT 50000 SETTINGS join_algorithm='grace_hash',+ grace_hash_join_initial_buckets=2,+ readonly=2,+ max_execution_time=600,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=39728447488,+ 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: TestExperimentMeanMetric.test_threshold_sum_metric_counts_users_crossing_1_precomputed+ '''+ WITH exposures AS+ (SELECT accurateCastOrNull(t.entity_id, 'UUID') AS entity_id,+ if(greater(uniqExact(t.variant), 1), '$multiple', argMin(t.variant, toTimeZone(t.first_exposure_time, 'UTC'))) AS variant,+ min(toTimeZone(t.first_exposure_time, 'UTC')) AS first_exposure_time,+ max(toTimeZone(t.last_exposure_time, 'UTC')) AS last_exposure_time,+ argMin(t.exposure_event_uuid, toTimeZone(t.first_exposure_time, 'UTC')) AS exposure_event_uuid,+ argMin(t.exposure_session_id, toTimeZone(t.first_exposure_time, 'UTC')) AS exposure_session_id+ FROM experiment_exposures_preaggregated AS t+ WHERE and(equals(t.team_id, 99999), in(t.job_id, ['00000000-0000-0000-0000-000000000000']), equals(t.team_id, 99999), greaterOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-01 00:00:00', 'UTC'))), lessOrEquals(t.first_exposure_time, assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC'))))+ 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,+ coalesce(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'amount'), ''), 'null'), '^"|"$', ''), 'Float64'), 0) AS value+ FROM events+ LEFT OUTER JOIN+ (SELECT tupleElement(argMax(tuple(person_distinct_id_overrides.person_id), person_distinct_id_overrides.version), 1) 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(tupleElement(argMax(tuple(person_distinct_id_overrides.is_deleted), person_distinct_id_overrides.version), 1), 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 00:00:00', 'UTC'))), less(events.timestamp, plus(assumeNotNull(toDateTime('2020-01-15 12:00:00', 'UTC')), toIntervalSecond(0))), equals(events.event, 'purchase'))),+ entity_metrics AS+ (SELECT exposures.entity_id AS entity_id,+ exposures.variant AS variant,+ sum(coalesce(accurateCastOrNull(metric_events.value, 'Float64'), 0)) AS value+ FROM exposures+ LEFT JOIN metric_events ON and(equals(exposures.entity_id, metric_events.entity_id), greaterOrEquals(toTimeZone(metric_events.timestamp, 'UTC'), toTimeZone(exposures.first_exposure_time, 'UTC')))+ GROUP BY exposures.entity_id,+ exposures.variant)+ SELECT entity_metrics.variant AS variant,+ count(entity_metrics.entity_id) AS num_users,+ sum(if(ifNull(greaterOrEquals(entity_metrics.value, 100.0), 0), 1, 0)) AS total_sum,+ sum(if(ifNull(greaterOrEquals(entity_metrics.value, 100.0), 0), 1, 0)) AS total_sum_of_squares+ FROM entity_metrics+ GROUP BY entity_metrics.variant+ LIMIT 50000 SETTINGS join_algorithm='grace_hash',+ grace_hash_join_initial_buckets=2,+ load_balancing='in_order',+ readonly=2,+ max_execution_time=600,+ allow_experimental_object_type=1,+ max_ast_elements=4000000,+ max_expanded_ast_elements=4000000,+ max_bytes_before_external_group_by=39728447488,+ 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: TestExperimentMeanMetric.test_unique_sessions_math_type_0_direct'''WITH exposures ASdiff --git a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_mean_metric.py b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_mean_metric.pyindex 61f9dc3935fd..40560c256719 100644--- a/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_mean_metric.py+++ b/products/experiments/backend/hogql_queries/test/experiment_query_runner/test_mean_metric.py@@ -1,3 +1,4 @@+from collections.abc import Sequencefrom datetime import datetimefrom typing import cast@@ -1287,3 +1288,165 @@ class TestExperimentMeanMetric(ExperimentQueryRunnerBaseTest):self.assertEqual(len(result.variant_results), 1)self.assertEqual(result.baseline.number_of_samples, 10)self.assertEqual(result.variant_results[0].number_of_samples, 10)++ def _create_threshold_users(+ self,+ feature_flag,+ variant: str,+ per_user_purchases: Sequence[Sequence[float]],+ ) -> None:+ """Create one user per entry in per_user_purchases, each making the listed purchase amounts."""+ feature_flag_property = f"$feature/{feature_flag.key}"+ for i, amounts in enumerate(per_user_purchases):+ distinct_id = f"user_{variant}_{i}"+ _create_person(distinct_ids=[distinct_id], team_id=self.team.pk)+ _create_event(+ team=self.team,+ event="$feature_flag_called",+ distinct_id=distinct_id,+ timestamp="2020-01-02T12:00:00Z",+ properties={+ feature_flag_property: variant,+ "$feature_flag_response": variant,+ "$feature_flag": feature_flag.key,+ },+ )+ for amount in amounts:+ _create_event(+ team=self.team,+ event="purchase",+ distinct_id=distinct_id,+ timestamp="2020-01-02T12:01:00Z",+ properties={feature_flag_property: variant, "amount": amount},+ )++ @parameterized.expand(+ [+ ("direct", False),+ ("precomputed", True),+ ]+ )+ @freeze_time("2020-01-01T12:00:00Z")+ @snapshot_clickhouse_queries+ def test_threshold_sum_metric_counts_users_crossing(self, name, use_precomputation):+ self._setup_precomputation_test(use_precomputation)++ feature_flag = self.create_feature_flag()+ experiment = self.create_experiment(feature_flag=feature_flag)++ metric = ExperimentMeanMetric(+ source=EventsNode(+ event="purchase",+ math=ExperimentMetricMathType.SUM,+ math_property="amount",+ ),+ threshold=100,+ )++ experiment_query = ExperimentQuery(+ experiment_id=experiment.id,+ kind="ExperimentQuery",+ metric=metric,+ )++ experiment.metrics = [metric.model_dump(mode="json")]+ self._save_experiment_with_precomputation(experiment, use_precomputation)++ # Control: 4 users cross (sum 120), 6 do not (sum 50)+ self._create_threshold_users(+ feature_flag,+ "control",+ [[60, 60]] * 4 + [[50]] * 6,+ )+ # Test: 7 users cross (sum 120), 3 do not (sum 50)+ self._create_threshold_users(+ feature_flag,+ "test",+ [[60, 60]] * 7 + [[50]] * 3,+ )++ flush_persons_and_events()++ query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)+ result = cast(ExperimentQueryResponse, query_runner.calculate())++ assert result.baseline is not None+ assert result.variant_results is not None+ self.assertEqual(len(result.variant_results), 1)++ control_variant = result.baseline+ test_variant = result.variant_results[0]++ # sum becomes the count of users whose per-user sum reached the threshold+ self.assertEqual(control_variant.sum, 4)+ self.assertEqual(test_variant.sum, 7)+ self.assertEqual(control_variant.number_of_samples, 10)+ self.assertEqual(test_variant.number_of_samples, 10)++ @freeze_time("2020-01-01T12:00:00Z")+ def test_threshold_is_inclusive_and_zero_for_users_without_events(self):+ """A user whose sum exactly equals the threshold crosses; a user with no events does not."""+ feature_flag = self.create_feature_flag()+ experiment = self.create_experiment(feature_flag=feature_flag)++ metric = ExperimentMeanMetric(+ source=EventsNode(+ event="purchase",+ math=ExperimentMetricMathType.SUM,+ math_property="amount",+ ),+ threshold=100,+ )++ experiment_query = ExperimentQuery(experiment_id=experiment.id, kind="ExperimentQuery", metric=metric)+ experiment.metrics = [metric.model_dump(mode="json")]+ experiment.save()++ # Control: 1 user exactly at threshold (crosses), 1 user with no purchases (does not cross)+ self._create_threshold_users(feature_flag, "control", [[100], []])+ # Test: 1 user just below threshold (does not cross), 1 user above (crosses)+ self._create_threshold_users(feature_flag, "test", [[99], [101]])++ flush_persons_and_events()++ query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)+ result = cast(ExperimentQueryResponse, query_runner.calculate())++ assert result.baseline is not None+ assert result.variant_results is not None++ self.assertEqual(result.baseline.sum, 1)+ self.assertEqual(result.baseline.number_of_samples, 2)+ self.assertEqual(result.variant_results[0].sum, 1)+ self.assertEqual(result.variant_results[0].number_of_samples, 2)++ @freeze_time("2020-01-01T12:00:00Z")+ def test_threshold_count_metric_counts_users_with_enough_events(self):+ """With TOTAL math the per-user value is the event count; threshold compares against it."""+ feature_flag = self.create_feature_flag()+ experiment = self.create_experiment(feature_flag=feature_flag)++ metric = ExperimentMeanMetric(+ source=EventsNode(event="purchase", math=ExperimentMetricMathType.TOTAL),+ threshold=3,+ )++ experiment_query = ExperimentQuery(experiment_id=experiment.id, kind="ExperimentQuery", metric=metric)+ experiment.metrics = [metric.model_dump(mode="json")]+ experiment.save()++ # Control: 1 user with 3 purchases (crosses), 1 user with 2 (does not)+ self._create_threshold_users(feature_flag, "control", [[1, 1, 1], [1, 1]])+ # Test: 2 users with 5 purchases each (both cross)+ self._create_threshold_users(feature_flag, "test", [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1]])++ flush_persons_and_events()++ query_runner = ExperimentQueryRunner(query=experiment_query, team=self.team)+ result = cast(ExperimentQueryResponse, query_runner.calculate())++ assert result.baseline is not None+ assert result.variant_results is not None++ self.assertEqual(result.baseline.sum, 1)+ self.assertEqual(result.variant_results[0].sum, 2)diff --git a/products/experiments/backend/hogql_queries/test/test_cuped_config.py b/products/experiments/backend/hogql_queries/test/test_cuped_config.pyindex d239b8568b09..87805ddc7a73 100644--- a/products/experiments/backend/hogql_queries/test/test_cuped_config.py+++ b/products/experiments/backend/hogql_queries/test/test_cuped_config.py@@ -53,6 +53,22 @@ def test_get_cuped_config_team_default_ignored_when_metric_unsupported():assert config.enabled is False+def _threshold_metric() -> ExperimentMeanMetric:+ return ExperimentMeanMetric(source=EventsNode(event="purchase", math="sum", math_property="amount"), threshold=100)+++ [+ ("experiment_explicit_true", {"cuped": {"enabled": True}}, False),+ ("team_default_enabled", None, True),+ ]+)+def test_get_cuped_config_disabled_for_threshold_metric(name, stats_config, team_default_enabled):+ # A thresholded mean is a binary outcome; CUPED variance reduction does not apply.+ config = get_cuped_config(stats_config, _threshold_metric(), team_default_enabled=team_default_enabled)+ assert config.enabled is False++@parameterized.expand([# (name, stats_config, team_default_lookback_days, expected_lookback_days)diff --git a/products/experiments/backend/hogql_queries/test/test_experiment_utils.py b/products/experiments/backend/hogql_queries/test/test_experiment_utils.pyindex 05b087cf8537..a38b7251f02d 100644--- a/products/experiments/backend/hogql_queries/test/test_experiment_utils.py+++ b/products/experiments/backend/hogql_queries/test/test_experiment_utils.py@@ -12,6 +12,7 @@ from posthog.schema import (ExperimentRatioMetric,ExperimentRetentionMetric,ExperimentStatsBase,+ ExperimentStatsBaseValidated,ExperimentStatsValidationFailure,FunnelConversionWindowTimeUnit,StartHandling,@@ -24,8 +25,10 @@ from products.experiments.backend.hogql_queries.utils import (get_experiment_query_debug,get_variant_result,get_variant_results,+ metric_variant_to_statistic,validate_variant_result,)+from products.experiments.stats.shared.statistics import ProportionStatistic, SampleMeanStatisticdef _columns_for(@@ -1136,3 +1139,39 @@ class TestGetExperimentQueryDebug:assert "SECRETKEY123" not in clickhouse_sqlassert "SECRETTOKEN456" not in clickhouse_sqlassert clickhouse_sql.count("[HIDDEN]") == 2+++class TestMetricVariantToStatistic:+ def _validated(self, *, n: int = 10, sum: float = 4, sum_squares: float = 4) -> ExperimentStatsBaseValidated:+ return ExperimentStatsBaseValidated(key="test", number_of_samples=n, sum=sum, sum_squares=sum_squares)++ def test_mean_without_threshold_maps_to_sample_mean(self) -> None:+ metric = ExperimentMeanMetric(+ source=EventsNode(event="purchase", math=ExperimentMetricMathType.SUM, math_property="amount"),+ )+ stat = metric_variant_to_statistic(metric, self._validated(sum=60, sum_squares=400))+ assert isinstance(stat, SampleMeanStatistic)+ assert stat.sum == 60+ assert stat.sum_squares == 400++ def test_mean_with_threshold_maps_to_proportion(self) -> None:+ metric = ExperimentMeanMetric(+ source=EventsNode(event="purchase", math=ExperimentMetricMathType.SUM, math_property="amount"),+ threshold=100,+ )+ stat = metric_variant_to_statistic(metric, self._validated(n=10, sum=4))+ assert isinstance(stat, ProportionStatistic)+ # sum is the count of users who crossed the threshold+ assert stat.n == 10+ assert stat.sum == 4++ def test_threshold_proportion_coerces_sum_to_int(self) -> None:+ """ClickHouse may return total_sum as a float; ProportionStatistic.sum must be an int count."""+ metric = ExperimentMeanMetric(+ source=EventsNode(event="purchase", math=ExperimentMetricMathType.SUM, math_property="amount"),+ threshold=100,+ )+ stat = metric_variant_to_statistic(metric, self._validated(n=10, sum=4.0))+ assert isinstance(stat, ProportionStatistic)+ assert isinstance(stat.sum, int)+ assert stat.sum == 4diff --git a/products/experiments/backend/hogql_queries/utils.py b/products/experiments/backend/hogql_queries/utils.pyindex 78c16bae514f..a822b163ff48 100644--- a/products/experiments/backend/hogql_queries/utils.py+++ b/products/experiments/backend/hogql_queries/utils.py@@ -325,6 +325,14 @@ def metric_variant_to_statistic(variant: ExperimentStatsBaseValidated,) -> SampleMeanStatistic | ProportionStatistic | RatioStatistic:if isinstance(metric, ExperimentMeanMetric):+ # A thresholded mean is a binary "did the user reach N" outcome, so it must be+ # analyzed as a proportion (Bernoulli), not a continuous mean (Gaussian).+ # The query builder emits total_sum as the count of users who crossed.+ if metric.threshold is not None:+ return ProportionStatistic(+ n=variant.number_of_samples,+ sum=int(variant.sum),+ )return SampleMeanStatistic(n=variant.number_of_samples,sum=variant.sum,diff --git a/products/experiments/backend/test/test_experiment_service.py b/products/experiments/backend/test/test_experiment_service.pyindex ba99d3c8c16f..1344b6db0799 100644--- a/products/experiments/backend/test/test_experiment_service.py+++ b/products/experiments/backend/test/test_experiment_service.py@@ -652,6 +652,103 @@ class TestExperimentService(APIBaseTest):f"Expected fragment {expected_fragment!r} in error: {ctx.exception}")+ # ------------------------------------------------------------------+ # validate_experiment_metrics — threshold / math-type compatibility+ # ------------------------------------------------------------------++ @parameterized.expand(+ [+ ("threshold_on_sum", "sum"),+ ("threshold_on_total_count", "total"),+ ]+ )+ def test_validate_experiment_metrics_accepts_threshold_on_summed_math(self, _: str, math: str) -> None:+ ExperimentService.validate_experiment_metrics(+ [+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "EventsNode", "event": "$pageview", "math": math, "math_property": "amount"},+ "threshold": 100,+ }+ ]+ )++ @parameterized.expand(+ [+ ("threshold_on_unique_session", "unique_session"),+ ("threshold_on_dau", "dau"),+ ("threshold_on_hogql", "hogql"),+ ]+ )+ def test_validate_experiment_metrics_rejects_threshold_on_unsupported_math(self, _: str, math: str) -> None:+ with self.assertRaises(ValidationError) as ctx:+ ExperimentService.validate_experiment_metrics(+ [+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {"kind": "EventsNode", "event": "$pageview", "math": math},+ "threshold": 100,+ }+ ]+ )+ assert "threshold" in str(ctx.exception), f"Expected 'threshold' in error: {ctx.exception}"++ @parameterized.expand(+ [+ ("zero", 0),+ ("negative", -5),+ ]+ )+ def test_validate_experiment_metrics_rejects_non_positive_threshold(self, _: str, threshold: int) -> None:+ # A non-positive threshold is always satisfied, yielding a meaningless 100% proportion.+ with self.assertRaises(ValidationError) as ctx:+ ExperimentService.validate_experiment_metrics(+ [+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {+ "kind": "EventsNode",+ "event": "$pageview",+ "math": "sum",+ "math_property": "amount",+ },+ "threshold": threshold,+ }+ ]+ )+ assert "threshold" in str(ctx.exception), f"Expected 'threshold' in error: {ctx.exception}"++ @parameterized.expand(+ [+ ("lower_bound", {"lower_bound_percentile": 0.01}),+ ("upper_bound", {"upper_bound_percentile": 0.99}),+ ]+ )+ def test_validate_experiment_metrics_rejects_threshold_with_winsorization(self, _: str, bounds: dict) -> None:+ # Winsorization caps continuous outliers, which is meaningless once the metric+ # collapses to a binary threshold outcome — reject the combination.+ with self.assertRaises(ValidationError) as ctx:+ ExperimentService.validate_experiment_metrics(+ [+ {+ "kind": "ExperimentMetric",+ "metric_type": "mean",+ "source": {+ "kind": "EventsNode",+ "event": "$pageview",+ "math": "sum",+ "math_property": "amount",+ },+ "threshold": 100,+ **bounds,+ }+ ]+ )+ assert "threshold" in str(ctx.exception), f"Expected 'threshold' 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.tsindex 0c1a531cee15..c4eb6562c437 100644--- a/products/experiments/frontend/generated/api.schemas.ts+++ b/products/experiments/frontend/generated/api.schemas.ts@@ -500,6 +500,8 @@ export interface ExperimentApiMetricApi {/** For retention metrics: start event. */start_event?: ExperimentApiEventSourceApi | nullstart_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. */+ threshold?: number | null/** For mean metrics: winsorization upper percentile bound, as a fraction in [0, 1] (e.g. 0.99 for the 99th percentile). Per-user values above this percentile are clamped to it before aggregation. */upper_bound_percentile?: number | null/** Unique identifier. Auto-generated if omitted. */diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 7e8e5cfc1209..2839d5015977 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -4635,6 +4635,8 @@ export interface ExperimentMeanMetricApi {response?: ExperimentMeanMetricApiResponsesharedMetricId?: number | nullsource: EventsNodeApi | ActionsNodeApi | ExperimentDataWarehouseNodeApi+ /** 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. */+ threshold?: number | null/** Winsorization upper percentile bound, as a fraction in [0, 1] (e.g. 0.99 for the 99th percentile). */upper_bound_percentile?: number | nulluuid?: string | nulldiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d4df0eea2357..050c338ae4b9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -3515,6 +3515,8 @@ export namespace Schemas {response?: ExperimentMeanMetricResponse;sharedMetricId?: number | null;source: EventsNode | ActionsNode | ExperimentDataWarehouseNode;+ /** 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. */+ threshold?: number | null;/** Winsorization upper percentile bound, as a fraction in [0, 1] (e.g. 0.99 for the 99th percentile). */upper_bound_percentile?: number | null;uuid?: string | null;@@ -20081,6 +20083,8 @@ export namespace Schemas {/** For retention metrics: start event. */start_event?: ExperimentApiEventSource | 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. */+ threshold?: number | null;/** For mean metrics: winsorization upper percentile bound, as a fraction in [0, 1] (e.g. 0.99 for the 99th percentile). Per-user values above this percentile are clamped to it before aggregation. */upper_bound_percentile?: number | null;/** Unique identifier. Auto-generated if omitted. */diff --git a/services/mcp/src/generated/experiments/api.ts b/services/mcp/src/generated/experiments/api.tsindex 5fd01ba2b72c..000ba49c3b72 100644--- a/services/mcp/src/generated/experiments/api.ts+++ b/services/mcp/src/generated/experiments/api.ts@@ -1452,6 +1452,12 @@ export const ExperimentsCreateBody = /* @__PURE__ */ zod.optional().describe('For retention metrics: start event.'),start_handling: zod.union([zod.enum(['first_seen', 'last_seen']), zod.null()]).optional(),+ threshold: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ '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.'+ ),upper_bound_percentile: zod.union([zod@@ -2444,6 +2450,12 @@ export const ExperimentsCreateBody = /* @__PURE__ */ zod.optional().describe('For retention metrics: start event.'),start_handling: zod.union([zod.enum(['first_seen', 'last_seen']), zod.null()]).optional(),+ threshold: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ '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.'+ ),upper_bound_percentile: zod.union([zod@@ -3805,6 +3817,12 @@ export const ExperimentsPartialUpdateBody = /* @__PURE__ */ zod.optional().describe('For retention metrics: start event.'),start_handling: zod.union([zod.enum(['first_seen', 'last_seen']), zod.null()]).optional(),+ threshold: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ '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.'+ ),upper_bound_percentile: zod.union([zod@@ -4801,6 +4819,12 @@ export const ExperimentsPartialUpdateBody = /* @__PURE__ */ zod.optional().describe('For retention metrics: start event.'),start_handling: zod.union([zod.enum(['first_seen', 'last_seen']), zod.null()]).optional(),+ threshold: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ '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.'+ ),upper_bound_percentile: zod.union([zod@@ -6210,6 +6234,12 @@ export const ExperimentsDuplicateCreateBody = /* @__PURE__ */ zod.optional().describe('For retention metrics: start event.'),start_handling: zod.union([zod.enum(['first_seen', 'last_seen']), zod.null()]).optional(),+ threshold: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ '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.'+ ),upper_bound_percentile: zod.union([zod@@ -7206,6 +7236,12 @@ export const ExperimentsDuplicateCreateBody = /* @__PURE__ */ zod.optional().describe('For retention metrics: start event.'),start_handling: zod.union([zod.enum(['first_seen', 'last_seen']), zod.null()]).optional(),+ threshold: zod+ .union([zod.number(), zod.null()])+ .optional()+ .describe(+ '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.'+ ),upper_bound_percentile: zod.union([zoddiff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-duplicate.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-duplicate.jsonindex 73df8126d15c..744956b00bac 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-duplicate.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-duplicate.json@@ -1869,6 +1869,17 @@}]},+ "threshold": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "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."+ },"upper_bound_percentile": {"anyOf": [{@@ -3507,6 +3518,17 @@}]},+ "threshold": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "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."+ },"upper_bound_percentile": {"anyOf": [{diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.jsonindex e8b7efa88a04..1ff538a7ae82 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/experiment-update.json@@ -1840,6 +1840,17 @@}]},+ "threshold": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "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."+ },"upper_bound_percentile": {"anyOf": [{@@ -3478,6 +3489,17 @@}]},+ "threshold": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "description": "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."+ },"upper_bound_percentile": {"anyOf": [{