Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(experiments): prevent negative running-time estimates (#87258)

posthog[bot]7a5d857371fa
diff --git a/frontend/src/scenes/experiments/ExperimentTabContent/RelatedExperimentsTable.tsx b/frontend/src/scenes/experiments/ExperimentTabContent/RelatedExperimentsTable.tsx
index a3f16b053411..dd52e0bd8c16 100644
--- a/frontend/src/scenes/experiments/ExperimentTabContent/RelatedExperimentsTable.tsx
+++ b/frontend/src/scenes/experiments/ExperimentTabContent/RelatedExperimentsTable.tsx
@@ -128,7 +128,9 @@ export const RelatedExperimentsTable = ({
? dayjs().diff(dayjs(experiment.start_date), 'day')
: undefined
- if (remainingDays === undefined || remainingDays === null) {
+ // A negative stored estimate isn't a real duration, so read it as "no estimate"
+ // rather than "~-N days remaining" (records saved before the persist guard can still hold one).
+ if (remainingDays === undefined || remainingDays === null || remainingDays < 0) {
return (
<Tooltip title="Remaining time will be calculated once the experiment has enough data">
<div className="w-full">
diff --git a/frontend/src/scenes/experiments/Experiments.tsx b/frontend/src/scenes/experiments/Experiments.tsx
index 26204549f040..1a6137f38817 100644
--- a/frontend/src/scenes/experiments/Experiments.tsx
+++ b/frontend/src/scenes/experiments/Experiments.tsx
@@ -292,7 +292,9 @@ const ExperimentsTable = ({
? dayjs().diff(dayjs(experiment.start_date), 'day')
: undefined
- if (remainingDays === undefined || remainingDays === null) {
+ // A negative stored estimate isn't a real duration, so read it as "no estimate"
+ // rather than "~-N days remaining" (records saved before the persist guard can still hold one).
+ if (remainingDays === undefined || remainingDays === null || remainingDays < 0) {
return (
<Tooltip title="Remaining time will be calculated once the experiment has enough data">
<div className="w-full">
diff --git a/frontend/src/scenes/experiments/RunningTimeCalculator/RunningTimeConfigModal.tsx b/frontend/src/scenes/experiments/RunningTimeCalculator/RunningTimeConfigModal.tsx
index bebbcae582b9..6fde245e14e0 100644
--- a/frontend/src/scenes/experiments/RunningTimeCalculator/RunningTimeConfigModal.tsx
+++ b/frontend/src/scenes/experiments/RunningTimeCalculator/RunningTimeConfigModal.tsx
@@ -102,7 +102,18 @@ export function RunningTimeConfigModal({ experiment: experimentProp }: RunningTi
fullWidth
options={METRIC_TYPE_OPTIONS}
value={config.metricType}
- onChange={(value) => setConfig({ metricType: value as ManualCalculatorMetricType })}
+ onChange={(value) => {
+ const metricType = value as ManualCalculatorMetricType
+ // Switching to funnel reinterprets baselineValue as a conversion rate, so carry
+ // the same 100% clamp the baseline input applies. Otherwise a large mean value
+ // survives the switch as an out-of-range rate.
+ setConfig({
+ metricType,
+ ...(metricType === 'funnel' && config.baselineValue > 100
+ ? { baselineValue: 100 }
+ : {}),
+ })
+ }}
/>
</div>
@@ -112,7 +123,16 @@ export function RunningTimeConfigModal({ experiment: experimentProp }: RunningTi
<LemonInput
type="number"
value={config.baselineValue}
- onChange={(value) => setConfig({ baselineValue: value as number })}
+ onChange={(value) => {
+ const next = value as number
+ // A funnel conversion rate above 100% is impossible and makes the
+ // sample-size math produce a negative estimate. Clamp it for real,
+ // since the `max` prop below only guides the stepper.
+ setConfig({
+ baselineValue:
+ config.metricType === 'funnel' && next > 100 ? 100 : next,
+ })
+ }}
min={0}
max={config.metricType === 'funnel' ? 100 : undefined}
step={config.metricType === 'funnel' ? 0.1 : 1}
diff --git a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.ts b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.ts
index 836c31b219e7..b495af6c099b 100644
--- a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.ts
+++ b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.test.ts
@@ -126,6 +126,22 @@ describe('runningTimeLogic', () => {
expect(lemonToast.error).not.toHaveBeenCalled()
})
+ it('never persists a non-positive estimate', async () => {
+ // A bad baseline can make the backend return a negative sample size. It must not reach the record.
+ calculateRunningTimeMock.mockResolvedValue({
+ recommended_sample_size: -2000,
+ recommended_running_time_days: -20,
+ })
+
+ logic = runningTimeLogic({ experiment })
+ logic.mount()
+
+ await expectLogic(logic).toDispatchActions(['persistRunningTimeEstimate']).toFinishAllListeners()
+
+ expect(api.update).not.toHaveBeenCalled()
+ expect(logic.values.remainingDays).toBeNull()
+ })
+
it('drops the estimate silently and resyncs the snapshot when it loses a concurrency race', async () => {
calculateRunningTimeMock.mockResolvedValue({
recommended_sample_size: 2000,
diff --git a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts
index 62e4b77b7eea..fd6cb9f48966 100644
--- a/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts
+++ b/frontend/src/scenes/experiments/RunningTimeCalculator/runningTimeLogic.ts
@@ -545,7 +545,7 @@ export const runningTimeLogic = kea<runningTimeLogicType>([
rate: number | null,
experiment: Experiment
): number | null => {
- if (!target || !rate || rate <= 0) {
+ if (!target || target <= 0 || !rate || rate <= 0) {
return null
}
@@ -618,7 +618,11 @@ export const runningTimeLogic = kea<runningTimeLogicType>([
isManualMode ||
!isLaunched(experiment) ||
remainingDays === null ||
- targetSampleSize === null
+ targetSampleSize === null ||
+ // Never store a non-positive estimate — a negative sample size or running time is
+ // meaningless and would surface in the header and list view.
+ remainingDays < 0 ||
+ targetSampleSize <= 0
) {
return
}
diff --git a/products/experiments/backend/running_time_calculator.py b/products/experiments/backend/running_time_calculator.py
index 3758933136f8..2ae25dbeb668 100644
--- a/products/experiments/backend/running_time_calculator.py
+++ b/products/experiments/backend/running_time_calculator.py
@@ -132,7 +132,15 @@ def calculate_sample_size(
# Count / Sum / Ratio / Retention: N = (16 · variance) / d²
sample_size_formula = (SAMPLE_SIZE_Z_FACTOR * variance) / d**2
- return math.ceil(sample_size_formula * number_of_variants)
+ sample_size = math.ceil(sample_size_formula * number_of_variants)
+
+ # A funnel baseline above 1 flips the (1 - p) term negative, and the delta method can return a
+ # negative variance for ratio/retention. Both make the sample size non-positive, which has no
+ # meaning as a count and downstream renders as a negative running time. Treat it as no estimate.
+ if sample_size <= 0:
+ return None
+
+ return sample_size
def calculate_baseline_value(baseline: BaselineStats, metric_type: CalculatorMetricType) -> float | None:
diff --git a/products/experiments/backend/test/test_running_time_calculator.py b/products/experiments/backend/test/test_running_time_calculator.py
index 2dc15b3478f5..8a0dd7118832 100644
--- a/products/experiments/backend/test/test_running_time_calculator.py
+++ b/products/experiments/backend/test/test_running_time_calculator.py
@@ -165,6 +165,14 @@ class TestCalculateSampleSize:
assert calculate_sample_size("ratio", 10, 10, 2) is None
assert calculate_sample_size("ratio", 10, 10, 2, variance=32) == 1024
+ def test_returns_none_for_funnel_baseline_above_one(self):
+ # A conversion rate above 1 flips the (1 - p) term negative, so the sample size is negative.
+ assert calculate_sample_size("funnel", 1.5, 50, 2) is None
+
+ def test_returns_none_for_negative_variance(self):
+ # The delta method can return a negative variance, which yields a negative sample size.
+ assert calculate_sample_size("ratio", 10, 10, 2, variance=-32) is None
+
class TestCalculateRecommendedSampleSize:
@parameterized.expand(