: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): add sequential testing for always-valid p-values (#60879)
Andersae68dfe4f63a
diff --git a/frontend/src/scenes/experiments/ExperimentView/SettingsTab.tsx b/frontend/src/scenes/experiments/ExperimentView/SettingsTab.tsxindex 239f23c30cc3..8433d65ccbce 100644--- a/frontend/src/scenes/experiments/ExperimentView/SettingsTab.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/SettingsTab.tsx@@ -15,6 +15,7 @@ import { experimentLogic } from '../experimentLogic'import { modalsLogic } from '../modalsLogic'import { getCupedSelection, resolveCupedEnabled, resolveCupedLookbackDays } from './cuped'import { CupedModal } from './CupedModal'+import { resolveSequentialEnabled } from './sequential'import { StatsMethodModal } from './StatsMethodModal'export function SettingsTab(): JSX.Element {@@ -40,6 +41,12 @@ export function SettingsTab(): JSX.Element {DEFAULT_LOOKBACK_DAYS)+ const teamDefaultSequentialEnabled = experimentsConfig?.default_sequential_testing_enabled ?? false+ const sequentialEnabled = resolveSequentialEnabled(+ experiment.stats_config?.frequentist,+ teamDefaultSequentialEnabled+ )+const returnTo = urls.experiment(experiment.id)// Only show alerts section for saved experiments, as the alert relies on experiment.id for filtering@@ -52,6 +59,7 @@ export function SettingsTab(): JSX.Element {<div className="flex items-center gap-2"><span>{isBayesian ? 'Bayesian' : 'Frequentist'} / {confidenceDisplay}+ {!isBayesian && sequentialEnabled && ' · Sequential testing'}</span><LemonButton type="secondary" size="xsmall" icon={<IconPencil />} onClick={openStatsEngineModal} /></div>diff --git a/frontend/src/scenes/experiments/ExperimentView/StatsMethodModal.tsx b/frontend/src/scenes/experiments/ExperimentView/StatsMethodModal.tsxindex 5d3ac324b7a8..809615e46c7a 100644--- a/frontend/src/scenes/experiments/ExperimentView/StatsMethodModal.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/StatsMethodModal.tsx@@ -1,20 +1,30 @@import { useActions, useValues } from 'kea'-import { LemonButton, LemonLabel, LemonSelect } from '@posthog/lemon-ui'+import { LemonButton, LemonInput, LemonLabel, LemonSelect } from '@posthog/lemon-ui'import { LemonModal } from '@posthog/lemon-ui'+import { experimentsConfigLogic } from 'scenes/settings/environment/experimentsConfigLogic'+import { ExperimentStatsMethod } from '~/types'import { StatsMethodSelector } from '../components/StatsMethodSelector'import { CONFIDENCE_LEVEL_OPTIONS } from '../constants'import { experimentLogic } from '../experimentLogic'import { modalsLogic } from '../modalsLogic'+import {+ DEFAULT_SEQUENTIAL_TUNING_PARAMETER,+ MAX_SEQUENTIAL_TUNING_PARAMETER,+ SequentialSelection,+ getSequentialSelection,+ resolveSequentialTuningParameter,+} from './sequential'export function StatsMethodModal(): JSX.Element {const { experiment, statsMethod } = useValues(experimentLogic)const { updateExperimentSettings, setExperiment, restoreUnmodifiedExperiment } = useActions(experimentLogic)const { closeStatsEngineModal } = useActions(modalsLogic)const { isStatsEngineModalOpen } = useValues(modalsLogic)+ const { experimentsConfig } = useValues(experimentsConfigLogic)const onClose = (): void => {restoreUnmodifiedExperiment()@@ -53,6 +63,55 @@ export function StatsMethodModal(): JSX.Element {}}+ const sequentialSelection = getSequentialSelection(experiment.stats_config?.frequentist)+ const teamDefaultSequentialEnabled = experimentsConfig?.default_sequential_testing_enabled ?? false+ const teamDefaultSequentialTuningParameter = experimentsConfig?.default_sequential_tuning_parameter ?? null+ const sequentialTuningParameter = resolveSequentialTuningParameter(+ experiment.stats_config?.frequentist,+ teamDefaultSequentialTuningParameter,+ DEFAULT_SEQUENTIAL_TUNING_PARAMETER+ )++ const updateSequentialSelection = (next: SequentialSelection): void => {+ const existingFrequentist = experiment.stats_config?.frequentist ?? {}+ if (next === 'default') {+ // Drop the sequential keys entirely so the team default applies at evaluation time.+ const {+ sequential_testing_enabled: _enabled,+ sequential_tuning_parameter: _param,+ ...restFrequentist+ } = existingFrequentist+ setExperiment({+ stats_config: {+ ...experiment.stats_config,+ frequentist: restFrequentist,+ },+ })+ return+ }+ setExperiment({+ stats_config: {+ ...experiment.stats_config,+ frequentist: {+ ...existingFrequentist,+ sequential_testing_enabled: next === 'enabled',+ },+ },+ })+ }++ const updateSequentialTuningParameter = (sequential_tuning_parameter: number): void => {+ setExperiment({+ stats_config: {+ ...experiment.stats_config,+ frequentist: {+ ...experiment.stats_config?.frequentist,+ sequential_tuning_parameter,+ },+ },+ })+ }+return (<LemonModalmaxWidth={600}@@ -103,6 +162,57 @@ export function StatsMethodModal(): JSX.Element {: `Higher confidence means we need stronger evidence before declaring a winner. ${currentConfidenceLevel * 100}% confidence requires a p-value below ${(1 - currentConfidenceLevel).toFixed(2)}.`}</p></div>+ {!isBayesian && (+ <div className="flex flex-col gap-2 mt-4">+ <LemonLabel>Sequential testing</LemonLabel>+ <LemonSelect<SequentialSelection>+ value={sequentialSelection}+ onChange={updateSequentialSelection}+ options={[+ {+ value: 'default',+ label: `Use team default (${teamDefaultSequentialEnabled ? 'Enabled' : 'Disabled'})`,+ },+ { value: 'enabled', label: 'Enabled' },+ { value: 'disabled', label: 'Disabled' },+ ]}+ className="w-72"+ />+ <p className="text-xs text-secondary m-0">+ Always-valid p-values that are robust to peeking. You can check the experiment as often as you+ want without inflating the false positive rate, at the cost of slightly wider confidence+ intervals.+ </p>+ {sequentialSelection === 'enabled' && (+ <div className="flex flex-col gap-1 mt-1">+ <LemonLabel>Tuning parameter</LemonLabel>+ <LemonInput+ type="number"+ min={1}+ max={MAX_SEQUENTIAL_TUNING_PARAMETER}+ value={sequentialTuningParameter}+ onChange={(value) => {+ if (+ typeof value !== 'number' ||+ !Number.isFinite(value) ||+ value < 1 ||+ value > MAX_SEQUENTIAL_TUNING_PARAMETER+ ) {+ return+ }+ updateSequentialTuningParameter(Math.round(value))+ }}+ className="w-32"+ />+ <p className="text-xs text-secondary m-0">+ Roughly the sample size at which the confidence sequence is tightest. Set close to the+ expected total sample size of the experiment. Default is{' '}+ {DEFAULT_SEQUENTIAL_TUNING_PARAMETER}.+ </p>+ </div>+ )}+ </div>+ )}</LemonModal>)}diff --git a/frontend/src/scenes/experiments/ExperimentView/sequential.ts b/frontend/src/scenes/experiments/ExperimentView/sequential.tsnew file mode 100644index 000000000000..9f5bf3536a24--- /dev/null+++ b/frontend/src/scenes/experiments/ExperimentView/sequential.ts@@ -0,0 +1,40 @@+export type SequentialSelection = 'default' | 'enabled' | 'disabled'++type SequentialConfig =+ | { sequential_testing_enabled?: boolean; sequential_tuning_parameter?: number }+ | null+ | undefined++export const DEFAULT_SEQUENTIAL_TUNING_PARAMETER = 5000+// Largest tuning parameter the backend will actually use. Values above this are reverted to+// the default at evaluation time (see _validate_numeric_range in+// posthog/hogql_queries/experiments/utils.py), so cap the inputs here to avoid a silent revert.+export const MAX_SEQUENTIAL_TUNING_PARAMETER = 1_000_000_000++export function getSequentialSelection(frequentist: SequentialConfig): SequentialSelection {+ const explicit = frequentist?.sequential_testing_enabled+ if (explicit === undefined) {+ return 'default'+ }+ return explicit ? 'enabled' : 'disabled'+}++export function resolveSequentialEnabled(frequentist: SequentialConfig, teamDefaultEnabled: boolean): boolean {+ return frequentist?.sequential_testing_enabled === undefined+ ? teamDefaultEnabled+ : !!frequentist.sequential_testing_enabled+}++export function resolveSequentialTuningParameter(+ frequentist: SequentialConfig,+ teamDefaultTuningParameter: number | null | undefined,+ fallback: number = DEFAULT_SEQUENTIAL_TUNING_PARAMETER+): number {+ if (typeof frequentist?.sequential_tuning_parameter === 'number') {+ return frequentist.sequential_tuning_parameter+ }+ if (typeof teamDefaultTuningParameter === 'number') {+ return teamDefaultTuningParameter+ }+ return fallback+}diff --git a/frontend/src/scenes/experiments/ExperimentsSettings.tsx b/frontend/src/scenes/experiments/ExperimentsSettings.tsxindex 50f7835c69f4..dcee1052a454 100644--- a/frontend/src/scenes/experiments/ExperimentsSettings.tsx+++ b/frontend/src/scenes/experiments/ExperimentsSettings.tsx@@ -9,6 +9,8 @@ import { DefaultCupedLookbackDays } from 'scenes/settings/environment/DefaultCupimport { DefaultExperimentConfidenceLevel } from 'scenes/settings/environment/DefaultExperimentConfidenceLevel'import { DefaultExperimentStatsMethod } from 'scenes/settings/environment/DefaultExperimentStatsMethod'import { DefaultOnlyCountMaturedUsers } from 'scenes/settings/environment/DefaultOnlyCountMaturedUsers'+import { DefaultSequentialTestingEnabled } from 'scenes/settings/environment/DefaultSequentialTestingEnabled'+import { DefaultSequentialTuningParameter } from 'scenes/settings/environment/DefaultSequentialTuningParameter'import { ExperimentRecalculationTime } from 'scenes/settings/environment/ExperimentRecalculationTime'import { experimentsConfigLogic } from 'scenes/settings/environment/experimentsConfigLogic'@@ -88,6 +90,24 @@ export function ExperimentsSettings(): JSX.Element {</div></>)}+ <div>+ <LemonLabel className="text-base">Default sequential testing</LemonLabel>+ <p className="text-secondary mt-2">+ When enabled, frequentist experiments will use sequential testing by default, producing always-valid+ p-values that are robust to peeking. Confidence intervals are wider in exchange. Only applies to the+ frequentist statistical method. Can be overridden per experiment.+ </p>+ <DefaultSequentialTestingEnabled />+ </div>+ <div>+ <LemonLabel className="text-base">Default sequential testing tuning parameter</LemonLabel>+ <p className="text-secondary mt-2">+ Roughly the sample size at which the always-valid confidence sequence is tightest. Set close to the+ expected total sample size of new experiments to minimize the width penalty. Can be overridden per+ experiment.+ </p>+ <DefaultSequentialTuningParameter />+ </div></div>)}diff --git a/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx b/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsxindex 683ee4a065b5..ce1ae05f2a83 100644--- a/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx+++ b/frontend/src/scenes/experiments/MetricsView/new/MetricsTable.tsx@@ -1,5 +1,7 @@import { useActions, useValues } from 'kea'+import { experimentsConfigLogic } from 'scenes/settings/environment/experimentsConfigLogic'+import {ExperimentFunnelsQuery,ExperimentMetric,@@ -10,6 +12,7 @@ import { ExperimentStatsMethod, InsightType } from '~/types'import { experimentLogic } from '../../experimentLogic'import { isLaunched } from '../../experimentsLogic'+import { resolveSequentialEnabled } from '../../ExperimentView/sequential'import { type ExperimentVariantResult, getVariantInterval } from '../shared/utils'import { MAX_AXIS_RANGE } from './constants'import { MetricRowGroup } from './MetricRowGroup'@@ -35,6 +38,12 @@ export function MetricsTable({showDetailsModal = true,}: MetricsTableProps): JSX.Element {const { experiment, exposuresLoading } = useValues(experimentLogic)+ const { experimentsConfig } = useValues(experimentsConfigLogic)+ const teamDefaultSequentialEnabled = experimentsConfig?.default_sequential_testing_enabled ?? false+ const sequentialTestingEnabled = resolveSequentialEnabled(+ experiment.stats_config?.frequentist,+ teamDefaultSequentialEnabled+ )const {duplicateMetric,updateExperimentMetrics,@@ -99,6 +108,7 @@ export function MetricsTable({<TableHeaderaxisRange={axisRange}statsMethod={experiment.stats_config?.method || ExperimentStatsMethod.Bayesian}+ sequentialTestingEnabled={sequentialTestingEnabled}/><tbody>{metrics.map((metric, index) => {diff --git a/frontend/src/scenes/experiments/MetricsView/new/TableHeader.tsx b/frontend/src/scenes/experiments/MetricsView/new/TableHeader.tsxindex 027a96e7f136..05e9ee9ba237 100644--- a/frontend/src/scenes/experiments/MetricsView/new/TableHeader.tsx+++ b/frontend/src/scenes/experiments/MetricsView/new/TableHeader.tsx@@ -14,9 +14,10 @@ import { useAxisScale } from './useAxisScale'interface TableHeaderProps {axisRange?: numberstatsMethod?: ExperimentStatsMethod+ sequentialTestingEnabled?: boolean}-export function TableHeader({ axisRange, statsMethod }: TableHeaderProps): JSX.Element {+export function TableHeader({ axisRange, statsMethod, sequentialTestingEnabled }: TableHeaderProps): JSX.Element {const [svgWidth, setSvgWidth] = useState<number | undefined>(undefined)// Set up tick values and scaling for the header@@ -57,7 +58,16 @@ export function TableHeader({ axisRange, statsMethod }: TableHeaderProps): JSX.E</th><th className="w-1/15 border-b-2 bg-bg-table p-3 text-center text-xs sticky top-0 z-10 metric-cell-header whitespace-nowrap">{statsMethod === ExperimentStatsMethod.Frequentist ? (- 'P-value'+ sequentialTestingEnabled ? (+ <span className="inline-flex items-center gap-1">+ P-value+ <Tooltip title="Sequential testing is enabled. These are always-valid p-values, robust to peeking. They have a slightly different interpretation than ordinary p-values and can often be exactly 1.000 early in the experiment. The result is still statistically significant if the p-value drops below your threshold.">+ <IconInfo className="text-secondary text-base" />+ </Tooltip>+ </span>+ ) : (+ 'P-value'+ )) : (<span className="inline-flex items-center gap-1">Win %diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex 020f9f693638..16a25cfc934b 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -67,6 +67,8 @@ import { DefaultCupedLookbackDays } from './environment/DefaultCupedLookbackDaysimport { DefaultExperimentConfidenceLevel } from './environment/DefaultExperimentConfidenceLevel'import { DefaultExperimentStatsMethod } from './environment/DefaultExperimentStatsMethod'import { DefaultOnlyCountMaturedUsers } from './environment/DefaultOnlyCountMaturedUsers'+import { DefaultSequentialTestingEnabled } from './environment/DefaultSequentialTestingEnabled'+import { DefaultSequentialTuningParameter } from './environment/DefaultSequentialTuningParameter'import { DiscussionMentionNotifications } from './environment/DiscussionSettings'import { ErrorTrackingConfigurationMovedBanner } from './environment/ErrorTrackingConfigurationMovedBanner'import { ErrorTrackingIntegrations } from './environment/ErrorTrackingIntegrations'@@ -578,6 +580,22 @@ export const SETTINGS_MAP: SettingSection[] = [component: <DefaultCupedLookbackDays />,keywords: ['cuped', 'lookback', 'pre-experiment', 'covariate', 'window'],},+ {+ id: 'environment-experiment-sequential-testing-enabled',+ title: 'Default sequential testing',+ description:+ 'When enabled, frequentist experiments will use sequential testing by default, producing always-valid p-values that are robust to peeking. Confidence intervals are wider in exchange. Only applies to the frequentist statistical method. Can be overridden per experiment.',+ component: <DefaultSequentialTestingEnabled />,+ keywords: ['sequential', 'peeking', 'always-valid', 'p-value', 'frequentist'],+ },+ {+ id: 'environment-experiment-sequential-tuning-parameter',+ title: 'Default sequential testing tuning parameter',+ description:+ 'Roughly the sample size at which the always-valid confidence sequence is tightest. Set close to the expected total sample size of new experiments to minimize the width penalty. Can be overridden per experiment.',+ component: <DefaultSequentialTuningParameter />,+ keywords: ['sequential', 'tuning', 'parameter', 'rho', 'frequentist'],+ },],},{diff --git a/frontend/src/scenes/settings/environment/DefaultSequentialTestingEnabled.tsx b/frontend/src/scenes/settings/environment/DefaultSequentialTestingEnabled.tsxnew file mode 100644index 000000000000..4ef882d9bfdc--- /dev/null+++ b/frontend/src/scenes/settings/environment/DefaultSequentialTestingEnabled.tsx@@ -0,0 +1,29 @@+import { useActions, useValues } from 'kea'++import { LemonCheckbox } from '@posthog/lemon-ui'++import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { TeamMembershipLevel } from 'lib/constants'++import { experimentsConfigLogic } from './experimentsConfigLogic'++export function DefaultSequentialTestingEnabled(): JSX.Element | null {+ const { experimentsConfig, experimentsConfigLoading } = useValues(experimentsConfigLogic)+ const { updateExperimentsConfig } = useActions(experimentsConfigLogic)++ const restrictionReason = useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: TeamMembershipLevel.Admin,+ })++ return (+ <LemonCheckbox+ label="Apply sequential testing by default"+ checked={experimentsConfig?.default_sequential_testing_enabled ?? false}+ onChange={(checked) => {+ updateExperimentsConfig({ default_sequential_testing_enabled: checked })+ }}+ disabled={!!restrictionReason || experimentsConfigLoading}+ />+ )+}diff --git a/frontend/src/scenes/settings/environment/DefaultSequentialTuningParameter.tsx b/frontend/src/scenes/settings/environment/DefaultSequentialTuningParameter.tsxnew file mode 100644index 000000000000..32309d34507e--- /dev/null+++ b/frontend/src/scenes/settings/environment/DefaultSequentialTuningParameter.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_SEQUENTIAL_TUNING_PARAMETER,+ MAX_SEQUENTIAL_TUNING_PARAMETER,+} from 'scenes/experiments/ExperimentView/sequential'++import { experimentsConfigLogic } from './experimentsConfigLogic'++export function DefaultSequentialTuningParameter(): JSX.Element {+ const { experimentsConfig, experimentsConfigLoading } = useValues(experimentsConfigLogic)+ const { updateExperimentsConfig } = useActions(experimentsConfigLogic)++ const restrictionReason = useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: TeamMembershipLevel.Admin,+ })++ const savedValue = experimentsConfig?.default_sequential_tuning_parameter ?? null+ const displayValue = savedValue ?? DEFAULT_SEQUENTIAL_TUNING_PARAMETER+ const [localValue, setLocalValue] = useState<number | undefined>(displayValue)++ useEffect(() => {+ setLocalValue(displayValue)+ }, [displayValue])++ const isInvalid =+ localValue !== undefined &&+ (!Number.isFinite(localValue) || localValue < 1 || localValue > MAX_SEQUENTIAL_TUNING_PARAMETER)++ const commit = (): void => {+ if (isInvalid) {+ setLocalValue(displayValue)+ return+ }+ if (localValue === undefined) {+ if (savedValue === null) {+ setLocalValue(displayValue)+ return+ }+ updateExperimentsConfig({ default_sequential_tuning_parameter: null })+ return+ }+ const rounded = Math.round(localValue)+ if (rounded === savedValue) {+ return+ }+ updateExperimentsConfig({ default_sequential_tuning_parameter: rounded })+ }++ return (+ <LemonInput+ type="number"+ min={1}+ max={MAX_SEQUENTIAL_TUNING_PARAMETER}+ value={localValue}+ onChange={(value) => setLocalValue(value)}+ onBlur={commit}+ onPressEnter={commit}+ status={isInvalid ? '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.tsindex 0b032391f607..4a6282c32650 100644--- a/frontend/src/scenes/settings/environment/experimentsConfigLogic.ts+++ b/frontend/src/scenes/settings/environment/experimentsConfigLogic.ts@@ -16,6 +16,8 @@ export interface ExperimentsConfig {default_cuped_enabled: booleandefault_cuped_lookback_days: number | nulldefault_minimum_detectable_effect: number+ default_sequential_testing_enabled: boolean+ default_sequential_tuning_parameter: number | null}export const experimentsConfigLogic = kea<experimentsConfigLogicType>([diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.tsindex 5f14236e520e..c100b21baf15 100644--- a/frontend/src/scenes/settings/types.ts+++ b/frontend/src/scenes/settings/types.ts@@ -131,6 +131,8 @@ export type SettingId =| 'environment-experiment-matured-users'| 'environment-experiment-mde'| 'environment-experiment-recalculation-time'+ | 'environment-experiment-sequential-testing-enabled'+ | 'environment-experiment-sequential-tuning-parameter'| 'environment-experiment-stats-method'| 'environment-secret-api-keys'| 'error-tracking-alerting'diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex f127940c3a1f..b75b131a2f75 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -4669,6 +4669,8 @@ export interface Experiment {}frequentist?: {alpha?: number+ sequential_testing_enabled?: boolean+ sequential_tuning_parameter?: number}cuped?: {enabled?: booleandiff --git a/posthog/admin/inlines/team_experiments_config_inline.py b/posthog/admin/inlines/team_experiments_config_inline.pyindex 64e9e94dd74a..f98cf9463685 100644--- a/posthog/admin/inlines/team_experiments_config_inline.py+++ b/posthog/admin/inlines/team_experiments_config_inline.py@@ -22,6 +22,8 @@ class TeamExperimentsConfigInline(admin.StackedInline):"funnel_steps_data_disabled","default_cuped_enabled","default_cuped_lookback_days",+ "default_sequential_testing_enabled",+ "default_sequential_tuning_parameter",],},),diff --git a/posthog/api/team.py b/posthog/api/team.pyindex 31a0a0b67dd7..aa1511733fc7 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -1794,6 +1794,8 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mo"default_cuped_enabled","default_cuped_lookback_days","default_minimum_detectable_effect",+ "default_sequential_testing_enabled",+ "default_sequential_tuning_parameter",]team = self.get_object()diff --git a/posthog/hogql_queries/experiments/experiment_query_runner.py b/posthog/hogql_queries/experiments/experiment_query_runner.pyindex 5ffa4873aa35..1200c363f6e3 100644--- a/posthog/hogql_queries/experiments/experiment_query_runner.py+++ b/posthog/hogql_queries/experiments/experiment_query_runner.py@@ -512,6 +512,8 @@ class ExperimentQueryRunner(QueryRunner):test_variants=test_variants,stats_config=self.experiment.stats_config,cuped_config=self.cuped_config,+ team_default_sequential_testing_enabled=self._team_experiments_config.default_sequential_testing_enabled,+ team_default_sequential_tuning_parameter=self._team_experiments_config.default_sequential_tuning_parameter,)return get_bayesian_experiment_result(diff --git a/posthog/hogql_queries/experiments/test/experiment_query_runner/test_frequentist_method.py b/posthog/hogql_queries/experiments/test/experiment_query_runner/test_frequentist_method.pyindex 2dc7c50cac9a..9254133f5d0b 100644--- a/posthog/hogql_queries/experiments/test/experiment_query_runner/test_frequentist_method.py+++ b/posthog/hogql_queries/experiments/test/experiment_query_runner/test_frequentist_method.py@@ -1,7 +1,8 @@+from datetime import datetimefrom typing import castfrom freezegun import freeze_time-from posthog.test.base import flush_persons_and_events, snapshot_clickhouse_queries+from posthog.test.base import _create_event, _create_person, flush_persons_and_events, snapshot_clickhouse_queriesfrom django.test import override_settings@@ -10,6 +11,7 @@ from posthog.schema import (ExperimentMeanMetric,ExperimentMetricMathType,ExperimentQuery,+ ExperimentQueryResponse,ExperimentStatsValidationFailure,ExperimentVariantResultFrequentist,NewExperimentQueryResponse,@@ -68,3 +70,90 @@ class TestFrequentistMethod(ExperimentQueryRunnerBaseTest):self.assertFalse(test_variant.significant)self.assertEqual(test_variant.p_value, None)self.assertEqual(test_variant.validation_failures, [ExperimentStatsValidationFailure.NOT_ENOUGH_EXPOSURES])++ def _populate_purchases(self, feature_flag, samples_per_variant: int = 60) -> None:+ feature_flag_property = f"$feature/{feature_flag.key}"+ for variant, treatment_effect in [("control", 0), ("test", 5)]:+ for i in range(samples_per_variant):+ distinct_id = f"{feature_flag.key}_{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,+ },+ )+ _create_event(+ team=self.team,+ event="purchase",+ distinct_id=distinct_id,+ timestamp="2020-01-02T13:00:00Z",+ properties={feature_flag_property: variant, "amount": 10 + treatment_effect + (i % 3)},+ )++ def _run_metric(self, experiment) -> ExperimentQueryResponse:+ metric = ExperimentMeanMetric(+ source=EventsNode(+ event="purchase",+ math=ExperimentMetricMathType.SUM,+ math_property="amount",+ ),+ )+ experiment.metrics = [metric.model_dump(mode="json")]+ experiment.save()+ query = ExperimentQuery(experiment_id=experiment.id, kind="ExperimentQuery", metric=metric)+ return cast(ExperimentQueryResponse, ExperimentQueryRunner(query=query, team=self.team).calculate())++ @freeze_time("2020-01-03T12:00:00Z")+ def test_sequential_testing_widens_ci_versus_fixed_horizon(self) -> None:+ # Run identical data through fixed-horizon then sequential frequentist; verify+ # the sequential CI is strictly wider end-to-end through the query runner.+ experiment_start = datetime(2020, 1, 1, 0, 0, 0)+ experiment_end = datetime(2020, 1, 5, 0, 0, 0)++ feature_flag_fixed = self.create_feature_flag(key="test-experiment-fixed")+ experiment_fixed = self.create_experiment(+ name="fixed",+ feature_flag=feature_flag_fixed,+ start_date=experiment_start,+ end_date=experiment_end,+ )+ experiment_fixed.stats_config = {"method": "frequentist"}+ experiment_fixed.save()+ self._populate_purchases(feature_flag_fixed)++ feature_flag_seq = self.create_feature_flag(key="test-experiment-seq")+ experiment_seq = self.create_experiment(+ name="seq",+ feature_flag=feature_flag_seq,+ start_date=experiment_start,+ end_date=experiment_end,+ )+ experiment_seq.stats_config = {+ "method": "frequentist",+ "frequentist": {"sequential_testing_enabled": True, "sequential_tuning_parameter": 5000},+ }+ experiment_seq.save()+ self._populate_purchases(feature_flag_seq)++ flush_persons_and_events()++ fixed_result = self._run_metric(experiment_fixed)+ seq_result = self._run_metric(experiment_seq)++ assert fixed_result.variant_results is not None and seq_result.variant_results is not None+ fixed_variant = cast(ExperimentVariantResultFrequentist, fixed_result.variant_results[0])+ seq_variant = cast(ExperimentVariantResultFrequentist, seq_result.variant_results[0])++ assert fixed_variant.confidence_interval is not None+ assert seq_variant.confidence_interval is not None++ fixed_width = fixed_variant.confidence_interval[1] - fixed_variant.confidence_interval[0]+ seq_width = seq_variant.confidence_interval[1] - seq_variant.confidence_interval[0]++ self.assertGreater(seq_width, fixed_width)diff --git a/posthog/hogql_queries/experiments/test/test_stats_config.py b/posthog/hogql_queries/experiments/test/test_stats_config.pyindex 0d4e9c648469..915003076a83 100644--- a/posthog/hogql_queries/experiments/test/test_stats_config.py+++ b/posthog/hogql_queries/experiments/test/test_stats_config.py@@ -400,3 +400,66 @@ class TestStatsConfig(APIBaseTest):runner = ExperimentQueryRunner(query=query, team=self.team)self.assertEqual(runner.baseline_variant_key, expected_baseline)+++class TestSequentialStatsConfig(APIBaseTest):+ """Verify sequential_testing flags propagate from stats_config (and team defaults) into the engine."""++ def _metric(self) -> ExperimentMeanMetric:+ return ExperimentMeanMetric(source=EventsNode(event="$pageview", math=ExperimentMetricMathType.TOTAL))++ def _variant(self, key: str, sum_val: float, sum_squares: float, samples: int) -> ExperimentStatsBase:+ return ExperimentStatsBase(key=key, sum=sum_val, sum_squares=sum_squares, number_of_samples=samples)++ def _frequentist_ci(+ self,+ *,+ stats_config: dict | None = None,+ team_default_sequential_testing_enabled: bool = False,+ ) -> list[float]:+ result = get_frequentist_experiment_result(+ metric=self._metric(),+ control_variant=self._variant("control", sum_val=1000.0, sum_squares=105000.0, samples=1000),+ test_variants=[self._variant("test", sum_val=1200.0, sum_squares=145000.0, samples=1000)],+ stats_config=stats_config,+ team_default_sequential_testing_enabled=team_default_sequential_testing_enabled,+ )+ assert result.variant_results is not None+ variant = cast(ExperimentVariantResultFrequentist, result.variant_results[0])+ assert variant.confidence_interval is not None+ return variant.confidence_interval++ @parameterized.expand(+ [+ # (name, stats_config, team_default_enabled, expect_sequential)+ ("experiment_enables", {"frequentist": {"sequential_testing_enabled": True}}, False, True),+ ("team_default_enables_when_unset", None, True, True),+ (+ "experiment_false_overrides_team_default",+ {"frequentist": {"sequential_testing_enabled": False}},+ True,+ False,+ ),+ ]+ )+ def test_sequential_resolution(self, _name, stats_config, team_default_enabled, expect_sequential) -> None:+ default_ci = self._frequentist_ci()+ resolved_ci = self._frequentist_ci(+ stats_config=stats_config,+ team_default_sequential_testing_enabled=team_default_enabled,+ )+ if expect_sequential:+ # Always-valid intervals are wider than the fixed-horizon CI.+ self.assertGreater(resolved_ci[1] - resolved_ci[0], default_ci[1] - default_ci[0])+ else:+ # Sequential not applied → identical to the default fixed-horizon CI.+ self.assertEqual(resolved_ci, default_ci)++ def test_invalid_tuning_parameter_falls_back_to_default(self) -> None:+ # Garbage input should not raise; it should fall back to the hardcoded default.+ ci = self._frequentist_ci(+ stats_config={+ "frequentist": {"sequential_testing_enabled": True, "sequential_tuning_parameter": "not-a-number"}+ }+ )+ self.assertEqual(len(ci), 2)diff --git a/posthog/hogql_queries/experiments/utils.py b/posthog/hogql_queries/experiments/utils.pyindex 084f0da0b2e0..0d5f806eaac0 100644--- a/posthog/hogql_queries/experiments/utils.py+++ b/posthog/hogql_queries/experiments/utils.py@@ -30,7 +30,12 @@ from posthog.models import Teamfrom products.experiments.stats.bayesian.enums import PriorTypefrom products.experiments.stats.bayesian.method import BayesianConfig, BayesianMethod-from products.experiments.stats.frequentist.method import FrequentistConfig, FrequentistMethod, TestType+from products.experiments.stats.frequentist.method import (+ DEFAULT_SEQUENTIAL_TUNING_PARAMETER,+ FrequentistConfig,+ FrequentistMethod,+ TestType,+)from products.experiments.stats.shared.cuped import CupedData, cuped_adjustfrom products.experiments.stats.shared.enums import DifferenceTypefrom products.experiments.stats.shared.statistics import (@@ -433,22 +438,61 @@ def _apply_cuped_adjustment_if_enabled()+def _resolve_sequential_settings(+ frequentist_config: dict,+ team_default_enabled: bool,+ team_default_tuning_parameter: int | None,+) -> tuple[bool, float]:+ """Resolve sequential testing settings using precedence: experiment > team default > hardcoded.++ Mirrors the CUPED resolution pattern: an experiment value of `False` deliberately+ overrides a team default of `True` (explicit opt-out wins).+ """+ if "sequential_testing_enabled" in frequentist_config:+ enabled = bool(frequentist_config["sequential_testing_enabled"])+ else:+ enabled = team_default_enabled++ team_fallback = (+ _validate_numeric_range(team_default_tuning_parameter, 1, 1_000_000_000, DEFAULT_SEQUENTIAL_TUNING_PARAMETER)+ if team_default_tuning_parameter is not None+ else DEFAULT_SEQUENTIAL_TUNING_PARAMETER+ )+ tuning_parameter = _validate_numeric_range(+ frequentist_config.get("sequential_tuning_parameter", team_fallback),+ 1,+ 1_000_000_000,+ team_fallback,+ )+ return enabled, tuning_parameter++def get_frequentist_experiment_result(metric: ExperimentMeanMetric | ExperimentFunnelMetric | ExperimentRatioMetric | ExperimentRetentionMetric,control_variant: ExperimentStatsBase,test_variants: list[ExperimentStatsBase],stats_config: dict | None = None,cuped_config: CupedQueryConfig | None = None,+ team_default_sequential_testing_enabled: bool = False,+ team_default_sequential_tuning_parameter: int | None = None,) -> ExperimentQueryResponse:frequentist_config = stats_config.get("frequentist", {}) if stats_config else {}resolved_cuped_config = cuped_config or get_cuped_config(stats_config, metric)+ sequential_testing_enabled, sequential_tuning_parameter = _resolve_sequential_settings(+ frequentist_config,+ team_default_enabled=team_default_sequential_testing_enabled,+ team_default_tuning_parameter=team_default_sequential_tuning_parameter,+ )+config = FrequentistConfig(alpha=_validate_numeric_range(frequentist_config.get("alpha", 0.05), 0.0, 1.0, 0.05),test_type=TestType.TWO_SIDED,difference_type=_parse_enum_config(frequentist_config.get("difference_type", "RELATIVE"), DifferenceType, DifferenceType.RELATIVE),+ sequential_testing_enabled=sequential_testing_enabled,+ sequential_tuning_parameter=sequential_tuning_parameter,)method = FrequentistMethod(config)diff --git a/products/experiments/backend/migrations/0016_teamexperimentsconfig_default_sequential_testing_enabled_and_more.py b/products/experiments/backend/migrations/0016_teamexperimentsconfig_default_sequential_testing_enabled_and_more.pynew file mode 100644index 000000000000..f48a0d4a444f--- /dev/null+++ b/products/experiments/backend/migrations/0016_teamexperimentsconfig_default_sequential_testing_enabled_and_more.py@@ -0,0 +1,34 @@+# Generated by Django 5.2.14 on 2026-05-29 09:08++import django.core.validators+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("experiments", "0015_migrate_feature_flags_models"),+ ]++ operations = [+ migrations.AddField(+ model_name="teamexperimentsconfig",+ name="default_sequential_testing_enabled",+ field=models.BooleanField(+ default=False,+ help_text="Default for enabling sequential testing (always-valid p-values) on new experiments. Overridden by the experiment-level `stats_config.frequentist.sequential_testing_enabled` setting when set. Only applies to the frequentist statistical method.",+ ),+ ),+ migrations.AddField(+ model_name="teamexperimentsconfig",+ name="default_sequential_tuning_parameter",+ field=models.PositiveIntegerField(+ blank=True,+ help_text="Default tuning parameter for sequential testing. Roughly the sample size at which the confidence sequence is tightest. Overridden by the experiment-level `stats_config.frequentist.sequential_tuning_parameter` setting when set.",+ null=True,+ validators=[+ django.core.validators.MinValueValidator(1),+ django.core.validators.MaxValueValidator(1000000000),+ ],+ ),+ ),+ ]diff --git a/products/experiments/backend/migrations/max_migration.txt b/products/experiments/backend/migrations/max_migration.txtindex 8d04f1dfe060..d2426d41855c 100644--- a/products/experiments/backend/migrations/max_migration.txt+++ b/products/experiments/backend/migrations/max_migration.txt@@ -1 +1 @@-0015_migrate_feature_flags_models+0016_teamexperimentsconfig_default_sequential_testing_enabled_and_morediff --git a/products/experiments/backend/models/team_experiments_config.py b/products/experiments/backend/models/team_experiments_config.pyindex 6e469dd375d8..a1340018951c 100644--- a/products/experiments/backend/models/team_experiments_config.py+++ b/products/experiments/backend/models/team_experiments_config.py@@ -84,5 +84,25 @@ class TeamExperimentsConfig(models.Model):),)+ default_sequential_testing_enabled = models.BooleanField(+ default=False,+ help_text=(+ "Default for enabling sequential testing (always-valid p-values) on new experiments. "+ "Overridden by the experiment-level `stats_config.frequentist.sequential_testing_enabled` "+ "setting when set. Only applies to the frequentist statistical method."+ ),+ )++ default_sequential_tuning_parameter = models.PositiveIntegerField(+ null=True,+ blank=True,+ validators=[MinValueValidator(1), MaxValueValidator(1_000_000_000)],+ help_text=(+ "Default tuning parameter for sequential testing. Roughly the sample size at which the "+ "confidence sequence is tightest. Overridden by the experiment-level "+ "`stats_config.frequentist.sequential_tuning_parameter` setting when set."+ ),+ )+register_team_extension_signal(TeamExperimentsConfig, logger=logger)diff --git a/products/experiments/stats/frequentist/method.py b/products/experiments/stats/frequentist/method.pyindex e5fcf7a688d5..7e6cd1666f82 100644--- a/products/experiments/stats/frequentist/method.py+++ b/products/experiments/stats/frequentist/method.py@@ -4,7 +4,7 @@ from typing import Any, Optionalfrom ..shared.enums import DifferenceTypefrom ..shared.statistics import AnyStatistic, StatisticError-from .tests import TestResult, TwoSidedTTest+from .tests import SequentialTwoSidedTTest, StatisticalTest, TestResult, TwoSidedTTestclass TestType(Enum):@@ -13,6 +13,9 @@ class TestType(Enum):TWO_SIDED = "two_sided"+DEFAULT_SEQUENTIAL_TUNING_PARAMETER: float = SequentialTwoSidedTTest.DEFAULT_TUNING_PARAMETER++@dataclassclass FrequentistConfig:"""Configuration for frequentist testing."""@@ -20,11 +23,15 @@ class FrequentistConfig:alpha: float = 0.05difference_type: DifferenceType = DifferenceType.RELATIVEtest_type: TestType = TestType.TWO_SIDED+ sequential_testing_enabled: bool = False+ sequential_tuning_parameter: float = DEFAULT_SEQUENTIAL_TUNING_PARAMETERdef __post_init__(self):"""Validate configuration parameters."""if not (0 < self.alpha < 1):raise StatisticError("Alpha must be between 0 and 1")+ if self.sequential_testing_enabled and self.sequential_tuning_parameter <= 0:+ raise StatisticError("Sequential tuning parameter must be positive")class FrequentistMethod:@@ -74,7 +81,13 @@ class FrequentistMethod:StatisticError: If inputs are invalid or test fails"""if self.config.test_type == TestType.TWO_SIDED:- test = TwoSidedTTest(self.config.alpha)+ if self.config.sequential_testing_enabled:+ test: StatisticalTest = SequentialTwoSidedTTest(+ alpha=self.config.alpha,+ sequential_tuning_parameter=self.config.sequential_tuning_parameter,+ )+ else:+ test = TwoSidedTTest(self.config.alpha)else:raise StatisticError(f"Unknown test type: {self.config.test_type}")diff --git a/products/experiments/stats/frequentist/tests.py b/products/experiments/stats/frequentist/tests.pyindex 52aef1d926cf..f3f540a30e1d 100644--- a/products/experiments/stats/frequentist/tests.py+++ b/products/experiments/stats/frequentist/tests.py@@ -1,8 +1,10 @@+import mathfrom abc import ABC, abstractmethodfrom dataclasses import dataclassfrom ..shared.enums import DifferenceTypefrom ..shared.statistics import AnyStatistic, StatisticError+from ..shared.utils import get_sample_sizefrom .utils import (calculate_confidence_interval,calculate_p_value,@@ -10,6 +12,9 @@ from .utils import (calculate_t_statistic,calculate_variance_pooled,calculate_welch_satterthwaite_df,+ sequential_interval_halfwidth,+ sequential_p_value,+ sequential_rho,validate_sample_sizes,)@@ -137,3 +142,85 @@ class TwoSidedTTest(StatisticalTest):test_type=self.test_type,alpha=self.alpha,)+++class SequentialTwoSidedTTest(StatisticalTest):+ """+ Two-sided sequential test producing always-valid p-values and confidence+ sequences, following Waudby-Smith et al. 2023+ (https://arxiv.org/pdf/2103.06476v7.pdf).++ Unlike a fixed-horizon t-test, the result is robust to continuous monitoring+ ("peeking"): the false positive rate stays bounded by alpha no matter how many+ times the experimenter checks the dashboard. The cost is a wider confidence+ interval that is narrowest near n ~ tuning_parameter.+ """++ DEFAULT_TUNING_PARAMETER: float = 5000.0++ def __init__(self, alpha: float = 0.05, sequential_tuning_parameter: float = DEFAULT_TUNING_PARAMETER):+ super().__init__(alpha=alpha)+ if sequential_tuning_parameter <= 0:+ raise StatisticError("Sequential tuning parameter must be positive")+ self.sequential_tuning_parameter = sequential_tuning_parameter+ self._rho = sequential_rho(alpha, sequential_tuning_parameter)++ @property+ def test_type(self) -> str:+ return "sequential_two_sided"++ @property+ def p_value_type(self) -> str:+ return "two_sided"++ def run_test(+ self,+ treatment_stat: AnyStatistic,+ control_stat: AnyStatistic,+ difference_type: DifferenceType = DifferenceType.RELATIVE,+ **kwargs,+ ) -> TestResult:+ validate_sample_sizes(treatment_stat, control_stat)++ unadjusted_mean = kwargs.get("unadjusted_mean")+ point_estimate = calculate_point_estimate(treatment_stat, control_stat, difference_type, unadjusted_mean)+ pooled_variance = calculate_variance_pooled(treatment_stat, control_stat, difference_type, unadjusted_mean)+ n = get_sample_size(treatment_stat) + get_sample_size(control_stat)++ # No t-distribution in the always-valid construction, so neither the degrees of+ # freedom nor a t-statistic carry meaning here. Surface both as NaN so downstream+ # consumers don't quietly use a meaningless value.+ degrees_of_freedom = math.nan+ t_statistic = math.nan++ p_value = sequential_p_value(+ point_estimate=point_estimate,+ pooled_variance=pooled_variance,+ n=n,+ sequential_tuning_parameter=self.sequential_tuning_parameter,+ rho=self._rho,+ )+ # The Waudby-Smith eq. 9 takes the per-observation variance, but the rest of+ # PostHog's frequentist plumbing passes around the variance of the estimator+ # (SE^2 = Var_T/n_T + Var_C/n_C). Convert by multiplying by the combined sample+ # size; this keeps the e-value (eq. 155) and the half-width (eq. 9) consistent.+ s2_per_observation = pooled_variance * n+ halfwidth = sequential_interval_halfwidth(+ s2=s2_per_observation,+ n=n,+ sequential_tuning_parameter=self.sequential_tuning_parameter,+ alpha=self.alpha,+ rho=self._rho,+ )+ confidence_interval = (point_estimate - halfwidth, point_estimate + halfwidth)++ return TestResult(+ point_estimate=point_estimate,+ confidence_interval=confidence_interval,+ p_value=p_value,+ test_statistic=t_statistic,+ degrees_of_freedom=degrees_of_freedom,+ is_significant=p_value < self.alpha,+ test_type=self.test_type,+ alpha=self.alpha,+ )diff --git a/products/experiments/stats/frequentist/utils.py b/products/experiments/stats/frequentist/utils.pyindex ff84d1b48671..c9e5d49cca1f 100644--- a/products/experiments/stats/frequentist/utils.py+++ b/products/experiments/stats/frequentist/utils.py@@ -230,6 +230,126 @@ def validate_sample_sizes(treatment_stat: AnyStatistic, control_stat: AnyStatistraise StatisticError(f"Control sample size ({control_n}) below minimum ({min_sample_size})")+def sequential_rho(alpha: float, sequential_tuning_parameter: float) -> float:+ """+ Convert the sequential testing tuning parameter `N` into the mixing parameter `rho`.++ Implements eq. 161 of Waudby-Smith et al. 2023 (two-sided form):+ rho = sqrt( ( -2*ln(alpha) + ln(-2*ln(alpha) + 1) ) / N )++ Args:+ alpha: Significance level (must be in (0, 1)).+ sequential_tuning_parameter: Positive number `N` controlling where along the+ data-collection timeline the confidence sequence is tightest.++ Returns:+ The mixing parameter rho.+ """+ if not (0 < alpha < 1):+ raise StatisticError("Alpha must be between 0 and 1")+ if sequential_tuning_parameter <= 0:+ raise StatisticError("Sequential tuning parameter must be positive")++ log_alpha = np.log(alpha)+ return float(np.sqrt((-2 * log_alpha + np.log(-2 * log_alpha + 1)) / sequential_tuning_parameter))+++def sequential_interval_halfwidth(+ s2: float,+ n: int,+ sequential_tuning_parameter: float,+ alpha: float,+ rho: float | None = None,+) -> float:+ """+ Half-width of the two-sided always-valid confidence sequence.++ Implements eq. 9 of Waudby-Smith et al. 2023:+ halfwidth = sqrt(s2) * sqrt( 2*(n*rho^2 + 1) * ln(sqrt(n*rho^2 + 1)/alpha) / (n*rho)^2 )++ `s2` here is the per-observation variance (matching the paper's notation), NOT the+ variance of the estimator. For a two-sample test where the caller has+ SE^2 = Var_T/n_T + Var_C/n_C, the corresponding per-observation analog to pass in+ is `SE^2 * (n_T + n_C)`.++ Args:+ s2: Per-observation variance (must be positive).+ n: Combined sample size across treatment + control (must be >= 1).+ sequential_tuning_parameter: Tuning parameter `N`.+ alpha: Significance level.+ rho: Optional precomputed rho. If omitted, derived from alpha and N.++ Returns:+ Half-width of the confidence sequence.+ """+ if s2 <= 0:+ raise StatisticError("s2 must be positive")+ if n < 1:+ raise StatisticError("Sample size must be at least 1")++ if rho is None:+ rho = sequential_rho(alpha, sequential_tuning_parameter)++ n_rho_sq_p1 = n * rho**2 + 1+ return float(np.sqrt(s2) * np.sqrt(2 * n_rho_sq_p1 * np.log(np.sqrt(n_rho_sq_p1) / alpha) / (n * rho) ** 2))+++def sequential_p_value(+ point_estimate: float,+ pooled_variance: float,+ n: int,+ sequential_tuning_parameter: float,+ rho: float | None = None,+ alpha: float | None = None,+ null_hypothesis_value: float = 0.0,+) -> float:+ """+ Two-sided always-valid p-value, derived analytically from the e-value.++ Implements eq. 155 of Waudby-Smith et al. 2023:+ t^2 = (theta_hat - theta_0)^2 * n / SE^2+ evalue = exp( rho^2 * t^2 / (2*(n*rho^2 + 1)) ) / sqrt(n*rho^2 + 1)+ p_value = min(1 / evalue, 1)++ Here `pooled_variance` is SE^2 of the estimator (e.g. Var_T/n_T + Var_C/n_C for the+ two-sample diff). The `* n` factor is applied internally.++ The e-value is < 1 (and so the p-value clamps to 1) until enough evidence has+ accumulated. Early-in-experiment p-values of exactly 1.0 are expected behavior,+ not a bug.++ Args:+ point_estimate: Estimated difference between treatment and control.+ pooled_variance: Variance of the estimator (i.e. SE^2).+ n: Combined sample size.+ sequential_tuning_parameter: Tuning parameter `N`.+ rho: Optional precomputed rho. If omitted, must supply alpha.+ alpha: Significance level used to derive rho when not given.+ null_hypothesis_value: Value under the null hypothesis.++ Returns:+ Always-valid p-value in (0, 1].+ """+ if pooled_variance <= 0:+ raise StatisticError("Pooled variance must be positive")+ if n < 1:+ raise StatisticError("Sample size must be at least 1")++ if rho is None:+ if alpha is None:+ raise StatisticError("Must supply either rho or alpha to compute sequential p-value")+ rho = sequential_rho(alpha, sequential_tuning_parameter)++ t_squared = (point_estimate - null_hypothesis_value) ** 2 * n / pooled_variance+ n_rho_sq_p1 = n * rho**2 + 1+ # Work in log-space to avoid np.exp overflowing to +inf for extremely strong evidence;+ # the e-value can be astronomical but 1/e-value just collapses smoothly toward 0.+ log_evalue = rho**2 * t_squared / (2 * n_rho_sq_p1) - 0.5 * np.log(n_rho_sq_p1)+ if log_evalue <= 0:+ return 1.0+ return float(min(np.exp(-log_evalue), 1.0))++def check_normal_approximation_validity(statistic: AnyStatistic) -> bool:"""Check if normal approximation is valid for the given statistic.diff --git a/products/experiments/stats/tests/test_frequentist.py b/products/experiments/stats/tests/test_frequentist.pyindex dcafc9536ee2..37a4aa5f7587 100644--- a/products/experiments/stats/tests/test_frequentist.py+++ b/products/experiments/stats/tests/test_frequentist.py@@ -1,10 +1,25 @@+import mathfrom typing import Any, castfrom unittest import TestCase+from parameterized import parameterized+from products.experiments.stats.frequentist.method import FrequentistConfig, FrequentistMethod+from products.experiments.stats.frequentist.tests import SequentialTwoSidedTTest+from products.experiments.stats.frequentist.utils import (+ calculate_variance_pooled,+ sequential_interval_halfwidth,+ sequential_p_value,+ sequential_rho,+)from products.experiments.stats.shared.enums import DifferenceType-from products.experiments.stats.shared.statistics import ProportionStatistic, RatioStatistic, SampleMeanStatistic+from products.experiments.stats.shared.statistics import (+ ProportionStatistic,+ RatioStatistic,+ SampleMeanStatistic,+ StatisticError,+)def create_test_result_dict(result: Any) -> dict[str, Any]:@@ -149,3 +164,191 @@ class TestTwoSidedTTest(TestCase):expected_uplift = get_expected_uplift(expected_dict)self.assertAlmostEqual(uplift["mean"], expected_uplift["mean"], places=4)self.assertAlmostEqual(uplift["stddev"], expected_uplift["stddev"], places=4)+++class TestSequentialMath(TestCase):+ """Unit tests for the sequential testing primitives (rho, half-width, p-value)."""++ def test_sequential_rho_matches_formula(self):+ alpha = 0.05+ n_tuning = 5000.0+ rho = sequential_rho(alpha, n_tuning)+ log_alpha = math.log(alpha)+ expected = math.sqrt((-2 * log_alpha + math.log(-2 * log_alpha + 1)) / n_tuning)+ self.assertAlmostEqual(rho, expected, places=10)++ def test_sequential_rho_rejects_invalid_alpha(self):+ with self.assertRaises(StatisticError):+ sequential_rho(0.0, 5000)+ with self.assertRaises(StatisticError):+ sequential_rho(1.0, 5000)++ def test_sequential_rho_rejects_nonpositive_tuning_parameter(self):+ with self.assertRaises(StatisticError):+ sequential_rho(0.05, 0)+ with self.assertRaises(StatisticError):+ sequential_rho(0.05, -1)++ def test_sequential_halfwidth_wider_than_fixed_horizon(self):+ # Per-observation variance sigma^2 = 1, total n = 5000.+ # Fixed-horizon halfwidth (1.96 * SE) uses SE = sqrt(sigma^2/n).+ s2 = 1.0+ n = 5000+ alpha = 0.05+ seq_halfwidth = sequential_interval_halfwidth(s2, n, 5000, alpha)+ fixed_halfwidth = 1.96 * math.sqrt(s2 / n)+ self.assertGreater(seq_halfwidth, fixed_halfwidth)++ def test_sequential_p_value_clamps_to_one_with_small_n(self):+ # Tiny effect, tiny n: e-value < 1 so p-value clamps to 1.+ p = sequential_p_value(+ point_estimate=0.01,+ pooled_variance=1.0,+ n=10,+ sequential_tuning_parameter=5000,+ alpha=0.05,+ )+ self.assertEqual(p, 1.0)++ def test_sequential_p_value_drops_with_strong_evidence(self):+ # Strong, well-powered effect should produce a small always-valid p-value.+ # SE^2 = 0.0001 (so SE = 0.01) means a 0.5 effect is ~50 standard errors out.+ p_strong = sequential_p_value(+ point_estimate=0.5,+ pooled_variance=0.0001,+ n=10000,+ sequential_tuning_parameter=5000,+ alpha=0.05,+ )+ self.assertLess(p_strong, 0.05)+++class TestSequentialTwoSidedTTest(TestCase):+ """End-to-end behavior of SequentialTwoSidedTTest via FrequentistMethod."""++ def test_sequential_ci_is_wider_than_fixed_horizon_ci(self):+ from products.experiments.stats.frequentist.method import TestType++ stat_a = SampleMeanStatistic(sum=1922.7, sum_squares=94698.29, n=2461)+ stat_b = SampleMeanStatistic(sum=1196.87, sum_squares=37377.9767, n=2507)++ config_fixed = FrequentistConfig(+ alpha=0.05, test_type=TestType.TWO_SIDED, difference_type=DifferenceType.RELATIVE+ )+ config_seq = FrequentistConfig(+ alpha=0.05,+ test_type=TestType.TWO_SIDED,+ difference_type=DifferenceType.RELATIVE,+ sequential_testing_enabled=True,+ sequential_tuning_parameter=5000,+ )++ fixed_result = FrequentistMethod(config_fixed).run_test(stat_a, stat_b)+ seq_result = FrequentistMethod(config_seq).run_test(stat_a, stat_b)++ fixed_width = fixed_result.confidence_interval[1] - fixed_result.confidence_interval[0]+ seq_width = seq_result.confidence_interval[1] - seq_result.confidence_interval[0]++ self.assertGreater(seq_width, fixed_width)+ self.assertAlmostEqual(seq_result.point_estimate, fixed_result.point_estimate, places=6)+ self.assertEqual(seq_result.test_type, "sequential_two_sided")+ self.assertTrue(math.isnan(seq_result.degrees_of_freedom))+ self.assertTrue(math.isnan(seq_result.test_statistic))++ def test_sequential_p_value_with_zero_effect_returns_one(self):+ from products.experiments.stats.frequentist.method import TestType++ stat_a = ProportionStatistic(sum=100, n=2000)+ stat_b = ProportionStatistic(sum=100, n=2000)++ config = FrequentistConfig(+ alpha=0.05,+ test_type=TestType.TWO_SIDED,+ difference_type=DifferenceType.ABSOLUTE,+ sequential_testing_enabled=True,+ sequential_tuning_parameter=5000,+ )+ result = FrequentistMethod(config).run_test(stat_a, stat_b)+ self.assertEqual(result.p_value, 1.0)+ self.assertFalse(result.is_significant)++ def test_invalid_tuning_parameter_raises(self):+ with self.assertRaises(StatisticError):+ SequentialTwoSidedTTest(alpha=0.05, sequential_tuning_parameter=0)+++class TestSequentialTwoSidedTTestGoldenValues(TestCase):+ """Golden fixtures for the two-sided sequential test.++ The implementation was validated to reproduce the published reference values of+ Waudby-Smith et al. 2023; these fixtures then lock in that behavior on our own+ chosen inputs, guarding the end-to-end computation (point estimate, confidence+ sequence, p-value, and the standard error the CI is built from) against drift.+ run_test takes (treatment, control), so the higher-mean stat is passed first.+ """++ @parameterized.expand(+ [+ (+ "sample_mean_tuning_1000",+ SampleMeanStatistic(sum=2500.0, sum_squares=135000.0, n=3500),+ SampleMeanStatistic(sum=1400.0, sum_squares=52000.0, n=3000),+ 1000,+ 0.53061,+ (-0.53230, 1.59353),+ 0.33368,+ 1.0,+ ),+ (+ "proportion_default_tuning",+ ProportionStatistic(sum=2600, n=3500),+ ProportionStatistic(sum=1450, n=3050),+ 5000,+ 0.56256,+ (0.46064, 0.66448),+ 0.03354,+ # Very strong evidence: the e-value is astronomical, so the p-value is a+ # near-zero (~6e-56) that rounds to 0.0 at 5 decimals. The log-space form+ # keeps the accurate tiny value instead of underflowing 1/e-value to 0.+ 0.0,+ ),+ ]+ )+ def test_matches_reference_values(self, _name, treatment, control, tuning_parameter, expected, ci, stddev, p_value):+ result = SequentialTwoSidedTTest(alpha=0.05, sequential_tuning_parameter=tuning_parameter).run_test(+ treatment, control, DifferenceType.RELATIVE+ )++ self.assertAlmostEqual(result.point_estimate, expected, places=5)+ self.assertAlmostEqual(result.confidence_interval[0], ci[0], places=5)+ self.assertAlmostEqual(result.confidence_interval[1], ci[1], places=5)+ self.assertAlmostEqual(result.p_value, p_value, places=5)++ # Assert the standard error directly (the SE the sequential CI is built from) so a+ # variance regression is pinpointed, not just inferred from a shifted CI.+ standard_error = math.sqrt(calculate_variance_pooled(treatment, control, DifferenceType.RELATIVE))+ self.assertAlmostEqual(standard_error, stddev, places=5)++ def test_interval_narrowest_near_true_sample_size(self):+ # Same stats as the sample-mean fixture; true total n = 3500 + 3000 = 6500. The+ # confidence sequence is tightest when the tuning parameter ~ true n and widens as+ # it badly under- (10) or over-estimates (10000) it.+ treatment = SampleMeanStatistic(sum=2500.0, sum_squares=135000.0, n=3500)+ control = SampleMeanStatistic(sum=1400.0, sum_squares=52000.0, n=3000)++ def interval(tuning_parameter: float) -> tuple[float, float]:+ test = SequentialTwoSidedTTest(alpha=0.05, sequential_tuning_parameter=tuning_parameter)+ return test.run_test(treatment, control, DifferenceType.RELATIVE).confidence_interval++ below = interval(10)+ near = interval(6500)+ above = interval(10000)++ # Under-estimating the sample size gives the widest interval.+ self.assertLess(below[0], near[0])+ self.assertGreater(below[1], near[1])+ self.assertLess(below[0], above[0])+ self.assertGreater(below[1], above[1])+ # Over-estimating is wider than estimating well, but narrower than under-estimating.+ self.assertLess(above[0], near[0])+ self.assertGreater(above[1], near[1])