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): add team-level default for CUPED lookback days (#59080)

Anders3d083345f813
diff --git a/frontend/src/scenes/experiments/ExperimentView/CupedModal.tsx b/frontend/src/scenes/experiments/ExperimentView/CupedModal.tsx
index 39346607ae62..87ae42a81c60 100644
--- a/frontend/src/scenes/experiments/ExperimentView/CupedModal.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/CupedModal.tsx
@@ -7,7 +7,7 @@ import { experimentsConfigLogic } from 'scenes/settings/environment/experimentsC
import { DEFAULT_LOOKBACK_DAYS, MAX_LOOKBACK_DAYS, MIN_LOOKBACK_DAYS } from '../constants'
import { experimentLogic } from '../experimentLogic'
import { modalsLogic } from '../modalsLogic'
-import { CupedSelection, getCupedSelection } from './cuped'
+import { CupedSelection, getCupedSelection, resolveCupedLookbackDays } from './cuped'
export function CupedModal(): JSX.Element {
const { experiment } = useValues(experimentLogic)
@@ -17,8 +17,13 @@ export function CupedModal(): JSX.Element {
const { isCupedModalOpen } = useValues(modalsLogic)
const selection = getCupedSelection(experiment.stats_config?.cuped)
- const lookbackDays = experiment.stats_config?.cuped?.lookback_days ?? DEFAULT_LOOKBACK_DAYS
const teamDefaultEnabled = experimentsConfig?.default_cuped_enabled ?? false
+ const teamDefaultLookbackDays = experimentsConfig?.default_cuped_lookback_days ?? null
+ const lookbackDays = resolveCupedLookbackDays(
+ experiment.stats_config?.cuped,
+ teamDefaultLookbackDays,
+ DEFAULT_LOOKBACK_DAYS
+ )
const onClose = (): void => {
restoreUnmodifiedExperiment()
diff --git a/frontend/src/scenes/experiments/ExperimentView/SettingsTab.tsx b/frontend/src/scenes/experiments/ExperimentView/SettingsTab.tsx
index c76c561eeb72..c8bdf81dc034 100644
--- a/frontend/src/scenes/experiments/ExperimentView/SettingsTab.tsx
+++ b/frontend/src/scenes/experiments/ExperimentView/SettingsTab.tsx
@@ -13,7 +13,7 @@ import { ExperimentStatsMethod, PropertyFilterType, PropertyOperator } from '~/t
import { DEFAULT_LOOKBACK_DAYS } from '../constants'
import { experimentLogic } from '../experimentLogic'
import { modalsLogic } from '../modalsLogic'
-import { getCupedSelection, resolveCupedEnabled } from './cuped'
+import { getCupedSelection, resolveCupedEnabled, resolveCupedLookbackDays } from './cuped'
import { CupedModal } from './CupedModal'
import { StatsMethodModal } from './StatsMethodModal'
@@ -31,9 +31,14 @@ export function SettingsTab(): JSX.Element {
: `${((1 - (experiment.stats_config?.frequentist?.alpha ?? 0.05)) * 100).toFixed(0)}%`
const teamDefaultCupedEnabled = experimentsConfig?.default_cuped_enabled ?? false
+ const teamDefaultCupedLookbackDays = experimentsConfig?.default_cuped_lookback_days ?? null
const cupedExplicitlySet = getCupedSelection(experiment.stats_config?.cuped) !== 'default'
const cupedEnabled = resolveCupedEnabled(experiment.stats_config?.cuped, teamDefaultCupedEnabled)
- const cupedLookbackDays = experiment.stats_config?.cuped?.lookback_days ?? DEFAULT_LOOKBACK_DAYS
+ const cupedLookbackDays = resolveCupedLookbackDays(
+ experiment.stats_config?.cuped,
+ teamDefaultCupedLookbackDays,
+ DEFAULT_LOOKBACK_DAYS
+ )
const returnTo = urls.experiment(experiment.id)
diff --git a/frontend/src/scenes/experiments/ExperimentView/cuped.ts b/frontend/src/scenes/experiments/ExperimentView/cuped.ts
index 570531e51fb9..66ae6c79bb90 100644
--- a/frontend/src/scenes/experiments/ExperimentView/cuped.ts
+++ b/frontend/src/scenes/experiments/ExperimentView/cuped.ts
@@ -13,3 +13,17 @@ export function getCupedSelection(cuped: CupedConfig): CupedSelection {
export function resolveCupedEnabled(cuped: CupedConfig, teamDefaultEnabled: boolean): boolean {
return cuped?.enabled === undefined ? teamDefaultEnabled : !!cuped.enabled
}
+
+export function resolveCupedLookbackDays(
+ cuped: CupedConfig,
+ teamDefaultLookbackDays: number | null | undefined,
+ fallbackLookbackDays: number
+): number {
+ if (typeof cuped?.lookback_days === 'number') {
+ return cuped.lookback_days
+ }
+ if (typeof teamDefaultLookbackDays === 'number') {
+ return teamDefaultLookbackDays
+ }
+ return fallbackLookbackDays
+}
diff --git a/frontend/src/scenes/experiments/ExperimentsSettings.tsx b/frontend/src/scenes/experiments/ExperimentsSettings.tsx
index 6c3fbec9840a..50f7835c69f4 100644
--- a/frontend/src/scenes/experiments/ExperimentsSettings.tsx
+++ b/frontend/src/scenes/experiments/ExperimentsSettings.tsx
@@ -3,7 +3,9 @@ import { useValues } from 'kea'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { LemonLabel } from 'lib/lemon-ui/LemonLabel'
import { SpinnerOverlay } from 'lib/lemon-ui/Spinner'
+import { MAX_LOOKBACK_DAYS, MIN_LOOKBACK_DAYS } from 'scenes/experiments/constants'
import { DefaultCupedEnabled } from 'scenes/settings/environment/DefaultCupedEnabled'
+import { DefaultCupedLookbackDays } from 'scenes/settings/environment/DefaultCupedLookbackDays'
import { DefaultExperimentConfidenceLevel } from 'scenes/settings/environment/DefaultExperimentConfidenceLevel'
import { DefaultExperimentStatsMethod } from 'scenes/settings/environment/DefaultExperimentStatsMethod'
import { DefaultOnlyCountMaturedUsers } from 'scenes/settings/environment/DefaultOnlyCountMaturedUsers'
@@ -67,14 +69,24 @@ export function ExperimentsSettings(): JSX.Element {
<DefaultOnlyCountMaturedUsers />
</div>
{showCupedOption && (
- <div>
- <LemonLabel className="text-base">Default CUPED variance reduction</LemonLabel>
- <p className="text-secondary mt-2">
- When enabled, experiments will use CUPED variance reduction. CUPED uses pre-experiment data to
- detect significant effects faster on supported metrics. Can be overridden per experiment.
- </p>
- <DefaultCupedEnabled />
- </div>
+ <>
+ <div>
+ <LemonLabel className="text-base">Default CUPED variance reduction</LemonLabel>
+ <p className="text-secondary mt-2">
+ When enabled, experiments will use CUPED variance reduction. CUPED uses pre-experiment data
+ to detect significant effects faster on supported metrics. Can be overridden per experiment.
+ </p>
+ <DefaultCupedEnabled />
+ </div>
+ <div>
+ <LemonLabel className="text-base">Default CUPED lookback window</LemonLabel>
+ <p className="text-secondary mt-2">
+ Number of days before the experiment start to use as the pre-experiment window. Must be
+ between {MIN_LOOKBACK_DAYS} and {MAX_LOOKBACK_DAYS} days. Can be overridden per experiment.
+ </p>
+ <DefaultCupedLookbackDays />
+ </div>
+ </>
)}
</div>
)
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index ef382d20f252..f90c894f6364 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -16,6 +16,7 @@ import { GoalsConfiguration } from '@posthog/products-revenue-analytics/frontend
import { BaseCurrency } from 'lib/components/BaseCurrency/BaseCurrency'
import { FEATURE_SUPPORT } from 'lib/components/SupportedPlatforms/featureSupport'
import { OrganizationMembershipLevel } from 'lib/constants'
+import { MAX_LOOKBACK_DAYS, MIN_LOOKBACK_DAYS } from 'scenes/experiments/constants'
import { DefaultMinimumDetectableEffect } from 'scenes/experiments/DefaultMinimumDetectableEffect'
import { BounceRateDurationSetting } from 'scenes/settings/environment/BounceRateDuration'
import { BounceRatePageViewModeSetting } from 'scenes/settings/environment/BounceRatePageViewMode'
@@ -62,6 +63,7 @@ import { CSPReportingSettings } from './environment/CSPReportingSettings'
import { DataAttributes } from './environment/DataAttributes'
import { DataColorThemes } from './environment/DataColorThemes'
import { DefaultCupedEnabled } from './environment/DefaultCupedEnabled'
+import { DefaultCupedLookbackDays } from './environment/DefaultCupedLookbackDays'
import { DefaultExperimentConfidenceLevel } from './environment/DefaultExperimentConfidenceLevel'
import { DefaultExperimentStatsMethod } from './environment/DefaultExperimentStatsMethod'
import { DefaultOnlyCountMaturedUsers } from './environment/DefaultOnlyCountMaturedUsers'
@@ -612,6 +614,14 @@ export const SETTINGS_MAP: SettingSection[] = [
component: <DefaultCupedEnabled />,
keywords: ['cuped', 'variance', 'reduction', 'pre-experiment', 'covariate'],
},
+ {
+ id: 'environment-experiment-cuped-lookback-days',
+ title: 'Default CUPED lookback window',
+ description: `Number of days before the experiment start to use as the pre-experiment window for CUPED. Must be between ${MIN_LOOKBACK_DAYS} and ${MAX_LOOKBACK_DAYS} days. Can be overridden per experiment.`,
+ flag: 'EXPERIMENT_CUPED',
+ component: <DefaultCupedLookbackDays />,
+ keywords: ['cuped', 'lookback', 'pre-experiment', 'covariate', 'window'],
+ },
],
},
{
diff --git a/frontend/src/scenes/settings/environment/DefaultCupedLookbackDays.tsx b/frontend/src/scenes/settings/environment/DefaultCupedLookbackDays.tsx
new file mode 100644
index 000000000000..c9315c96efb5
--- /dev/null
+++ b/frontend/src/scenes/settings/environment/DefaultCupedLookbackDays.tsx
@@ -0,0 +1,70 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useState } from 'react'
+
+import { LemonInput } from '@posthog/lemon-ui'
+
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
+import { TeamMembershipLevel } from 'lib/constants'
+import { DEFAULT_LOOKBACK_DAYS, MAX_LOOKBACK_DAYS, MIN_LOOKBACK_DAYS } from 'scenes/experiments/constants'
+
+import { experimentsConfigLogic } from './experimentsConfigLogic'
+
+export function DefaultCupedLookbackDays(): JSX.Element {
+ const { experimentsConfig, experimentsConfigLoading } = useValues(experimentsConfigLogic)
+ const { updateExperimentsConfig } = useActions(experimentsConfigLogic)
+
+ const restrictionReason = useRestrictedArea({
+ scope: RestrictionScope.Project,
+ minimumAccessLevel: TeamMembershipLevel.Admin,
+ })
+
+ const savedValue = experimentsConfig?.default_cuped_lookback_days ?? null
+ const displayValue = savedValue ?? DEFAULT_LOOKBACK_DAYS
+ const [localValue, setLocalValue] = useState<number | undefined>(displayValue)
+
+ useEffect(() => {
+ setLocalValue(displayValue)
+ }, [displayValue])
+
+ const isOutOfRange =
+ localValue !== undefined &&
+ Number.isFinite(localValue) &&
+ (localValue < MIN_LOOKBACK_DAYS || localValue > MAX_LOOKBACK_DAYS)
+ const isNonFinite = localValue !== undefined && !Number.isFinite(localValue)
+ const showDanger = isOutOfRange || isNonFinite
+
+ const commit = (): void => {
+ if (showDanger) {
+ setLocalValue(displayValue)
+ return
+ }
+ if (localValue === undefined) {
+ if (savedValue === null) {
+ setLocalValue(displayValue)
+ return
+ }
+ updateExperimentsConfig({ default_cuped_lookback_days: null })
+ return
+ }
+ const rounded = Math.round(localValue)
+ if (rounded === savedValue) {
+ return
+ }
+ updateExperimentsConfig({ default_cuped_lookback_days: rounded })
+ }
+
+ return (
+ <LemonInput
+ type="number"
+ min={MIN_LOOKBACK_DAYS}
+ max={MAX_LOOKBACK_DAYS}
+ value={localValue}
+ onChange={(value) => setLocalValue(value)}
+ onBlur={commit}
+ onPressEnter={commit}
+ status={showDanger ? 'danger' : 'default'}
+ disabled={!!restrictionReason || experimentsConfigLoading}
+ className="w-32"
+ />
+ )
+}
diff --git a/frontend/src/scenes/settings/environment/experimentsConfigLogic.ts b/frontend/src/scenes/settings/environment/experimentsConfigLogic.ts
index 9a5406e9d4d2..0b032391f607 100644
--- a/frontend/src/scenes/settings/environment/experimentsConfigLogic.ts
+++ b/frontend/src/scenes/settings/environment/experimentsConfigLogic.ts
@@ -14,6 +14,7 @@ export interface ExperimentsConfig {
default_experiment_stats_method: string | null
default_only_count_matured_users: boolean
default_cuped_enabled: boolean
+ default_cuped_lookback_days: number | null
default_minimum_detectable_effect: number
}
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index 5c3b90e8f3f9..287c75aaee0f 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -130,6 +130,7 @@ export type SettingId =
| 'environment-experiment-recalculation-time'
| 'environment-experiment-matured-users'
| 'environment-experiment-cuped-enabled'
+ | 'environment-experiment-cuped-lookback-days'
| 'environment-experiment-mde'
| 'error-tracking-exception-autocapture'
| 'error-tracking-suppression-rules'
diff --git a/posthog/admin/inlines/team_experiments_config_inline.py b/posthog/admin/inlines/team_experiments_config_inline.py
index feaa6875c902..64e9e94dd74a 100644
--- a/posthog/admin/inlines/team_experiments_config_inline.py
+++ b/posthog/admin/inlines/team_experiments_config_inline.py
@@ -21,6 +21,7 @@ class TeamExperimentsConfigInline(admin.StackedInline):
"default_only_count_matured_users",
"funnel_steps_data_disabled",
"default_cuped_enabled",
+ "default_cuped_lookback_days",
],
},
),
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 2d0a4501be8b..7f0c6afd2e54 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -1721,6 +1721,7 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mo
"experiment_precomputation_enabled",
"default_only_count_matured_users",
"default_cuped_enabled",
+ "default_cuped_lookback_days",
"default_minimum_detectable_effect",
]
diff --git a/posthog/hogql_queries/experiments/cuped_config.py b/posthog/hogql_queries/experiments/cuped_config.py
index 41605a9a8b96..fb021ed0ea5b 100644
--- a/posthog/hogql_queries/experiments/cuped_config.py
+++ b/posthog/hogql_queries/experiments/cuped_config.py
@@ -23,11 +23,11 @@ class CupedQueryConfig:
lookback_days: int = DEFAULT_CUPED_LOOKBACK_DAYS
-def _parse_lookback_days(value: Any) -> int:
+def _parse_lookback_days(value: Any, fallback: int = DEFAULT_CUPED_LOOKBACK_DAYS) -> int:
try:
days = int(value)
except (TypeError, ValueError):
- return DEFAULT_CUPED_LOOKBACK_DAYS
+ return fallback
if days < MIN_CUPED_LOOKBACK_DAYS:
return MIN_CUPED_LOOKBACK_DAYS
@@ -36,6 +36,17 @@ def _parse_lookback_days(value: Any) -> int:
return days
+def _resolve_lookback_days(experiment_value: Any, team_default: Any) -> int:
+ """Resolve lookback days using precedence: experiment value > team default > hardcoded default.
+
+ Invalid values at either level fall through to the next level rather than failing.
+ """
+ team_fallback = _parse_lookback_days(team_default) if team_default is not None else DEFAULT_CUPED_LOOKBACK_DAYS
+ if experiment_value is None:
+ return team_fallback
+ return _parse_lookback_days(experiment_value, fallback=team_fallback)
+
+
def _metric_supports_cuped(metric: object) -> bool:
if isinstance(metric, ExperimentMeanMetric):
# Session property metrics use a separate session-deduplication CTE pipeline.
@@ -63,6 +74,7 @@ def get_cuped_config(
stats_config: dict | None,
metric: object,
team_default_enabled: bool = False,
+ team_default_lookback_days: int | None = None,
) -> CupedQueryConfig:
if not _metric_supports_cuped(metric):
return CupedQueryConfig()
@@ -80,5 +92,5 @@ def get_cuped_config(
return CupedQueryConfig(
enabled=True,
- lookback_days=_parse_lookback_days(cuped_config.get("lookback_days", DEFAULT_CUPED_LOOKBACK_DAYS)),
+ lookback_days=_resolve_lookback_days(cuped_config.get("lookback_days"), team_default_lookback_days),
)
diff --git a/posthog/hogql_queries/experiments/experiment_query_runner.py b/posthog/hogql_queries/experiments/experiment_query_runner.py
index 9fdc8333b046..1322e98b0670 100644
--- a/posthog/hogql_queries/experiments/experiment_query_runner.py
+++ b/posthog/hogql_queries/experiments/experiment_query_runner.py
@@ -186,6 +186,7 @@ class ExperimentQueryRunner(QueryRunner):
self.experiment.stats_config,
self.metric,
team_default_enabled=self._team_experiments_config.default_cuped_enabled,
+ team_default_lookback_days=self._team_experiments_config.default_cuped_lookback_days,
)
self.clickhouse_sql: str | None = None
diff --git a/posthog/hogql_queries/experiments/test/test_cuped_config.py b/posthog/hogql_queries/experiments/test/test_cuped_config.py
index 38e9c2462fe0..e29fa8f10b50 100644
--- a/posthog/hogql_queries/experiments/test/test_cuped_config.py
+++ b/posthog/hogql_queries/experiments/test/test_cuped_config.py
@@ -2,7 +2,12 @@ from parameterized import parameterized
from posthog.schema import EventsNode, ExperimentMeanMetric
-from posthog.hogql_queries.experiments.cuped_config import DEFAULT_CUPED_LOOKBACK_DAYS, get_cuped_config
+from posthog.hogql_queries.experiments.cuped_config import (
+ DEFAULT_CUPED_LOOKBACK_DAYS,
+ MAX_CUPED_LOOKBACK_DAYS,
+ MIN_CUPED_LOOKBACK_DAYS,
+ get_cuped_config,
+)
def _supported_metric() -> ExperimentMeanMetric:
@@ -46,3 +51,45 @@ def test_get_cuped_config_team_default_ignored_when_metric_unsupported():
# An object that's neither ExperimentMeanMetric nor ExperimentFunnelMetric is unsupported.
config = get_cuped_config(None, object(), team_default_enabled=True)
assert config.enabled is False
+
+
+ [
+ # (name, stats_config, team_default_lookback_days, expected_lookback_days)
+ ("no_team_default_uses_hardcoded", None, None, DEFAULT_CUPED_LOOKBACK_DAYS),
+ ("team_default_used_when_no_experiment_setting", None, 7, 7),
+ ("experiment_lookback_wins_over_team_default", {"cuped": {"enabled": True, "lookback_days": 21}}, 7, 21),
+ (
+ "team_default_used_when_experiment_has_cuped_but_no_lookback",
+ {"cuped": {"enabled": True}},
+ 10,
+ 10,
+ ),
+ ("invalid_team_default_falls_back_to_hardcoded", None, "not-a-number", DEFAULT_CUPED_LOOKBACK_DAYS),
+ ("team_default_below_min_clamps_to_min", None, 0, MIN_CUPED_LOOKBACK_DAYS),
+ ("team_default_above_max_clamps_to_max", None, 1000, MAX_CUPED_LOOKBACK_DAYS),
+ (
+ "invalid_experiment_lookback_falls_back_to_team_default",
+ {"cuped": {"enabled": True, "lookback_days": "abc"}},
+ 7,
+ 7,
+ ),
+ (
+ "invalid_experiment_lookback_with_no_team_default_falls_back_to_hardcoded",
+ {"cuped": {"enabled": True, "lookback_days": "abc"}},
+ None,
+ DEFAULT_CUPED_LOOKBACK_DAYS,
+ ),
+ ]
+)
+def test_get_cuped_config_lookback_days_resolution(
+ name, stats_config, team_default_lookback_days, expected_lookback_days
+):
+ config = get_cuped_config(
+ stats_config,
+ _supported_metric(),
+ team_default_enabled=True,
+ team_default_lookback_days=team_default_lookback_days,
+ )
+ assert config.enabled is True
+ assert config.lookback_days == expected_lookback_days
diff --git a/products/experiments/backend/migrations/0014_teamexperimentsconfig_default_cuped_lookback_days.py b/products/experiments/backend/migrations/0014_teamexperimentsconfig_default_cuped_lookback_days.py
new file mode 100644
index 000000000000..561332fb6e5f
--- /dev/null
+++ b/products/experiments/backend/migrations/0014_teamexperimentsconfig_default_cuped_lookback_days.py
@@ -0,0 +1,26 @@
+# Generated by Django 5.2.13 on 2026-05-19 19:47
+
+import django.core.validators
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("experiments", "0013_teamexperimentsconfig_default_minimum_detectable_effect"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="teamexperimentsconfig",
+ name="default_cuped_lookback_days",
+ field=models.PositiveSmallIntegerField(
+ blank=True,
+ help_text="Default lookback window (in days) for CUPED variance reduction. Overridden by the experiment-level `stats_config.cuped.lookback_days` setting when set. Must be between 1 and 30 days.",
+ null=True,
+ validators=[
+ django.core.validators.MinValueValidator(1),
+ django.core.validators.MaxValueValidator(30),
+ ],
+ ),
+ ),
+ ]
diff --git a/products/experiments/backend/migrations/max_migration.txt b/products/experiments/backend/migrations/max_migration.txt
index 7b6e40c08b70..28aee939a655 100644
--- a/products/experiments/backend/migrations/max_migration.txt
+++ b/products/experiments/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0013_teamexperimentsconfig_default_minimum_detectable_effect
+0014_teamexperimentsconfig_default_cuped_lookback_days
diff --git a/products/experiments/backend/models/team_experiments_config.py b/products/experiments/backend/models/team_experiments_config.py
index e71f7292bcb0..6e469dd375d8 100644
--- a/products/experiments/backend/models/team_experiments_config.py
+++ b/products/experiments/backend/models/team_experiments_config.py
@@ -62,6 +62,17 @@ class TeamExperimentsConfig(models.Model):
),
)
+ default_cuped_lookback_days = models.PositiveSmallIntegerField(
+ null=True,
+ blank=True,
+ validators=[MinValueValidator(1), MaxValueValidator(30)],
+ help_text=(
+ "Default lookback window (in days) for CUPED variance reduction. "
+ "Overridden by the experiment-level `stats_config.cuped.lookback_days` setting when set. "
+ "Must be between 1 and 30 days."
+ ),
+ )
+
default_minimum_detectable_effect = models.PositiveSmallIntegerField(
null=True,
blank=True,