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(flags): block saving variant rollouts that don't sum to 100 (#84543)

Patricio91f435ac6fb6
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx b/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx
index 574f34cddd9c..198c4efaae4d 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagForm.tsx
@@ -67,7 +67,12 @@ import { FeatureFlagBucketingIdentifier, FeatureFlagEvaluationRuntime, Multivari
import { FeatureFlagCodeExample } from './FeatureFlagCodeExample'
import { FeatureFlagEvaluationContexts } from './FeatureFlagEvaluationContexts'
-import { FeatureFlagLogicProps, featureFlagLogic, slugifyFeatureFlagKey } from './featureFlagLogic'
+import {
+ FeatureFlagLogicProps,
+ featureFlagLogic,
+ slugifyFeatureFlagKey,
+ validateVariantRolloutSum,
+} from './featureFlagLogic'
import { FeatureFlagReleaseConditionsCollapsible } from './FeatureFlagReleaseConditionsCollapsible'
import { PercentageInput } from './PercentageInput'
@@ -297,6 +302,8 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {
}
}
+ const rolloutSumError = validateVariantRolloutSum(variants)
+
const FLAG_TYPE_OPTIONS = [
{
value: 'boolean',
@@ -810,6 +817,10 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {
</div>
</div>
+ {rolloutSumError && (
+ <span className="Field--error text-danger text-xs">{rolloutSumError}</span>
+ )}
+
<DndContext
sensors={sensors}
onDragStart={handleDragStart}
@@ -858,17 +869,19 @@ export function FeatureFlagForm({ id }: FeatureFlagLogicProps): JSX.Element {
)}
<LemonLabel>Rollout percentage</LemonLabel>
- <PercentageInput
- value={variant.rollout_percentage}
- onChange={(value) =>
- updateVariant(
- index,
- 'rollout_percentage',
- value
- )
- }
- data-attr={`feature-flag-variant-rollout-${index}`}
- />
+ <LemonField.Pure error={!!rolloutSumError}>
+ <PercentageInput
+ value={variant.rollout_percentage}
+ onChange={(value) =>
+ updateVariant(
+ index,
+ 'rollout_percentage',
+ value
+ )
+ }
+ data-attr={`feature-flag-variant-rollout-${index}`}
+ />
+ </LemonField.Pure>
<LemonLabel>Description</LemonLabel>
<LemonTextArea
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.test.tsx b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.test.tsx
index 14fac6d9c7bb..b87e5758bb46 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.test.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.test.tsx
@@ -3,6 +3,8 @@ import '@testing-library/jest-dom'
import { act, cleanup, render, screen } from '@testing-library/react'
import { BindLogic, Provider } from 'kea'
+import { dayjs } from 'lib/dayjs'
+
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { FeatureFlagType, ScheduledChangeOperationType } from '~/types'
@@ -83,6 +85,54 @@ describe('FeatureFlagSchedule', () => {
cleanup()
})
+ // A bad sum is only rejected when the change fires, long after it was scheduled.
+ it.each([
+ {
+ name: 'sums to 100',
+ percentages: [50, 50],
+ operation: ScheduledChangeOperationType.UpdateVariants,
+ expectedDisabled: false,
+ },
+ {
+ name: 'falls short',
+ percentages: [50, 20],
+ operation: ScheduledChangeOperationType.UpdateVariants,
+ expectedDisabled: true,
+ },
+ {
+ name: 'exceeds 100',
+ percentages: [60, 60],
+ operation: ScheduledChangeOperationType.UpdateVariants,
+ expectedDisabled: true,
+ },
+ // Variants are read from the flag whatever the operation, so a legacy flag stored at 70
+ // must still be schedulable for a change that leaves them alone.
+ {
+ name: 'falls short but the operation leaves variants untouched',
+ percentages: [50, 20],
+ operation: ScheduledChangeOperationType.UpdateStatus,
+ expectedDisabled: false,
+ },
+ ])('variant rollout $name: Schedule disabled=$expectedDisabled', ({ percentages, operation, expectedDisabled }) => {
+ const featureFlag = buildFeatureFlag({ active: true, rolloutPercentage: 100 })
+ featureFlag.filters.multivariate = {
+ variants: percentages.map((rollout_percentage, index) => ({
+ key: `variant-${index}`,
+ name: '',
+ rollout_percentage,
+ })),
+ }
+ renderSchedule(featureFlag, operation)
+
+ act(() => {
+ featureFlagLogic(logicProps).actions.setScheduleDateMarker(dayjs('2030-01-01T00:00:00Z'))
+ })
+
+ // LemonButton uses aria-disabled, not the disabled attribute.
+ const scheduleButton = screen.getByText('Schedule').closest('button')
+ expect(scheduleButton).toHaveAttribute('aria-disabled', String(expectedDisabled))
+ })
+
it.each([
{
name: 'disabled flag',
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx
index c96339f33d46..79cb279d310d 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagSchedule.tsx
@@ -48,6 +48,7 @@ import {
hasZeroRollout,
PAIRED_PRESETS,
validateFeatureFlagVariantKey,
+ validateVariantRolloutSum,
variantKeyToIndexFeatureFlagPayloads,
} from './featureFlagLogic'
import { FeatureFlagReleaseConditionsCollapsible } from './FeatureFlagReleaseConditionsCollapsible'
@@ -472,6 +473,37 @@ export default function FeatureFlagSchedule(): JSX.Element {
key: validateFeatureFlagVariantKey(variantKey),
}))
+ // A bad sum is rejected when the change fires. Other operations leave variants untouched.
+ const variantRolloutSumError =
+ scheduledChangeOperation === ScheduledChangeOperationType.UpdateVariants
+ ? validateVariantRolloutSum(displayVariants)
+ : undefined
+
+ function getScheduleDisabledReason(): string | undefined {
+ if (!scheduleDateMarker) {
+ return 'Select the scheduled date and time'
+ }
+ if (isRecurring && repeatsValue === 'none') {
+ return 'Select a repeat interval'
+ }
+ if (isRecurring && cronExpression !== null && cronExpression.trim() === '') {
+ return 'Enter a cron expression'
+ }
+ if (repeatsValue === 'cron' && cronPreview === 'Invalid cron expression') {
+ return 'Enter a valid cron expression'
+ }
+ if (hasFormErrors(schedulePayloadErrors)) {
+ return 'Fix release condition errors'
+ }
+ if (
+ scheduledChangeOperation === ScheduledChangeOperationType.UpdateVariants &&
+ variantErrors.some((error) => error.key != null)
+ ) {
+ return 'Fix schedule variant changes errors'
+ }
+ return variantRolloutSumError
+ }
+
const supportsRecurring = RECURRING_SUPPORTED_OPERATIONS.has(scheduledChangeOperation)
// UpdateVariants is only available for multivariate flags
@@ -906,23 +938,7 @@ export default function FeatureFlagSchedule(): JSX.Element {
<LemonButton
type="primary"
onClick={createScheduledChange}
- disabledReason={
- !scheduleDateMarker
- ? 'Select the scheduled date and time'
- : isRecurring && repeatsValue === 'none'
- ? 'Select a repeat interval'
- : isRecurring && cronExpression !== null && cronExpression.trim() === ''
- ? 'Enter a cron expression'
- : repeatsValue === 'cron' && cronPreview === 'Invalid cron expression'
- ? 'Enter a valid cron expression'
- : hasFormErrors(schedulePayloadErrors)
- ? 'Fix release condition errors'
- : scheduledChangeOperation ===
- ScheduledChangeOperationType.UpdateVariants &&
- variantErrors.some((error) => error.key != null)
- ? 'Fix schedule variant changes errors'
- : undefined
- }
+ disabledReason={getScheduleDisabledReason()}
>
Schedule
</LemonButton>
diff --git a/frontend/src/scenes/feature-flags/FeatureFlagVariantsForm.tsx b/frontend/src/scenes/feature-flags/FeatureFlagVariantsForm.tsx
index de4ade1c78fa..c4548ba019e3 100644
--- a/frontend/src/scenes/feature-flags/FeatureFlagVariantsForm.tsx
+++ b/frontend/src/scenes/feature-flags/FeatureFlagVariantsForm.tsx
@@ -16,7 +16,7 @@ import { urls } from 'scenes/urls'
import { FeatureFlagGroupType, MultivariateFlagVariant, Survey } from '~/types'
-import { VariantError, getRecordingFilterForFlagVariant } from './featureFlagLogic'
+import { VariantError, getRecordingFilterForFlagVariant, validateVariantRolloutSum } from './featureFlagLogic'
export interface FeatureFlagVariantsFormProps {
variants: MultivariateFlagVariant[]
@@ -70,8 +70,8 @@ export function FeatureFlagVariantsForm({
variantErrors,
surveys,
}: FeatureFlagVariantsFormProps): JSX.Element {
- const variantRolloutSum = variants.reduce((sum, variant) => sum + (variant.rollout_percentage || 0), 0)
- const areVariantRolloutsValid = variantRolloutSum === 100
+ const rolloutSumError = validateVariantRolloutSum(variants)
+ const areVariantRolloutsValid = !rolloutSumError
const experimentLink = experimentId ? (
<Link target="_blank" to={urls.experiment(experimentId)}>
@@ -255,12 +255,14 @@ export function FeatureFlagVariantsForm({
</div>
<div className="col-span-3">
<div>
- <PercentageInput
- value={variant.rollout_percentage}
- onChange={(value) => onVariantChange?.(index, 'rollout_percentage', value)}
- step={0.01}
- data-attr="feature-flag-variant-rollout-percentage-input"
- />
+ <LemonField.Pure error={!areVariantRolloutsValid}>
+ <PercentageInput
+ value={variant.rollout_percentage}
+ onChange={(value) => onVariantChange?.(index, 'rollout_percentage', value)}
+ step={0.01}
+ data-attr="feature-flag-variant-rollout-percentage-input"
+ />
+ </LemonField.Pure>
{filterGroups.filter((group) => group.variant === variant.key).length > 0 && (
<span className="text-secondary text-xs">
Overridden by{' '}
@@ -299,11 +301,7 @@ export function FeatureFlagVariantsForm({
</div>
</div>
))}
- {variants.length > 0 && !areVariantRolloutsValid && (
- <p className="text-danger">
- Percentage rollouts for variants must sum to 100 (currently {variantRolloutSum}).
- </p>
- )}
+ {rolloutSumError && <p className="text-danger">{rolloutSumError}</p>}
{onAddVariant && (
<LemonButton
type="secondary"
diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts
index ef5adc1c7b64..328663301904 100644
--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts
@@ -64,6 +64,7 @@ import {
slugifyFeatureFlagKey,
validateFeatureFlagKey,
validateFeatureFlagVariantKey,
+ validateVariantRolloutSum,
} from './featureFlagLogic'
import { FeatureFlagsTab, featureFlagsLogic } from './featureFlagsLogic'
@@ -2735,6 +2736,112 @@ describe('validateFeatureFlagVariantKey', () => {
})
})
+describe('validateVariantRolloutSum', () => {
+ // Float artifacts must not reach the user, and a rejected total must never read as 100.
+ it.each([
+ { percentages: [0.01, 64.04, 35], expected: '99.05' },
+ { percentages: [30.1, 30.1, 30.1], expected: '90.3' },
+ { percentages: [50, 49.99], expected: '99.99' },
+ ])('reports $expected without floating point noise', ({ percentages, expected }) => {
+ const variants = percentages.map((rollout_percentage, index) => ({
+ key: `variant-${index}`,
+ name: '',
+ rollout_percentage,
+ }))
+
+ expect(validateVariantRolloutSum(variants)).toBe(
+ `Percentage rollouts for variants must sum to 100 (currently ${expected}).`
+ )
+ })
+})
+
+describe('variant rollout sum validation', () => {
+ let logic: ReturnType<typeof featureFlagLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${MOCK_FEATURE_FLAG.id}/`]: () => [
+ 200,
+ MOCK_FEATURE_FLAG,
+ ],
+ [`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${MOCK_FEATURE_FLAG.id}/status`]: () => [
+ 200,
+ MOCK_FEATURE_FLAG_STATUS,
+ ],
+ },
+ })
+ initKeaTests()
+ logic = featureFlagLogic({ id: 1 })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ })
+
+ // Removing a variant leaves the rest short, and the API rejects that write.
+ it.each([
+ { desc: 'sums to 100', percentages: [50, 50], hasErrors: false },
+ { desc: 'falls short after a variant is removed', percentages: [50], hasErrors: true },
+ { desc: 'exceeds 100', percentages: [60, 60], hasErrors: true },
+ // Adds up to 100.00000000000001; the API tolerates the same drift.
+ { desc: 'sums to 100 with floating point drift', percentages: [0.01, 64.04, 35.95], hasErrors: false },
+ { desc: 'falls short by the smallest step the form allows', percentages: [50, 49.99], hasErrors: true },
+ ])('$desc: hasErrors=$hasErrors', ({ percentages, hasErrors }) => {
+ logic.actions.setFeatureFlag({
+ ...MOCK_FEATURE_FLAG,
+ filters: {
+ groups: [],
+ multivariate: {
+ variants: percentages.map((rollout_percentage, index) => ({
+ key: `variant-${index}`,
+ name: '',
+ rollout_percentage,
+ })),
+ },
+ payloads: {},
+ },
+ })
+
+ expect(logic.values.featureFlagHasErrors).toBe(hasErrors)
+ })
+
+ // Valid keys are load-bearing: a bad key already opens the panel via the older key check, so
+ // only a sum-only failure proves the rollout error reaches submitFeatureFlagFailure.
+ it('opens the collapsed variant panels so the blocked save shows a reason', async () => {
+ logic.actions.setFeatureFlag({
+ ...MOCK_FEATURE_FLAG,
+ filters: {
+ groups: [],
+ multivariate: {
+ variants: [
+ { key: 'control', name: '', rollout_percentage: 50 },
+ { key: 'test', name: '', rollout_percentage: 20 },
+ ],
+ },
+ payloads: {},
+ },
+ })
+ logic.actions.setOpenVariants([])
+
+ await expectLogic(logic, () => {
+ logic.actions.submitFeatureFlag()
+ }).toFinishAllListeners()
+
+ expect(logic.values.openVariants).toEqual(expect.arrayContaining(['variant-0', 'variant-1']))
+ })
+
+ it('does not block a boolean flag, which carries no variants', () => {
+ logic.actions.setFeatureFlag({
+ ...MOCK_FEATURE_FLAG,
+ filters: { groups: [], multivariate: null, payloads: {} },
+ })
+
+ expect(logic.values.featureFlagHasErrors).toBe(false)
+ })
+})
+
describe('variant reordering', () => {
let logic: ReturnType<typeof featureFlagLogic.build>
diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
index d70b1e123c66..b2b77ce7417f 100644
--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts
@@ -462,6 +462,30 @@ export function validateFeatureFlagVariantKey(key: string): string | undefined {
: undefined
}
+function getVariantRolloutSum(variants: MultivariateFlagVariant[] = []): number {
+ return variants.reduce((sum, { rollout_percentage }) => sum + (rollout_percentage || 0), 0)
+}
+
+// Absorbs float drift (0.01/64.04/35.95 adds up to 100.00000000000001) while staying below the
+// 0.01 this form can express. Mirrored by products/feature_flags/backend/variant_rollout.py.
+const ROLLOUT_SUM_TOLERANCE = 1e-9
+
+/** Reason string when variant rollouts do not add up, otherwise undefined.
+ * Boolean flags carry no variants and are exempt. */
+export function validateVariantRolloutSum(variants?: MultivariateFlagVariant[]): string | undefined {
+ if (!variants?.length) {
+ return undefined
+ }
+ const rolloutSum = getVariantRolloutSum(variants)
+ if (Math.abs(rolloutSum - 100) <= ROLLOUT_SUM_TOLERANCE) {
+ return undefined
+ }
+ // Hides float artifacts (99.05000000000001), but stays finer than the tolerance above so a
+ // rejected total never reads as exactly 100.
+ const displayedSum = parseFloat(rolloutSum.toFixed(10))
+ return `Percentage rollouts for variants must sum to 100 (currently ${displayedSum}).`
+}
+
function validatePayloadRequired(is_remote_configuration: boolean, payload?: JsonType): string | undefined {
if (!is_remote_configuration) {
return undefined
@@ -720,7 +744,6 @@ export interface featureFlagLogicValues {
activeSchedules: ScheduledChangeType[]
activeTab: FeatureFlagsTab
aggregationTargetName: string
- areVariantRolloutsValid: boolean
availableTabs: FeatureFlagsTab[]
breadcrumbs: Breadcrumb[]
canCreateEarlyAccessFeature: boolean
@@ -915,7 +938,6 @@ export interface featureFlagLogicValues {
urlIntentApplied: boolean
urlTemplateApplied: boolean
variantErrors: VariantError[]
- variantRolloutSum: number
variants: MultivariateFlagVariant[]
}
@@ -1893,8 +1915,6 @@ export interface featureFlagLogicMeta {
) => boolean
variants: (featureFlag: FeatureFlagType) => MultivariateFlagVariant[]
nonEmptyVariants: (variants: MultivariateFlagVariant[]) => MultivariateFlagVariant[]
- variantRolloutSum: (variants: MultivariateFlagVariant[]) => number
- areVariantRolloutsValid: (variants: MultivariateFlagVariant[], variantRolloutSum: number) => boolean
aggregationTargetName: (
featureFlag: FeatureFlagType,
aggregationLabel: (groupTypeIndex: number | null | undefined, deferToUserWording?: boolean) => Noun // groupsModel
@@ -2082,6 +2102,7 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
ensure_experience_continuity: values.currentTeam?.flags_persistence_default || false,
},
errors: ({ key, filters, is_remote_configuration }) => {
+ const rolloutSumError = validateVariantRolloutSum(filters?.multivariate?.variants)
return {
key: validateFeatureFlagKey(key),
filters: {
@@ -2089,6 +2110,9 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
variants: filters?.multivariate?.variants?.map(
({ key: variantKey }: MultivariateFlagVariant) => ({
key: validateFeatureFlagVariantKey(variantKey),
+ // One string on the array key (the usual form) can't say which
+ // panels to expand, so the set-level error fans out per index.
+ rollout_percentage: rolloutSumError,
})
),
},
@@ -3455,11 +3479,11 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
const formErrors = values.featureFlagErrors as DeepPartialMap<FeatureFlagType, ValidationErrorType>
const filtersErrors = formErrors?.filters as any
const variantErrorsList = filtersErrors?.multivariate?.variants as
- | Array<{ key?: string } | undefined>
+ | Array<{ key?: string; rollout_percentage?: string } | undefined>
| undefined
const variantKeysWithErrors =
variantErrorsList
- ?.map((err, index) => (err?.key ? `variant-${index}` : null))
+ ?.map((err, index) => (err?.key || err?.rollout_percentage ? `variant-${index}` : null))
.filter((key): key is string => key !== null) ?? []
if (variantKeysWithErrors.length) {
actions.setOpenVariants(Array.from(new Set([...values.openVariants, ...variantKeysWithErrors])))
@@ -4231,17 +4255,6 @@ export const featureFlagLogic = kea<featureFlagLogicType>([
(s) => [s.variants],
(variants: MultivariateFlagVariant[]) => variants.filter(({ key }) => !!key),
],
- variantRolloutSum: [
- (s) => [s.variants],
- (variants: MultivariateFlagVariant[]) =>
- variants.reduce((total: number, { rollout_percentage }) => total + rollout_percentage, 0),
- ],
- areVariantRolloutsValid: [
- (s) => [s.variants, s.variantRolloutSum],
- (variants: MultivariateFlagVariant[], variantRolloutSum: number) =>
- variants.every(({ rollout_percentage }) => rollout_percentage >= 0 && rollout_percentage <= 100) &&
- variantRolloutSum === 100,
- ],
aggregationTargetName: [
(s) => [s.featureFlag, s.aggregationLabel],
(
diff --git a/products/feature_flags/backend/filters_validation.py b/products/feature_flags/backend/filters_validation.py
index 2fce61eed895..cff389b5382b 100644
--- a/products/feature_flags/backend/filters_validation.py
+++ b/products/feature_flags/backend/filters_validation.py
@@ -26,6 +26,7 @@ from posthog.models.property.property import STRING_PREFIX_SUFFIX_OPERATORS
from posthog.queries.base import determine_parsed_date_for_property_matching
from products.feature_flags.backend.api.filters_schema import FeatureFlagFiltersSerializer
+from products.feature_flags.backend.variant_rollout import format_variant_rollout_sum, variant_rollout_sum_is_100
DATE_OPERATORS: frozenset[str] = frozenset({"is_date_exact", "is_date_after", "is_date_before"})
STRING_VALUE_OPERATORS: frozenset[str] = frozenset(
@@ -73,18 +74,13 @@ def check_variant_rollout_sum(filters: Mapping[str, Any]) -> list[Violation]:
variant_list = (filters.get("multivariate") or {}).get("variants", [])
if not variant_list:
return []
- # Exact equality is deliberate parity with the live write path, which enforces
- # `sum != 100`. Float summation is deterministic, so any flag that passed that check at
- # write time still sums to exactly 100 here; near-100 drift only exists on rows that
- # predate the check, and those genuinely need cleanup before enforcement because the
- # write path would reject them on their next update anyway.
rollout_sum = sum(variant.get("rollout_percentage", 0) for variant in variant_list)
- if rollout_sum != 100:
+ if not variant_rollout_sum_is_100(rollout_sum):
return [
Violation(
rule_id="cross_field.variant_rollout_sum_not_100",
path="multivariate.variants",
- message=f"Variant rollout percentages must sum to 100, got {rollout_sum}.",
+ message=f"Variant rollout percentages must sum to 100, got {format_variant_rollout_sum(rollout_sum)}.",
)
]
return []
diff --git a/products/feature_flags/backend/models/feature_flag.py b/products/feature_flags/backend/models/feature_flag.py
index 8eb6f1427963..4963cca2f1f4 100644
--- a/products/feature_flags/backend/models/feature_flag.py
+++ b/products/feature_flags/backend/models/feature_flag.py
@@ -22,6 +22,7 @@ from posthog.models.utils import RootTeamManager, RootTeamMixin, RootTeamQuerySe
from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty
from products.experiments.backend.models.experiment import live_experiment_exists
+from products.feature_flags.backend.variant_rollout import format_variant_rollout_sum, variant_rollout_sum_is_100
if TYPE_CHECKING:
from django.db.models.fields.related_descriptors import RelatedManager
@@ -471,8 +472,11 @@ class FeatureFlag(FileSystemSyncMixin, ModelActivityMixin, RootTeamMixin, models
if new_variants:
total_rollout = sum(variant.get("rollout_percentage", 0) for variant in new_variants)
- if total_rollout != 100:
- raise ValueError(f"Invalid variant rollout percentages: sum is {total_rollout}, must be 100")
+ if not variant_rollout_sum_is_100(total_rollout):
+ raise ValueError(
+ f"Invalid variant rollout percentages: sum is "
+ f"{format_variant_rollout_sum(total_rollout)}, must be 100"
+ )
variant_keys = {v.get("key") for v in new_variants}
payload_keys = set(new_payloads.keys()) if new_payloads else set()
diff --git a/products/feature_flags/backend/test/test_filters_validation.py b/products/feature_flags/backend/test/test_filters_validation.py
index 1348b850dc41..68436653c5cc 100644
--- a/products/feature_flags/backend/test/test_filters_validation.py
+++ b/products/feature_flags/backend/test/test_filters_validation.py
@@ -12,6 +12,7 @@ from products.feature_flags.backend.filters_validation import (
CROSS_FIELD_CHECKS,
Violation,
check_groups_non_empty_for_create,
+ check_variant_rollout_sum,
collect_cross_field_violations,
collect_filters_violations,
flatten_structural_errors,
@@ -35,6 +36,18 @@ class TestFiltersValidation(SimpleTestCase):
["cross_field.variant_rollout_sum_not_100"],
),
("variant_sum_exactly_100", {"multivariate": _multivariate(("a", 50), ("b", 50))}, []),
+ # Sums to 100.00000000000001; the flag UI accepts the same split.
+ (
+ "variant_sum_100_with_float_drift",
+ {"multivariate": _multivariate(("a", 0.01), ("b", 64.04), ("c", 35.95))},
+ [],
+ ),
+ # The smallest miss the flag UI can express, so the tolerance cannot swallow it.
+ (
+ "variant_sum_short_by_smallest_step",
+ {"multivariate": _multivariate(("a", 50), ("b", 49.99))},
+ ["cross_field.variant_rollout_sum_not_100"],
+ ),
(
"variant_keys_duplicated",
{"multivariate": _multivariate(("a", 50), ("a", 50))},
@@ -260,6 +273,11 @@ class TestFiltersValidation(SimpleTestCase):
rule_ids = [violation.rule_id for violation in collect_filters_violations(filters)]
assert rule_ids == ["structural.payloads.invalid_payload_json"]
+ def test_variant_rollout_sum_violation_message_hides_float_artifacts(self) -> None:
+ violations = check_variant_rollout_sum({"multivariate": _multivariate(("a", 0.01), ("b", 64.04), ("c", 35))})
+
+ assert violations[0].message == "Variant rollout percentages must sum to 100, got 99.05."
+
def test_collect_filters_violations_end_to_end(self) -> None:
structural = collect_filters_violations({"groups": [{"properties": [{"type": "person"}]}]})
assert [violation.rule_id for violation in structural] == ["structural.groups[].properties[].key.required"]
diff --git a/products/feature_flags/backend/variant_rollout.py b/products/feature_flags/backend/variant_rollout.py
new file mode 100644
index 000000000000..215642e32986
--- /dev/null
+++ b/products/feature_flags/backend/variant_rollout.py
@@ -0,0 +1,22 @@
+"""Shared rule for when multivariate rollout percentages add up (issue #50084).
+
+The tolerance moves the audit gate: rows within it are in-policy, so audit_flag_filters stops
+reporting them and the cross_field.variant_rollout_sum_not_100 counter steps down at deploy.
+A baseline collected before that deploy is not comparable to one after.
+"""
+
+# Absorbs float drift (0.01/64.04/35.95 adds up to 100.00000000000001) while staying below the
+# 0.01 the flag UI can express. Mirrored by validateVariantRolloutSum in featureFlagLogic.ts.
+VARIANT_ROLLOUT_SUM_TOLERANCE = 1e-9
+
+
+def variant_rollout_sum_is_100(rollout_sum: float) -> bool:
+ return abs(rollout_sum - 100) <= VARIANT_ROLLOUT_SUM_TOLERANCE
+
+
+def format_variant_rollout_sum(rollout_sum: float) -> float:
+ """Drop the float artifact so a message never reads `99.05000000000001`.
+
+ Finer than the tolerance, so a failing sum cannot read as exactly 100.
+ """
+ return round(rollout_sum, 10)